python,class,decorator,with-statement
Each with statement creates a new instance of fcount2 so each instance only has one block_count - I don't have an answer but some additions to your code will illustrate what is happening. class fcount2(object): def __init__(self, inner_func): self.inner_func = inner_func self.count = 0 self.block_count =0 def __call__(self, *args, **kwargs):...
vba,excel-vba,if-statement,with-statement
The With is simply an abbreviation. For example With Sheets("DL Data") .Range("W7:W" & .Cells(.Rows.Count, "A").End(xlUp).Row).Formula = "\L" End With Is equivalent to Sheets("DL Data").Range("W7:W" & Sheets("DL Data").Cells(Sheets("DL Data").Rows.Count, "A").End(xlUp).Row).Formula = "\L" You need a loop in order to apply this condition to all of the rows, for example: Dim i...
As you mentioned you need to use Recursive CTE. Try this. DECLARE @Startdate DATE= '01/01/2015', @enddate DATE = '01/31/2015', @Patterndays INT=7; WITH cte AS (SELECT CONVERT(DATE, @Startdate) [dates], 1 AS id, CONVERT(VARCHAR(20), 'On Duty') AS duty UNION ALL SELECT Dateadd(dd, @Patterndays, [dates]), ID + 1, CASE WHEN ( id +...
python,python-3.x,with-statement
Note that: with foo as bar: is (very, very roughly) equivalent to: bar = foo (This is consistent with other uses of as in Python, e.g. except ValueError as err:.) Therefore when you try: with outfile as open('/Users/jmanley/Desktop/Table.sql', 'wb'): you are actually trying to assign: open('/Users/jmanley/Desktop/Table.sql', 'wb') = outfile which...
All answers so far do not provide what (I think) OP wants directly. (I think) OP wants something like this: >>> with X() as x: ... # ok >>> x = X() # ERROR Traceback (most recent call last): File "run.py", line 18, in <module> x = X() File "run.py",...
The problems with with statements are all rooted in the same problem: when using with, scoping becomes complicated. Consider the following sample: with (foo) { with (bar) { return x; } } This seems simple, but it actually can have all sorts of possible outcomes. If foo is defined and...
excel,excel-vba,with-statement
As you are clearing cells, cl may be Nothing so you need to either delete the range outside the loop, or add a testing for Nothing Method 1 will be quicker Method 1 - delete range in single shot Sub A() Dim ws As Worksheet Dim SrchRng As Range Dim...
python,conditional,indentation,conditional-statements,with-statement
If you want to avoid duplicating code, you could do something like: class dummy_context_mgr(): def __enter__(self): return None def __exit__(self): return False with get_stuff() if needs_with() else dummy_context_mgr() as gs: # do stuff involving gs or not or make get_stuff() return different things based on needs_with()....
database,postgresql,recursion,recursive-query,with-statement
There is no "recursion" taking place here and I think that this is where you get confused. From the PostgreSQL documentation: http://www.postgresql.org/docs/9.4/static/queries-with.html Note: Strictly speaking, this process is iteration not recursion, but RECURSIVE is the terminology chosen by the SQL standards committee. To paraphrase this sentence, a WITH RECURSIVE can...
python,try-catch,with-statement,contextmanager
Keep your try / except statement as close to the source of the exception as possible. If you are not catching IOErrors, put it inside the with statement. On the other hand, if it is an exception that open() throws, put it around the with statement. If the with statement...
Don't define an scope: <template repeat="{{items}}"> <tr><td> {{name}} </td><td> {{count}} </td></tr> </template> ...
Yes, you are correct with automatically closes the file when its scope ends, so if you use with statement in your __init__() function, the write_something function would not work. Maybe you can use the with statement in the main part of the program, and instead of opening the file in...
To give you an example of how this would work with the dplyr package if you want to calculate the means of Handle by groups of Period AND Queue: require(dplyr) ctrlmeans <- #data.frame to store your results ttp1 %.% #data.frane to use for analysis group_by(Period,Queue) %.% #grouping variables (you can...
sql,nested,subquery,with-statement
Is this what you want? with t1 as ( select a.col1 as c1, a.col2 as c2, b.col1 as c3, b.col2 as c4 from table1 a left join table2 b on a.col1 = b.col1 ), t2 as ( select c.c1, c.c2, c.c3, c.c4 from t1 c ) select * from t2;...
python,python-3.x,with-statement,shelve
In Python 3.3 shelve.open() is not a context manager and cannot be used in a with statement. The with statement expects there to be __enter__ and __exit__ methods; the error you see is because there are no such methods. You can use contextlib.closing() to wrap the shelve.open() result in a...
python,python-3.x,with-statement,class-method
__enter__ and __exit__ are special methods, and as such only work correctly when defined on a object's type, not in it's instance dictionary. Now Spam is a instance of type, and type(Spam).__enter__ and type(Spam).__exit__ do not exist. Therefore you get an attribute error. To make this work, the methods would...
Are you sure that the first query is doing what you think that it is? In your query if sCount > 1 then I think that means you have more than one relationship between p and some SKU (i.e multiple relationships between the same nodes). If your WITH statement were...
email,python-3.x,gmail,raspberry-pi,with-statement
You are not using Python 3.3 or up. In your version of Python, smtplib.SMTP() is not a context manager and cannot be using in a with statement. The traceback is directly caused because there is no __exit__ method, a requirement for context managers. From the smptlib.SMTP() documentation: Changed in version...
The constructor (__init__ method) for your ExclusiveSqlConnection needs to take a path parameter. On the other hand, __enter__ takes no parameter other than self. import sqlite3 as sql class ExclusiveSqlConnection(object): """meant to be used with a with statement to ensure proper closure""" def __init__(self, path): self.path = path def __enter__(self):...
haskell,types,with-statement,xmonad
What you will want to do is make a newtype wrapper for X, using GeneralizedNewtypeDeriving to get a free Monad instance: {-# LANGUAGE GeneralizedNewtypeDeriving #-} newtype XNeedsCleanup a = FromX { toX :: X a } deriving (Functor, Applicative, Monad) Because XNeedsCleanup is a monad, you can bind multiple XNeedsCleanup...
vb.net,function,with-statement
I'm not entirely sure this addresses everything you are asking for, but maybe it will give you an idea. EDIT: based on the updated question, I have another solution. This requires understanding of two-dimensional arrays in programming. You just load all the "coordinates" into an array and then iterate them...
python,with-statement,filelock,contextmanager
You should use something like the following: @contextmanager def FileLock(lock_file): while os.path.exists(lock_file): print 'Only one script can run at once. '\ 'Script is locked with %s' % lock_file time.sleep(1) open(lock_file, 'w').write("1") try: yield finally: os.remove(lock_file) This directly answers your declared need. OTOH the method is very buggy because there is...
Why don't you consult the D Language Reference? With just few clicks I found http://dlang.org/statement#WithStatement, which answers your question. If you are lazy to follow the link, here is the short answer: yes, D has the with statement, and it behaves exactly as you want.
python,with-statement,contextmanager
The with statement only manages exceptions in step 3. If an exception is raised in step 1 (executing expression) or in step 2 (executing the context manager __enter__ method), you do not have a (valid and working) context manager to hand the exception to. So if the file does not...
python,csv,compare,diff,with-statement
Not sure how effective is this but IMO does what you want: import csv with open('English.csv', 'rb') as csvfile1: with open ("Dictionary.csv", "rb") as csvfile2: reader1 = csv.reader(csvfile1) reader2 = csv.reader(csvfile2) rows1_col_a = [row[0] for row in reader1] rows2 = [row for row in reader2] only_b = [] for row...
python,python-3.x,with-statement,iterable,chain
You misunderstood that line. The with statement takes more than one context manager, separated by commas, but not an iterable: with foo, bar: works. Use a contextlib.ExitStack() object if you need to support a dynamic set of context managers: from contextlib import ExitStack with ExitStack() as stack: for cm in...
javascript,security,sandbox,code-injection,with-statement
No, this is not secure. No matter what you do with your code's execution environment using with, it is still possible to retrieve the "real" global object using the following trick: var window = (function(){ return this }).call(undefined); This works because Function.call will use the global object as the value...
python,iterator,with-statement
Your code fails as you have already consumed the iterator on the first call, if you call none_context() in the with block the original code would work: none_context = contextmanager(lambda: iter([None])) printing=False with open(fa, "r") if printing else none_context() as writter, \ open(fb, "r") if printing else none_context() as another_writter:...
You can use within for something like this x = list() x <- within(x, { a <- 1 b <- 2 c <- 3 }) x ...
python,with-statement,contextmanager
Using backslash characters: Two or more physical lines may be joined into logical lines using backslash characters (\) (citing the Explicit line joining section) At least this works: with context1 as a,\ context2 as b: pass Using contextlib.ExitStack(Python 3.3+): A context manager that is designed to make it easy to...
You can't stop the creation as part of the with block. When you do with obj as A, obj has to exist before the with block can do anything with it. The call open('a.output', 'w') creates the file before the with can have any say in the matter. You could...
python,python-3.x,stdin,with-statement,contextmanager
In your case, you could use fileinput module: from fileinput import FileInput with FileInput(args.infile) as file: process(file) # sys.stdin is still open here If args.infile='-' then it uses sys.stdin. If inplace=True parameter then it redirects sys.stdout to the input file. You could pass several filenames. If there are no filenames...
python,syntax-error,with-statement
The with statement was added in Python 2.5; you must be using a version older than that. Either upgrade Python, or not use the with statement; you could use try/finally here to ensure the file object is closed: f = open('test.txt') try: for row in f: # ... finally: f.close()...
Yes there are, you can find a couple of them in this answer : What is the python "with" statement designed for? The most straightforward I can think of is the thread lock (also listed in the previous link): lock = threading.Lock() with lock: # Critical section of code For...
javascript,with-statement,ecma262
OK, lets first simplify the code a little. I've refactored out that foo is a method, which is not necessary do demonstrate the unexpected behaviour. function foo(a) { // var x, y, bar - hoisting function bar() { console.log(x); console.log(y); console.log(a.x); } with (a) { var x = 20; var...
python,file-handling,with-statement
You could create a "no-op" context manager: import subprocess import contextlib @contextlib.contextmanager def noop(): yield None logging = False file_path = '/tmp/out' with open(file_path, 'wb') if logging else noop() as shell_stdout: subprocess.call(['ls'], stdout=shell_stdout) When logging is True, the conditional expression returns a file object. When logging is False, it returns...
python,python-3.x,multiline,with-statement
Given that you've tagged this Python 3, if you need to intersperse comments with your context managers, I would use a contextlib.ExitStack: with ExitStack() as stack: a = stack.enter_context(Dummy()) # Relevant comment b = stack.enter_context(Dummy()) # Comment about b c = stack.enter_context(Dummy()) # Further information This is equivalent to with...
python,with-statement,contextmanager,del,resource-cleanup
The problem has nothing to do with garbage collection. As documented, the as clause binds the return value of the __enter__ method. You aren't returning anything, so you get None. If you want the Writer object to be returned, you need to do return self at the end of the...
Try it as a generator: def return_file_handle(input_file, open_mode="r"): """ Handles compressed and uncompressed files. Accepts open modes r/w/w+ """ if input_file.endswith(".gz") with gzip.open(input_file, open_mode) as gzipped_file_handle: yield gzipped_file_handle When you call it: for line in return_file_handle("file.gz"): print line.read() ...
.net,vb.net,instance,with-statement
There is no way to do that by using the With syntax. You could just add a local variable that references the new object though: Dim dep as new Department Dim emp = dep.AddNewEmployee() With emp .FirstName = "Mr. A" .LastName = "B" If emp.GetType().IsSerializable Then 'Do something End If...