partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
NotificationCenter.post_notification
Post notification to all registered observers. The registered callback will be called as:: callback(ntype, sender, *args, **kwargs) Parameters ---------- ntype : hashable The notification type. sender : hashable The object sending the notification. *args : tuple The positional arguments to be passed to the callback. **kwargs : dict The keyword argument to be passed to the callback. Notes ----- * If no registered observers, performance is O(1). * Notificaiton order is undefined. * Notifications are posted synchronously.
environment/lib/python2.7/site-packages/IPython/utils/notification.py
def post_notification(self, ntype, sender, *args, **kwargs): """Post notification to all registered observers. The registered callback will be called as:: callback(ntype, sender, *args, **kwargs) Parameters ---------- ntype : hashable The notification type. sender : hashable The object sending the notification. *args : tuple The positional arguments to be passed to the callback. **kwargs : dict The keyword argument to be passed to the callback. Notes ----- * If no registered observers, performance is O(1). * Notificaiton order is undefined. * Notifications are posted synchronously. """ if(ntype==None or sender==None): raise NotificationError( "Notification type and sender are required.") # If there are no registered observers for the type/sender pair if((ntype not in self.registered_types and None not in self.registered_types) or (sender not in self.registered_senders and None not in self.registered_senders)): return for o in self._observers_for_notification(ntype, sender): o(ntype, sender, *args, **kwargs)
def post_notification(self, ntype, sender, *args, **kwargs): """Post notification to all registered observers. The registered callback will be called as:: callback(ntype, sender, *args, **kwargs) Parameters ---------- ntype : hashable The notification type. sender : hashable The object sending the notification. *args : tuple The positional arguments to be passed to the callback. **kwargs : dict The keyword argument to be passed to the callback. Notes ----- * If no registered observers, performance is O(1). * Notificaiton order is undefined. * Notifications are posted synchronously. """ if(ntype==None or sender==None): raise NotificationError( "Notification type and sender are required.") # If there are no registered observers for the type/sender pair if((ntype not in self.registered_types and None not in self.registered_types) or (sender not in self.registered_senders and None not in self.registered_senders)): return for o in self._observers_for_notification(ntype, sender): o(ntype, sender, *args, **kwargs)
[ "Post", "notification", "to", "all", "registered", "observers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/notification.py#L56-L93
[ "def", "post_notification", "(", "self", ",", "ntype", ",", "sender", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "(", "ntype", "==", "None", "or", "sender", "==", "None", ")", ":", "raise", "NotificationError", "(", "\"Notification type and sender are required.\"", ")", "# If there are no registered observers for the type/sender pair", "if", "(", "(", "ntype", "not", "in", "self", ".", "registered_types", "and", "None", "not", "in", "self", ".", "registered_types", ")", "or", "(", "sender", "not", "in", "self", ".", "registered_senders", "and", "None", "not", "in", "self", ".", "registered_senders", ")", ")", ":", "return", "for", "o", "in", "self", ".", "_observers_for_notification", "(", "ntype", ",", "sender", ")", ":", "o", "(", "ntype", ",", "sender", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
NotificationCenter._observers_for_notification
Find all registered observers that should recieve notification
environment/lib/python2.7/site-packages/IPython/utils/notification.py
def _observers_for_notification(self, ntype, sender): """Find all registered observers that should recieve notification""" keys = ( (ntype,sender), (ntype, None), (None, sender), (None,None) ) obs = set() for k in keys: obs.update(self.observers.get(k, set())) return obs
def _observers_for_notification(self, ntype, sender): """Find all registered observers that should recieve notification""" keys = ( (ntype,sender), (ntype, None), (None, sender), (None,None) ) obs = set() for k in keys: obs.update(self.observers.get(k, set())) return obs
[ "Find", "all", "registered", "observers", "that", "should", "recieve", "notification" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/notification.py#L95-L109
[ "def", "_observers_for_notification", "(", "self", ",", "ntype", ",", "sender", ")", ":", "keys", "=", "(", "(", "ntype", ",", "sender", ")", ",", "(", "ntype", ",", "None", ")", ",", "(", "None", ",", "sender", ")", ",", "(", "None", ",", "None", ")", ")", "obs", "=", "set", "(", ")", "for", "k", "in", "keys", ":", "obs", ".", "update", "(", "self", ".", "observers", ".", "get", "(", "k", ",", "set", "(", ")", ")", ")", "return", "obs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
NotificationCenter.add_observer
Add an observer callback to this notification center. The given callback will be called upon posting of notifications of the given type/sender and will receive any additional arguments passed to post_notification. Parameters ---------- callback : callable The callable that will be called by :meth:`post_notification` as ``callback(ntype, sender, *args, **kwargs) ntype : hashable The notification type. If None, all notifications from sender will be posted. sender : hashable The notification sender. If None, all notifications of ntype will be posted.
environment/lib/python2.7/site-packages/IPython/utils/notification.py
def add_observer(self, callback, ntype, sender): """Add an observer callback to this notification center. The given callback will be called upon posting of notifications of the given type/sender and will receive any additional arguments passed to post_notification. Parameters ---------- callback : callable The callable that will be called by :meth:`post_notification` as ``callback(ntype, sender, *args, **kwargs) ntype : hashable The notification type. If None, all notifications from sender will be posted. sender : hashable The notification sender. If None, all notifications of ntype will be posted. """ assert(callback != None) self.registered_types.add(ntype) self.registered_senders.add(sender) self.observers.setdefault((ntype,sender), set()).add(callback)
def add_observer(self, callback, ntype, sender): """Add an observer callback to this notification center. The given callback will be called upon posting of notifications of the given type/sender and will receive any additional arguments passed to post_notification. Parameters ---------- callback : callable The callable that will be called by :meth:`post_notification` as ``callback(ntype, sender, *args, **kwargs) ntype : hashable The notification type. If None, all notifications from sender will be posted. sender : hashable The notification sender. If None, all notifications of ntype will be posted. """ assert(callback != None) self.registered_types.add(ntype) self.registered_senders.add(sender) self.observers.setdefault((ntype,sender), set()).add(callback)
[ "Add", "an", "observer", "callback", "to", "this", "notification", "center", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/notification.py#L111-L133
[ "def", "add_observer", "(", "self", ",", "callback", ",", "ntype", ",", "sender", ")", ":", "assert", "(", "callback", "!=", "None", ")", "self", ".", "registered_types", ".", "add", "(", "ntype", ")", "self", ".", "registered_senders", ".", "add", "(", "sender", ")", "self", ".", "observers", ".", "setdefault", "(", "(", "ntype", ",", "sender", ")", ",", "set", "(", ")", ")", ".", "add", "(", "callback", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager.new
Add a new background job and start it in a separate thread. There are two types of jobs which can be created: 1. Jobs based on expressions which can be passed to an eval() call. The expression must be given as a string. For example: job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]]) The given expression is passed to eval(), along with the optional global/local dicts provided. If no dicts are given, they are extracted automatically from the caller's frame. A Python statement is NOT a valid eval() expression. Basically, you can only use as an eval() argument something which can go on the right of an '=' sign and be assigned to a variable. For example,"print 'hello'" is not valid, but '2+3' is. 2. Jobs given a function object, optionally passing additional positional arguments: job_manager.new(myfunc, x, y) The function is called with the given arguments. If you need to pass keyword arguments to your function, you must supply them as a dict named kw: job_manager.new(myfunc, x, y, kw=dict(z=1)) The reason for this assymmetry is that the new() method needs to maintain access to its own keywords, and this prevents name collisions between arguments to new() and arguments to your own functions. In both cases, the result is stored in the job.result field of the background job object. You can set `daemon` attribute of the thread by giving the keyword argument `daemon`. Notes and caveats: 1. All threads running share the same standard output. Thus, if your background jobs generate output, it will come out on top of whatever you are currently writing. For this reason, background jobs are best used with silent functions which simply return their output. 2. Threads also all work within the same global namespace, and this system does not lock interactive variables. So if you send job to the background which operates on a mutable object for a long time, and start modifying that same mutable object interactively (or in another backgrounded job), all sorts of bizarre behaviour will occur. 3. If a background job is spending a lot of time inside a C extension module which does not release the Python Global Interpreter Lock (GIL), this will block the IPython prompt. This is simply because the Python interpreter can only switch between threads at Python bytecodes. While the execution is inside C code, the interpreter must simply wait unless the extension module releases the GIL. 4. There is no way, due to limitations in the Python threads library, to kill a thread once it has started.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def new(self, func_or_exp, *args, **kwargs): """Add a new background job and start it in a separate thread. There are two types of jobs which can be created: 1. Jobs based on expressions which can be passed to an eval() call. The expression must be given as a string. For example: job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]]) The given expression is passed to eval(), along with the optional global/local dicts provided. If no dicts are given, they are extracted automatically from the caller's frame. A Python statement is NOT a valid eval() expression. Basically, you can only use as an eval() argument something which can go on the right of an '=' sign and be assigned to a variable. For example,"print 'hello'" is not valid, but '2+3' is. 2. Jobs given a function object, optionally passing additional positional arguments: job_manager.new(myfunc, x, y) The function is called with the given arguments. If you need to pass keyword arguments to your function, you must supply them as a dict named kw: job_manager.new(myfunc, x, y, kw=dict(z=1)) The reason for this assymmetry is that the new() method needs to maintain access to its own keywords, and this prevents name collisions between arguments to new() and arguments to your own functions. In both cases, the result is stored in the job.result field of the background job object. You can set `daemon` attribute of the thread by giving the keyword argument `daemon`. Notes and caveats: 1. All threads running share the same standard output. Thus, if your background jobs generate output, it will come out on top of whatever you are currently writing. For this reason, background jobs are best used with silent functions which simply return their output. 2. Threads also all work within the same global namespace, and this system does not lock interactive variables. So if you send job to the background which operates on a mutable object for a long time, and start modifying that same mutable object interactively (or in another backgrounded job), all sorts of bizarre behaviour will occur. 3. If a background job is spending a lot of time inside a C extension module which does not release the Python Global Interpreter Lock (GIL), this will block the IPython prompt. This is simply because the Python interpreter can only switch between threads at Python bytecodes. While the execution is inside C code, the interpreter must simply wait unless the extension module releases the GIL. 4. There is no way, due to limitations in the Python threads library, to kill a thread once it has started.""" if callable(func_or_exp): kw = kwargs.get('kw',{}) job = BackgroundJobFunc(func_or_exp,*args,**kw) elif isinstance(func_or_exp, basestring): if not args: frame = sys._getframe(1) glob, loc = frame.f_globals, frame.f_locals elif len(args)==1: glob = loc = args[0] elif len(args)==2: glob,loc = args else: raise ValueError( 'Expression jobs take at most 2 args (globals,locals)') job = BackgroundJobExpr(func_or_exp, glob, loc) else: raise TypeError('invalid args for new job') if kwargs.get('daemon', False): job.daemon = True job.num = len(self.all)+1 if self.all else 0 self.running.append(job) self.all[job.num] = job print 'Starting job # %s in a separate thread.' % job.num job.start() return job
def new(self, func_or_exp, *args, **kwargs): """Add a new background job and start it in a separate thread. There are two types of jobs which can be created: 1. Jobs based on expressions which can be passed to an eval() call. The expression must be given as a string. For example: job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]]) The given expression is passed to eval(), along with the optional global/local dicts provided. If no dicts are given, they are extracted automatically from the caller's frame. A Python statement is NOT a valid eval() expression. Basically, you can only use as an eval() argument something which can go on the right of an '=' sign and be assigned to a variable. For example,"print 'hello'" is not valid, but '2+3' is. 2. Jobs given a function object, optionally passing additional positional arguments: job_manager.new(myfunc, x, y) The function is called with the given arguments. If you need to pass keyword arguments to your function, you must supply them as a dict named kw: job_manager.new(myfunc, x, y, kw=dict(z=1)) The reason for this assymmetry is that the new() method needs to maintain access to its own keywords, and this prevents name collisions between arguments to new() and arguments to your own functions. In both cases, the result is stored in the job.result field of the background job object. You can set `daemon` attribute of the thread by giving the keyword argument `daemon`. Notes and caveats: 1. All threads running share the same standard output. Thus, if your background jobs generate output, it will come out on top of whatever you are currently writing. For this reason, background jobs are best used with silent functions which simply return their output. 2. Threads also all work within the same global namespace, and this system does not lock interactive variables. So if you send job to the background which operates on a mutable object for a long time, and start modifying that same mutable object interactively (or in another backgrounded job), all sorts of bizarre behaviour will occur. 3. If a background job is spending a lot of time inside a C extension module which does not release the Python Global Interpreter Lock (GIL), this will block the IPython prompt. This is simply because the Python interpreter can only switch between threads at Python bytecodes. While the execution is inside C code, the interpreter must simply wait unless the extension module releases the GIL. 4. There is no way, due to limitations in the Python threads library, to kill a thread once it has started.""" if callable(func_or_exp): kw = kwargs.get('kw',{}) job = BackgroundJobFunc(func_or_exp,*args,**kw) elif isinstance(func_or_exp, basestring): if not args: frame = sys._getframe(1) glob, loc = frame.f_globals, frame.f_locals elif len(args)==1: glob = loc = args[0] elif len(args)==2: glob,loc = args else: raise ValueError( 'Expression jobs take at most 2 args (globals,locals)') job = BackgroundJobExpr(func_or_exp, glob, loc) else: raise TypeError('invalid args for new job') if kwargs.get('daemon', False): job.daemon = True job.num = len(self.all)+1 if self.all else 0 self.running.append(job) self.all[job.num] = job print 'Starting job # %s in a separate thread.' % job.num job.start() return job
[ "Add", "a", "new", "background", "job", "and", "start", "it", "in", "a", "separate", "thread", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L104-L194
[ "def", "new", "(", "self", ",", "func_or_exp", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "func_or_exp", ")", ":", "kw", "=", "kwargs", ".", "get", "(", "'kw'", ",", "{", "}", ")", "job", "=", "BackgroundJobFunc", "(", "func_or_exp", ",", "*", "args", ",", "*", "*", "kw", ")", "elif", "isinstance", "(", "func_or_exp", ",", "basestring", ")", ":", "if", "not", "args", ":", "frame", "=", "sys", ".", "_getframe", "(", "1", ")", "glob", ",", "loc", "=", "frame", ".", "f_globals", ",", "frame", ".", "f_locals", "elif", "len", "(", "args", ")", "==", "1", ":", "glob", "=", "loc", "=", "args", "[", "0", "]", "elif", "len", "(", "args", ")", "==", "2", ":", "glob", ",", "loc", "=", "args", "else", ":", "raise", "ValueError", "(", "'Expression jobs take at most 2 args (globals,locals)'", ")", "job", "=", "BackgroundJobExpr", "(", "func_or_exp", ",", "glob", ",", "loc", ")", "else", ":", "raise", "TypeError", "(", "'invalid args for new job'", ")", "if", "kwargs", ".", "get", "(", "'daemon'", ",", "False", ")", ":", "job", ".", "daemon", "=", "True", "job", ".", "num", "=", "len", "(", "self", ".", "all", ")", "+", "1", "if", "self", ".", "all", "else", "0", "self", ".", "running", ".", "append", "(", "job", ")", "self", ".", "all", "[", "job", ".", "num", "]", "=", "job", "print", "'Starting job # %s in a separate thread.'", "%", "job", ".", "num", "job", ".", "start", "(", ")", "return", "job" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager._update_status
Update the status of the job lists. This method moves finished jobs to one of two lists: - self.completed: jobs which completed successfully - self.dead: jobs which finished but died. It also copies those jobs to corresponding _report lists. These lists are used to report jobs completed/dead since the last update, and are then cleared by the reporting function after each call.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def _update_status(self): """Update the status of the job lists. This method moves finished jobs to one of two lists: - self.completed: jobs which completed successfully - self.dead: jobs which finished but died. It also copies those jobs to corresponding _report lists. These lists are used to report jobs completed/dead since the last update, and are then cleared by the reporting function after each call.""" # Status codes srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead # State lists, use the actual lists b/c the public names are properties # that call this very function on access running, completed, dead = self._running, self._completed, self._dead # Now, update all state lists for num, job in enumerate(running): stat = job.stat_code if stat == srun: continue elif stat == scomp: completed.append(job) self._comp_report.append(job) running[num] = False elif stat == sdead: dead.append(job) self._dead_report.append(job) running[num] = False # Remove dead/completed jobs from running list running[:] = filter(None, running)
def _update_status(self): """Update the status of the job lists. This method moves finished jobs to one of two lists: - self.completed: jobs which completed successfully - self.dead: jobs which finished but died. It also copies those jobs to corresponding _report lists. These lists are used to report jobs completed/dead since the last update, and are then cleared by the reporting function after each call.""" # Status codes srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead # State lists, use the actual lists b/c the public names are properties # that call this very function on access running, completed, dead = self._running, self._completed, self._dead # Now, update all state lists for num, job in enumerate(running): stat = job.stat_code if stat == srun: continue elif stat == scomp: completed.append(job) self._comp_report.append(job) running[num] = False elif stat == sdead: dead.append(job) self._dead_report.append(job) running[num] = False # Remove dead/completed jobs from running list running[:] = filter(None, running)
[ "Update", "the", "status", "of", "the", "job", "lists", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L208-L239
[ "def", "_update_status", "(", "self", ")", ":", "# Status codes", "srun", ",", "scomp", ",", "sdead", "=", "self", ".", "_s_running", ",", "self", ".", "_s_completed", ",", "self", ".", "_s_dead", "# State lists, use the actual lists b/c the public names are properties", "# that call this very function on access", "running", ",", "completed", ",", "dead", "=", "self", ".", "_running", ",", "self", ".", "_completed", ",", "self", ".", "_dead", "# Now, update all state lists", "for", "num", ",", "job", "in", "enumerate", "(", "running", ")", ":", "stat", "=", "job", ".", "stat_code", "if", "stat", "==", "srun", ":", "continue", "elif", "stat", "==", "scomp", ":", "completed", ".", "append", "(", "job", ")", "self", ".", "_comp_report", ".", "append", "(", "job", ")", "running", "[", "num", "]", "=", "False", "elif", "stat", "==", "sdead", ":", "dead", ".", "append", "(", "job", ")", "self", ".", "_dead_report", ".", "append", "(", "job", ")", "running", "[", "num", "]", "=", "False", "# Remove dead/completed jobs from running list", "running", "[", ":", "]", "=", "filter", "(", "None", ",", "running", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager._group_report
Report summary for a given job group. Return True if the group had any elements.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def _group_report(self,group,name): """Report summary for a given job group. Return True if the group had any elements.""" if group: print '%s jobs:' % name for job in group: print '%s : %s' % (job.num,job) print return True
def _group_report(self,group,name): """Report summary for a given job group. Return True if the group had any elements.""" if group: print '%s jobs:' % name for job in group: print '%s : %s' % (job.num,job) print return True
[ "Report", "summary", "for", "a", "given", "job", "group", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L241-L251
[ "def", "_group_report", "(", "self", ",", "group", ",", "name", ")", ":", "if", "group", ":", "print", "'%s jobs:'", "%", "name", "for", "job", "in", "group", ":", "print", "'%s : %s'", "%", "(", "job", ".", "num", ",", "job", ")", "print", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager._group_flush
Flush a given job group Return True if the group had any elements.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def _group_flush(self,group,name): """Flush a given job group Return True if the group had any elements.""" njobs = len(group) if njobs: plural = {1:''}.setdefault(njobs,'s') print 'Flushing %s %s job%s.' % (njobs,name,plural) group[:] = [] return True
def _group_flush(self,group,name): """Flush a given job group Return True if the group had any elements.""" njobs = len(group) if njobs: plural = {1:''}.setdefault(njobs,'s') print 'Flushing %s %s job%s.' % (njobs,name,plural) group[:] = [] return True
[ "Flush", "a", "given", "job", "group" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L253-L263
[ "def", "_group_flush", "(", "self", ",", "group", ",", "name", ")", ":", "njobs", "=", "len", "(", "group", ")", "if", "njobs", ":", "plural", "=", "{", "1", ":", "''", "}", ".", "setdefault", "(", "njobs", ",", "'s'", ")", "print", "'Flushing %s %s job%s.'", "%", "(", "njobs", ",", "name", ",", "plural", ")", "group", "[", ":", "]", "=", "[", "]", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager._status_new
Print the status of newly finished jobs. Return True if any new jobs are reported. This call resets its own state every time, so it only reports jobs which have finished since the last time it was called.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def _status_new(self): """Print the status of newly finished jobs. Return True if any new jobs are reported. This call resets its own state every time, so it only reports jobs which have finished since the last time it was called.""" self._update_status() new_comp = self._group_report(self._comp_report, 'Completed') new_dead = self._group_report(self._dead_report, 'Dead, call jobs.traceback() for details') self._comp_report[:] = [] self._dead_report[:] = [] return new_comp or new_dead
def _status_new(self): """Print the status of newly finished jobs. Return True if any new jobs are reported. This call resets its own state every time, so it only reports jobs which have finished since the last time it was called.""" self._update_status() new_comp = self._group_report(self._comp_report, 'Completed') new_dead = self._group_report(self._dead_report, 'Dead, call jobs.traceback() for details') self._comp_report[:] = [] self._dead_report[:] = [] return new_comp or new_dead
[ "Print", "the", "status", "of", "newly", "finished", "jobs", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L265-L279
[ "def", "_status_new", "(", "self", ")", ":", "self", ".", "_update_status", "(", ")", "new_comp", "=", "self", ".", "_group_report", "(", "self", ".", "_comp_report", ",", "'Completed'", ")", "new_dead", "=", "self", ".", "_group_report", "(", "self", ".", "_dead_report", ",", "'Dead, call jobs.traceback() for details'", ")", "self", ".", "_comp_report", "[", ":", "]", "=", "[", "]", "self", ".", "_dead_report", "[", ":", "]", "=", "[", "]", "return", "new_comp", "or", "new_dead" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager.status
Print a status of all jobs currently being managed.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def status(self,verbose=0): """Print a status of all jobs currently being managed.""" self._update_status() self._group_report(self.running,'Running') self._group_report(self.completed,'Completed') self._group_report(self.dead,'Dead') # Also flush the report queues self._comp_report[:] = [] self._dead_report[:] = []
def status(self,verbose=0): """Print a status of all jobs currently being managed.""" self._update_status() self._group_report(self.running,'Running') self._group_report(self.completed,'Completed') self._group_report(self.dead,'Dead') # Also flush the report queues self._comp_report[:] = [] self._dead_report[:] = []
[ "Print", "a", "status", "of", "all", "jobs", "currently", "being", "managed", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L281-L290
[ "def", "status", "(", "self", ",", "verbose", "=", "0", ")", ":", "self", ".", "_update_status", "(", ")", "self", ".", "_group_report", "(", "self", ".", "running", ",", "'Running'", ")", "self", ".", "_group_report", "(", "self", ".", "completed", ",", "'Completed'", ")", "self", ".", "_group_report", "(", "self", ".", "dead", ",", "'Dead'", ")", "# Also flush the report queues", "self", ".", "_comp_report", "[", ":", "]", "=", "[", "]", "self", ".", "_dead_report", "[", ":", "]", "=", "[", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager.remove
Remove a finished (completed or dead) job.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def remove(self,num): """Remove a finished (completed or dead) job.""" try: job = self.all[num] except KeyError: error('Job #%s not found' % num) else: stat_code = job.stat_code if stat_code == self._s_running: error('Job #%s is still running, it can not be removed.' % num) return elif stat_code == self._s_completed: self.completed.remove(job) elif stat_code == self._s_dead: self.dead.remove(job)
def remove(self,num): """Remove a finished (completed or dead) job.""" try: job = self.all[num] except KeyError: error('Job #%s not found' % num) else: stat_code = job.stat_code if stat_code == self._s_running: error('Job #%s is still running, it can not be removed.' % num) return elif stat_code == self._s_completed: self.completed.remove(job) elif stat_code == self._s_dead: self.dead.remove(job)
[ "Remove", "a", "finished", "(", "completed", "or", "dead", ")", "job", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L292-L307
[ "def", "remove", "(", "self", ",", "num", ")", ":", "try", ":", "job", "=", "self", ".", "all", "[", "num", "]", "except", "KeyError", ":", "error", "(", "'Job #%s not found'", "%", "num", ")", "else", ":", "stat_code", "=", "job", ".", "stat_code", "if", "stat_code", "==", "self", ".", "_s_running", ":", "error", "(", "'Job #%s is still running, it can not be removed.'", "%", "num", ")", "return", "elif", "stat_code", "==", "self", ".", "_s_completed", ":", "self", ".", "completed", ".", "remove", "(", "job", ")", "elif", "stat_code", "==", "self", ".", "_s_dead", ":", "self", ".", "dead", ".", "remove", "(", "job", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager.flush
Flush all finished jobs (completed and dead) from lists. Running jobs are never flushed. It first calls _status_new(), to update info. If any jobs have completed since the last _status_new() call, the flush operation aborts.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def flush(self): """Flush all finished jobs (completed and dead) from lists. Running jobs are never flushed. It first calls _status_new(), to update info. If any jobs have completed since the last _status_new() call, the flush operation aborts.""" # Remove the finished jobs from the master dict alljobs = self.all for job in self.completed+self.dead: del(alljobs[job.num]) # Now flush these lists completely fl_comp = self._group_flush(self.completed, 'Completed') fl_dead = self._group_flush(self.dead, 'Dead') if not (fl_comp or fl_dead): print 'No jobs to flush.'
def flush(self): """Flush all finished jobs (completed and dead) from lists. Running jobs are never flushed. It first calls _status_new(), to update info. If any jobs have completed since the last _status_new() call, the flush operation aborts.""" # Remove the finished jobs from the master dict alljobs = self.all for job in self.completed+self.dead: del(alljobs[job.num]) # Now flush these lists completely fl_comp = self._group_flush(self.completed, 'Completed') fl_dead = self._group_flush(self.dead, 'Dead') if not (fl_comp or fl_dead): print 'No jobs to flush.'
[ "Flush", "all", "finished", "jobs", "(", "completed", "and", "dead", ")", "from", "lists", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L309-L327
[ "def", "flush", "(", "self", ")", ":", "# Remove the finished jobs from the master dict", "alljobs", "=", "self", ".", "all", "for", "job", "in", "self", ".", "completed", "+", "self", ".", "dead", ":", "del", "(", "alljobs", "[", "job", ".", "num", "]", ")", "# Now flush these lists completely", "fl_comp", "=", "self", ".", "_group_flush", "(", "self", ".", "completed", ",", "'Completed'", ")", "fl_dead", "=", "self", ".", "_group_flush", "(", "self", ".", "dead", ",", "'Dead'", ")", "if", "not", "(", "fl_comp", "or", "fl_dead", ")", ":", "print", "'No jobs to flush.'" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobManager.result
result(N) -> return the result of job N.
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def result(self,num): """result(N) -> return the result of job N.""" try: return self.all[num].result except KeyError: error('Job #%s not found' % num)
def result(self,num): """result(N) -> return the result of job N.""" try: return self.all[num].result except KeyError: error('Job #%s not found' % num)
[ "result", "(", "N", ")", "-", ">", "return", "the", "result", "of", "job", "N", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L329-L334
[ "def", "result", "(", "self", ",", "num", ")", ":", "try", ":", "return", "self", ".", "all", "[", "num", "]", ".", "result", "except", "KeyError", ":", "error", "(", "'Job #%s not found'", "%", "num", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BackgroundJobBase._init
Common initialization for all BackgroundJob objects
environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py
def _init(self): """Common initialization for all BackgroundJob objects""" for attr in ['call','strform']: assert hasattr(self,attr), "Missing attribute <%s>" % attr # The num tag can be set by an external job manager self.num = None self.status = BackgroundJobBase.stat_created self.stat_code = BackgroundJobBase.stat_created_c self.finished = False self.result = '<BackgroundJob has not completed>' # reuse the ipython traceback handler if we can get to it, otherwise # make a new one try: make_tb = get_ipython().InteractiveTB.text except: make_tb = AutoFormattedTB(mode = 'Context', color_scheme='NoColor', tb_offset = 1).text # Note that the actual API for text() requires the three args to be # passed in, so we wrap it in a simple lambda. self._make_tb = lambda : make_tb(None, None, None) # Hold a formatted traceback if one is generated. self._tb = None threading.Thread.__init__(self)
def _init(self): """Common initialization for all BackgroundJob objects""" for attr in ['call','strform']: assert hasattr(self,attr), "Missing attribute <%s>" % attr # The num tag can be set by an external job manager self.num = None self.status = BackgroundJobBase.stat_created self.stat_code = BackgroundJobBase.stat_created_c self.finished = False self.result = '<BackgroundJob has not completed>' # reuse the ipython traceback handler if we can get to it, otherwise # make a new one try: make_tb = get_ipython().InteractiveTB.text except: make_tb = AutoFormattedTB(mode = 'Context', color_scheme='NoColor', tb_offset = 1).text # Note that the actual API for text() requires the three args to be # passed in, so we wrap it in a simple lambda. self._make_tb = lambda : make_tb(None, None, None) # Hold a formatted traceback if one is generated. self._tb = None threading.Thread.__init__(self)
[ "Common", "initialization", "for", "all", "BackgroundJob", "objects" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/backgroundjobs.py#L381-L410
[ "def", "_init", "(", "self", ")", ":", "for", "attr", "in", "[", "'call'", ",", "'strform'", "]", ":", "assert", "hasattr", "(", "self", ",", "attr", ")", ",", "\"Missing attribute <%s>\"", "%", "attr", "# The num tag can be set by an external job manager", "self", ".", "num", "=", "None", "self", ".", "status", "=", "BackgroundJobBase", ".", "stat_created", "self", ".", "stat_code", "=", "BackgroundJobBase", ".", "stat_created_c", "self", ".", "finished", "=", "False", "self", ".", "result", "=", "'<BackgroundJob has not completed>'", "# reuse the ipython traceback handler if we can get to it, otherwise", "# make a new one", "try", ":", "make_tb", "=", "get_ipython", "(", ")", ".", "InteractiveTB", ".", "text", "except", ":", "make_tb", "=", "AutoFormattedTB", "(", "mode", "=", "'Context'", ",", "color_scheme", "=", "'NoColor'", ",", "tb_offset", "=", "1", ")", ".", "text", "# Note that the actual API for text() requires the three args to be", "# passed in, so we wrap it in a simple lambda.", "self", ".", "_make_tb", "=", "lambda", ":", "make_tb", "(", "None", ",", "None", ",", "None", ")", "# Hold a formatted traceback if one is generated.", "self", ".", "_tb", "=", "None", "threading", ".", "Thread", ".", "__init__", "(", "self", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ListVariable.insert
Inserts a value in the ``ListVariable`` at an appropriate index. :param idx: The index before which to insert the new value. :param value: The value to insert.
timid/environment.py
def insert(self, idx, value): """ Inserts a value in the ``ListVariable`` at an appropriate index. :param idx: The index before which to insert the new value. :param value: The value to insert. """ self._value.insert(idx, value) self._rebuild()
def insert(self, idx, value): """ Inserts a value in the ``ListVariable`` at an appropriate index. :param idx: The index before which to insert the new value. :param value: The value to insert. """ self._value.insert(idx, value) self._rebuild()
[ "Inserts", "a", "value", "in", "the", "ListVariable", "at", "an", "appropriate", "index", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/environment.py#L179-L188
[ "def", "insert", "(", "self", ",", "idx", ",", "value", ")", ":", "self", ".", "_value", ".", "insert", "(", "idx", ",", "value", ")", "self", ".", "_rebuild", "(", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
Environment.copy
Retrieve a copy of the Environment. Note that this is a shallow copy.
timid/environment.py
def copy(self): """ Retrieve a copy of the Environment. Note that this is a shallow copy. """ return self.__class__(self._data.copy(), self._sensitive.copy(), self._cwd)
def copy(self): """ Retrieve a copy of the Environment. Note that this is a shallow copy. """ return self.__class__(self._data.copy(), self._sensitive.copy(), self._cwd)
[ "Retrieve", "a", "copy", "of", "the", "Environment", ".", "Note", "that", "this", "is", "a", "shallow", "copy", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/environment.py#L365-L372
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "_data", ".", "copy", "(", ")", ",", "self", ".", "_sensitive", ".", "copy", "(", ")", ",", "self", ".", "_cwd", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
Environment._declare_special
Declare an environment variable as a special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered special. :param sep: The separator to be used. :param klass: The subclass of ``SpecialVariable`` used to represent the variable.
timid/environment.py
def _declare_special(self, name, sep, klass): """ Declare an environment variable as a special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered special. :param sep: The separator to be used. :param klass: The subclass of ``SpecialVariable`` used to represent the variable. """ # First, has it already been declared? if name in self._special: special = self._special[name] if not isinstance(special, klass) or sep != special._sep: raise ValueError('variable %s already declared as %s ' 'with separator "%s"' % (name, special.__class__.__name__, special._sep)) # OK, it's new; declare it else: self._special[name] = klass(self, name, sep)
def _declare_special(self, name, sep, klass): """ Declare an environment variable as a special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered special. :param sep: The separator to be used. :param klass: The subclass of ``SpecialVariable`` used to represent the variable. """ # First, has it already been declared? if name in self._special: special = self._special[name] if not isinstance(special, klass) or sep != special._sep: raise ValueError('variable %s already declared as %s ' 'with separator "%s"' % (name, special.__class__.__name__, special._sep)) # OK, it's new; declare it else: self._special[name] = klass(self, name, sep)
[ "Declare", "an", "environment", "variable", "as", "a", "special", "variable", ".", "This", "can", "be", "used", "even", "if", "the", "environment", "variable", "is", "not", "present", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/environment.py#L374-L397
[ "def", "_declare_special", "(", "self", ",", "name", ",", "sep", ",", "klass", ")", ":", "# First, has it already been declared?", "if", "name", "in", "self", ".", "_special", ":", "special", "=", "self", ".", "_special", "[", "name", "]", "if", "not", "isinstance", "(", "special", ",", "klass", ")", "or", "sep", "!=", "special", ".", "_sep", ":", "raise", "ValueError", "(", "'variable %s already declared as %s '", "'with separator \"%s\"'", "%", "(", "name", ",", "special", ".", "__class__", ".", "__name__", ",", "special", ".", "_sep", ")", ")", "# OK, it's new; declare it", "else", ":", "self", ".", "_special", "[", "name", "]", "=", "klass", "(", "self", ",", "name", ",", "sep", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
Environment.declare_list
Declare an environment variable as a list-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered list-like. :param sep: The separator to be used. Defaults to the value of ``os.pathsep``.
timid/environment.py
def declare_list(self, name, sep=os.pathsep): """ Declare an environment variable as a list-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered list-like. :param sep: The separator to be used. Defaults to the value of ``os.pathsep``. """ self._declare_special(name, sep, ListVariable)
def declare_list(self, name, sep=os.pathsep): """ Declare an environment variable as a list-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered list-like. :param sep: The separator to be used. Defaults to the value of ``os.pathsep``. """ self._declare_special(name, sep, ListVariable)
[ "Declare", "an", "environment", "variable", "as", "a", "list", "-", "like", "special", "variable", ".", "This", "can", "be", "used", "even", "if", "the", "environment", "variable", "is", "not", "present", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/environment.py#L399-L411
[ "def", "declare_list", "(", "self", ",", "name", ",", "sep", "=", "os", ".", "pathsep", ")", ":", "self", ".", "_declare_special", "(", "name", ",", "sep", ",", "ListVariable", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
Environment.declare_set
Declare an environment variable as a set-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered set-like. :param sep: The separator to be used. Defaults to the value of ``os.pathsep``.
timid/environment.py
def declare_set(self, name, sep=os.pathsep): """ Declare an environment variable as a set-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered set-like. :param sep: The separator to be used. Defaults to the value of ``os.pathsep``. """ self._declare_special(name, sep, SetVariable)
def declare_set(self, name, sep=os.pathsep): """ Declare an environment variable as a set-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered set-like. :param sep: The separator to be used. Defaults to the value of ``os.pathsep``. """ self._declare_special(name, sep, SetVariable)
[ "Declare", "an", "environment", "variable", "as", "a", "set", "-", "like", "special", "variable", ".", "This", "can", "be", "used", "even", "if", "the", "environment", "variable", "is", "not", "present", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/environment.py#L413-L425
[ "def", "declare_set", "(", "self", ",", "name", ",", "sep", "=", "os", ".", "pathsep", ")", ":", "self", ".", "_declare_special", "(", "name", ",", "sep", ",", "SetVariable", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
Environment.call
A thin wrapper around ``subprocess.Popen``. Takes the same options as ``subprocess.Popen``, with the exception of the ``cwd``, and ``env`` parameters, which come from the ``Environment`` instance. Note that if the sole positional argument is a string, it will be converted into a sequence using the ``shlex.split()`` function.
timid/environment.py
def call(self, args, **kwargs): """ A thin wrapper around ``subprocess.Popen``. Takes the same options as ``subprocess.Popen``, with the exception of the ``cwd``, and ``env`` parameters, which come from the ``Environment`` instance. Note that if the sole positional argument is a string, it will be converted into a sequence using the ``shlex.split()`` function. """ # Convert string args into a sequence if isinstance(args, six.string_types): args = shlex.split(args) # Substitute cwd and env kwargs['cwd'] = self._cwd kwargs['env'] = self._data # Set a default for close_fds kwargs.setdefault('close_fds', True) return subprocess.Popen(args, **kwargs)
def call(self, args, **kwargs): """ A thin wrapper around ``subprocess.Popen``. Takes the same options as ``subprocess.Popen``, with the exception of the ``cwd``, and ``env`` parameters, which come from the ``Environment`` instance. Note that if the sole positional argument is a string, it will be converted into a sequence using the ``shlex.split()`` function. """ # Convert string args into a sequence if isinstance(args, six.string_types): args = shlex.split(args) # Substitute cwd and env kwargs['cwd'] = self._cwd kwargs['env'] = self._data # Set a default for close_fds kwargs.setdefault('close_fds', True) return subprocess.Popen(args, **kwargs)
[ "A", "thin", "wrapper", "around", "subprocess", ".", "Popen", ".", "Takes", "the", "same", "options", "as", "subprocess", ".", "Popen", "with", "the", "exception", "of", "the", "cwd", "and", "env", "parameters", "which", "come", "from", "the", "Environment", "instance", ".", "Note", "that", "if", "the", "sole", "positional", "argument", "is", "a", "string", "it", "will", "be", "converted", "into", "a", "sequence", "using", "the", "shlex", ".", "split", "()", "function", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/environment.py#L427-L448
[ "def", "call", "(", "self", ",", "args", ",", "*", "*", "kwargs", ")", ":", "# Convert string args into a sequence", "if", "isinstance", "(", "args", ",", "six", ".", "string_types", ")", ":", "args", "=", "shlex", ".", "split", "(", "args", ")", "# Substitute cwd and env", "kwargs", "[", "'cwd'", "]", "=", "self", ".", "_cwd", "kwargs", "[", "'env'", "]", "=", "self", ".", "_data", "# Set a default for close_fds", "kwargs", ".", "setdefault", "(", "'close_fds'", ",", "True", ")", "return", "subprocess", ".", "Popen", "(", "args", ",", "*", "*", "kwargs", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
Environment.cwd
Change the working directory that processes should be executed in. :param value: The new path to change to. If relative, will be interpreted relative to the current working directory.
timid/environment.py
def cwd(self, value): """ Change the working directory that processes should be executed in. :param value: The new path to change to. If relative, will be interpreted relative to the current working directory. """ self._cwd = utils.canonicalize_path(self._cwd, value)
def cwd(self, value): """ Change the working directory that processes should be executed in. :param value: The new path to change to. If relative, will be interpreted relative to the current working directory. """ self._cwd = utils.canonicalize_path(self._cwd, value)
[ "Change", "the", "working", "directory", "that", "processes", "should", "be", "executed", "in", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/environment.py#L460-L469
[ "def", "cwd", "(", "self", ",", "value", ")", ":", "self", ".", "_cwd", "=", "utils", ".", "canonicalize_path", "(", "self", ".", "_cwd", ",", "value", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
TSPProblem.move
Swaps two cities in the route. :type state: TSPState
pyrallelsa/examples/tsp/__init__.py
def move(self, state=None): """Swaps two cities in the route. :type state: TSPState """ state = self.state if state is None else state route = state a = random.randint(self.locked_range, len(route) - 1) b = random.randint(self.locked_range, len(route) - 1) route[a], route[b] = route[b], route[a]
def move(self, state=None): """Swaps two cities in the route. :type state: TSPState """ state = self.state if state is None else state route = state a = random.randint(self.locked_range, len(route) - 1) b = random.randint(self.locked_range, len(route) - 1) route[a], route[b] = route[b], route[a]
[ "Swaps", "two", "cities", "in", "the", "route", "." ]
mesos-magellan/pyrallelsa
python
https://github.com/mesos-magellan/pyrallelsa/blob/bbdeefd0c7ea4fd9a2e29624bf1b21e3da039cb1/pyrallelsa/examples/tsp/__init__.py#L84-L93
[ "def", "move", "(", "self", ",", "state", "=", "None", ")", ":", "state", "=", "self", ".", "state", "if", "state", "is", "None", "else", "state", "route", "=", "state", "a", "=", "random", ".", "randint", "(", "self", ".", "locked_range", ",", "len", "(", "route", ")", "-", "1", ")", "b", "=", "random", ".", "randint", "(", "self", ".", "locked_range", ",", "len", "(", "route", ")", "-", "1", ")", "route", "[", "a", "]", ",", "route", "[", "b", "]", "=", "route", "[", "b", "]", ",", "route", "[", "a", "]" ]
bbdeefd0c7ea4fd9a2e29624bf1b21e3da039cb1
test
TSPProblem.energy
Calculates the length of the route.
pyrallelsa/examples/tsp/__init__.py
def energy(self, state=None): """Calculates the length of the route.""" state = self.state if state is None else state route = state e = 0 if self.distance_matrix: for i in range(len(route)): e += self.distance_matrix["{},{}".format(route[i-1], route[i])] else: for i in range(len(route)): e += distance(self.cities[route[i-1]], self.cities[route[i]]) return e
def energy(self, state=None): """Calculates the length of the route.""" state = self.state if state is None else state route = state e = 0 if self.distance_matrix: for i in range(len(route)): e += self.distance_matrix["{},{}".format(route[i-1], route[i])] else: for i in range(len(route)): e += distance(self.cities[route[i-1]], self.cities[route[i]]) return e
[ "Calculates", "the", "length", "of", "the", "route", "." ]
mesos-magellan/pyrallelsa
python
https://github.com/mesos-magellan/pyrallelsa/blob/bbdeefd0c7ea4fd9a2e29624bf1b21e3da039cb1/pyrallelsa/examples/tsp/__init__.py#L95-L106
[ "def", "energy", "(", "self", ",", "state", "=", "None", ")", ":", "state", "=", "self", ".", "state", "if", "state", "is", "None", "else", "state", "route", "=", "state", "e", "=", "0", "if", "self", ".", "distance_matrix", ":", "for", "i", "in", "range", "(", "len", "(", "route", ")", ")", ":", "e", "+=", "self", ".", "distance_matrix", "[", "\"{},{}\"", ".", "format", "(", "route", "[", "i", "-", "1", "]", ",", "route", "[", "i", "]", ")", "]", "else", ":", "for", "i", "in", "range", "(", "len", "(", "route", ")", ")", ":", "e", "+=", "distance", "(", "self", ".", "cities", "[", "route", "[", "i", "-", "1", "]", "]", ",", "self", ".", "cities", "[", "route", "[", "i", "]", "]", ")", "return", "e" ]
bbdeefd0c7ea4fd9a2e29624bf1b21e3da039cb1
test
TSPProblem.divide
divide :type problem_data: dict
pyrallelsa/examples/tsp/__init__.py
def divide(cls, divisions, problem_data): """divide :type problem_data: dict """ tspp = TSPProblem(**problem_data) def routes_for_subgroup(cs): for city in cs: if city == tspp.start_city: continue cities = tspp.cities.keys() cities.remove(tspp.start_city) cities.remove(city) random.shuffle(cities) route = [tspp.start_city, city] + cities assert len(set(route)) == len(route) assert len(route) == len(tspp.cities) yield json.dumps(route) if divisions: chunk_size = int(math.ceil(len(tspp.cities) / divisions)) else: chunk_size = 1 for subgroup in chunks(tspp.cities.keys(), chunk_size): routes = list(routes_for_subgroup(subgroup)) if routes: yield routes
def divide(cls, divisions, problem_data): """divide :type problem_data: dict """ tspp = TSPProblem(**problem_data) def routes_for_subgroup(cs): for city in cs: if city == tspp.start_city: continue cities = tspp.cities.keys() cities.remove(tspp.start_city) cities.remove(city) random.shuffle(cities) route = [tspp.start_city, city] + cities assert len(set(route)) == len(route) assert len(route) == len(tspp.cities) yield json.dumps(route) if divisions: chunk_size = int(math.ceil(len(tspp.cities) / divisions)) else: chunk_size = 1 for subgroup in chunks(tspp.cities.keys(), chunk_size): routes = list(routes_for_subgroup(subgroup)) if routes: yield routes
[ "divide" ]
mesos-magellan/pyrallelsa
python
https://github.com/mesos-magellan/pyrallelsa/blob/bbdeefd0c7ea4fd9a2e29624bf1b21e3da039cb1/pyrallelsa/examples/tsp/__init__.py#L109-L136
[ "def", "divide", "(", "cls", ",", "divisions", ",", "problem_data", ")", ":", "tspp", "=", "TSPProblem", "(", "*", "*", "problem_data", ")", "def", "routes_for_subgroup", "(", "cs", ")", ":", "for", "city", "in", "cs", ":", "if", "city", "==", "tspp", ".", "start_city", ":", "continue", "cities", "=", "tspp", ".", "cities", ".", "keys", "(", ")", "cities", ".", "remove", "(", "tspp", ".", "start_city", ")", "cities", ".", "remove", "(", "city", ")", "random", ".", "shuffle", "(", "cities", ")", "route", "=", "[", "tspp", ".", "start_city", ",", "city", "]", "+", "cities", "assert", "len", "(", "set", "(", "route", ")", ")", "==", "len", "(", "route", ")", "assert", "len", "(", "route", ")", "==", "len", "(", "tspp", ".", "cities", ")", "yield", "json", ".", "dumps", "(", "route", ")", "if", "divisions", ":", "chunk_size", "=", "int", "(", "math", ".", "ceil", "(", "len", "(", "tspp", ".", "cities", ")", "/", "divisions", ")", ")", "else", ":", "chunk_size", "=", "1", "for", "subgroup", "in", "chunks", "(", "tspp", ".", "cities", ".", "keys", "(", ")", ",", "chunk_size", ")", ":", "routes", "=", "list", "(", "routes_for_subgroup", "(", "subgroup", ")", ")", "if", "routes", ":", "yield", "routes" ]
bbdeefd0c7ea4fd9a2e29624bf1b21e3da039cb1
test
SQLiteDB._defaults
create an empty record
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def _defaults(self, keys=None): """create an empty record""" d = {} keys = self._keys if keys is None else keys for key in keys: d[key] = None return d
def _defaults(self, keys=None): """create an empty record""" d = {} keys = self._keys if keys is None else keys for key in keys: d[key] = None return d
[ "create", "an", "empty", "record" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L181-L187
[ "def", "_defaults", "(", "self", ",", "keys", "=", "None", ")", ":", "d", "=", "{", "}", "keys", "=", "self", ".", "_keys", "if", "keys", "is", "None", "else", "keys", "for", "key", "in", "keys", ":", "d", "[", "key", "]", "=", "None", "return", "d" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB._check_table
Ensure that an incorrect table doesn't exist If a bad (old) table does exist, return False
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def _check_table(self): """Ensure that an incorrect table doesn't exist If a bad (old) table does exist, return False """ cursor = self._db.execute("PRAGMA table_info(%s)"%self.table) lines = cursor.fetchall() if not lines: # table does not exist return True types = {} keys = [] for line in lines: keys.append(line[1]) types[line[1]] = line[2] if self._keys != keys: # key mismatch self.log.warn('keys mismatch') return False for key in self._keys: if types[key] != self._types[key]: self.log.warn( 'type mismatch: %s: %s != %s'%(key,types[key],self._types[key]) ) return False return True
def _check_table(self): """Ensure that an incorrect table doesn't exist If a bad (old) table does exist, return False """ cursor = self._db.execute("PRAGMA table_info(%s)"%self.table) lines = cursor.fetchall() if not lines: # table does not exist return True types = {} keys = [] for line in lines: keys.append(line[1]) types[line[1]] = line[2] if self._keys != keys: # key mismatch self.log.warn('keys mismatch') return False for key in self._keys: if types[key] != self._types[key]: self.log.warn( 'type mismatch: %s: %s != %s'%(key,types[key],self._types[key]) ) return False return True
[ "Ensure", "that", "an", "incorrect", "table", "doesn", "t", "exist" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L189-L214
[ "def", "_check_table", "(", "self", ")", ":", "cursor", "=", "self", ".", "_db", ".", "execute", "(", "\"PRAGMA table_info(%s)\"", "%", "self", ".", "table", ")", "lines", "=", "cursor", ".", "fetchall", "(", ")", "if", "not", "lines", ":", "# table does not exist", "return", "True", "types", "=", "{", "}", "keys", "=", "[", "]", "for", "line", "in", "lines", ":", "keys", ".", "append", "(", "line", "[", "1", "]", ")", "types", "[", "line", "[", "1", "]", "]", "=", "line", "[", "2", "]", "if", "self", ".", "_keys", "!=", "keys", ":", "# key mismatch", "self", ".", "log", ".", "warn", "(", "'keys mismatch'", ")", "return", "False", "for", "key", "in", "self", ".", "_keys", ":", "if", "types", "[", "key", "]", "!=", "self", ".", "_types", "[", "key", "]", ":", "self", ".", "log", ".", "warn", "(", "'type mismatch: %s: %s != %s'", "%", "(", "key", ",", "types", "[", "key", "]", ",", "self", ".", "_types", "[", "key", "]", ")", ")", "return", "False", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB._init_db
Connect to the database and get new session number.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def _init_db(self): """Connect to the database and get new session number.""" # register adapters sqlite3.register_adapter(dict, _adapt_dict) sqlite3.register_converter('dict', _convert_dict) sqlite3.register_adapter(list, _adapt_bufs) sqlite3.register_converter('bufs', _convert_bufs) # connect to the db dbfile = os.path.join(self.location, self.filename) self._db = sqlite3.connect(dbfile, detect_types=sqlite3.PARSE_DECLTYPES, # isolation_level = None)#, cached_statements=64) # print dir(self._db) first_table = previous_table = self.table i=0 while not self._check_table(): i+=1 self.table = first_table+'_%i'%i self.log.warn( "Table %s exists and doesn't match db format, trying %s"% (previous_table, self.table) ) previous_table = self.table self._db.execute("""CREATE TABLE IF NOT EXISTS %s (msg_id text PRIMARY KEY, header dict text, content dict text, buffers bufs blob, submitted timestamp, client_uuid text, engine_uuid text, started timestamp, completed timestamp, resubmitted text, received timestamp, result_header dict text, result_content dict text, result_buffers bufs blob, queue text, pyin text, pyout text, pyerr text, stdout text, stderr text) """%self.table) self._db.commit()
def _init_db(self): """Connect to the database and get new session number.""" # register adapters sqlite3.register_adapter(dict, _adapt_dict) sqlite3.register_converter('dict', _convert_dict) sqlite3.register_adapter(list, _adapt_bufs) sqlite3.register_converter('bufs', _convert_bufs) # connect to the db dbfile = os.path.join(self.location, self.filename) self._db = sqlite3.connect(dbfile, detect_types=sqlite3.PARSE_DECLTYPES, # isolation_level = None)#, cached_statements=64) # print dir(self._db) first_table = previous_table = self.table i=0 while not self._check_table(): i+=1 self.table = first_table+'_%i'%i self.log.warn( "Table %s exists and doesn't match db format, trying %s"% (previous_table, self.table) ) previous_table = self.table self._db.execute("""CREATE TABLE IF NOT EXISTS %s (msg_id text PRIMARY KEY, header dict text, content dict text, buffers bufs blob, submitted timestamp, client_uuid text, engine_uuid text, started timestamp, completed timestamp, resubmitted text, received timestamp, result_header dict text, result_content dict text, result_buffers bufs blob, queue text, pyin text, pyout text, pyerr text, stdout text, stderr text) """%self.table) self._db.commit()
[ "Connect", "to", "the", "database", "and", "get", "new", "session", "number", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L216-L262
[ "def", "_init_db", "(", "self", ")", ":", "# register adapters", "sqlite3", ".", "register_adapter", "(", "dict", ",", "_adapt_dict", ")", "sqlite3", ".", "register_converter", "(", "'dict'", ",", "_convert_dict", ")", "sqlite3", ".", "register_adapter", "(", "list", ",", "_adapt_bufs", ")", "sqlite3", ".", "register_converter", "(", "'bufs'", ",", "_convert_bufs", ")", "# connect to the db", "dbfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "location", ",", "self", ".", "filename", ")", "self", ".", "_db", "=", "sqlite3", ".", "connect", "(", "dbfile", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ",", "# isolation_level = None)#,", "cached_statements", "=", "64", ")", "# print dir(self._db)", "first_table", "=", "previous_table", "=", "self", ".", "table", "i", "=", "0", "while", "not", "self", ".", "_check_table", "(", ")", ":", "i", "+=", "1", "self", ".", "table", "=", "first_table", "+", "'_%i'", "%", "i", "self", ".", "log", ".", "warn", "(", "\"Table %s exists and doesn't match db format, trying %s\"", "%", "(", "previous_table", ",", "self", ".", "table", ")", ")", "previous_table", "=", "self", ".", "table", "self", ".", "_db", ".", "execute", "(", "\"\"\"CREATE TABLE IF NOT EXISTS %s\n (msg_id text PRIMARY KEY,\n header dict text,\n content dict text,\n buffers bufs blob,\n submitted timestamp,\n client_uuid text,\n engine_uuid text,\n started timestamp,\n completed timestamp,\n resubmitted text,\n received timestamp,\n result_header dict text,\n result_content dict text,\n result_buffers bufs blob,\n queue text,\n pyin text,\n pyout text,\n pyerr text,\n stdout text,\n stderr text)\n \"\"\"", "%", "self", ".", "table", ")", "self", ".", "_db", ".", "commit", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB._list_to_dict
Inverse of dict_to_list
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def _list_to_dict(self, line, keys=None): """Inverse of dict_to_list""" keys = self._keys if keys is None else keys d = self._defaults(keys) for key,value in zip(keys, line): d[key] = value return d
def _list_to_dict(self, line, keys=None): """Inverse of dict_to_list""" keys = self._keys if keys is None else keys d = self._defaults(keys) for key,value in zip(keys, line): d[key] = value return d
[ "Inverse", "of", "dict_to_list" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L269-L276
[ "def", "_list_to_dict", "(", "self", ",", "line", ",", "keys", "=", "None", ")", ":", "keys", "=", "self", ".", "_keys", "if", "keys", "is", "None", "else", "keys", "d", "=", "self", ".", "_defaults", "(", "keys", ")", "for", "key", ",", "value", "in", "zip", "(", "keys", ",", "line", ")", ":", "d", "[", "key", "]", "=", "value", "return", "d" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB._render_expression
Turn a mongodb-style search dict into an SQL query.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def _render_expression(self, check): """Turn a mongodb-style search dict into an SQL query.""" expressions = [] args = [] skeys = set(check.keys()) skeys.difference_update(set(self._keys)) skeys.difference_update(set(['buffers', 'result_buffers'])) if skeys: raise KeyError("Illegal testing key(s): %s"%skeys) for name,sub_check in check.iteritems(): if isinstance(sub_check, dict): for test,value in sub_check.iteritems(): try: op = operators[test] except KeyError: raise KeyError("Unsupported operator: %r"%test) if isinstance(op, tuple): op, join = op if value is None and op in null_operators: expr = "%s %s" % (name, null_operators[op]) else: expr = "%s %s ?"%(name, op) if isinstance(value, (tuple,list)): if op in null_operators and any([v is None for v in value]): # equality tests don't work with NULL raise ValueError("Cannot use %r test with NULL values on SQLite backend"%test) expr = '( %s )'%( join.join([expr]*len(value)) ) args.extend(value) else: args.append(value) expressions.append(expr) else: # it's an equality check if sub_check is None: expressions.append("%s IS NULL" % name) else: expressions.append("%s = ?"%name) args.append(sub_check) expr = " AND ".join(expressions) return expr, args
def _render_expression(self, check): """Turn a mongodb-style search dict into an SQL query.""" expressions = [] args = [] skeys = set(check.keys()) skeys.difference_update(set(self._keys)) skeys.difference_update(set(['buffers', 'result_buffers'])) if skeys: raise KeyError("Illegal testing key(s): %s"%skeys) for name,sub_check in check.iteritems(): if isinstance(sub_check, dict): for test,value in sub_check.iteritems(): try: op = operators[test] except KeyError: raise KeyError("Unsupported operator: %r"%test) if isinstance(op, tuple): op, join = op if value is None and op in null_operators: expr = "%s %s" % (name, null_operators[op]) else: expr = "%s %s ?"%(name, op) if isinstance(value, (tuple,list)): if op in null_operators and any([v is None for v in value]): # equality tests don't work with NULL raise ValueError("Cannot use %r test with NULL values on SQLite backend"%test) expr = '( %s )'%( join.join([expr]*len(value)) ) args.extend(value) else: args.append(value) expressions.append(expr) else: # it's an equality check if sub_check is None: expressions.append("%s IS NULL" % name) else: expressions.append("%s = ?"%name) args.append(sub_check) expr = " AND ".join(expressions) return expr, args
[ "Turn", "a", "mongodb", "-", "style", "search", "dict", "into", "an", "SQL", "query", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L278-L321
[ "def", "_render_expression", "(", "self", ",", "check", ")", ":", "expressions", "=", "[", "]", "args", "=", "[", "]", "skeys", "=", "set", "(", "check", ".", "keys", "(", ")", ")", "skeys", ".", "difference_update", "(", "set", "(", "self", ".", "_keys", ")", ")", "skeys", ".", "difference_update", "(", "set", "(", "[", "'buffers'", ",", "'result_buffers'", "]", ")", ")", "if", "skeys", ":", "raise", "KeyError", "(", "\"Illegal testing key(s): %s\"", "%", "skeys", ")", "for", "name", ",", "sub_check", "in", "check", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "sub_check", ",", "dict", ")", ":", "for", "test", ",", "value", "in", "sub_check", ".", "iteritems", "(", ")", ":", "try", ":", "op", "=", "operators", "[", "test", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "\"Unsupported operator: %r\"", "%", "test", ")", "if", "isinstance", "(", "op", ",", "tuple", ")", ":", "op", ",", "join", "=", "op", "if", "value", "is", "None", "and", "op", "in", "null_operators", ":", "expr", "=", "\"%s %s\"", "%", "(", "name", ",", "null_operators", "[", "op", "]", ")", "else", ":", "expr", "=", "\"%s %s ?\"", "%", "(", "name", ",", "op", ")", "if", "isinstance", "(", "value", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "op", "in", "null_operators", "and", "any", "(", "[", "v", "is", "None", "for", "v", "in", "value", "]", ")", ":", "# equality tests don't work with NULL", "raise", "ValueError", "(", "\"Cannot use %r test with NULL values on SQLite backend\"", "%", "test", ")", "expr", "=", "'( %s )'", "%", "(", "join", ".", "join", "(", "[", "expr", "]", "*", "len", "(", "value", ")", ")", ")", "args", ".", "extend", "(", "value", ")", "else", ":", "args", ".", "append", "(", "value", ")", "expressions", ".", "append", "(", "expr", ")", "else", ":", "# it's an equality check", "if", "sub_check", "is", "None", ":", "expressions", ".", "append", "(", "\"%s IS NULL\"", "%", "name", ")", "else", ":", "expressions", ".", "append", "(", "\"%s = ?\"", "%", "name", ")", "args", ".", "append", "(", "sub_check", ")", "expr", "=", "\" AND \"", ".", "join", "(", "expressions", ")", "return", "expr", ",", "args" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB.add_record
Add a new Task Record, by msg_id.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" d = self._defaults() d.update(rec) d['msg_id'] = msg_id line = self._dict_to_list(d) tups = '(%s)'%(','.join(['?']*len(line))) self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups), line)
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" d = self._defaults() d.update(rec) d['msg_id'] = msg_id line = self._dict_to_list(d) tups = '(%s)'%(','.join(['?']*len(line))) self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups), line)
[ "Add", "a", "new", "Task", "Record", "by", "msg_id", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L323-L330
[ "def", "add_record", "(", "self", ",", "msg_id", ",", "rec", ")", ":", "d", "=", "self", ".", "_defaults", "(", ")", "d", ".", "update", "(", "rec", ")", "d", "[", "'msg_id'", "]", "=", "msg_id", "line", "=", "self", ".", "_dict_to_list", "(", "d", ")", "tups", "=", "'(%s)'", "%", "(", "','", ".", "join", "(", "[", "'?'", "]", "*", "len", "(", "line", ")", ")", ")", "self", ".", "_db", ".", "execute", "(", "\"INSERT INTO %s VALUES %s\"", "%", "(", "self", ".", "table", ",", "tups", ")", ",", "line", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB.get_record
Get a specific Task Record, by msg_id.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) line = cursor.fetchone() if line is None: raise KeyError("No such msg: %r"%msg_id) return self._list_to_dict(line)
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) line = cursor.fetchone() if line is None: raise KeyError("No such msg: %r"%msg_id) return self._list_to_dict(line)
[ "Get", "a", "specific", "Task", "Record", "by", "msg_id", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L333-L339
[ "def", "get_record", "(", "self", ",", "msg_id", ")", ":", "cursor", "=", "self", ".", "_db", ".", "execute", "(", "\"\"\"SELECT * FROM %s WHERE msg_id==?\"\"\"", "%", "self", ".", "table", ",", "(", "msg_id", ",", ")", ")", "line", "=", "cursor", ".", "fetchone", "(", ")", "if", "line", "is", "None", ":", "raise", "KeyError", "(", "\"No such msg: %r\"", "%", "msg_id", ")", "return", "self", ".", "_list_to_dict", "(", "line", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB.update_record
Update the data in an existing record.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def update_record(self, msg_id, rec): """Update the data in an existing record.""" query = "UPDATE %s SET "%self.table sets = [] keys = sorted(rec.keys()) values = [] for key in keys: sets.append('%s = ?'%key) values.append(rec[key]) query += ', '.join(sets) query += ' WHERE msg_id == ?' values.append(msg_id) self._db.execute(query, values)
def update_record(self, msg_id, rec): """Update the data in an existing record.""" query = "UPDATE %s SET "%self.table sets = [] keys = sorted(rec.keys()) values = [] for key in keys: sets.append('%s = ?'%key) values.append(rec[key]) query += ', '.join(sets) query += ' WHERE msg_id == ?' values.append(msg_id) self._db.execute(query, values)
[ "Update", "the", "data", "in", "an", "existing", "record", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L341-L353
[ "def", "update_record", "(", "self", ",", "msg_id", ",", "rec", ")", ":", "query", "=", "\"UPDATE %s SET \"", "%", "self", ".", "table", "sets", "=", "[", "]", "keys", "=", "sorted", "(", "rec", ".", "keys", "(", ")", ")", "values", "=", "[", "]", "for", "key", "in", "keys", ":", "sets", ".", "append", "(", "'%s = ?'", "%", "key", ")", "values", ".", "append", "(", "rec", "[", "key", "]", ")", "query", "+=", "', '", ".", "join", "(", "sets", ")", "query", "+=", "' WHERE msg_id == ?'", "values", ".", "append", "(", "msg_id", ")", "self", ".", "_db", ".", "execute", "(", "query", ",", "values", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB.drop_matching_records
Remove a record from the DB.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def drop_matching_records(self, check): """Remove a record from the DB.""" expr,args = self._render_expression(check) query = "DELETE FROM %s WHERE %s"%(self.table, expr) self._db.execute(query,args)
def drop_matching_records(self, check): """Remove a record from the DB.""" expr,args = self._render_expression(check) query = "DELETE FROM %s WHERE %s"%(self.table, expr) self._db.execute(query,args)
[ "Remove", "a", "record", "from", "the", "DB", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L361-L365
[ "def", "drop_matching_records", "(", "self", ",", "check", ")", ":", "expr", ",", "args", "=", "self", ".", "_render_expression", "(", "check", ")", "query", "=", "\"DELETE FROM %s WHERE %s\"", "%", "(", "self", ".", "table", ",", "expr", ")", "self", ".", "_db", ".", "execute", "(", "query", ",", "args", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB.find_records
Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included. """ if keys: bad_keys = [ key for key in keys if key not in self._keys ] if bad_keys: raise KeyError("Bad record key(s): %s"%bad_keys) if keys: # ensure msg_id is present and first: if 'msg_id' in keys: keys.remove('msg_id') keys.insert(0, 'msg_id') req = ', '.join(keys) else: req = '*' expr,args = self._render_expression(check) query = """SELECT %s FROM %s WHERE %s"""%(req, self.table, expr) cursor = self._db.execute(query, args) matches = cursor.fetchall() records = [] for line in matches: rec = self._list_to_dict(line, keys) records.append(rec) return records
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included. """ if keys: bad_keys = [ key for key in keys if key not in self._keys ] if bad_keys: raise KeyError("Bad record key(s): %s"%bad_keys) if keys: # ensure msg_id is present and first: if 'msg_id' in keys: keys.remove('msg_id') keys.insert(0, 'msg_id') req = ', '.join(keys) else: req = '*' expr,args = self._render_expression(check) query = """SELECT %s FROM %s WHERE %s"""%(req, self.table, expr) cursor = self._db.execute(query, args) matches = cursor.fetchall() records = [] for line in matches: rec = self._list_to_dict(line, keys) records.append(rec) return records
[ "Find", "records", "matching", "a", "query", "dict", "optionally", "extracting", "subset", "of", "keys", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L368-L403
[ "def", "find_records", "(", "self", ",", "check", ",", "keys", "=", "None", ")", ":", "if", "keys", ":", "bad_keys", "=", "[", "key", "for", "key", "in", "keys", "if", "key", "not", "in", "self", ".", "_keys", "]", "if", "bad_keys", ":", "raise", "KeyError", "(", "\"Bad record key(s): %s\"", "%", "bad_keys", ")", "if", "keys", ":", "# ensure msg_id is present and first:", "if", "'msg_id'", "in", "keys", ":", "keys", ".", "remove", "(", "'msg_id'", ")", "keys", ".", "insert", "(", "0", ",", "'msg_id'", ")", "req", "=", "', '", ".", "join", "(", "keys", ")", "else", ":", "req", "=", "'*'", "expr", ",", "args", "=", "self", ".", "_render_expression", "(", "check", ")", "query", "=", "\"\"\"SELECT %s FROM %s WHERE %s\"\"\"", "%", "(", "req", ",", "self", ".", "table", ",", "expr", ")", "cursor", "=", "self", ".", "_db", ".", "execute", "(", "query", ",", "args", ")", "matches", "=", "cursor", ".", "fetchall", "(", ")", "records", "=", "[", "]", "for", "line", "in", "matches", ":", "rec", "=", "self", ".", "_list_to_dict", "(", "line", ",", "keys", ")", "records", ".", "append", "(", "rec", ")", "return", "records" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SQLiteDB.get_history
get all msg_ids, ordered by time submitted.
environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py
def get_history(self): """get all msg_ids, ordered by time submitted.""" query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table cursor = self._db.execute(query) # will be a list of length 1 tuples return [ tup[0] for tup in cursor.fetchall()]
def get_history(self): """get all msg_ids, ordered by time submitted.""" query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table cursor = self._db.execute(query) # will be a list of length 1 tuples return [ tup[0] for tup in cursor.fetchall()]
[ "get", "all", "msg_ids", "ordered", "by", "time", "submitted", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L405-L410
[ "def", "get_history", "(", "self", ")", ":", "query", "=", "\"\"\"SELECT msg_id FROM %s ORDER by submitted ASC\"\"\"", "%", "self", ".", "table", "cursor", "=", "self", ".", "_db", ".", "execute", "(", "query", ")", "# will be a list of length 1 tuples", "return", "[", "tup", "[", "0", "]", "for", "tup", "in", "cursor", ".", "fetchall", "(", ")", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
warn
Standard warning printer. Gives formatting consistency. Output is sent to io.stderr (sys.stderr by default). Options: -level(2): allows finer control: 0 -> Do nothing, dummy function. 1 -> Print message. 2 -> Print 'WARNING:' + message. (Default level). 3 -> Print 'ERROR:' + message. 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). -exit_val (1): exit value returned by sys.exit() for a level 4 warning. Ignored for all other levels.
environment/lib/python2.7/site-packages/IPython/utils/warn.py
def warn(msg,level=2,exit_val=1): """Standard warning printer. Gives formatting consistency. Output is sent to io.stderr (sys.stderr by default). Options: -level(2): allows finer control: 0 -> Do nothing, dummy function. 1 -> Print message. 2 -> Print 'WARNING:' + message. (Default level). 3 -> Print 'ERROR:' + message. 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). -exit_val (1): exit value returned by sys.exit() for a level 4 warning. Ignored for all other levels.""" if level>0: header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] io.stderr.write('%s%s' % (header[level],msg)) if level == 4: print >> io.stderr,'Exiting.\n' sys.exit(exit_val)
def warn(msg,level=2,exit_val=1): """Standard warning printer. Gives formatting consistency. Output is sent to io.stderr (sys.stderr by default). Options: -level(2): allows finer control: 0 -> Do nothing, dummy function. 1 -> Print message. 2 -> Print 'WARNING:' + message. (Default level). 3 -> Print 'ERROR:' + message. 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). -exit_val (1): exit value returned by sys.exit() for a level 4 warning. Ignored for all other levels.""" if level>0: header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] io.stderr.write('%s%s' % (header[level],msg)) if level == 4: print >> io.stderr,'Exiting.\n' sys.exit(exit_val)
[ "Standard", "warning", "printer", ".", "Gives", "formatting", "consistency", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/warn.py#L25-L47
[ "def", "warn", "(", "msg", ",", "level", "=", "2", ",", "exit_val", "=", "1", ")", ":", "if", "level", ">", "0", ":", "header", "=", "[", "''", ",", "''", ",", "'WARNING: '", ",", "'ERROR: '", ",", "'FATAL ERROR: '", "]", "io", ".", "stderr", ".", "write", "(", "'%s%s'", "%", "(", "header", "[", "level", "]", ",", "msg", ")", ")", "if", "level", "==", "4", ":", "print", ">>", "io", ".", "stderr", ",", "'Exiting.\\n'", "sys", ".", "exit", "(", "exit_val", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Reader.parse
Read a config_file, check the validity with a JSON Schema as specs and get default values from default_file if asked. All parameters are optionnal. If there is no config_file defined, read the venv base dir and try to get config/app.yml. If no specs, don't validate anything. If no default_file, don't merge with default values.
impulsare_config/reader.py
def parse(self, config_file=None, specs=None, default_file=None): """Read a config_file, check the validity with a JSON Schema as specs and get default values from default_file if asked. All parameters are optionnal. If there is no config_file defined, read the venv base dir and try to get config/app.yml. If no specs, don't validate anything. If no default_file, don't merge with default values.""" self._config_exists(config_file) self._specs_exists(specs) self.loaded_config = anyconfig.load(self.config_file, ac_parser='yaml') if default_file is not None: self._merge_default(default_file) if self.specs is None: return self.loaded_config self._validate() return self.loaded_config
def parse(self, config_file=None, specs=None, default_file=None): """Read a config_file, check the validity with a JSON Schema as specs and get default values from default_file if asked. All parameters are optionnal. If there is no config_file defined, read the venv base dir and try to get config/app.yml. If no specs, don't validate anything. If no default_file, don't merge with default values.""" self._config_exists(config_file) self._specs_exists(specs) self.loaded_config = anyconfig.load(self.config_file, ac_parser='yaml') if default_file is not None: self._merge_default(default_file) if self.specs is None: return self.loaded_config self._validate() return self.loaded_config
[ "Read", "a", "config_file", "check", "the", "validity", "with", "a", "JSON", "Schema", "as", "specs", "and", "get", "default", "values", "from", "default_file", "if", "asked", "." ]
impulsare/config
python
https://github.com/impulsare/config/blob/cc9a043d389c132ac42c987fe4740f84c74f53a2/impulsare_config/reader.py#L10-L36
[ "def", "parse", "(", "self", ",", "config_file", "=", "None", ",", "specs", "=", "None", ",", "default_file", "=", "None", ")", ":", "self", ".", "_config_exists", "(", "config_file", ")", "self", ".", "_specs_exists", "(", "specs", ")", "self", ".", "loaded_config", "=", "anyconfig", ".", "load", "(", "self", ".", "config_file", ",", "ac_parser", "=", "'yaml'", ")", "if", "default_file", "is", "not", "None", ":", "self", ".", "_merge_default", "(", "default_file", ")", "if", "self", ".", "specs", "is", "None", ":", "return", "self", ".", "loaded_config", "self", ".", "_validate", "(", ")", "return", "self", ".", "loaded_config" ]
cc9a043d389c132ac42c987fe4740f84c74f53a2
test
table
Output a simple table with several columns.
django_baseline/templatetags/helpers.py
def table(rows): ''' Output a simple table with several columns. ''' output = '<table>' for row in rows: output += '<tr>' for column in row: output += '<td>{s}</td>'.format(s=column) output += '</tr>' output += '</table>' return output
def table(rows): ''' Output a simple table with several columns. ''' output = '<table>' for row in rows: output += '<tr>' for column in row: output += '<td>{s}</td>'.format(s=column) output += '</tr>' output += '</table>' return output
[ "Output", "a", "simple", "table", "with", "several", "columns", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L18-L33
[ "def", "table", "(", "rows", ")", ":", "output", "=", "'<table>'", "for", "row", "in", "rows", ":", "output", "+=", "'<tr>'", "for", "column", "in", "row", ":", "output", "+=", "'<td>{s}</td>'", ".", "format", "(", "s", "=", "column", ")", "output", "+=", "'</tr>'", "output", "+=", "'</table>'", "return", "output" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
link
Output a link tag.
django_baseline/templatetags/helpers.py
def link(url, text='', classes='', target='', get="", **kwargs): ''' Output a link tag. ''' if not (url.startswith('http') or url.startswith('/')): # Handle additional reverse args. urlargs = {} for arg, val in kwargs.items(): if arg[:4] == "url_": urlargs[arg[4:]] = val url = reverse(url, kwargs=urlargs) if get: url += '?' + get return html.tag('a', text or url, { 'class': classes, 'target': target, 'href': url})
def link(url, text='', classes='', target='', get="", **kwargs): ''' Output a link tag. ''' if not (url.startswith('http') or url.startswith('/')): # Handle additional reverse args. urlargs = {} for arg, val in kwargs.items(): if arg[:4] == "url_": urlargs[arg[4:]] = val url = reverse(url, kwargs=urlargs) if get: url += '?' + get return html.tag('a', text or url, { 'class': classes, 'target': target, 'href': url})
[ "Output", "a", "link", "tag", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L36-L54
[ "def", "link", "(", "url", ",", "text", "=", "''", ",", "classes", "=", "''", ",", "target", "=", "''", ",", "get", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "url", ".", "startswith", "(", "'http'", ")", "or", "url", ".", "startswith", "(", "'/'", ")", ")", ":", "# Handle additional reverse args.", "urlargs", "=", "{", "}", "for", "arg", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "if", "arg", "[", ":", "4", "]", "==", "\"url_\"", ":", "urlargs", "[", "arg", "[", "4", ":", "]", "]", "=", "val", "url", "=", "reverse", "(", "url", ",", "kwargs", "=", "urlargs", ")", "if", "get", ":", "url", "+=", "'?'", "+", "get", "return", "html", ".", "tag", "(", "'a'", ",", "text", "or", "url", ",", "{", "'class'", ":", "classes", ",", "'target'", ":", "target", ",", "'href'", ":", "url", "}", ")" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
jsfile
Output a script tag to a js file.
django_baseline/templatetags/helpers.py
def jsfile(url): ''' Output a script tag to a js file. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<script type="text/javascript" src="{src}"></script>'.format( src=url)
def jsfile(url): ''' Output a script tag to a js file. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<script type="text/javascript" src="{src}"></script>'.format( src=url)
[ "Output", "a", "script", "tag", "to", "a", "js", "file", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L58-L68
[ "def", "jsfile", "(", "url", ")", ":", "if", "not", "url", ".", "startswith", "(", "'http://'", ")", "and", "not", "url", "[", ":", "1", "]", "==", "'/'", ":", "#add media_url for relative paths", "url", "=", "settings", ".", "STATIC_URL", "+", "url", "return", "'<script type=\"text/javascript\" src=\"{src}\"></script>'", ".", "format", "(", "src", "=", "url", ")" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
cssfile
Output a link tag to a css stylesheet.
django_baseline/templatetags/helpers.py
def cssfile(url): ''' Output a link tag to a css stylesheet. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<link href="{src}" rel="stylesheet">'.format(src=url)
def cssfile(url): ''' Output a link tag to a css stylesheet. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<link href="{src}" rel="stylesheet">'.format(src=url)
[ "Output", "a", "link", "tag", "to", "a", "css", "stylesheet", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L72-L81
[ "def", "cssfile", "(", "url", ")", ":", "if", "not", "url", ".", "startswith", "(", "'http://'", ")", "and", "not", "url", "[", ":", "1", "]", "==", "'/'", ":", "#add media_url for relative paths", "url", "=", "settings", ".", "STATIC_URL", "+", "url", "return", "'<link href=\"{src}\" rel=\"stylesheet\">'", ".", "format", "(", "src", "=", "url", ")" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
img
Image tag helper.
django_baseline/templatetags/helpers.py
def img(url, alt='', classes='', style=''): ''' Image tag helper. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url attr = { 'class': classes, 'alt': alt, 'style': style, 'src': url } return html.tag('img', '', attr)
def img(url, alt='', classes='', style=''): ''' Image tag helper. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url attr = { 'class': classes, 'alt': alt, 'style': style, 'src': url } return html.tag('img', '', attr)
[ "Image", "tag", "helper", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L85-L101
[ "def", "img", "(", "url", ",", "alt", "=", "''", ",", "classes", "=", "''", ",", "style", "=", "''", ")", ":", "if", "not", "url", ".", "startswith", "(", "'http://'", ")", "and", "not", "url", "[", ":", "1", "]", "==", "'/'", ":", "#add media_url for relative paths", "url", "=", "settings", ".", "STATIC_URL", "+", "url", "attr", "=", "{", "'class'", ":", "classes", ",", "'alt'", ":", "alt", ",", "'style'", ":", "style", ",", "'src'", ":", "url", "}", "return", "html", ".", "tag", "(", "'img'", ",", "''", ",", "attr", ")" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
sub
Subtract the arg from the value.
django_baseline/templatetags/helpers.py
def sub(value, arg): """Subtract the arg from the value.""" try: return valid_numeric(value) - valid_numeric(arg) except (ValueError, TypeError): try: return value - arg except Exception: return ''
def sub(value, arg): """Subtract the arg from the value.""" try: return valid_numeric(value) - valid_numeric(arg) except (ValueError, TypeError): try: return value - arg except Exception: return ''
[ "Subtract", "the", "arg", "from", "the", "value", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L114-L122
[ "def", "sub", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "valid_numeric", "(", "value", ")", "-", "valid_numeric", "(", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "return", "value", "-", "arg", "except", "Exception", ":", "return", "''" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
mul
Multiply the arg with the value.
django_baseline/templatetags/helpers.py
def mul(value, arg): """Multiply the arg with the value.""" try: return valid_numeric(value) * valid_numeric(arg) except (ValueError, TypeError): try: return value * arg except Exception: return ''
def mul(value, arg): """Multiply the arg with the value.""" try: return valid_numeric(value) * valid_numeric(arg) except (ValueError, TypeError): try: return value * arg except Exception: return ''
[ "Multiply", "the", "arg", "with", "the", "value", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L127-L135
[ "def", "mul", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "valid_numeric", "(", "value", ")", "*", "valid_numeric", "(", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "return", "value", "*", "arg", "except", "Exception", ":", "return", "''" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
div
Divide the arg by the value.
django_baseline/templatetags/helpers.py
def div(value, arg): """Divide the arg by the value.""" try: return valid_numeric(value) / valid_numeric(arg) except (ValueError, TypeError): try: return value / arg except Exception: return ''
def div(value, arg): """Divide the arg by the value.""" try: return valid_numeric(value) / valid_numeric(arg) except (ValueError, TypeError): try: return value / arg except Exception: return ''
[ "Divide", "the", "arg", "by", "the", "value", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L140-L148
[ "def", "div", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "valid_numeric", "(", "value", ")", "/", "valid_numeric", "(", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "return", "value", "/", "arg", "except", "Exception", ":", "return", "''" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
mod
Return the modulo value.
django_baseline/templatetags/helpers.py
def mod(value, arg): """Return the modulo value.""" try: return valid_numeric(value) % valid_numeric(arg) except (ValueError, TypeError): try: return value % arg except Exception: return ''
def mod(value, arg): """Return the modulo value.""" try: return valid_numeric(value) % valid_numeric(arg) except (ValueError, TypeError): try: return value % arg except Exception: return ''
[ "Return", "the", "modulo", "value", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L166-L174
[ "def", "mod", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "valid_numeric", "(", "value", ")", "%", "valid_numeric", "(", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "return", "value", "%", "arg", "except", "Exception", ":", "return", "''" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
model_verbose
Return the verbose name of a model. The obj argument can be either a Model instance, or a ModelForm instance. This allows to retrieve the verbose name of the model of a ModelForm easily, without adding extra context vars.
django_baseline/templatetags/helpers.py
def model_verbose(obj, capitalize=True): """ Return the verbose name of a model. The obj argument can be either a Model instance, or a ModelForm instance. This allows to retrieve the verbose name of the model of a ModelForm easily, without adding extra context vars. """ if isinstance(obj, ModelForm): name = obj._meta.model._meta.verbose_name elif isinstance(obj, Model): name = obj._meta.verbose_name else: raise Exception('Unhandled type: ' + type(obj)) return name.capitalize() if capitalize else name
def model_verbose(obj, capitalize=True): """ Return the verbose name of a model. The obj argument can be either a Model instance, or a ModelForm instance. This allows to retrieve the verbose name of the model of a ModelForm easily, without adding extra context vars. """ if isinstance(obj, ModelForm): name = obj._meta.model._meta.verbose_name elif isinstance(obj, Model): name = obj._meta.verbose_name else: raise Exception('Unhandled type: ' + type(obj)) return name.capitalize() if capitalize else name
[ "Return", "the", "verbose", "name", "of", "a", "model", ".", "The", "obj", "argument", "can", "be", "either", "a", "Model", "instance", "or", "a", "ModelForm", "instance", ".", "This", "allows", "to", "retrieve", "the", "verbose", "name", "of", "the", "model", "of", "a", "ModelForm", "easily", "without", "adding", "extra", "context", "vars", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/templatetags/helpers.py#L181-L196
[ "def", "model_verbose", "(", "obj", ",", "capitalize", "=", "True", ")", ":", "if", "isinstance", "(", "obj", ",", "ModelForm", ")", ":", "name", "=", "obj", ".", "_meta", ".", "model", ".", "_meta", ".", "verbose_name", "elif", "isinstance", "(", "obj", ",", "Model", ")", ":", "name", "=", "obj", ".", "_meta", ".", "verbose_name", "else", ":", "raise", "Exception", "(", "'Unhandled type: '", "+", "type", "(", "obj", ")", ")", "return", "name", ".", "capitalize", "(", ")", "if", "capitalize", "else", "name" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
extendManager
Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte = django.utils.timezone.now()).order_by('-published') ... publishedArticles = Article.objects.getPublished()
django_libretto/models.py
def extendManager(mixinClass): ''' Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte = django.utils.timezone.now()).order_by('-published') ... publishedArticles = Article.objects.getPublished() ''' class MixinManager(models.Manager, mixinClass): class MixinQuerySet(models.query.QuerySet, mixinClass): pass def get_queryset(self): return self.MixinQuerySet(self.model, using = self._db) return MixinManager()
def extendManager(mixinClass): ''' Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte = django.utils.timezone.now()).order_by('-published') ... publishedArticles = Article.objects.getPublished() ''' class MixinManager(models.Manager, mixinClass): class MixinQuerySet(models.query.QuerySet, mixinClass): pass def get_queryset(self): return self.MixinQuerySet(self.model, using = self._db) return MixinManager()
[ "Use", "as", "a", "class", "decorator", "to", "add", "extra", "methods", "to", "your", "model", "manager", ".", "Example", "usage", ":" ]
ze-phyr-us/django-libretto
python
https://github.com/ze-phyr-us/django-libretto/blob/b19d8aa21b9579ee91e81967a44d1c40f5588b17/django_libretto/models.py#L9-L34
[ "def", "extendManager", "(", "mixinClass", ")", ":", "class", "MixinManager", "(", "models", ".", "Manager", ",", "mixinClass", ")", ":", "class", "MixinQuerySet", "(", "models", ".", "query", ".", "QuerySet", ",", "mixinClass", ")", ":", "pass", "def", "get_queryset", "(", "self", ")", ":", "return", "self", ".", "MixinQuerySet", "(", "self", ".", "model", ",", "using", "=", "self", ".", "_db", ")", "return", "MixinManager", "(", ")" ]
b19d8aa21b9579ee91e81967a44d1c40f5588b17
test
run
Main method where all logic is defined
myhelp/myhelp.py
def run(): """Main method where all logic is defined""" config_option_help="'show' - displays configured options, 'set [section] [name] [value]' - sets config under a section,'set [name] [value]' - sets configuration globally" parser = OptionParser() parser.add_option("-a", "--add", action="store", type="string", dest="addfile", help="adds a notes") parser.add_option("-c", "--config", action="store", type="string", dest="config", help=config_option_help) parser.add_option("-e", "--edit", action="store", type="string", dest="editfile", help="edits a notes") parser.add_option("-o", "--open", action="store", type="string", dest="openfile", help="opens a notes") parser.add_option("-r", "--remove", action="store", type="string", dest="remove", help="removes a notes") options, args = parser.parse_args() if options.config: if options.config == "show": config_option_list='' config_sections = config.sections() for section in config_sections: config_option_list=config_option_list+section+"\n" section_items =config.items(section) for item in section_items: config_option_list=config_option_list+" "+item[0]+" "+item[1]+"\n" print config_option_list quit() def add_notes(note_name,existing_tags): call([editor,environ["HOME"] + "/.mypy/myhelp/notes/"+note_name+".note"]) definedtags = raw_input("Define Tags (separated by spaces): ").split(" ") definedtags.append(note_name) print definedtags print existing_tags definedtags=list(set(definedtags)-set(existing_tags)) print definedtags if len(definedtags)>0: modify_tags_xml(note_name,definedtags,files,rootfiles,tags,roottags,tree,TAGS_XML_DIR) def get_tags_from_file(note_name): fil = get_file_from_files(note_name) filetags = fil.iter('tag') filetaglist=[] for tag in filetags: filetaglist.append(tag.text) return filetaglist if options.addfile: existing_tags=[] if isFile(options.addfile,files): existing_tags=get_tags_from_file(options.addfile) raw_input("Note exists with tags - "+" ".join(existing_tags)+"\nDo you want to edit the notes ? [Press enter to continue]\n") add_notes(options.addfile,existing_tags) quit() if options.editfile: if isFile(options.editfile,files): add_notes(note_name,[]) else: raw_input("Note doesn't exist.\nDo you want add note ? [Press enter to continue]") add_notes(note_name) if options.remove: pass if len(args) != 1: print "Please use a search term\n example : myhelp <some tag word> " quit() _key_File = "Note" _key_Results = " Results " table={_key_Results:[]} for tag in tags: if tag.attrib["value"] == args[0]: fileelements = tag.iter("file") for fileelement in fileelements: f = open( environ["HOME"] + "/.mypy/myhelp/notes/" + fileelement.text+".note", "r") table[_key_Results].append(f.read()+"\r\n\tfile: ~/.mypy/myhelp/notes/"+fileelement.text+".note") f.close() print tabulate(table,headers=[],tablefmt="rst")
def run(): """Main method where all logic is defined""" config_option_help="'show' - displays configured options, 'set [section] [name] [value]' - sets config under a section,'set [name] [value]' - sets configuration globally" parser = OptionParser() parser.add_option("-a", "--add", action="store", type="string", dest="addfile", help="adds a notes") parser.add_option("-c", "--config", action="store", type="string", dest="config", help=config_option_help) parser.add_option("-e", "--edit", action="store", type="string", dest="editfile", help="edits a notes") parser.add_option("-o", "--open", action="store", type="string", dest="openfile", help="opens a notes") parser.add_option("-r", "--remove", action="store", type="string", dest="remove", help="removes a notes") options, args = parser.parse_args() if options.config: if options.config == "show": config_option_list='' config_sections = config.sections() for section in config_sections: config_option_list=config_option_list+section+"\n" section_items =config.items(section) for item in section_items: config_option_list=config_option_list+" "+item[0]+" "+item[1]+"\n" print config_option_list quit() def add_notes(note_name,existing_tags): call([editor,environ["HOME"] + "/.mypy/myhelp/notes/"+note_name+".note"]) definedtags = raw_input("Define Tags (separated by spaces): ").split(" ") definedtags.append(note_name) print definedtags print existing_tags definedtags=list(set(definedtags)-set(existing_tags)) print definedtags if len(definedtags)>0: modify_tags_xml(note_name,definedtags,files,rootfiles,tags,roottags,tree,TAGS_XML_DIR) def get_tags_from_file(note_name): fil = get_file_from_files(note_name) filetags = fil.iter('tag') filetaglist=[] for tag in filetags: filetaglist.append(tag.text) return filetaglist if options.addfile: existing_tags=[] if isFile(options.addfile,files): existing_tags=get_tags_from_file(options.addfile) raw_input("Note exists with tags - "+" ".join(existing_tags)+"\nDo you want to edit the notes ? [Press enter to continue]\n") add_notes(options.addfile,existing_tags) quit() if options.editfile: if isFile(options.editfile,files): add_notes(note_name,[]) else: raw_input("Note doesn't exist.\nDo you want add note ? [Press enter to continue]") add_notes(note_name) if options.remove: pass if len(args) != 1: print "Please use a search term\n example : myhelp <some tag word> " quit() _key_File = "Note" _key_Results = " Results " table={_key_Results:[]} for tag in tags: if tag.attrib["value"] == args[0]: fileelements = tag.iter("file") for fileelement in fileelements: f = open( environ["HOME"] + "/.mypy/myhelp/notes/" + fileelement.text+".note", "r") table[_key_Results].append(f.read()+"\r\n\tfile: ~/.mypy/myhelp/notes/"+fileelement.text+".note") f.close() print tabulate(table,headers=[],tablefmt="rst")
[ "Main", "method", "where", "all", "logic", "is", "defined" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/myhelp/myhelp.py#L26-L105
[ "def", "run", "(", ")", ":", "config_option_help", "=", "\"'show' - displays configured options, 'set [section] [name] [value]' - sets config under a section,'set [name] [value]' - sets configuration globally\"", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "\"-a\"", ",", "\"--add\"", ",", "action", "=", "\"store\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"addfile\"", ",", "help", "=", "\"adds a notes\"", ")", "parser", ".", "add_option", "(", "\"-c\"", ",", "\"--config\"", ",", "action", "=", "\"store\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"config\"", ",", "help", "=", "config_option_help", ")", "parser", ".", "add_option", "(", "\"-e\"", ",", "\"--edit\"", ",", "action", "=", "\"store\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"editfile\"", ",", "help", "=", "\"edits a notes\"", ")", "parser", ".", "add_option", "(", "\"-o\"", ",", "\"--open\"", ",", "action", "=", "\"store\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"openfile\"", ",", "help", "=", "\"opens a notes\"", ")", "parser", ".", "add_option", "(", "\"-r\"", ",", "\"--remove\"", ",", "action", "=", "\"store\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"remove\"", ",", "help", "=", "\"removes a notes\"", ")", "options", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "options", ".", "config", ":", "if", "options", ".", "config", "==", "\"show\"", ":", "config_option_list", "=", "''", "config_sections", "=", "config", ".", "sections", "(", ")", "for", "section", "in", "config_sections", ":", "config_option_list", "=", "config_option_list", "+", "section", "+", "\"\\n\"", "section_items", "=", "config", ".", "items", "(", "section", ")", "for", "item", "in", "section_items", ":", "config_option_list", "=", "config_option_list", "+", "\" \"", "+", "item", "[", "0", "]", "+", "\" \"", "+", "item", "[", "1", "]", "+", "\"\\n\"", "print", "config_option_list", "quit", "(", ")", "def", "add_notes", "(", "note_name", ",", "existing_tags", ")", ":", "call", "(", "[", "editor", ",", "environ", "[", "\"HOME\"", "]", "+", "\"/.mypy/myhelp/notes/\"", "+", "note_name", "+", "\".note\"", "]", ")", "definedtags", "=", "raw_input", "(", "\"Define Tags (separated by spaces): \"", ")", ".", "split", "(", "\" \"", ")", "definedtags", ".", "append", "(", "note_name", ")", "print", "definedtags", "print", "existing_tags", "definedtags", "=", "list", "(", "set", "(", "definedtags", ")", "-", "set", "(", "existing_tags", ")", ")", "print", "definedtags", "if", "len", "(", "definedtags", ")", ">", "0", ":", "modify_tags_xml", "(", "note_name", ",", "definedtags", ",", "files", ",", "rootfiles", ",", "tags", ",", "roottags", ",", "tree", ",", "TAGS_XML_DIR", ")", "def", "get_tags_from_file", "(", "note_name", ")", ":", "fil", "=", "get_file_from_files", "(", "note_name", ")", "filetags", "=", "fil", ".", "iter", "(", "'tag'", ")", "filetaglist", "=", "[", "]", "for", "tag", "in", "filetags", ":", "filetaglist", ".", "append", "(", "tag", ".", "text", ")", "return", "filetaglist", "if", "options", ".", "addfile", ":", "existing_tags", "=", "[", "]", "if", "isFile", "(", "options", ".", "addfile", ",", "files", ")", ":", "existing_tags", "=", "get_tags_from_file", "(", "options", ".", "addfile", ")", "raw_input", "(", "\"Note exists with tags - \"", "+", "\" \"", ".", "join", "(", "existing_tags", ")", "+", "\"\\nDo you want to edit the notes ? [Press enter to continue]\\n\"", ")", "add_notes", "(", "options", ".", "addfile", ",", "existing_tags", ")", "quit", "(", ")", "if", "options", ".", "editfile", ":", "if", "isFile", "(", "options", ".", "editfile", ",", "files", ")", ":", "add_notes", "(", "note_name", ",", "[", "]", ")", "else", ":", "raw_input", "(", "\"Note doesn't exist.\\nDo you want add note ? [Press enter to continue]\"", ")", "add_notes", "(", "note_name", ")", "if", "options", ".", "remove", ":", "pass", "if", "len", "(", "args", ")", "!=", "1", ":", "print", "\"Please use a search term\\n example : myhelp <some tag word> \"", "quit", "(", ")", "_key_File", "=", "\"Note\"", "_key_Results", "=", "\" Results \"", "table", "=", "{", "_key_Results", ":", "[", "]", "}", "for", "tag", "in", "tags", ":", "if", "tag", ".", "attrib", "[", "\"value\"", "]", "==", "args", "[", "0", "]", ":", "fileelements", "=", "tag", ".", "iter", "(", "\"file\"", ")", "for", "fileelement", "in", "fileelements", ":", "f", "=", "open", "(", "environ", "[", "\"HOME\"", "]", "+", "\"/.mypy/myhelp/notes/\"", "+", "fileelement", ".", "text", "+", "\".note\"", ",", "\"r\"", ")", "table", "[", "_key_Results", "]", ".", "append", "(", "f", ".", "read", "(", ")", "+", "\"\\r\\n\\tfile: ~/.mypy/myhelp/notes/\"", "+", "fileelement", ".", "text", "+", "\".note\"", ")", "f", ".", "close", "(", ")", "print", "tabulate", "(", "table", ",", "headers", "=", "[", "]", ",", "tablefmt", "=", "\"rst\"", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
split_user_input
Split user input into initial whitespace, escape character, function part and the rest.
environment/lib/python2.7/site-packages/IPython/core/splitinput.py
def split_user_input(line, pattern=None): """Split user input into initial whitespace, escape character, function part and the rest. """ # We need to ensure that the rest of this routine deals only with unicode encoding = get_stream_enc(sys.stdin, 'utf-8') line = py3compat.cast_unicode(line, encoding) if pattern is None: pattern = line_split match = pattern.match(line) if not match: # print "match failed for line '%s'" % line try: ifun, the_rest = line.split(None,1) except ValueError: # print "split failed for line '%s'" % line ifun, the_rest = line, u'' pre = re.match('^(\s*)(.*)',line).groups()[0] esc = "" else: pre, esc, ifun, the_rest = match.groups() #print 'line:<%s>' % line # dbg #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg return pre, esc or '', ifun.strip(), the_rest.lstrip()
def split_user_input(line, pattern=None): """Split user input into initial whitespace, escape character, function part and the rest. """ # We need to ensure that the rest of this routine deals only with unicode encoding = get_stream_enc(sys.stdin, 'utf-8') line = py3compat.cast_unicode(line, encoding) if pattern is None: pattern = line_split match = pattern.match(line) if not match: # print "match failed for line '%s'" % line try: ifun, the_rest = line.split(None,1) except ValueError: # print "split failed for line '%s'" % line ifun, the_rest = line, u'' pre = re.match('^(\s*)(.*)',line).groups()[0] esc = "" else: pre, esc, ifun, the_rest = match.groups() #print 'line:<%s>' % line # dbg #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg return pre, esc or '', ifun.strip(), the_rest.lstrip()
[ "Split", "user", "input", "into", "initial", "whitespace", "escape", "character", "function", "part", "and", "the", "rest", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/splitinput.py#L53-L78
[ "def", "split_user_input", "(", "line", ",", "pattern", "=", "None", ")", ":", "# We need to ensure that the rest of this routine deals only with unicode", "encoding", "=", "get_stream_enc", "(", "sys", ".", "stdin", ",", "'utf-8'", ")", "line", "=", "py3compat", ".", "cast_unicode", "(", "line", ",", "encoding", ")", "if", "pattern", "is", "None", ":", "pattern", "=", "line_split", "match", "=", "pattern", ".", "match", "(", "line", ")", "if", "not", "match", ":", "# print \"match failed for line '%s'\" % line", "try", ":", "ifun", ",", "the_rest", "=", "line", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "# print \"split failed for line '%s'\" % line", "ifun", ",", "the_rest", "=", "line", ",", "u''", "pre", "=", "re", ".", "match", "(", "'^(\\s*)(.*)'", ",", "line", ")", ".", "groups", "(", ")", "[", "0", "]", "esc", "=", "\"\"", "else", ":", "pre", ",", "esc", ",", "ifun", ",", "the_rest", "=", "match", ".", "groups", "(", ")", "#print 'line:<%s>' % line # dbg", "#print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg", "return", "pre", ",", "esc", "or", "''", ",", "ifun", ".", "strip", "(", ")", ",", "the_rest", ".", "lstrip", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
current
Return a class name (string) if the current URL matches the route name specified in ``className``. If any URL keyword arguments are provided, they must be matched as well. :param urlName: The route name that the current URL should match. Example: 'accounts:login'. :param className: The string that is returned if the current URL matches the specified one. :param kwargs: Any extra URL keyword arguments that must also be present in the current URL for it to match. :returns: ``className`` if the current URL matches, or an empty string otherwise.
django_libretto/templatetags/navigation.py
def current(context, urlName, className = 'active', **kwargs): ''' Return a class name (string) if the current URL matches the route name specified in ``className``. If any URL keyword arguments are provided, they must be matched as well. :param urlName: The route name that the current URL should match. Example: 'accounts:login'. :param className: The string that is returned if the current URL matches the specified one. :param kwargs: Any extra URL keyword arguments that must also be present in the current URL for it to match. :returns: ``className`` if the current URL matches, or an empty string otherwise. ''' matches = pathMatches(context['request'].path, urlName, **kwargs) return className if matches else ''
def current(context, urlName, className = 'active', **kwargs): ''' Return a class name (string) if the current URL matches the route name specified in ``className``. If any URL keyword arguments are provided, they must be matched as well. :param urlName: The route name that the current URL should match. Example: 'accounts:login'. :param className: The string that is returned if the current URL matches the specified one. :param kwargs: Any extra URL keyword arguments that must also be present in the current URL for it to match. :returns: ``className`` if the current URL matches, or an empty string otherwise. ''' matches = pathMatches(context['request'].path, urlName, **kwargs) return className if matches else ''
[ "Return", "a", "class", "name", "(", "string", ")", "if", "the", "current", "URL", "matches", "the", "route", "name", "specified", "in", "className", ".", "If", "any", "URL", "keyword", "arguments", "are", "provided", "they", "must", "be", "matched", "as", "well", "." ]
ze-phyr-us/django-libretto
python
https://github.com/ze-phyr-us/django-libretto/blob/b19d8aa21b9579ee91e81967a44d1c40f5588b17/django_libretto/templatetags/navigation.py#L11-L22
[ "def", "current", "(", "context", ",", "urlName", ",", "className", "=", "'active'", ",", "*", "*", "kwargs", ")", ":", "matches", "=", "pathMatches", "(", "context", "[", "'request'", "]", ".", "path", ",", "urlName", ",", "*", "*", "kwargs", ")", "return", "className", "if", "matches", "else", "''" ]
b19d8aa21b9579ee91e81967a44d1c40f5588b17
test
pathMatches
:param path: str :param urlName: str :returns: bool.
django_libretto/templatetags/navigation.py
def pathMatches(path, urlName, **kwargs): ''' :param path: str :param urlName: str :returns: bool. ''' resolved = urlresolvers.resolve(path) # Different URL name => the current URL cannot match. resolvedName = '{r.namespace}:{r.url_name}'.format(r = resolved) if resolved.namespace else resolved.url_name if urlName != resolvedName: return False # If any of the current keyword args is missing or different, the URL cannot match. for key, value in kwargs.items(): currentArg = resolved.kwargs.get(key) if currentArg is None or str(value) != str(currentArg): return False return True
def pathMatches(path, urlName, **kwargs): ''' :param path: str :param urlName: str :returns: bool. ''' resolved = urlresolvers.resolve(path) # Different URL name => the current URL cannot match. resolvedName = '{r.namespace}:{r.url_name}'.format(r = resolved) if resolved.namespace else resolved.url_name if urlName != resolvedName: return False # If any of the current keyword args is missing or different, the URL cannot match. for key, value in kwargs.items(): currentArg = resolved.kwargs.get(key) if currentArg is None or str(value) != str(currentArg): return False return True
[ ":", "param", "path", ":", "str", ":", "param", "urlName", ":", "str", ":", "returns", ":", "bool", "." ]
ze-phyr-us/django-libretto
python
https://github.com/ze-phyr-us/django-libretto/blob/b19d8aa21b9579ee91e81967a44d1c40f5588b17/django_libretto/templatetags/navigation.py#L26-L45
[ "def", "pathMatches", "(", "path", ",", "urlName", ",", "*", "*", "kwargs", ")", ":", "resolved", "=", "urlresolvers", ".", "resolve", "(", "path", ")", "# Different URL name => the current URL cannot match.", "resolvedName", "=", "'{r.namespace}:{r.url_name}'", ".", "format", "(", "r", "=", "resolved", ")", "if", "resolved", ".", "namespace", "else", "resolved", ".", "url_name", "if", "urlName", "!=", "resolvedName", ":", "return", "False", "# If any of the current keyword args is missing or different, the URL cannot match.", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "currentArg", "=", "resolved", ".", "kwargs", ".", "get", "(", "key", ")", "if", "currentArg", "is", "None", "or", "str", "(", "value", ")", "!=", "str", "(", "currentArg", ")", ":", "return", "False", "return", "True" ]
b19d8aa21b9579ee91e81967a44d1c40f5588b17
test
MultiProcess.options
Register command-line options.
environment/lib/python2.7/site-packages/nose/plugins/multiprocess.py
def options(self, parser, env): """ Register command-line options. """ parser.add_option("--processes", action="store", default=env.get('NOSE_PROCESSES', 0), dest="multiprocess_workers", metavar="NUM", help="Spread test run among this many processes. " "Set a number equal to the number of processors " "or cores in your machine for best results. " "[NOSE_PROCESSES]") parser.add_option("--process-timeout", action="store", default=env.get('NOSE_PROCESS_TIMEOUT', 10), dest="multiprocess_timeout", metavar="SECONDS", help="Set timeout for return of results from each " "test runner process. [NOSE_PROCESS_TIMEOUT]") parser.add_option("--process-restartworker", action="store_true", default=env.get('NOSE_PROCESS_RESTARTWORKER', False), dest="multiprocess_restartworker", help="If set, will restart each worker process once" " their tests are done, this helps control memory " "leaks from killing the system. " "[NOSE_PROCESS_RESTARTWORKER]")
def options(self, parser, env): """ Register command-line options. """ parser.add_option("--processes", action="store", default=env.get('NOSE_PROCESSES', 0), dest="multiprocess_workers", metavar="NUM", help="Spread test run among this many processes. " "Set a number equal to the number of processors " "or cores in your machine for best results. " "[NOSE_PROCESSES]") parser.add_option("--process-timeout", action="store", default=env.get('NOSE_PROCESS_TIMEOUT', 10), dest="multiprocess_timeout", metavar="SECONDS", help="Set timeout for return of results from each " "test runner process. [NOSE_PROCESS_TIMEOUT]") parser.add_option("--process-restartworker", action="store_true", default=env.get('NOSE_PROCESS_RESTARTWORKER', False), dest="multiprocess_restartworker", help="If set, will restart each worker process once" " their tests are done, this helps control memory " "leaks from killing the system. " "[NOSE_PROCESS_RESTARTWORKER]")
[ "Register", "command", "-", "line", "options", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/multiprocess.py#L187-L211
[ "def", "options", "(", "self", ",", "parser", ",", "env", ")", ":", "parser", ".", "add_option", "(", "\"--processes\"", ",", "action", "=", "\"store\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_PROCESSES'", ",", "0", ")", ",", "dest", "=", "\"multiprocess_workers\"", ",", "metavar", "=", "\"NUM\"", ",", "help", "=", "\"Spread test run among this many processes. \"", "\"Set a number equal to the number of processors \"", "\"or cores in your machine for best results. \"", "\"[NOSE_PROCESSES]\"", ")", "parser", ".", "add_option", "(", "\"--process-timeout\"", ",", "action", "=", "\"store\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_PROCESS_TIMEOUT'", ",", "10", ")", ",", "dest", "=", "\"multiprocess_timeout\"", ",", "metavar", "=", "\"SECONDS\"", ",", "help", "=", "\"Set timeout for return of results from each \"", "\"test runner process. [NOSE_PROCESS_TIMEOUT]\"", ")", "parser", ".", "add_option", "(", "\"--process-restartworker\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_PROCESS_RESTARTWORKER'", ",", "False", ")", ",", "dest", "=", "\"multiprocess_restartworker\"", ",", "help", "=", "\"If set, will restart each worker process once\"", "\" their tests are done, this helps control memory \"", "\"leaks from killing the system. \"", "\"[NOSE_PROCESS_RESTARTWORKER]\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MultiProcess.configure
Configure plugin.
environment/lib/python2.7/site-packages/nose/plugins/multiprocess.py
def configure(self, options, config): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass if not hasattr(options, 'multiprocess_workers'): self.enabled = False return # don't start inside of a worker process if config.worker: return self.config = config try: workers = int(options.multiprocess_workers) except (TypeError, ValueError): workers = 0 if workers: _import_mp() if Process is None: self.enabled = False return self.enabled = True self.config.multiprocess_workers = workers t = float(options.multiprocess_timeout) self.config.multiprocess_timeout = t r = int(options.multiprocess_restartworker) self.config.multiprocess_restartworker = r self.status['active'] = True
def configure(self, options, config): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass if not hasattr(options, 'multiprocess_workers'): self.enabled = False return # don't start inside of a worker process if config.worker: return self.config = config try: workers = int(options.multiprocess_workers) except (TypeError, ValueError): workers = 0 if workers: _import_mp() if Process is None: self.enabled = False return self.enabled = True self.config.multiprocess_workers = workers t = float(options.multiprocess_timeout) self.config.multiprocess_timeout = t r = int(options.multiprocess_restartworker) self.config.multiprocess_restartworker = r self.status['active'] = True
[ "Configure", "plugin", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/multiprocess.py#L213-L243
[ "def", "configure", "(", "self", ",", "options", ",", "config", ")", ":", "try", ":", "self", ".", "status", ".", "pop", "(", "'active'", ")", "except", "KeyError", ":", "pass", "if", "not", "hasattr", "(", "options", ",", "'multiprocess_workers'", ")", ":", "self", ".", "enabled", "=", "False", "return", "# don't start inside of a worker process", "if", "config", ".", "worker", ":", "return", "self", ".", "config", "=", "config", "try", ":", "workers", "=", "int", "(", "options", ".", "multiprocess_workers", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "workers", "=", "0", "if", "workers", ":", "_import_mp", "(", ")", "if", "Process", "is", "None", ":", "self", ".", "enabled", "=", "False", "return", "self", ".", "enabled", "=", "True", "self", ".", "config", ".", "multiprocess_workers", "=", "workers", "t", "=", "float", "(", "options", ".", "multiprocess_timeout", ")", "self", ".", "config", ".", "multiprocess_timeout", "=", "t", "r", "=", "int", "(", "options", ".", "multiprocess_restartworker", ")", "self", ".", "config", ".", "multiprocess_restartworker", "=", "r", "self", ".", "status", "[", "'active'", "]", "=", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
NoSharedFixtureContextSuite.run
Run tests in suite inside of suite fixtures.
environment/lib/python2.7/site-packages/nose/plugins/multiprocess.py
def run(self, result): """Run tests in suite inside of suite fixtures. """ # proxy the result for myself log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests) if self.resultProxy: result, orig = self.resultProxy(result, self), result else: result, orig = result, result try: #log.debug('setUp for %s', id(self)); self.setUp() except KeyboardInterrupt: raise except: self.error_context = 'setup' result.addError(self, self._exc_info()) return try: for test in self._tests: if (isinstance(test,nose.case.Test) and self.arg is not None): test.test.arg = self.arg else: test.arg = self.arg test.testQueue = self.testQueue test.tasks = self.tasks if result.shouldStop: log.debug("stopping") break # each nose.case.Test will create its own result proxy # so the cases need the original result, to avoid proxy # chains #log.debug('running test %s in suite %s', test, self); try: test(orig) except KeyboardInterrupt, e: timeout = isinstance(e, TimedOutException) if timeout: msg = 'Timeout when running test %s in suite %s' else: msg = 'KeyboardInterrupt when running test %s in suite %s' log.debug(msg, test, self) err = (TimedOutException,TimedOutException(str(test)), sys.exc_info()[2]) test.config.plugins.addError(test,err) orig.addError(test,err) if not timeout: raise finally: self.has_run = True try: #log.debug('tearDown for %s', id(self)); self.tearDown() except KeyboardInterrupt: raise except: self.error_context = 'teardown' result.addError(self, self._exc_info())
def run(self, result): """Run tests in suite inside of suite fixtures. """ # proxy the result for myself log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests) if self.resultProxy: result, orig = self.resultProxy(result, self), result else: result, orig = result, result try: #log.debug('setUp for %s', id(self)); self.setUp() except KeyboardInterrupt: raise except: self.error_context = 'setup' result.addError(self, self._exc_info()) return try: for test in self._tests: if (isinstance(test,nose.case.Test) and self.arg is not None): test.test.arg = self.arg else: test.arg = self.arg test.testQueue = self.testQueue test.tasks = self.tasks if result.shouldStop: log.debug("stopping") break # each nose.case.Test will create its own result proxy # so the cases need the original result, to avoid proxy # chains #log.debug('running test %s in suite %s', test, self); try: test(orig) except KeyboardInterrupt, e: timeout = isinstance(e, TimedOutException) if timeout: msg = 'Timeout when running test %s in suite %s' else: msg = 'KeyboardInterrupt when running test %s in suite %s' log.debug(msg, test, self) err = (TimedOutException,TimedOutException(str(test)), sys.exc_info()[2]) test.config.plugins.addError(test,err) orig.addError(test,err) if not timeout: raise finally: self.has_run = True try: #log.debug('tearDown for %s', id(self)); self.tearDown() except KeyboardInterrupt: raise except: self.error_context = 'teardown' result.addError(self, self._exc_info())
[ "Run", "tests", "in", "suite", "inside", "of", "suite", "fixtures", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/multiprocess.py#L760-L819
[ "def", "run", "(", "self", ",", "result", ")", ":", "# proxy the result for myself", "log", ".", "debug", "(", "\"suite %s (%s) run called, tests: %s\"", ",", "id", "(", "self", ")", ",", "self", ",", "self", ".", "_tests", ")", "if", "self", ".", "resultProxy", ":", "result", ",", "orig", "=", "self", ".", "resultProxy", "(", "result", ",", "self", ")", ",", "result", "else", ":", "result", ",", "orig", "=", "result", ",", "result", "try", ":", "#log.debug('setUp for %s', id(self));", "self", ".", "setUp", "(", ")", "except", "KeyboardInterrupt", ":", "raise", "except", ":", "self", ".", "error_context", "=", "'setup'", "result", ".", "addError", "(", "self", ",", "self", ".", "_exc_info", "(", ")", ")", "return", "try", ":", "for", "test", "in", "self", ".", "_tests", ":", "if", "(", "isinstance", "(", "test", ",", "nose", ".", "case", ".", "Test", ")", "and", "self", ".", "arg", "is", "not", "None", ")", ":", "test", ".", "test", ".", "arg", "=", "self", ".", "arg", "else", ":", "test", ".", "arg", "=", "self", ".", "arg", "test", ".", "testQueue", "=", "self", ".", "testQueue", "test", ".", "tasks", "=", "self", ".", "tasks", "if", "result", ".", "shouldStop", ":", "log", ".", "debug", "(", "\"stopping\"", ")", "break", "# each nose.case.Test will create its own result proxy", "# so the cases need the original result, to avoid proxy", "# chains", "#log.debug('running test %s in suite %s', test, self);", "try", ":", "test", "(", "orig", ")", "except", "KeyboardInterrupt", ",", "e", ":", "timeout", "=", "isinstance", "(", "e", ",", "TimedOutException", ")", "if", "timeout", ":", "msg", "=", "'Timeout when running test %s in suite %s'", "else", ":", "msg", "=", "'KeyboardInterrupt when running test %s in suite %s'", "log", ".", "debug", "(", "msg", ",", "test", ",", "self", ")", "err", "=", "(", "TimedOutException", ",", "TimedOutException", "(", "str", "(", "test", ")", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "test", ".", "config", ".", "plugins", ".", "addError", "(", "test", ",", "err", ")", "orig", ".", "addError", "(", "test", ",", "err", ")", "if", "not", "timeout", ":", "raise", "finally", ":", "self", ".", "has_run", "=", "True", "try", ":", "#log.debug('tearDown for %s', id(self));", "self", ".", "tearDown", "(", ")", "except", "KeyboardInterrupt", ":", "raise", "except", ":", "self", ".", "error_context", "=", "'teardown'", "result", ".", "addError", "(", "self", ",", "self", ".", "_exc_info", "(", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BuiltinTrap.add_builtin
Add a builtin and save the original.
environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py
def add_builtin(self, key, value): """Add a builtin and save the original.""" bdict = __builtin__.__dict__ orig = bdict.get(key, BuiltinUndefined) if value is HideBuiltin: if orig is not BuiltinUndefined: #same as 'key in bdict' self._orig_builtins[key] = orig del bdict[key] else: self._orig_builtins[key] = orig bdict[key] = value
def add_builtin(self, key, value): """Add a builtin and save the original.""" bdict = __builtin__.__dict__ orig = bdict.get(key, BuiltinUndefined) if value is HideBuiltin: if orig is not BuiltinUndefined: #same as 'key in bdict' self._orig_builtins[key] = orig del bdict[key] else: self._orig_builtins[key] = orig bdict[key] = value
[ "Add", "a", "builtin", "and", "save", "the", "original", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py#L79-L89
[ "def", "add_builtin", "(", "self", ",", "key", ",", "value", ")", ":", "bdict", "=", "__builtin__", ".", "__dict__", "orig", "=", "bdict", ".", "get", "(", "key", ",", "BuiltinUndefined", ")", "if", "value", "is", "HideBuiltin", ":", "if", "orig", "is", "not", "BuiltinUndefined", ":", "#same as 'key in bdict'", "self", ".", "_orig_builtins", "[", "key", "]", "=", "orig", "del", "bdict", "[", "key", "]", "else", ":", "self", ".", "_orig_builtins", "[", "key", "]", "=", "orig", "bdict", "[", "key", "]", "=", "value" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BuiltinTrap.remove_builtin
Remove an added builtin and re-set the original.
environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py
def remove_builtin(self, key, orig): """Remove an added builtin and re-set the original.""" if orig is BuiltinUndefined: del __builtin__.__dict__[key] else: __builtin__.__dict__[key] = orig
def remove_builtin(self, key, orig): """Remove an added builtin and re-set the original.""" if orig is BuiltinUndefined: del __builtin__.__dict__[key] else: __builtin__.__dict__[key] = orig
[ "Remove", "an", "added", "builtin", "and", "re", "-", "set", "the", "original", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py#L91-L96
[ "def", "remove_builtin", "(", "self", ",", "key", ",", "orig", ")", ":", "if", "orig", "is", "BuiltinUndefined", ":", "del", "__builtin__", ".", "__dict__", "[", "key", "]", "else", ":", "__builtin__", ".", "__dict__", "[", "key", "]", "=", "orig" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BuiltinTrap.activate
Store ipython references in the __builtin__ namespace.
environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py
def activate(self): """Store ipython references in the __builtin__ namespace.""" add_builtin = self.add_builtin for name, func in self.auto_builtins.iteritems(): add_builtin(name, func)
def activate(self): """Store ipython references in the __builtin__ namespace.""" add_builtin = self.add_builtin for name, func in self.auto_builtins.iteritems(): add_builtin(name, func)
[ "Store", "ipython", "references", "in", "the", "__builtin__", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py#L98-L103
[ "def", "activate", "(", "self", ")", ":", "add_builtin", "=", "self", ".", "add_builtin", "for", "name", ",", "func", "in", "self", ".", "auto_builtins", ".", "iteritems", "(", ")", ":", "add_builtin", "(", "name", ",", "func", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BuiltinTrap.deactivate
Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.
environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py
def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin for key, val in self._orig_builtins.iteritems(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False
def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin for key, val in self._orig_builtins.iteritems(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False
[ "Remove", "any", "builtins", "which", "might", "have", "been", "added", "by", "add_builtins", "or", "restore", "overwritten", "ones", "to", "their", "previous", "values", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/builtin_trap.py#L105-L112
[ "def", "deactivate", "(", "self", ")", ":", "remove_builtin", "=", "self", ".", "remove_builtin", "for", "key", ",", "val", "in", "self", ".", "_orig_builtins", ".", "iteritems", "(", ")", ":", "remove_builtin", "(", "key", ",", "val", ")", "self", ".", "_orig_builtins", ".", "clear", "(", ")", "self", ".", "_builtins_added", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PackageFinder._find_url_name
Finds the true URL name of a package, when the given name isn't quite correct. This is usually used to implement case-insensitivity.
virtualEnvironment/lib/python2.7/site-packages/pip/index.py
def _find_url_name(self, index_url, url_name, req): """ Finds the true URL name of a package, when the given name isn't quite correct. This is usually used to implement case-insensitivity. """ if not index_url.url.endswith('/'): # Vaguely part of the PyPI API... weird but true. # FIXME: bad to modify this? index_url.url += '/' page = self._get_page(index_url, req) if page is None: logger.critical('Cannot fetch index base URL %s', index_url) return norm_name = normalize_name(req.url_name) for link in page.links: base = posixpath.basename(link.path.rstrip('/')) if norm_name == normalize_name(base): logger.debug( 'Real name of requirement %s is %s', url_name, base, ) return base return None
def _find_url_name(self, index_url, url_name, req): """ Finds the true URL name of a package, when the given name isn't quite correct. This is usually used to implement case-insensitivity. """ if not index_url.url.endswith('/'): # Vaguely part of the PyPI API... weird but true. # FIXME: bad to modify this? index_url.url += '/' page = self._get_page(index_url, req) if page is None: logger.critical('Cannot fetch index base URL %s', index_url) return norm_name = normalize_name(req.url_name) for link in page.links: base = posixpath.basename(link.path.rstrip('/')) if norm_name == normalize_name(base): logger.debug( 'Real name of requirement %s is %s', url_name, base, ) return base return None
[ "Finds", "the", "true", "URL", "name", "of", "a", "package", "when", "the", "given", "name", "isn", "t", "quite", "correct", ".", "This", "is", "usually", "used", "to", "implement", "case", "-", "insensitivity", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/index.py#L528-L550
[ "def", "_find_url_name", "(", "self", ",", "index_url", ",", "url_name", ",", "req", ")", ":", "if", "not", "index_url", ".", "url", ".", "endswith", "(", "'/'", ")", ":", "# Vaguely part of the PyPI API... weird but true.", "# FIXME: bad to modify this?", "index_url", ".", "url", "+=", "'/'", "page", "=", "self", ".", "_get_page", "(", "index_url", ",", "req", ")", "if", "page", "is", "None", ":", "logger", ".", "critical", "(", "'Cannot fetch index base URL %s'", ",", "index_url", ")", "return", "norm_name", "=", "normalize_name", "(", "req", ".", "url_name", ")", "for", "link", "in", "page", ".", "links", ":", "base", "=", "posixpath", ".", "basename", "(", "link", ".", "path", ".", "rstrip", "(", "'/'", ")", ")", "if", "norm_name", "==", "normalize_name", "(", "base", ")", ":", "logger", ".", "debug", "(", "'Real name of requirement %s is %s'", ",", "url_name", ",", "base", ",", ")", "return", "base", "return", "None" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
PackageFinder._link_package_versions
Return an iterable of triples (pkg_resources_version_key, link, python_version) that can be extracted from the given link. Meant to be overridden by subclasses, not called by clients.
virtualEnvironment/lib/python2.7/site-packages/pip/index.py
def _link_package_versions(self, link, search_name): """ Return an iterable of triples (pkg_resources_version_key, link, python_version) that can be extracted from the given link. Meant to be overridden by subclasses, not called by clients. """ platform = get_platform() version = None if link.egg_fragment: egg_info = link.egg_fragment else: egg_info, ext = link.splitext() if not ext: if link not in self.logged_links: logger.debug('Skipping link %s; not a file', link) self.logged_links.add(link) return if egg_info.endswith('.tar'): # Special double-extension case: egg_info = egg_info[:-4] ext = '.tar' + ext if ext not in self._known_extensions(): if link not in self.logged_links: logger.debug( 'Skipping link %s; unknown archive format: %s', link, ext, ) self.logged_links.add(link) return if "macosx10" in link.path and ext == '.zip': if link not in self.logged_links: logger.debug('Skipping link %s; macosx10 one', link) self.logged_links.add(link) return if ext == wheel_ext: try: wheel = Wheel(link.filename) except InvalidWheelFilename: logger.debug( 'Skipping %s because the wheel filename is invalid', link ) return if (pkg_resources.safe_name(wheel.name).lower() != pkg_resources.safe_name(search_name).lower()): logger.debug( 'Skipping link %s; wrong project name (not %s)', link, search_name, ) return if not wheel.supported(): logger.debug( 'Skipping %s because it is not compatible with this ' 'Python', link, ) return # This is a dirty hack to prevent installing Binary Wheels from # PyPI unless it is a Windows or Mac Binary Wheel. This is # paired with a change to PyPI disabling uploads for the # same. Once we have a mechanism for enabling support for # binary wheels on linux that deals with the inherent problems # of binary distribution this can be removed. comes_from = getattr(link, "comes_from", None) if ( ( not platform.startswith('win') and not platform.startswith('macosx') and not platform == 'cli' ) and comes_from is not None and urllib_parse.urlparse( comes_from.url ).netloc.endswith(PyPI.netloc)): if not wheel.supported(tags=supported_tags_noarch): logger.debug( "Skipping %s because it is a pypi-hosted binary " "Wheel on an unsupported platform", link, ) return version = wheel.version if not version: version = self._egg_info_matches(egg_info, search_name, link) if version is None: logger.debug( 'Skipping link %s; wrong project name (not %s)', link, search_name, ) return if (link.internal is not None and not link.internal and not normalize_name(search_name).lower() in self.allow_external and not self.allow_all_external): # We have a link that we are sure is external, so we should skip # it unless we are allowing externals logger.debug("Skipping %s because it is externally hosted.", link) self.need_warn_external = True return if (link.verifiable is not None and not link.verifiable and not (normalize_name(search_name).lower() in self.allow_unverified)): # We have a link that we are sure we cannot verify its integrity, # so we should skip it unless we are allowing unsafe installs # for this requirement. logger.debug( "Skipping %s because it is an insecure and unverifiable file.", link, ) self.need_warn_unverified = True return match = self._py_version_re.search(version) if match: version = version[:match.start()] py_version = match.group(1) if py_version != sys.version[:3]: logger.debug( 'Skipping %s because Python version is incorrect', link ) return logger.debug('Found link %s, version: %s', link, version) return InstallationCandidate(search_name, version, link)
def _link_package_versions(self, link, search_name): """ Return an iterable of triples (pkg_resources_version_key, link, python_version) that can be extracted from the given link. Meant to be overridden by subclasses, not called by clients. """ platform = get_platform() version = None if link.egg_fragment: egg_info = link.egg_fragment else: egg_info, ext = link.splitext() if not ext: if link not in self.logged_links: logger.debug('Skipping link %s; not a file', link) self.logged_links.add(link) return if egg_info.endswith('.tar'): # Special double-extension case: egg_info = egg_info[:-4] ext = '.tar' + ext if ext not in self._known_extensions(): if link not in self.logged_links: logger.debug( 'Skipping link %s; unknown archive format: %s', link, ext, ) self.logged_links.add(link) return if "macosx10" in link.path and ext == '.zip': if link not in self.logged_links: logger.debug('Skipping link %s; macosx10 one', link) self.logged_links.add(link) return if ext == wheel_ext: try: wheel = Wheel(link.filename) except InvalidWheelFilename: logger.debug( 'Skipping %s because the wheel filename is invalid', link ) return if (pkg_resources.safe_name(wheel.name).lower() != pkg_resources.safe_name(search_name).lower()): logger.debug( 'Skipping link %s; wrong project name (not %s)', link, search_name, ) return if not wheel.supported(): logger.debug( 'Skipping %s because it is not compatible with this ' 'Python', link, ) return # This is a dirty hack to prevent installing Binary Wheels from # PyPI unless it is a Windows or Mac Binary Wheel. This is # paired with a change to PyPI disabling uploads for the # same. Once we have a mechanism for enabling support for # binary wheels on linux that deals with the inherent problems # of binary distribution this can be removed. comes_from = getattr(link, "comes_from", None) if ( ( not platform.startswith('win') and not platform.startswith('macosx') and not platform == 'cli' ) and comes_from is not None and urllib_parse.urlparse( comes_from.url ).netloc.endswith(PyPI.netloc)): if not wheel.supported(tags=supported_tags_noarch): logger.debug( "Skipping %s because it is a pypi-hosted binary " "Wheel on an unsupported platform", link, ) return version = wheel.version if not version: version = self._egg_info_matches(egg_info, search_name, link) if version is None: logger.debug( 'Skipping link %s; wrong project name (not %s)', link, search_name, ) return if (link.internal is not None and not link.internal and not normalize_name(search_name).lower() in self.allow_external and not self.allow_all_external): # We have a link that we are sure is external, so we should skip # it unless we are allowing externals logger.debug("Skipping %s because it is externally hosted.", link) self.need_warn_external = True return if (link.verifiable is not None and not link.verifiable and not (normalize_name(search_name).lower() in self.allow_unverified)): # We have a link that we are sure we cannot verify its integrity, # so we should skip it unless we are allowing unsafe installs # for this requirement. logger.debug( "Skipping %s because it is an insecure and unverifiable file.", link, ) self.need_warn_unverified = True return match = self._py_version_re.search(version) if match: version = version[:match.start()] py_version = match.group(1) if py_version != sys.version[:3]: logger.debug( 'Skipping %s because Python version is incorrect', link ) return logger.debug('Found link %s, version: %s', link, version) return InstallationCandidate(search_name, version, link)
[ "Return", "an", "iterable", "of", "triples", "(", "pkg_resources_version_key", "link", "python_version", ")", "that", "can", "be", "extracted", "from", "the", "given", "link", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/index.py#L631-L765
[ "def", "_link_package_versions", "(", "self", ",", "link", ",", "search_name", ")", ":", "platform", "=", "get_platform", "(", ")", "version", "=", "None", "if", "link", ".", "egg_fragment", ":", "egg_info", "=", "link", ".", "egg_fragment", "else", ":", "egg_info", ",", "ext", "=", "link", ".", "splitext", "(", ")", "if", "not", "ext", ":", "if", "link", "not", "in", "self", ".", "logged_links", ":", "logger", ".", "debug", "(", "'Skipping link %s; not a file'", ",", "link", ")", "self", ".", "logged_links", ".", "add", "(", "link", ")", "return", "if", "egg_info", ".", "endswith", "(", "'.tar'", ")", ":", "# Special double-extension case:", "egg_info", "=", "egg_info", "[", ":", "-", "4", "]", "ext", "=", "'.tar'", "+", "ext", "if", "ext", "not", "in", "self", ".", "_known_extensions", "(", ")", ":", "if", "link", "not", "in", "self", ".", "logged_links", ":", "logger", ".", "debug", "(", "'Skipping link %s; unknown archive format: %s'", ",", "link", ",", "ext", ",", ")", "self", ".", "logged_links", ".", "add", "(", "link", ")", "return", "if", "\"macosx10\"", "in", "link", ".", "path", "and", "ext", "==", "'.zip'", ":", "if", "link", "not", "in", "self", ".", "logged_links", ":", "logger", ".", "debug", "(", "'Skipping link %s; macosx10 one'", ",", "link", ")", "self", ".", "logged_links", ".", "add", "(", "link", ")", "return", "if", "ext", "==", "wheel_ext", ":", "try", ":", "wheel", "=", "Wheel", "(", "link", ".", "filename", ")", "except", "InvalidWheelFilename", ":", "logger", ".", "debug", "(", "'Skipping %s because the wheel filename is invalid'", ",", "link", ")", "return", "if", "(", "pkg_resources", ".", "safe_name", "(", "wheel", ".", "name", ")", ".", "lower", "(", ")", "!=", "pkg_resources", ".", "safe_name", "(", "search_name", ")", ".", "lower", "(", ")", ")", ":", "logger", ".", "debug", "(", "'Skipping link %s; wrong project name (not %s)'", ",", "link", ",", "search_name", ",", ")", "return", "if", "not", "wheel", ".", "supported", "(", ")", ":", "logger", ".", "debug", "(", "'Skipping %s because it is not compatible with this '", "'Python'", ",", "link", ",", ")", "return", "# This is a dirty hack to prevent installing Binary Wheels from", "# PyPI unless it is a Windows or Mac Binary Wheel. This is", "# paired with a change to PyPI disabling uploads for the", "# same. Once we have a mechanism for enabling support for", "# binary wheels on linux that deals with the inherent problems", "# of binary distribution this can be removed.", "comes_from", "=", "getattr", "(", "link", ",", "\"comes_from\"", ",", "None", ")", "if", "(", "(", "not", "platform", ".", "startswith", "(", "'win'", ")", "and", "not", "platform", ".", "startswith", "(", "'macosx'", ")", "and", "not", "platform", "==", "'cli'", ")", "and", "comes_from", "is", "not", "None", "and", "urllib_parse", ".", "urlparse", "(", "comes_from", ".", "url", ")", ".", "netloc", ".", "endswith", "(", "PyPI", ".", "netloc", ")", ")", ":", "if", "not", "wheel", ".", "supported", "(", "tags", "=", "supported_tags_noarch", ")", ":", "logger", ".", "debug", "(", "\"Skipping %s because it is a pypi-hosted binary \"", "\"Wheel on an unsupported platform\"", ",", "link", ",", ")", "return", "version", "=", "wheel", ".", "version", "if", "not", "version", ":", "version", "=", "self", ".", "_egg_info_matches", "(", "egg_info", ",", "search_name", ",", "link", ")", "if", "version", "is", "None", ":", "logger", ".", "debug", "(", "'Skipping link %s; wrong project name (not %s)'", ",", "link", ",", "search_name", ",", ")", "return", "if", "(", "link", ".", "internal", "is", "not", "None", "and", "not", "link", ".", "internal", "and", "not", "normalize_name", "(", "search_name", ")", ".", "lower", "(", ")", "in", "self", ".", "allow_external", "and", "not", "self", ".", "allow_all_external", ")", ":", "# We have a link that we are sure is external, so we should skip", "# it unless we are allowing externals", "logger", ".", "debug", "(", "\"Skipping %s because it is externally hosted.\"", ",", "link", ")", "self", ".", "need_warn_external", "=", "True", "return", "if", "(", "link", ".", "verifiable", "is", "not", "None", "and", "not", "link", ".", "verifiable", "and", "not", "(", "normalize_name", "(", "search_name", ")", ".", "lower", "(", ")", "in", "self", ".", "allow_unverified", ")", ")", ":", "# We have a link that we are sure we cannot verify its integrity,", "# so we should skip it unless we are allowing unsafe installs", "# for this requirement.", "logger", ".", "debug", "(", "\"Skipping %s because it is an insecure and unverifiable file.\"", ",", "link", ",", ")", "self", ".", "need_warn_unverified", "=", "True", "return", "match", "=", "self", ".", "_py_version_re", ".", "search", "(", "version", ")", "if", "match", ":", "version", "=", "version", "[", ":", "match", ".", "start", "(", ")", "]", "py_version", "=", "match", ".", "group", "(", "1", ")", "if", "py_version", "!=", "sys", ".", "version", "[", ":", "3", "]", ":", "logger", ".", "debug", "(", "'Skipping %s because Python version is incorrect'", ",", "link", ")", "return", "logger", ".", "debug", "(", "'Found link %s, version: %s'", ",", "link", ",", "version", ")", "return", "InstallationCandidate", "(", "search_name", ",", "version", ",", "link", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
HTMLPage.explicit_rel_links
Yields all links with the given relations
virtualEnvironment/lib/python2.7/site-packages/pip/index.py
def explicit_rel_links(self, rels=('homepage', 'download')): """Yields all links with the given relations""" rels = set(rels) for anchor in self.parsed.findall(".//a"): if anchor.get("rel") and anchor.get("href"): found_rels = set(anchor.get("rel").split()) # Determine the intersection between what rels were found and # what rels were being looked for if found_rels & rels: href = anchor.get("href") url = self.clean_link( urllib_parse.urljoin(self.base_url, href) ) yield Link(url, self, trusted=False)
def explicit_rel_links(self, rels=('homepage', 'download')): """Yields all links with the given relations""" rels = set(rels) for anchor in self.parsed.findall(".//a"): if anchor.get("rel") and anchor.get("href"): found_rels = set(anchor.get("rel").split()) # Determine the intersection between what rels were found and # what rels were being looked for if found_rels & rels: href = anchor.get("href") url = self.clean_link( urllib_parse.urljoin(self.base_url, href) ) yield Link(url, self, trusted=False)
[ "Yields", "all", "links", "with", "the", "given", "relations" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/index.py#L993-L1007
[ "def", "explicit_rel_links", "(", "self", ",", "rels", "=", "(", "'homepage'", ",", "'download'", ")", ")", ":", "rels", "=", "set", "(", "rels", ")", "for", "anchor", "in", "self", ".", "parsed", ".", "findall", "(", "\".//a\"", ")", ":", "if", "anchor", ".", "get", "(", "\"rel\"", ")", "and", "anchor", ".", "get", "(", "\"href\"", ")", ":", "found_rels", "=", "set", "(", "anchor", ".", "get", "(", "\"rel\"", ")", ".", "split", "(", ")", ")", "# Determine the intersection between what rels were found and", "# what rels were being looked for", "if", "found_rels", "&", "rels", ":", "href", "=", "anchor", ".", "get", "(", "\"href\"", ")", "url", "=", "self", ".", "clean_link", "(", "urllib_parse", ".", "urljoin", "(", "self", ".", "base_url", ",", "href", ")", ")", "yield", "Link", "(", "url", ",", "self", ",", "trusted", "=", "False", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
send_multi_alt_email
Send a message to one more email address(s). With text content as primary and html content as alternative.
toolware/utils/email.py
def send_multi_alt_email( subject, # single line with no line-breaks text_content, to_emails, html_content=None, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With text content as primary and html content as alternative. """ messenger = EmailMultiAlternatives(subject, text_content, from_email, to_emails) if html_content: messenger.attach_alternative(html_content, "text/html") try: messenger.send() except Exception as e: if not fail_silently: raise
def send_multi_alt_email( subject, # single line with no line-breaks text_content, to_emails, html_content=None, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With text content as primary and html content as alternative. """ messenger = EmailMultiAlternatives(subject, text_content, from_email, to_emails) if html_content: messenger.attach_alternative(html_content, "text/html") try: messenger.send() except Exception as e: if not fail_silently: raise
[ "Send", "a", "message", "to", "one", "more", "email", "address", "(", "s", ")", ".", "With", "text", "content", "as", "primary", "and", "html", "content", "as", "alternative", "." ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/email.py#L15-L34
[ "def", "send_multi_alt_email", "(", "subject", ",", "# single line with no line-breaks", "text_content", ",", "to_emails", ",", "html_content", "=", "None", ",", "from_email", "=", "DEFAULT_FROM_EMAIL", ",", "fail_silently", "=", "True", ")", ":", "messenger", "=", "EmailMultiAlternatives", "(", "subject", ",", "text_content", ",", "from_email", ",", "to_emails", ")", "if", "html_content", ":", "messenger", ".", "attach_alternative", "(", "html_content", ",", "\"text/html\"", ")", "try", ":", "messenger", ".", "send", "(", ")", "except", "Exception", "as", "e", ":", "if", "not", "fail_silently", ":", "raise" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
send_html_email
Send a message to one more email address(s). With html content as primary.
toolware/utils/email.py
def send_html_email( subject, # single line with no line-breaks html_content, to_emails, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With html content as primary. """ messenger = EmailMessage(subject, html_content, from_email, to_emails) messenger.content_subtype = "html" # Main content is now text/html try: messenger.send() except Exception as e: if not fail_silently: raise
def send_html_email( subject, # single line with no line-breaks html_content, to_emails, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With html content as primary. """ messenger = EmailMessage(subject, html_content, from_email, to_emails) messenger.content_subtype = "html" # Main content is now text/html try: messenger.send() except Exception as e: if not fail_silently: raise
[ "Send", "a", "message", "to", "one", "more", "email", "address", "(", "s", ")", ".", "With", "html", "content", "as", "primary", "." ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/email.py#L37-L54
[ "def", "send_html_email", "(", "subject", ",", "# single line with no line-breaks", "html_content", ",", "to_emails", ",", "from_email", "=", "DEFAULT_FROM_EMAIL", ",", "fail_silently", "=", "True", ")", ":", "messenger", "=", "EmailMessage", "(", "subject", ",", "html_content", ",", "from_email", ",", "to_emails", ")", "messenger", ".", "content_subtype", "=", "\"html\"", "# Main content is now text/html", "try", ":", "messenger", ".", "send", "(", ")", "except", "Exception", "as", "e", ":", "if", "not", "fail_silently", ":", "raise" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
trim_form
Returns a form that only contains a subset of the original fields (opcode: incude/exclude fields) Exampel: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form fields biz_name,biz_city,biz_email,biz_phone as new_form %} {{ new_form.as_ul }} </ul> </fieldset> OR: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form exclude biz_country,biz_url as new_form %} {{ new_form.as_ul }} </ul> </fieldset>
toolware/templatetags/forms.py
def trim_form(parser, token): """ Returns a form that only contains a subset of the original fields (opcode: incude/exclude fields) Exampel: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form fields biz_name,biz_city,biz_email,biz_phone as new_form %} {{ new_form.as_ul }} </ul> </fieldset> OR: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form exclude biz_country,biz_url as new_form %} {{ new_form.as_ul }} </ul> </fieldset> """ try: trim_form, orig_form, opcode, fields, as_, new_form = token.split_contents() except ValueError: raise template.TemplateSyntaxError('Invalid arguments for %r' % token.split_contents()[0]) return FieldSetNode(opcode, fields.split(','), orig_form, new_form)
def trim_form(parser, token): """ Returns a form that only contains a subset of the original fields (opcode: incude/exclude fields) Exampel: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form fields biz_name,biz_city,biz_email,biz_phone as new_form %} {{ new_form.as_ul }} </ul> </fieldset> OR: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form exclude biz_country,biz_url as new_form %} {{ new_form.as_ul }} </ul> </fieldset> """ try: trim_form, orig_form, opcode, fields, as_, new_form = token.split_contents() except ValueError: raise template.TemplateSyntaxError('Invalid arguments for %r' % token.split_contents()[0]) return FieldSetNode(opcode, fields.split(','), orig_form, new_form)
[ "Returns", "a", "form", "that", "only", "contains", "a", "subset", "of", "the", "original", "fields", "(", "opcode", ":", "incude", "/", "exclude", "fields", ")", "Exampel", ":", "<fieldset", ">", "<legend", ">", "Business", "Info<", "/", "legend", ">", "<ul", ">", "{", "%", "trim_form", "orig_form", "fields", "biz_name", "biz_city", "biz_email", "biz_phone", "as", "new_form", "%", "}", "{{", "new_form", ".", "as_ul", "}}", "<", "/", "ul", ">", "<", "/", "fieldset", ">", "OR", ":", "<fieldset", ">", "<legend", ">", "Business", "Info<", "/", "legend", ">", "<ul", ">", "{", "%", "trim_form", "orig_form", "exclude", "biz_country", "biz_url", "as", "new_form", "%", "}", "{{", "new_form", ".", "as_ul", "}}", "<", "/", "ul", ">", "<", "/", "fieldset", ">" ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/templatetags/forms.py#L31-L56
[ "def", "trim_form", "(", "parser", ",", "token", ")", ":", "try", ":", "trim_form", ",", "orig_form", ",", "opcode", ",", "fields", ",", "as_", ",", "new_form", "=", "token", ".", "split_contents", "(", ")", "except", "ValueError", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "'Invalid arguments for %r'", "%", "token", ".", "split_contents", "(", ")", "[", "0", "]", ")", "return", "FieldSetNode", "(", "opcode", ",", "fields", ".", "split", "(", "','", ")", ",", "orig_form", ",", "new_form", ")" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
unshell_list
Turn a command-line argument into a list.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def unshell_list(s): """Turn a command-line argument into a list.""" if not s: return None if sys.platform == 'win32': # When running coverage as coverage.exe, some of the behavior # of the shell is emulated: wildcards are expanded into a list of # filenames. So you have to single-quote patterns on the command # line, but (not) helpfully, the single quotes are included in the # argument, so we have to strip them off here. s = s.strip("'") return s.split(',')
def unshell_list(s): """Turn a command-line argument into a list.""" if not s: return None if sys.platform == 'win32': # When running coverage as coverage.exe, some of the behavior # of the shell is emulated: wildcards are expanded into a list of # filenames. So you have to single-quote patterns on the command # line, but (not) helpfully, the single quotes are included in the # argument, so we have to strip them off here. s = s.strip("'") return s.split(',')
[ "Turn", "a", "command", "-", "line", "argument", "into", "a", "list", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L617-L628
[ "def", "unshell_list", "(", "s", ")", ":", "if", "not", "s", ":", "return", "None", "if", "sys", ".", "platform", "==", "'win32'", ":", "# When running coverage as coverage.exe, some of the behavior", "# of the shell is emulated: wildcards are expanded into a list of", "# filenames. So you have to single-quote patterns on the command", "# line, but (not) helpfully, the single quotes are included in the", "# argument, so we have to strip them off here.", "s", "=", "s", ".", "strip", "(", "\"'\"", ")", "return", "s", ".", "split", "(", "','", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
main
The main entry point to Coverage. This is installed as the script entry point.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def main(argv=None): """The main entry point to Coverage. This is installed as the script entry point. """ if argv is None: argv = sys.argv[1:] try: start = time.clock() status = CoverageScript().command_line(argv) end = time.clock() if 0: print("time: %.3fs" % (end - start)) except ExceptionDuringRun: # An exception was caught while running the product code. The # sys.exc_info() return tuple is packed into an ExceptionDuringRun # exception. _, err, _ = sys.exc_info() traceback.print_exception(*err.args) status = ERR except CoverageException: # A controlled error inside coverage.py: print the message to the user. _, err, _ = sys.exc_info() print(err) status = ERR except SystemExit: # The user called `sys.exit()`. Exit with their argument, if any. _, err, _ = sys.exc_info() if err.args: status = err.args[0] else: status = None return status
def main(argv=None): """The main entry point to Coverage. This is installed as the script entry point. """ if argv is None: argv = sys.argv[1:] try: start = time.clock() status = CoverageScript().command_line(argv) end = time.clock() if 0: print("time: %.3fs" % (end - start)) except ExceptionDuringRun: # An exception was caught while running the product code. The # sys.exc_info() return tuple is packed into an ExceptionDuringRun # exception. _, err, _ = sys.exc_info() traceback.print_exception(*err.args) status = ERR except CoverageException: # A controlled error inside coverage.py: print the message to the user. _, err, _ = sys.exc_info() print(err) status = ERR except SystemExit: # The user called `sys.exit()`. Exit with their argument, if any. _, err, _ = sys.exc_info() if err.args: status = err.args[0] else: status = None return status
[ "The", "main", "entry", "point", "to", "Coverage", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L711-L744
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "try", ":", "start", "=", "time", ".", "clock", "(", ")", "status", "=", "CoverageScript", "(", ")", ".", "command_line", "(", "argv", ")", "end", "=", "time", ".", "clock", "(", ")", "if", "0", ":", "print", "(", "\"time: %.3fs\"", "%", "(", "end", "-", "start", ")", ")", "except", "ExceptionDuringRun", ":", "# An exception was caught while running the product code. The", "# sys.exc_info() return tuple is packed into an ExceptionDuringRun", "# exception.", "_", ",", "err", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "traceback", ".", "print_exception", "(", "*", "err", ".", "args", ")", "status", "=", "ERR", "except", "CoverageException", ":", "# A controlled error inside coverage.py: print the message to the user.", "_", ",", "err", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "print", "(", "err", ")", "status", "=", "ERR", "except", "SystemExit", ":", "# The user called `sys.exit()`. Exit with their argument, if any.", "_", ",", "err", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "err", ".", "args", ":", "status", "=", "err", ".", "args", "[", "0", "]", "else", ":", "status", "=", "None", "return", "status" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageOptionParser.parse_args
Call optparse.parse_args, but return a triple: (ok, options, args)
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def parse_args(self, args=None, options=None): """Call optparse.parse_args, but return a triple: (ok, options, args) """ try: options, args = \ super(CoverageOptionParser, self).parse_args(args, options) except self.OptionParserError: return False, None, None return True, options, args
def parse_args(self, args=None, options=None): """Call optparse.parse_args, but return a triple: (ok, options, args) """ try: options, args = \ super(CoverageOptionParser, self).parse_args(args, options) except self.OptionParserError: return False, None, None return True, options, args
[ "Call", "optparse", ".", "parse_args", "but", "return", "a", "triple", ":" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L155-L166
[ "def", "parse_args", "(", "self", ",", "args", "=", "None", ",", "options", "=", "None", ")", ":", "try", ":", "options", ",", "args", "=", "super", "(", "CoverageOptionParser", ",", "self", ")", ".", "parse_args", "(", "args", ",", "options", ")", "except", "self", ".", "OptionParserError", ":", "return", "False", ",", "None", ",", "None", "return", "True", ",", "options", ",", "args" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
ClassicOptionParser.add_action
Add a specialized option that is the action to execute.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def add_action(self, dash, dashdash, action_code): """Add a specialized option that is the action to execute.""" option = self.add_option(dash, dashdash, action='callback', callback=self._append_action ) option.action_code = action_code
def add_action(self, dash, dashdash, action_code): """Add a specialized option that is the action to execute.""" option = self.add_option(dash, dashdash, action='callback', callback=self._append_action ) option.action_code = action_code
[ "Add", "a", "specialized", "option", "that", "is", "the", "action", "to", "execute", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L199-L204
[ "def", "add_action", "(", "self", ",", "dash", ",", "dashdash", ",", "action_code", ")", ":", "option", "=", "self", ".", "add_option", "(", "dash", ",", "dashdash", ",", "action", "=", "'callback'", ",", "callback", "=", "self", ".", "_append_action", ")", "option", ".", "action_code", "=", "action_code" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
ClassicOptionParser._append_action
Callback for an option that adds to the `actions` list.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def _append_action(self, option, opt_unused, value_unused, parser): """Callback for an option that adds to the `actions` list.""" parser.values.actions.append(option.action_code)
def _append_action(self, option, opt_unused, value_unused, parser): """Callback for an option that adds to the `actions` list.""" parser.values.actions.append(option.action_code)
[ "Callback", "for", "an", "option", "that", "adds", "to", "the", "actions", "list", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L206-L208
[ "def", "_append_action", "(", "self", ",", "option", ",", "opt_unused", ",", "value_unused", ",", "parser", ")", ":", "parser", ".", "values", ".", "actions", ".", "append", "(", "option", ".", "action_code", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageScript.command_line
The bulk of the command line interface to Coverage. `argv` is the argument list to process. Returns 0 if all is well, 1 if something went wrong.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def command_line(self, argv): """The bulk of the command line interface to Coverage. `argv` is the argument list to process. Returns 0 if all is well, 1 if something went wrong. """ # Collect the command-line options. if not argv: self.help_fn(topic='minimum_help') return OK # The command syntax we parse depends on the first argument. Classic # syntax always starts with an option. self.classic = argv[0].startswith('-') if self.classic: parser = ClassicOptionParser() else: parser = CMDS.get(argv[0]) if not parser: self.help_fn("Unknown command: '%s'" % argv[0]) return ERR argv = argv[1:] parser.help_fn = self.help_fn ok, options, args = parser.parse_args(argv) if not ok: return ERR # Handle help and version. if self.do_help(options, args, parser): return OK # Check for conflicts and problems in the options. if not self.args_ok(options, args): return ERR # Listify the list options. source = unshell_list(options.source) omit = unshell_list(options.omit) include = unshell_list(options.include) debug = unshell_list(options.debug) # Do something. self.coverage = self.covpkg.coverage( data_suffix = options.parallel_mode, cover_pylib = options.pylib, timid = options.timid, branch = options.branch, config_file = options.rcfile, source = source, omit = omit, include = include, debug = debug, ) if 'debug' in options.actions: return self.do_debug(args) if 'erase' in options.actions or options.erase_first: self.coverage.erase() else: self.coverage.load() if 'execute' in options.actions: self.do_execute(options, args) if 'combine' in options.actions: self.coverage.combine() self.coverage.save() # Remaining actions are reporting, with some common options. report_args = dict( morfs = args, ignore_errors = options.ignore_errors, omit = omit, include = include, ) if 'report' in options.actions: total = self.coverage.report( show_missing=options.show_missing, **report_args) if 'annotate' in options.actions: self.coverage.annotate( directory=options.directory, **report_args) if 'html' in options.actions: total = self.coverage.html_report( directory=options.directory, title=options.title, **report_args) if 'xml' in options.actions: outfile = options.outfile total = self.coverage.xml_report(outfile=outfile, **report_args) if options.fail_under is not None: if total >= options.fail_under: return OK else: return FAIL_UNDER else: return OK
def command_line(self, argv): """The bulk of the command line interface to Coverage. `argv` is the argument list to process. Returns 0 if all is well, 1 if something went wrong. """ # Collect the command-line options. if not argv: self.help_fn(topic='minimum_help') return OK # The command syntax we parse depends on the first argument. Classic # syntax always starts with an option. self.classic = argv[0].startswith('-') if self.classic: parser = ClassicOptionParser() else: parser = CMDS.get(argv[0]) if not parser: self.help_fn("Unknown command: '%s'" % argv[0]) return ERR argv = argv[1:] parser.help_fn = self.help_fn ok, options, args = parser.parse_args(argv) if not ok: return ERR # Handle help and version. if self.do_help(options, args, parser): return OK # Check for conflicts and problems in the options. if not self.args_ok(options, args): return ERR # Listify the list options. source = unshell_list(options.source) omit = unshell_list(options.omit) include = unshell_list(options.include) debug = unshell_list(options.debug) # Do something. self.coverage = self.covpkg.coverage( data_suffix = options.parallel_mode, cover_pylib = options.pylib, timid = options.timid, branch = options.branch, config_file = options.rcfile, source = source, omit = omit, include = include, debug = debug, ) if 'debug' in options.actions: return self.do_debug(args) if 'erase' in options.actions or options.erase_first: self.coverage.erase() else: self.coverage.load() if 'execute' in options.actions: self.do_execute(options, args) if 'combine' in options.actions: self.coverage.combine() self.coverage.save() # Remaining actions are reporting, with some common options. report_args = dict( morfs = args, ignore_errors = options.ignore_errors, omit = omit, include = include, ) if 'report' in options.actions: total = self.coverage.report( show_missing=options.show_missing, **report_args) if 'annotate' in options.actions: self.coverage.annotate( directory=options.directory, **report_args) if 'html' in options.actions: total = self.coverage.html_report( directory=options.directory, title=options.title, **report_args) if 'xml' in options.actions: outfile = options.outfile total = self.coverage.xml_report(outfile=outfile, **report_args) if options.fail_under is not None: if total >= options.fail_under: return OK else: return FAIL_UNDER else: return OK
[ "The", "bulk", "of", "the", "command", "line", "interface", "to", "Coverage", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L372-L472
[ "def", "command_line", "(", "self", ",", "argv", ")", ":", "# Collect the command-line options.", "if", "not", "argv", ":", "self", ".", "help_fn", "(", "topic", "=", "'minimum_help'", ")", "return", "OK", "# The command syntax we parse depends on the first argument. Classic", "# syntax always starts with an option.", "self", ".", "classic", "=", "argv", "[", "0", "]", ".", "startswith", "(", "'-'", ")", "if", "self", ".", "classic", ":", "parser", "=", "ClassicOptionParser", "(", ")", "else", ":", "parser", "=", "CMDS", ".", "get", "(", "argv", "[", "0", "]", ")", "if", "not", "parser", ":", "self", ".", "help_fn", "(", "\"Unknown command: '%s'\"", "%", "argv", "[", "0", "]", ")", "return", "ERR", "argv", "=", "argv", "[", "1", ":", "]", "parser", ".", "help_fn", "=", "self", ".", "help_fn", "ok", ",", "options", ",", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "if", "not", "ok", ":", "return", "ERR", "# Handle help and version.", "if", "self", ".", "do_help", "(", "options", ",", "args", ",", "parser", ")", ":", "return", "OK", "# Check for conflicts and problems in the options.", "if", "not", "self", ".", "args_ok", "(", "options", ",", "args", ")", ":", "return", "ERR", "# Listify the list options.", "source", "=", "unshell_list", "(", "options", ".", "source", ")", "omit", "=", "unshell_list", "(", "options", ".", "omit", ")", "include", "=", "unshell_list", "(", "options", ".", "include", ")", "debug", "=", "unshell_list", "(", "options", ".", "debug", ")", "# Do something.", "self", ".", "coverage", "=", "self", ".", "covpkg", ".", "coverage", "(", "data_suffix", "=", "options", ".", "parallel_mode", ",", "cover_pylib", "=", "options", ".", "pylib", ",", "timid", "=", "options", ".", "timid", ",", "branch", "=", "options", ".", "branch", ",", "config_file", "=", "options", ".", "rcfile", ",", "source", "=", "source", ",", "omit", "=", "omit", ",", "include", "=", "include", ",", "debug", "=", "debug", ",", ")", "if", "'debug'", "in", "options", ".", "actions", ":", "return", "self", ".", "do_debug", "(", "args", ")", "if", "'erase'", "in", "options", ".", "actions", "or", "options", ".", "erase_first", ":", "self", ".", "coverage", ".", "erase", "(", ")", "else", ":", "self", ".", "coverage", ".", "load", "(", ")", "if", "'execute'", "in", "options", ".", "actions", ":", "self", ".", "do_execute", "(", "options", ",", "args", ")", "if", "'combine'", "in", "options", ".", "actions", ":", "self", ".", "coverage", ".", "combine", "(", ")", "self", ".", "coverage", ".", "save", "(", ")", "# Remaining actions are reporting, with some common options.", "report_args", "=", "dict", "(", "morfs", "=", "args", ",", "ignore_errors", "=", "options", ".", "ignore_errors", ",", "omit", "=", "omit", ",", "include", "=", "include", ",", ")", "if", "'report'", "in", "options", ".", "actions", ":", "total", "=", "self", ".", "coverage", ".", "report", "(", "show_missing", "=", "options", ".", "show_missing", ",", "*", "*", "report_args", ")", "if", "'annotate'", "in", "options", ".", "actions", ":", "self", ".", "coverage", ".", "annotate", "(", "directory", "=", "options", ".", "directory", ",", "*", "*", "report_args", ")", "if", "'html'", "in", "options", ".", "actions", ":", "total", "=", "self", ".", "coverage", ".", "html_report", "(", "directory", "=", "options", ".", "directory", ",", "title", "=", "options", ".", "title", ",", "*", "*", "report_args", ")", "if", "'xml'", "in", "options", ".", "actions", ":", "outfile", "=", "options", ".", "outfile", "total", "=", "self", ".", "coverage", ".", "xml_report", "(", "outfile", "=", "outfile", ",", "*", "*", "report_args", ")", "if", "options", ".", "fail_under", "is", "not", "None", ":", "if", "total", ">=", "options", ".", "fail_under", ":", "return", "OK", "else", ":", "return", "FAIL_UNDER", "else", ":", "return", "OK" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageScript.help
Display an error message, or the named topic.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def help(self, error=None, topic=None, parser=None): """Display an error message, or the named topic.""" assert error or topic or parser if error: print(error) print("Use 'coverage help' for help.") elif parser: print(parser.format_help().strip()) else: help_msg = HELP_TOPICS.get(topic, '').strip() if help_msg: print(help_msg % self.covpkg.__dict__) else: print("Don't know topic %r" % topic)
def help(self, error=None, topic=None, parser=None): """Display an error message, or the named topic.""" assert error or topic or parser if error: print(error) print("Use 'coverage help' for help.") elif parser: print(parser.format_help().strip()) else: help_msg = HELP_TOPICS.get(topic, '').strip() if help_msg: print(help_msg % self.covpkg.__dict__) else: print("Don't know topic %r" % topic)
[ "Display", "an", "error", "message", "or", "the", "named", "topic", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L474-L487
[ "def", "help", "(", "self", ",", "error", "=", "None", ",", "topic", "=", "None", ",", "parser", "=", "None", ")", ":", "assert", "error", "or", "topic", "or", "parser", "if", "error", ":", "print", "(", "error", ")", "print", "(", "\"Use 'coverage help' for help.\"", ")", "elif", "parser", ":", "print", "(", "parser", ".", "format_help", "(", ")", ".", "strip", "(", ")", ")", "else", ":", "help_msg", "=", "HELP_TOPICS", ".", "get", "(", "topic", ",", "''", ")", ".", "strip", "(", ")", "if", "help_msg", ":", "print", "(", "help_msg", "%", "self", ".", "covpkg", ".", "__dict__", ")", "else", ":", "print", "(", "\"Don't know topic %r\"", "%", "topic", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageScript.do_help
Deal with help requests. Return True if it handled the request, False if not.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def do_help(self, options, args, parser): """Deal with help requests. Return True if it handled the request, False if not. """ # Handle help. if options.help: if self.classic: self.help_fn(topic='help') else: self.help_fn(parser=parser) return True if "help" in options.actions: if args: for a in args: parser = CMDS.get(a) if parser: self.help_fn(parser=parser) else: self.help_fn(topic=a) else: self.help_fn(topic='help') return True # Handle version. if options.version: self.help_fn(topic='version') return True return False
def do_help(self, options, args, parser): """Deal with help requests. Return True if it handled the request, False if not. """ # Handle help. if options.help: if self.classic: self.help_fn(topic='help') else: self.help_fn(parser=parser) return True if "help" in options.actions: if args: for a in args: parser = CMDS.get(a) if parser: self.help_fn(parser=parser) else: self.help_fn(topic=a) else: self.help_fn(topic='help') return True # Handle version. if options.version: self.help_fn(topic='version') return True return False
[ "Deal", "with", "help", "requests", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L489-L520
[ "def", "do_help", "(", "self", ",", "options", ",", "args", ",", "parser", ")", ":", "# Handle help.", "if", "options", ".", "help", ":", "if", "self", ".", "classic", ":", "self", ".", "help_fn", "(", "topic", "=", "'help'", ")", "else", ":", "self", ".", "help_fn", "(", "parser", "=", "parser", ")", "return", "True", "if", "\"help\"", "in", "options", ".", "actions", ":", "if", "args", ":", "for", "a", "in", "args", ":", "parser", "=", "CMDS", ".", "get", "(", "a", ")", "if", "parser", ":", "self", ".", "help_fn", "(", "parser", "=", "parser", ")", "else", ":", "self", ".", "help_fn", "(", "topic", "=", "a", ")", "else", ":", "self", ".", "help_fn", "(", "topic", "=", "'help'", ")", "return", "True", "# Handle version.", "if", "options", ".", "version", ":", "self", ".", "help_fn", "(", "topic", "=", "'version'", ")", "return", "True", "return", "False" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageScript.args_ok
Check for conflicts and problems in the options. Returns True if everything is ok, or False if not.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def args_ok(self, options, args): """Check for conflicts and problems in the options. Returns True if everything is ok, or False if not. """ for i in ['erase', 'execute']: for j in ['annotate', 'html', 'report', 'combine']: if (i in options.actions) and (j in options.actions): self.help_fn("You can't specify the '%s' and '%s' " "options at the same time." % (i, j)) return False if not options.actions: self.help_fn( "You must specify at least one of -e, -x, -c, -r, -a, or -b." ) return False args_allowed = ( 'execute' in options.actions or 'annotate' in options.actions or 'html' in options.actions or 'debug' in options.actions or 'report' in options.actions or 'xml' in options.actions ) if not args_allowed and args: self.help_fn("Unexpected arguments: %s" % " ".join(args)) return False if 'execute' in options.actions and not args: self.help_fn("Nothing to do.") return False return True
def args_ok(self, options, args): """Check for conflicts and problems in the options. Returns True if everything is ok, or False if not. """ for i in ['erase', 'execute']: for j in ['annotate', 'html', 'report', 'combine']: if (i in options.actions) and (j in options.actions): self.help_fn("You can't specify the '%s' and '%s' " "options at the same time." % (i, j)) return False if not options.actions: self.help_fn( "You must specify at least one of -e, -x, -c, -r, -a, or -b." ) return False args_allowed = ( 'execute' in options.actions or 'annotate' in options.actions or 'html' in options.actions or 'debug' in options.actions or 'report' in options.actions or 'xml' in options.actions ) if not args_allowed and args: self.help_fn("Unexpected arguments: %s" % " ".join(args)) return False if 'execute' in options.actions and not args: self.help_fn("Nothing to do.") return False return True
[ "Check", "for", "conflicts", "and", "problems", "in", "the", "options", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L522-L556
[ "def", "args_ok", "(", "self", ",", "options", ",", "args", ")", ":", "for", "i", "in", "[", "'erase'", ",", "'execute'", "]", ":", "for", "j", "in", "[", "'annotate'", ",", "'html'", ",", "'report'", ",", "'combine'", "]", ":", "if", "(", "i", "in", "options", ".", "actions", ")", "and", "(", "j", "in", "options", ".", "actions", ")", ":", "self", ".", "help_fn", "(", "\"You can't specify the '%s' and '%s' \"", "\"options at the same time.\"", "%", "(", "i", ",", "j", ")", ")", "return", "False", "if", "not", "options", ".", "actions", ":", "self", ".", "help_fn", "(", "\"You must specify at least one of -e, -x, -c, -r, -a, or -b.\"", ")", "return", "False", "args_allowed", "=", "(", "'execute'", "in", "options", ".", "actions", "or", "'annotate'", "in", "options", ".", "actions", "or", "'html'", "in", "options", ".", "actions", "or", "'debug'", "in", "options", ".", "actions", "or", "'report'", "in", "options", ".", "actions", "or", "'xml'", "in", "options", ".", "actions", ")", "if", "not", "args_allowed", "and", "args", ":", "self", ".", "help_fn", "(", "\"Unexpected arguments: %s\"", "%", "\" \"", ".", "join", "(", "args", ")", ")", "return", "False", "if", "'execute'", "in", "options", ".", "actions", "and", "not", "args", ":", "self", ".", "help_fn", "(", "\"Nothing to do.\"", ")", "return", "False", "return", "True" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageScript.do_execute
Implementation of 'coverage run'.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def do_execute(self, options, args): """Implementation of 'coverage run'.""" # Set the first path element properly. old_path0 = sys.path[0] # Run the script. self.coverage.start() code_ran = True try: try: if options.module: sys.path[0] = '' self.run_python_module(args[0], args) else: filename = args[0] sys.path[0] = os.path.abspath(os.path.dirname(filename)) self.run_python_file(filename, args) except NoSource: code_ran = False raise finally: self.coverage.stop() if code_ran: self.coverage.save() # Restore the old path sys.path[0] = old_path0
def do_execute(self, options, args): """Implementation of 'coverage run'.""" # Set the first path element properly. old_path0 = sys.path[0] # Run the script. self.coverage.start() code_ran = True try: try: if options.module: sys.path[0] = '' self.run_python_module(args[0], args) else: filename = args[0] sys.path[0] = os.path.abspath(os.path.dirname(filename)) self.run_python_file(filename, args) except NoSource: code_ran = False raise finally: self.coverage.stop() if code_ran: self.coverage.save() # Restore the old path sys.path[0] = old_path0
[ "Implementation", "of", "coverage", "run", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L558-L585
[ "def", "do_execute", "(", "self", ",", "options", ",", "args", ")", ":", "# Set the first path element properly.", "old_path0", "=", "sys", ".", "path", "[", "0", "]", "# Run the script.", "self", ".", "coverage", ".", "start", "(", ")", "code_ran", "=", "True", "try", ":", "try", ":", "if", "options", ".", "module", ":", "sys", ".", "path", "[", "0", "]", "=", "''", "self", ".", "run_python_module", "(", "args", "[", "0", "]", ",", "args", ")", "else", ":", "filename", "=", "args", "[", "0", "]", "sys", ".", "path", "[", "0", "]", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "self", ".", "run_python_file", "(", "filename", ",", "args", ")", "except", "NoSource", ":", "code_ran", "=", "False", "raise", "finally", ":", "self", ".", "coverage", ".", "stop", "(", ")", "if", "code_ran", ":", "self", ".", "coverage", ".", "save", "(", ")", "# Restore the old path", "sys", ".", "path", "[", "0", "]", "=", "old_path0" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageScript.do_debug
Implementation of 'coverage debug'.
virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py
def do_debug(self, args): """Implementation of 'coverage debug'.""" if not args: self.help_fn("What information would you like: data, sys?") return ERR for info in args: if info == 'sys': print("-- sys ----------------------------------------") for line in info_formatter(self.coverage.sysinfo()): print(" %s" % line) elif info == 'data': print("-- data ---------------------------------------") self.coverage.load() print("path: %s" % self.coverage.data.filename) print("has_arcs: %r" % self.coverage.data.has_arcs()) summary = self.coverage.data.summary(fullpath=True) if summary: filenames = sorted(summary.keys()) print("\n%d files:" % len(filenames)) for f in filenames: print("%s: %d lines" % (f, summary[f])) else: print("No data collected") else: self.help_fn("Don't know what you mean by %r" % info) return ERR return OK
def do_debug(self, args): """Implementation of 'coverage debug'.""" if not args: self.help_fn("What information would you like: data, sys?") return ERR for info in args: if info == 'sys': print("-- sys ----------------------------------------") for line in info_formatter(self.coverage.sysinfo()): print(" %s" % line) elif info == 'data': print("-- data ---------------------------------------") self.coverage.load() print("path: %s" % self.coverage.data.filename) print("has_arcs: %r" % self.coverage.data.has_arcs()) summary = self.coverage.data.summary(fullpath=True) if summary: filenames = sorted(summary.keys()) print("\n%d files:" % len(filenames)) for f in filenames: print("%s: %d lines" % (f, summary[f])) else: print("No data collected") else: self.help_fn("Don't know what you mean by %r" % info) return ERR return OK
[ "Implementation", "of", "coverage", "debug", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/cmdline.py#L587-L614
[ "def", "do_debug", "(", "self", ",", "args", ")", ":", "if", "not", "args", ":", "self", ".", "help_fn", "(", "\"What information would you like: data, sys?\"", ")", "return", "ERR", "for", "info", "in", "args", ":", "if", "info", "==", "'sys'", ":", "print", "(", "\"-- sys ----------------------------------------\"", ")", "for", "line", "in", "info_formatter", "(", "self", ".", "coverage", ".", "sysinfo", "(", ")", ")", ":", "print", "(", "\" %s\"", "%", "line", ")", "elif", "info", "==", "'data'", ":", "print", "(", "\"-- data ---------------------------------------\"", ")", "self", ".", "coverage", ".", "load", "(", ")", "print", "(", "\"path: %s\"", "%", "self", ".", "coverage", ".", "data", ".", "filename", ")", "print", "(", "\"has_arcs: %r\"", "%", "self", ".", "coverage", ".", "data", ".", "has_arcs", "(", ")", ")", "summary", "=", "self", ".", "coverage", ".", "data", ".", "summary", "(", "fullpath", "=", "True", ")", "if", "summary", ":", "filenames", "=", "sorted", "(", "summary", ".", "keys", "(", ")", ")", "print", "(", "\"\\n%d files:\"", "%", "len", "(", "filenames", ")", ")", "for", "f", "in", "filenames", ":", "print", "(", "\"%s: %d lines\"", "%", "(", "f", ",", "summary", "[", "f", "]", ")", ")", "else", ":", "print", "(", "\"No data collected\"", ")", "else", ":", "self", ".", "help_fn", "(", "\"Don't know what you mean by %r\"", "%", "info", ")", "return", "ERR", "return", "OK" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
serialize_object
Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized threshold : float The threshold for not double-pickling the content. Returns ------- ('pmd', [bufs]) : where pmd is the pickled metadata wrapper, bufs is a list of data buffers
environment/lib/python2.7/site-packages/IPython/zmq/serialize.py
def serialize_object(obj, threshold=64e-6): """Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized threshold : float The threshold for not double-pickling the content. Returns ------- ('pmd', [bufs]) : where pmd is the pickled metadata wrapper, bufs is a list of data buffers """ databuffers = [] if isinstance(obj, (list, tuple)): clist = canSequence(obj) slist = map(serialize, clist) for s in slist: if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None return pickle.dumps(slist,-1), databuffers elif isinstance(obj, dict): sobj = {} for k in sorted(obj.iterkeys()): s = serialize(can(obj[k])) if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None sobj[k] = s return pickle.dumps(sobj,-1),databuffers else: s = serialize(can(obj)) if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None return pickle.dumps(s,-1),databuffers
def serialize_object(obj, threshold=64e-6): """Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized threshold : float The threshold for not double-pickling the content. Returns ------- ('pmd', [bufs]) : where pmd is the pickled metadata wrapper, bufs is a list of data buffers """ databuffers = [] if isinstance(obj, (list, tuple)): clist = canSequence(obj) slist = map(serialize, clist) for s in slist: if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None return pickle.dumps(slist,-1), databuffers elif isinstance(obj, dict): sobj = {} for k in sorted(obj.iterkeys()): s = serialize(can(obj[k])) if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None sobj[k] = s return pickle.dumps(sobj,-1),databuffers else: s = serialize(can(obj)) if s.typeDescriptor in ('buffer', 'ndarray') or s.getDataSize() > threshold: databuffers.append(s.getData()) s.data = None return pickle.dumps(s,-1),databuffers
[ "Serialize", "an", "object", "into", "a", "list", "of", "sendable", "buffers", ".", "Parameters", "----------", "obj", ":", "object", "The", "object", "to", "be", "serialized", "threshold", ":", "float", "The", "threshold", "for", "not", "double", "-", "pickling", "the", "content", ".", "Returns", "-------", "(", "pmd", "[", "bufs", "]", ")", ":", "where", "pmd", "is", "the", "pickled", "metadata", "wrapper", "bufs", "is", "a", "list", "of", "data", "buffers" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/serialize.py#L45-L86
[ "def", "serialize_object", "(", "obj", ",", "threshold", "=", "64e-6", ")", ":", "databuffers", "=", "[", "]", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "clist", "=", "canSequence", "(", "obj", ")", "slist", "=", "map", "(", "serialize", ",", "clist", ")", "for", "s", "in", "slist", ":", "if", "s", ".", "typeDescriptor", "in", "(", "'buffer'", ",", "'ndarray'", ")", "or", "s", ".", "getDataSize", "(", ")", ">", "threshold", ":", "databuffers", ".", "append", "(", "s", ".", "getData", "(", ")", ")", "s", ".", "data", "=", "None", "return", "pickle", ".", "dumps", "(", "slist", ",", "-", "1", ")", ",", "databuffers", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "sobj", "=", "{", "}", "for", "k", "in", "sorted", "(", "obj", ".", "iterkeys", "(", ")", ")", ":", "s", "=", "serialize", "(", "can", "(", "obj", "[", "k", "]", ")", ")", "if", "s", ".", "typeDescriptor", "in", "(", "'buffer'", ",", "'ndarray'", ")", "or", "s", ".", "getDataSize", "(", ")", ">", "threshold", ":", "databuffers", ".", "append", "(", "s", ".", "getData", "(", ")", ")", "s", ".", "data", "=", "None", "sobj", "[", "k", "]", "=", "s", "return", "pickle", ".", "dumps", "(", "sobj", ",", "-", "1", ")", ",", "databuffers", "else", ":", "s", "=", "serialize", "(", "can", "(", "obj", ")", ")", "if", "s", ".", "typeDescriptor", "in", "(", "'buffer'", ",", "'ndarray'", ")", "or", "s", ".", "getDataSize", "(", ")", ">", "threshold", ":", "databuffers", ".", "append", "(", "s", ".", "getData", "(", ")", ")", "s", ".", "data", "=", "None", "return", "pickle", ".", "dumps", "(", "s", ",", "-", "1", ")", ",", "databuffers" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
unserialize_object
reconstruct an object serialized by serialize_object from data buffers.
environment/lib/python2.7/site-packages/IPython/zmq/serialize.py
def unserialize_object(bufs): """reconstruct an object serialized by serialize_object from data buffers.""" bufs = list(bufs) sobj = pickle.loads(bufs.pop(0)) if isinstance(sobj, (list, tuple)): for s in sobj: if s.data is None: s.data = bufs.pop(0) return uncanSequence(map(unserialize, sobj)), bufs elif isinstance(sobj, dict): newobj = {} for k in sorted(sobj.iterkeys()): s = sobj[k] if s.data is None: s.data = bufs.pop(0) newobj[k] = uncan(unserialize(s)) return newobj, bufs else: if sobj.data is None: sobj.data = bufs.pop(0) return uncan(unserialize(sobj)), bufs
def unserialize_object(bufs): """reconstruct an object serialized by serialize_object from data buffers.""" bufs = list(bufs) sobj = pickle.loads(bufs.pop(0)) if isinstance(sobj, (list, tuple)): for s in sobj: if s.data is None: s.data = bufs.pop(0) return uncanSequence(map(unserialize, sobj)), bufs elif isinstance(sobj, dict): newobj = {} for k in sorted(sobj.iterkeys()): s = sobj[k] if s.data is None: s.data = bufs.pop(0) newobj[k] = uncan(unserialize(s)) return newobj, bufs else: if sobj.data is None: sobj.data = bufs.pop(0) return uncan(unserialize(sobj)), bufs
[ "reconstruct", "an", "object", "serialized", "by", "serialize_object", "from", "data", "buffers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/serialize.py#L89-L109
[ "def", "unserialize_object", "(", "bufs", ")", ":", "bufs", "=", "list", "(", "bufs", ")", "sobj", "=", "pickle", ".", "loads", "(", "bufs", ".", "pop", "(", "0", ")", ")", "if", "isinstance", "(", "sobj", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "s", "in", "sobj", ":", "if", "s", ".", "data", "is", "None", ":", "s", ".", "data", "=", "bufs", ".", "pop", "(", "0", ")", "return", "uncanSequence", "(", "map", "(", "unserialize", ",", "sobj", ")", ")", ",", "bufs", "elif", "isinstance", "(", "sobj", ",", "dict", ")", ":", "newobj", "=", "{", "}", "for", "k", "in", "sorted", "(", "sobj", ".", "iterkeys", "(", ")", ")", ":", "s", "=", "sobj", "[", "k", "]", "if", "s", ".", "data", "is", "None", ":", "s", ".", "data", "=", "bufs", ".", "pop", "(", "0", ")", "newobj", "[", "k", "]", "=", "uncan", "(", "unserialize", "(", "s", ")", ")", "return", "newobj", ",", "bufs", "else", ":", "if", "sobj", ".", "data", "is", "None", ":", "sobj", ".", "data", "=", "bufs", ".", "pop", "(", "0", ")", "return", "uncan", "(", "unserialize", "(", "sobj", ")", ")", ",", "bufs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
pack_apply_message
pack up a function, args, and kwargs to be sent over the wire as a series of buffers. Any object whose data is larger than `threshold` will not have their data copied (currently only numpy arrays support zero-copy)
environment/lib/python2.7/site-packages/IPython/zmq/serialize.py
def pack_apply_message(f, args, kwargs, threshold=64e-6): """pack up a function, args, and kwargs to be sent over the wire as a series of buffers. Any object whose data is larger than `threshold` will not have their data copied (currently only numpy arrays support zero-copy)""" msg = [pickle.dumps(can(f),-1)] databuffers = [] # for large objects sargs, bufs = serialize_object(args,threshold) msg.append(sargs) databuffers.extend(bufs) skwargs, bufs = serialize_object(kwargs,threshold) msg.append(skwargs) databuffers.extend(bufs) msg.extend(databuffers) return msg
def pack_apply_message(f, args, kwargs, threshold=64e-6): """pack up a function, args, and kwargs to be sent over the wire as a series of buffers. Any object whose data is larger than `threshold` will not have their data copied (currently only numpy arrays support zero-copy)""" msg = [pickle.dumps(can(f),-1)] databuffers = [] # for large objects sargs, bufs = serialize_object(args,threshold) msg.append(sargs) databuffers.extend(bufs) skwargs, bufs = serialize_object(kwargs,threshold) msg.append(skwargs) databuffers.extend(bufs) msg.extend(databuffers) return msg
[ "pack", "up", "a", "function", "args", "and", "kwargs", "to", "be", "sent", "over", "the", "wire", "as", "a", "series", "of", "buffers", ".", "Any", "object", "whose", "data", "is", "larger", "than", "threshold", "will", "not", "have", "their", "data", "copied", "(", "currently", "only", "numpy", "arrays", "support", "zero", "-", "copy", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/serialize.py#L111-L124
[ "def", "pack_apply_message", "(", "f", ",", "args", ",", "kwargs", ",", "threshold", "=", "64e-6", ")", ":", "msg", "=", "[", "pickle", ".", "dumps", "(", "can", "(", "f", ")", ",", "-", "1", ")", "]", "databuffers", "=", "[", "]", "# for large objects", "sargs", ",", "bufs", "=", "serialize_object", "(", "args", ",", "threshold", ")", "msg", ".", "append", "(", "sargs", ")", "databuffers", ".", "extend", "(", "bufs", ")", "skwargs", ",", "bufs", "=", "serialize_object", "(", "kwargs", ",", "threshold", ")", "msg", ".", "append", "(", "skwargs", ")", "databuffers", ".", "extend", "(", "bufs", ")", "msg", ".", "extend", "(", "databuffers", ")", "return", "msg" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
unpack_apply_message
unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs
environment/lib/python2.7/site-packages/IPython/zmq/serialize.py
def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 3, "not enough buffers!" if not copy: for i in range(3): bufs[i] = bufs[i].bytes cf = pickle.loads(bufs.pop(0)) sargs = list(pickle.loads(bufs.pop(0))) skwargs = dict(pickle.loads(bufs.pop(0))) # print sargs, skwargs f = uncan(cf, g) for sa in sargs: if sa.data is None: m = bufs.pop(0) if sa.getTypeDescriptor() in ('buffer', 'ndarray'): # always use a buffer, until memoryviews get sorted out sa.data = buffer(m) # disable memoryview support # if copy: # sa.data = buffer(m) # else: # sa.data = m.buffer else: if copy: sa.data = m else: sa.data = m.bytes args = uncanSequence(map(unserialize, sargs), g) kwargs = {} for k in sorted(skwargs.iterkeys()): sa = skwargs[k] if sa.data is None: m = bufs.pop(0) if sa.getTypeDescriptor() in ('buffer', 'ndarray'): # always use a buffer, until memoryviews get sorted out sa.data = buffer(m) # disable memoryview support # if copy: # sa.data = buffer(m) # else: # sa.data = m.buffer else: if copy: sa.data = m else: sa.data = m.bytes kwargs[k] = uncan(unserialize(sa), g) return f,args,kwargs
def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 3, "not enough buffers!" if not copy: for i in range(3): bufs[i] = bufs[i].bytes cf = pickle.loads(bufs.pop(0)) sargs = list(pickle.loads(bufs.pop(0))) skwargs = dict(pickle.loads(bufs.pop(0))) # print sargs, skwargs f = uncan(cf, g) for sa in sargs: if sa.data is None: m = bufs.pop(0) if sa.getTypeDescriptor() in ('buffer', 'ndarray'): # always use a buffer, until memoryviews get sorted out sa.data = buffer(m) # disable memoryview support # if copy: # sa.data = buffer(m) # else: # sa.data = m.buffer else: if copy: sa.data = m else: sa.data = m.bytes args = uncanSequence(map(unserialize, sargs), g) kwargs = {} for k in sorted(skwargs.iterkeys()): sa = skwargs[k] if sa.data is None: m = bufs.pop(0) if sa.getTypeDescriptor() in ('buffer', 'ndarray'): # always use a buffer, until memoryviews get sorted out sa.data = buffer(m) # disable memoryview support # if copy: # sa.data = buffer(m) # else: # sa.data = m.buffer else: if copy: sa.data = m else: sa.data = m.bytes kwargs[k] = uncan(unserialize(sa), g) return f,args,kwargs
[ "unpack", "f", "args", "kwargs", "from", "buffers", "packed", "by", "pack_apply_message", "()", "Returns", ":", "original", "f", "args", "kwargs" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/serialize.py#L126-L178
[ "def", "unpack_apply_message", "(", "bufs", ",", "g", "=", "None", ",", "copy", "=", "True", ")", ":", "bufs", "=", "list", "(", "bufs", ")", "# allow us to pop", "assert", "len", "(", "bufs", ")", ">=", "3", ",", "\"not enough buffers!\"", "if", "not", "copy", ":", "for", "i", "in", "range", "(", "3", ")", ":", "bufs", "[", "i", "]", "=", "bufs", "[", "i", "]", ".", "bytes", "cf", "=", "pickle", ".", "loads", "(", "bufs", ".", "pop", "(", "0", ")", ")", "sargs", "=", "list", "(", "pickle", ".", "loads", "(", "bufs", ".", "pop", "(", "0", ")", ")", ")", "skwargs", "=", "dict", "(", "pickle", ".", "loads", "(", "bufs", ".", "pop", "(", "0", ")", ")", ")", "# print sargs, skwargs", "f", "=", "uncan", "(", "cf", ",", "g", ")", "for", "sa", "in", "sargs", ":", "if", "sa", ".", "data", "is", "None", ":", "m", "=", "bufs", ".", "pop", "(", "0", ")", "if", "sa", ".", "getTypeDescriptor", "(", ")", "in", "(", "'buffer'", ",", "'ndarray'", ")", ":", "# always use a buffer, until memoryviews get sorted out", "sa", ".", "data", "=", "buffer", "(", "m", ")", "# disable memoryview support", "# if copy:", "# sa.data = buffer(m)", "# else:", "# sa.data = m.buffer", "else", ":", "if", "copy", ":", "sa", ".", "data", "=", "m", "else", ":", "sa", ".", "data", "=", "m", ".", "bytes", "args", "=", "uncanSequence", "(", "map", "(", "unserialize", ",", "sargs", ")", ",", "g", ")", "kwargs", "=", "{", "}", "for", "k", "in", "sorted", "(", "skwargs", ".", "iterkeys", "(", ")", ")", ":", "sa", "=", "skwargs", "[", "k", "]", "if", "sa", ".", "data", "is", "None", ":", "m", "=", "bufs", ".", "pop", "(", "0", ")", "if", "sa", ".", "getTypeDescriptor", "(", ")", "in", "(", "'buffer'", ",", "'ndarray'", ")", ":", "# always use a buffer, until memoryviews get sorted out", "sa", ".", "data", "=", "buffer", "(", "m", ")", "# disable memoryview support", "# if copy:", "# sa.data = buffer(m)", "# else:", "# sa.data = m.buffer", "else", ":", "if", "copy", ":", "sa", ".", "data", "=", "m", "else", ":", "sa", ".", "data", "=", "m", ".", "bytes", "kwargs", "[", "k", "]", "=", "uncan", "(", "unserialize", "(", "sa", ")", ",", "g", ")", "return", "f", ",", "args", ",", "kwargs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DisplayTrap.set
Set the hook.
environment/lib/python2.7/site-packages/IPython/core/display_trap.py
def set(self): """Set the hook.""" if sys.displayhook is not self.hook: self.old_hook = sys.displayhook sys.displayhook = self.hook
def set(self): """Set the hook.""" if sys.displayhook is not self.hook: self.old_hook = sys.displayhook sys.displayhook = self.hook
[ "Set", "the", "hook", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/display_trap.py#L61-L65
[ "def", "set", "(", "self", ")", ":", "if", "sys", ".", "displayhook", "is", "not", "self", ".", "hook", ":", "self", ".", "old_hook", "=", "sys", ".", "displayhook", "sys", ".", "displayhook", "=", "self", ".", "hook" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
log_errors
decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed.
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def log_errors(f, self, *args, **kwargs): """decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed. """ try: return f(self, *args, **kwargs) except Exception: self.log.error("Uncaught exception in %r" % f, exc_info=True)
def log_errors(f, self, *args, **kwargs): """decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed. """ try: return f(self, *args, **kwargs) except Exception: self.log.error("Uncaught exception in %r" % f, exc_info=True)
[ "decorator", "to", "log", "unhandled", "exceptions", "raised", "in", "a", "method", ".", "For", "use", "wrapping", "on_recv", "callbacks", "so", "that", "exceptions", "do", "not", "cause", "the", "stream", "to", "be", "closed", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L115-L124
[ "def", "log_errors", "(", "f", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"Uncaught exception in %r\"", "%", "f", ",", "exc_info", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
is_url
boolean check for whether a string is a zmq url
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def is_url(url): """boolean check for whether a string is a zmq url""" if '://' not in url: return False proto, addr = url.split('://', 1) if proto.lower() not in ['tcp','pgm','epgm','ipc','inproc']: return False return True
def is_url(url): """boolean check for whether a string is a zmq url""" if '://' not in url: return False proto, addr = url.split('://', 1) if proto.lower() not in ['tcp','pgm','epgm','ipc','inproc']: return False return True
[ "boolean", "check", "for", "whether", "a", "string", "is", "a", "zmq", "url" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L127-L134
[ "def", "is_url", "(", "url", ")", ":", "if", "'://'", "not", "in", "url", ":", "return", "False", "proto", ",", "addr", "=", "url", ".", "split", "(", "'://'", ",", "1", ")", "if", "proto", ".", "lower", "(", ")", "not", "in", "[", "'tcp'", ",", "'pgm'", ",", "'epgm'", ",", "'ipc'", ",", "'inproc'", "]", ":", "return", "False", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
validate_url
validate a url for zeromq
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def validate_url(url): """validate a url for zeromq""" if not isinstance(url, basestring): raise TypeError("url must be a string, not %r"%type(url)) url = url.lower() proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr assert proto in ['tcp','pgm','epgm','ipc','inproc'], "Invalid protocol: %r"%proto # domain pattern adapted from http://www.regexlib.com/REDetails.aspx?regexp_id=391 # author: Remi Sabourin pat = re.compile(r'^([\w\d]([\w\d\-]{0,61}[\w\d])?\.)*[\w\d]([\w\d\-]{0,61}[\w\d])?$') if proto == 'tcp': lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis try: port = int(s_port) except ValueError: raise AssertionError("Invalid port %r in url: %r"%(port, url)) assert addr == '*' or pat.match(addr) is not None, 'Invalid url: %r'%url else: # only validate tcp urls currently pass return True
def validate_url(url): """validate a url for zeromq""" if not isinstance(url, basestring): raise TypeError("url must be a string, not %r"%type(url)) url = url.lower() proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr assert proto in ['tcp','pgm','epgm','ipc','inproc'], "Invalid protocol: %r"%proto # domain pattern adapted from http://www.regexlib.com/REDetails.aspx?regexp_id=391 # author: Remi Sabourin pat = re.compile(r'^([\w\d]([\w\d\-]{0,61}[\w\d])?\.)*[\w\d]([\w\d\-]{0,61}[\w\d])?$') if proto == 'tcp': lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis try: port = int(s_port) except ValueError: raise AssertionError("Invalid port %r in url: %r"%(port, url)) assert addr == '*' or pat.match(addr) is not None, 'Invalid url: %r'%url else: # only validate tcp urls currently pass return True
[ "validate", "a", "url", "for", "zeromq" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L136-L166
[ "def", "validate_url", "(", "url", ")", ":", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"url must be a string, not %r\"", "%", "type", "(", "url", ")", ")", "url", "=", "url", ".", "lower", "(", ")", "proto_addr", "=", "url", ".", "split", "(", "'://'", ")", "assert", "len", "(", "proto_addr", ")", "==", "2", ",", "'Invalid url: %r'", "%", "url", "proto", ",", "addr", "=", "proto_addr", "assert", "proto", "in", "[", "'tcp'", ",", "'pgm'", ",", "'epgm'", ",", "'ipc'", ",", "'inproc'", "]", ",", "\"Invalid protocol: %r\"", "%", "proto", "# domain pattern adapted from http://www.regexlib.com/REDetails.aspx?regexp_id=391", "# author: Remi Sabourin", "pat", "=", "re", ".", "compile", "(", "r'^([\\w\\d]([\\w\\d\\-]{0,61}[\\w\\d])?\\.)*[\\w\\d]([\\w\\d\\-]{0,61}[\\w\\d])?$'", ")", "if", "proto", "==", "'tcp'", ":", "lis", "=", "addr", ".", "split", "(", "':'", ")", "assert", "len", "(", "lis", ")", "==", "2", ",", "'Invalid url: %r'", "%", "url", "addr", ",", "s_port", "=", "lis", "try", ":", "port", "=", "int", "(", "s_port", ")", "except", "ValueError", ":", "raise", "AssertionError", "(", "\"Invalid port %r in url: %r\"", "%", "(", "port", ",", "url", ")", ")", "assert", "addr", "==", "'*'", "or", "pat", ".", "match", "(", "addr", ")", "is", "not", "None", ",", "'Invalid url: %r'", "%", "url", "else", ":", "# only validate tcp urls currently", "pass", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
validate_url_container
validate a potentially nested collection of urls.
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def validate_url_container(container): """validate a potentially nested collection of urls.""" if isinstance(container, basestring): url = container return validate_url(url) elif isinstance(container, dict): container = container.itervalues() for element in container: validate_url_container(element)
def validate_url_container(container): """validate a potentially nested collection of urls.""" if isinstance(container, basestring): url = container return validate_url(url) elif isinstance(container, dict): container = container.itervalues() for element in container: validate_url_container(element)
[ "validate", "a", "potentially", "nested", "collection", "of", "urls", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L169-L178
[ "def", "validate_url_container", "(", "container", ")", ":", "if", "isinstance", "(", "container", ",", "basestring", ")", ":", "url", "=", "container", "return", "validate_url", "(", "url", ")", "elif", "isinstance", "(", "container", ",", "dict", ")", ":", "container", "=", "container", ".", "itervalues", "(", ")", "for", "element", "in", "container", ":", "validate_url_container", "(", "element", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
split_url
split a zmq url (tcp://ip:port) into ('tcp','ip','port').
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def split_url(url): """split a zmq url (tcp://ip:port) into ('tcp','ip','port').""" proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis return proto,addr,s_port
def split_url(url): """split a zmq url (tcp://ip:port) into ('tcp','ip','port').""" proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis return proto,addr,s_port
[ "split", "a", "zmq", "url", "(", "tcp", ":", "//", "ip", ":", "port", ")", "into", "(", "tcp", "ip", "port", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L181-L189
[ "def", "split_url", "(", "url", ")", ":", "proto_addr", "=", "url", ".", "split", "(", "'://'", ")", "assert", "len", "(", "proto_addr", ")", "==", "2", ",", "'Invalid url: %r'", "%", "url", "proto", ",", "addr", "=", "proto_addr", "lis", "=", "addr", ".", "split", "(", "':'", ")", "assert", "len", "(", "lis", ")", "==", "2", ",", "'Invalid url: %r'", "%", "url", "addr", ",", "s_port", "=", "lis", "return", "proto", ",", "addr", ",", "s_port" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
disambiguate_ip_address
turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation of location is localhost).
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def disambiguate_ip_address(ip, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation of location is localhost).""" if ip in ('0.0.0.0', '*'): try: external_ips = socket.gethostbyname_ex(socket.gethostname())[2] except (socket.gaierror, IndexError): # couldn't identify this machine, assume localhost external_ips = [] if location is None or location in external_ips or not external_ips: # If location is unspecified or cannot be determined, assume local ip='127.0.0.1' elif location: return location return ip
def disambiguate_ip_address(ip, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation of location is localhost).""" if ip in ('0.0.0.0', '*'): try: external_ips = socket.gethostbyname_ex(socket.gethostname())[2] except (socket.gaierror, IndexError): # couldn't identify this machine, assume localhost external_ips = [] if location is None or location in external_ips or not external_ips: # If location is unspecified or cannot be determined, assume local ip='127.0.0.1' elif location: return location return ip
[ "turn", "multi", "-", "ip", "interfaces", "0", ".", "0", ".", "0", ".", "0", "and", "*", "into", "connectable", "ones", "based", "on", "the", "location", "(", "default", "interpretation", "of", "location", "is", "localhost", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L191-L205
[ "def", "disambiguate_ip_address", "(", "ip", ",", "location", "=", "None", ")", ":", "if", "ip", "in", "(", "'0.0.0.0'", ",", "'*'", ")", ":", "try", ":", "external_ips", "=", "socket", ".", "gethostbyname_ex", "(", "socket", ".", "gethostname", "(", ")", ")", "[", "2", "]", "except", "(", "socket", ".", "gaierror", ",", "IndexError", ")", ":", "# couldn't identify this machine, assume localhost", "external_ips", "=", "[", "]", "if", "location", "is", "None", "or", "location", "in", "external_ips", "or", "not", "external_ips", ":", "# If location is unspecified or cannot be determined, assume local", "ip", "=", "'127.0.0.1'", "elif", "location", ":", "return", "location", "return", "ip" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
disambiguate_url
turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation is localhost). This is for zeromq urls, such as tcp://*:10101.
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def disambiguate_url(url, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation is localhost). This is for zeromq urls, such as tcp://*:10101.""" try: proto,ip,port = split_url(url) except AssertionError: # probably not tcp url; could be ipc, etc. return url ip = disambiguate_ip_address(ip,location) return "%s://%s:%s"%(proto,ip,port)
def disambiguate_url(url, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation is localhost). This is for zeromq urls, such as tcp://*:10101.""" try: proto,ip,port = split_url(url) except AssertionError: # probably not tcp url; could be ipc, etc. return url ip = disambiguate_ip_address(ip,location) return "%s://%s:%s"%(proto,ip,port)
[ "turn", "multi", "-", "ip", "interfaces", "0", ".", "0", ".", "0", ".", "0", "and", "*", "into", "connectable", "ones", "based", "on", "the", "location", "(", "default", "interpretation", "is", "localhost", ")", ".", "This", "is", "for", "zeromq", "urls", "such", "as", "tcp", ":", "//", "*", ":", "10101", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L207-L220
[ "def", "disambiguate_url", "(", "url", ",", "location", "=", "None", ")", ":", "try", ":", "proto", ",", "ip", ",", "port", "=", "split_url", "(", "url", ")", "except", "AssertionError", ":", "# probably not tcp url; could be ipc, etc.", "return", "url", "ip", "=", "disambiguate_ip_address", "(", "ip", ",", "location", ")", "return", "\"%s://%s:%s\"", "%", "(", "proto", ",", "ip", ",", "port", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
_pull
helper method for implementing `client.pull` via `client.apply`
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def _pull(keys): """helper method for implementing `client.pull` via `client.apply`""" user_ns = globals() if isinstance(keys, (list,tuple, set)): for key in keys: if not user_ns.has_key(key): raise NameError("name '%s' is not defined"%key) return map(user_ns.get, keys) else: if not user_ns.has_key(keys): raise NameError("name '%s' is not defined"%keys) return user_ns.get(keys)
def _pull(keys): """helper method for implementing `client.pull` via `client.apply`""" user_ns = globals() if isinstance(keys, (list,tuple, set)): for key in keys: if not user_ns.has_key(key): raise NameError("name '%s' is not defined"%key) return map(user_ns.get, keys) else: if not user_ns.has_key(keys): raise NameError("name '%s' is not defined"%keys) return user_ns.get(keys)
[ "helper", "method", "for", "implementing", "client", ".", "pull", "via", "client", ".", "apply" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L241-L252
[ "def", "_pull", "(", "keys", ")", ":", "user_ns", "=", "globals", "(", ")", "if", "isinstance", "(", "keys", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "for", "key", "in", "keys", ":", "if", "not", "user_ns", ".", "has_key", "(", "key", ")", ":", "raise", "NameError", "(", "\"name '%s' is not defined\"", "%", "key", ")", "return", "map", "(", "user_ns", ".", "get", ",", "keys", ")", "else", ":", "if", "not", "user_ns", ".", "has_key", "(", "keys", ")", ":", "raise", "NameError", "(", "\"name '%s' is not defined\"", "%", "keys", ")", "return", "user_ns", ".", "get", "(", "keys", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
select_random_ports
Selects and return n random ports that are available.
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def select_random_ports(n): """Selects and return n random ports that are available.""" ports = [] for i in xrange(n): sock = socket.socket() sock.bind(('', 0)) while sock.getsockname()[1] in _random_ports: sock.close() sock = socket.socket() sock.bind(('', 0)) ports.append(sock) for i, sock in enumerate(ports): port = sock.getsockname()[1] sock.close() ports[i] = port _random_ports.add(port) return ports
def select_random_ports(n): """Selects and return n random ports that are available.""" ports = [] for i in xrange(n): sock = socket.socket() sock.bind(('', 0)) while sock.getsockname()[1] in _random_ports: sock.close() sock = socket.socket() sock.bind(('', 0)) ports.append(sock) for i, sock in enumerate(ports): port = sock.getsockname()[1] sock.close() ports[i] = port _random_ports.add(port) return ports
[ "Selects", "and", "return", "n", "random", "ports", "that", "are", "available", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L265-L281
[ "def", "select_random_ports", "(", "n", ")", ":", "ports", "=", "[", "]", "for", "i", "in", "xrange", "(", "n", ")", ":", "sock", "=", "socket", ".", "socket", "(", ")", "sock", ".", "bind", "(", "(", "''", ",", "0", ")", ")", "while", "sock", ".", "getsockname", "(", ")", "[", "1", "]", "in", "_random_ports", ":", "sock", ".", "close", "(", ")", "sock", "=", "socket", ".", "socket", "(", ")", "sock", ".", "bind", "(", "(", "''", ",", "0", ")", ")", "ports", ".", "append", "(", "sock", ")", "for", "i", ",", "sock", "in", "enumerate", "(", "ports", ")", ":", "port", "=", "sock", ".", "getsockname", "(", ")", "[", "1", "]", "sock", ".", "close", "(", ")", "ports", "[", "i", "]", "=", "port", "_random_ports", ".", "add", "(", "port", ")", "return", "ports" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
signal_children
Relay interupt/term signals to children, for more solid process cleanup.
environment/lib/python2.7/site-packages/IPython/parallel/util.py
def signal_children(children): """Relay interupt/term signals to children, for more solid process cleanup.""" def terminate_children(sig, frame): log = Application.instance().log log.critical("Got signal %i, terminating children..."%sig) for child in children: child.terminate() sys.exit(sig != SIGINT) # sys.exit(sig) for sig in (SIGINT, SIGABRT, SIGTERM): signal(sig, terminate_children)
def signal_children(children): """Relay interupt/term signals to children, for more solid process cleanup.""" def terminate_children(sig, frame): log = Application.instance().log log.critical("Got signal %i, terminating children..."%sig) for child in children: child.terminate() sys.exit(sig != SIGINT) # sys.exit(sig) for sig in (SIGINT, SIGABRT, SIGTERM): signal(sig, terminate_children)
[ "Relay", "interupt", "/", "term", "signals", "to", "children", "for", "more", "solid", "process", "cleanup", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L283-L294
[ "def", "signal_children", "(", "children", ")", ":", "def", "terminate_children", "(", "sig", ",", "frame", ")", ":", "log", "=", "Application", ".", "instance", "(", ")", ".", "log", "log", ".", "critical", "(", "\"Got signal %i, terminating children...\"", "%", "sig", ")", "for", "child", "in", "children", ":", "child", ".", "terminate", "(", ")", "sys", ".", "exit", "(", "sig", "!=", "SIGINT", ")", "# sys.exit(sig)", "for", "sig", "in", "(", "SIGINT", ",", "SIGABRT", ",", "SIGTERM", ")", ":", "signal", "(", "sig", ",", "terminate_children", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
remote
Turn a function into a remote function. This method can be used for map: In [1]: @remote(view,block=True) ...: def func(a): ...: pass
environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py
def remote(view, block=None, **flags): """Turn a function into a remote function. This method can be used for map: In [1]: @remote(view,block=True) ...: def func(a): ...: pass """ def remote_function(f): return RemoteFunction(view, f, block=block, **flags) return remote_function
def remote(view, block=None, **flags): """Turn a function into a remote function. This method can be used for map: In [1]: @remote(view,block=True) ...: def func(a): ...: pass """ def remote_function(f): return RemoteFunction(view, f, block=block, **flags) return remote_function
[ "Turn", "a", "function", "into", "a", "remote", "function", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py#L34-L46
[ "def", "remote", "(", "view", ",", "block", "=", "None", ",", "*", "*", "flags", ")", ":", "def", "remote_function", "(", "f", ")", ":", "return", "RemoteFunction", "(", "view", ",", "f", ",", "block", "=", "block", ",", "*", "*", "flags", ")", "return", "remote_function" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
parallel
Turn a function into a parallel remote function. This method can be used for map: In [1]: @parallel(view, block=True) ...: def func(a): ...: pass
environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py
def parallel(view, dist='b', block=None, ordered=True, **flags): """Turn a function into a parallel remote function. This method can be used for map: In [1]: @parallel(view, block=True) ...: def func(a): ...: pass """ def parallel_function(f): return ParallelFunction(view, f, dist=dist, block=block, ordered=ordered, **flags) return parallel_function
def parallel(view, dist='b', block=None, ordered=True, **flags): """Turn a function into a parallel remote function. This method can be used for map: In [1]: @parallel(view, block=True) ...: def func(a): ...: pass """ def parallel_function(f): return ParallelFunction(view, f, dist=dist, block=block, ordered=ordered, **flags) return parallel_function
[ "Turn", "a", "function", "into", "a", "parallel", "remote", "function", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py#L49-L61
[ "def", "parallel", "(", "view", ",", "dist", "=", "'b'", ",", "block", "=", "None", ",", "ordered", "=", "True", ",", "*", "*", "flags", ")", ":", "def", "parallel_function", "(", "f", ")", ":", "return", "ParallelFunction", "(", "view", ",", "f", ",", "dist", "=", "dist", ",", "block", "=", "block", ",", "ordered", "=", "ordered", ",", "*", "*", "flags", ")", "return", "parallel_function" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ParallelFunction.map
call a function on each element of a sequence remotely. This should behave very much like the builtin map, but return an AsyncMapResult if self.block is False.
environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py
def map(self, *sequences): """call a function on each element of a sequence remotely. This should behave very much like the builtin map, but return an AsyncMapResult if self.block is False. """ # set _map as a flag for use inside self.__call__ self._map = True try: ret = self.__call__(*sequences) finally: del self._map return ret
def map(self, *sequences): """call a function on each element of a sequence remotely. This should behave very much like the builtin map, but return an AsyncMapResult if self.block is False. """ # set _map as a flag for use inside self.__call__ self._map = True try: ret = self.__call__(*sequences) finally: del self._map return ret
[ "call", "a", "function", "on", "each", "element", "of", "a", "sequence", "remotely", ".", "This", "should", "behave", "very", "much", "like", "the", "builtin", "map", "but", "return", "an", "AsyncMapResult", "if", "self", ".", "block", "is", "False", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/client/remotefunction.py#L231-L242
[ "def", "map", "(", "self", ",", "*", "sequences", ")", ":", "# set _map as a flag for use inside self.__call__", "self", ".", "_map", "=", "True", "try", ":", "ret", "=", "self", ".", "__call__", "(", "*", "sequences", ")", "finally", ":", "del", "self", ".", "_map", "return", "ret" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ReadlineNoRecord.get_readline_tail
Get the last n items in readline history.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def get_readline_tail(self, n=10): """Get the last n items in readline history.""" end = self.shell.readline.get_current_history_length() + 1 start = max(end-n, 1) ghi = self.shell.readline.get_history_item return [ghi(x) for x in range(start, end)]
def get_readline_tail(self, n=10): """Get the last n items in readline history.""" end = self.shell.readline.get_current_history_length() + 1 start = max(end-n, 1) ghi = self.shell.readline.get_history_item return [ghi(x) for x in range(start, end)]
[ "Get", "the", "last", "n", "items", "in", "readline", "history", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L179-L184
[ "def", "get_readline_tail", "(", "self", ",", "n", "=", "10", ")", ":", "end", "=", "self", ".", "shell", ".", "readline", ".", "get_current_history_length", "(", ")", "+", "1", "start", "=", "max", "(", "end", "-", "n", ",", "1", ")", "ghi", "=", "self", ".", "shell", ".", "readline", ".", "get_history_item", "return", "[", "ghi", "(", "x", ")", "for", "x", "in", "range", "(", "start", ",", "end", ")", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.set_autoindent
Set the autoindent flag, checking for readline support. If called with no arguments, it acts as a toggle.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def set_autoindent(self,value=None): """Set the autoindent flag, checking for readline support. If called with no arguments, it acts as a toggle.""" if value != 0 and not self.has_readline: if os.name == 'posix': warn("The auto-indent feature requires the readline library") self.autoindent = 0 return if value is None: self.autoindent = not self.autoindent else: self.autoindent = value
def set_autoindent(self,value=None): """Set the autoindent flag, checking for readline support. If called with no arguments, it acts as a toggle.""" if value != 0 and not self.has_readline: if os.name == 'posix': warn("The auto-indent feature requires the readline library") self.autoindent = 0 return if value is None: self.autoindent = not self.autoindent else: self.autoindent = value
[ "Set", "the", "autoindent", "flag", "checking", "for", "readline", "support", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L498-L511
[ "def", "set_autoindent", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "!=", "0", "and", "not", "self", ".", "has_readline", ":", "if", "os", ".", "name", "==", "'posix'", ":", "warn", "(", "\"The auto-indent feature requires the readline library\"", ")", "self", ".", "autoindent", "=", "0", "return", "if", "value", "is", "None", ":", "self", ".", "autoindent", "=", "not", "self", ".", "autoindent", "else", ":", "self", ".", "autoindent", "=", "value" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.init_logstart
Initialize logging in case it was requested at the command line.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def init_logstart(self): """Initialize logging in case it was requested at the command line. """ if self.logappend: self.magic('logstart %s append' % self.logappend) elif self.logfile: self.magic('logstart %s' % self.logfile) elif self.logstart: self.magic('logstart')
def init_logstart(self): """Initialize logging in case it was requested at the command line. """ if self.logappend: self.magic('logstart %s append' % self.logappend) elif self.logfile: self.magic('logstart %s' % self.logfile) elif self.logstart: self.magic('logstart')
[ "Initialize", "logging", "in", "case", "it", "was", "requested", "at", "the", "command", "line", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L588-L596
[ "def", "init_logstart", "(", "self", ")", ":", "if", "self", ".", "logappend", ":", "self", ".", "magic", "(", "'logstart %s append'", "%", "self", ".", "logappend", ")", "elif", "self", ".", "logfile", ":", "self", ".", "magic", "(", "'logstart %s'", "%", "self", ".", "logfile", ")", "elif", "self", ".", "logstart", ":", "self", ".", "magic", "(", "'logstart'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.init_virtualenv
Add a virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough. Adapted from code snippets online. http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def init_virtualenv(self): """Add a virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough. Adapted from code snippets online. http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv """ if 'VIRTUAL_ENV' not in os.environ: # Not in a virtualenv return if sys.executable.startswith(os.environ['VIRTUAL_ENV']): # Running properly in the virtualenv, don't need to do anything return warn("Attempting to work in a virtualenv. If you encounter problems, please " "install IPython inside the virtualenv.\n") if sys.platform == "win32": virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') else: virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', 'python%d.%d' % sys.version_info[:2], 'site-packages') import site sys.path.insert(0, virtual_env) site.addsitedir(virtual_env)
def init_virtualenv(self): """Add a virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user installs IPython in the virtualenv, but for many cases, it probably works well enough. Adapted from code snippets online. http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv """ if 'VIRTUAL_ENV' not in os.environ: # Not in a virtualenv return if sys.executable.startswith(os.environ['VIRTUAL_ENV']): # Running properly in the virtualenv, don't need to do anything return warn("Attempting to work in a virtualenv. If you encounter problems, please " "install IPython inside the virtualenv.\n") if sys.platform == "win32": virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') else: virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', 'python%d.%d' % sys.version_info[:2], 'site-packages') import site sys.path.insert(0, virtual_env) site.addsitedir(virtual_env)
[ "Add", "a", "virtualenv", "to", "sys", ".", "path", "so", "the", "user", "can", "import", "modules", "from", "it", ".", "This", "isn", "t", "perfect", ":", "it", "doesn", "t", "use", "the", "Python", "interpreter", "with", "which", "the", "virtualenv", "was", "built", "and", "it", "ignores", "the", "--", "no", "-", "site", "-", "packages", "option", ".", "A", "warning", "will", "appear", "suggesting", "the", "user", "installs", "IPython", "in", "the", "virtualenv", "but", "for", "many", "cases", "it", "probably", "works", "well", "enough", ".", "Adapted", "from", "code", "snippets", "online", ".", "http", ":", "//", "blog", ".", "ufsoft", ".", "org", "/", "2009", "/", "1", "/", "29", "/", "ipython", "-", "and", "-", "virtualenv" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L670-L699
[ "def", "init_virtualenv", "(", "self", ")", ":", "if", "'VIRTUAL_ENV'", "not", "in", "os", ".", "environ", ":", "# Not in a virtualenv", "return", "if", "sys", ".", "executable", ".", "startswith", "(", "os", ".", "environ", "[", "'VIRTUAL_ENV'", "]", ")", ":", "# Running properly in the virtualenv, don't need to do anything", "return", "warn", "(", "\"Attempting to work in a virtualenv. If you encounter problems, please \"", "\"install IPython inside the virtualenv.\\n\"", ")", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "virtual_env", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'VIRTUAL_ENV'", "]", ",", "'Lib'", ",", "'site-packages'", ")", "else", ":", "virtual_env", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'VIRTUAL_ENV'", "]", ",", "'lib'", ",", "'python%d.%d'", "%", "sys", ".", "version_info", "[", ":", "2", "]", ",", "'site-packages'", ")", "import", "site", "sys", ".", "path", ".", "insert", "(", "0", ",", "virtual_env", ")", "site", ".", "addsitedir", "(", "virtual_env", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.save_sys_module_state
Save the state of hooks in the sys module. This has to be called after self.user_module is created.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def save_sys_module_state(self): """Save the state of hooks in the sys module. This has to be called after self.user_module is created. """ self._orig_sys_module_state = {} self._orig_sys_module_state['stdin'] = sys.stdin self._orig_sys_module_state['stdout'] = sys.stdout self._orig_sys_module_state['stderr'] = sys.stderr self._orig_sys_module_state['excepthook'] = sys.excepthook self._orig_sys_modules_main_name = self.user_module.__name__ self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
def save_sys_module_state(self): """Save the state of hooks in the sys module. This has to be called after self.user_module is created. """ self._orig_sys_module_state = {} self._orig_sys_module_state['stdin'] = sys.stdin self._orig_sys_module_state['stdout'] = sys.stdout self._orig_sys_module_state['stderr'] = sys.stderr self._orig_sys_module_state['excepthook'] = sys.excepthook self._orig_sys_modules_main_name = self.user_module.__name__ self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
[ "Save", "the", "state", "of", "hooks", "in", "the", "sys", "module", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L705-L716
[ "def", "save_sys_module_state", "(", "self", ")", ":", "self", ".", "_orig_sys_module_state", "=", "{", "}", "self", ".", "_orig_sys_module_state", "[", "'stdin'", "]", "=", "sys", ".", "stdin", "self", ".", "_orig_sys_module_state", "[", "'stdout'", "]", "=", "sys", ".", "stdout", "self", ".", "_orig_sys_module_state", "[", "'stderr'", "]", "=", "sys", ".", "stderr", "self", ".", "_orig_sys_module_state", "[", "'excepthook'", "]", "=", "sys", ".", "excepthook", "self", ".", "_orig_sys_modules_main_name", "=", "self", ".", "user_module", ".", "__name__", "self", ".", "_orig_sys_modules_main_mod", "=", "sys", ".", "modules", ".", "get", "(", "self", ".", "user_module", ".", "__name__", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.restore_sys_module_state
Restore the state of the sys module.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def restore_sys_module_state(self): """Restore the state of the sys module.""" try: for k, v in self._orig_sys_module_state.iteritems(): setattr(sys, k, v) except AttributeError: pass # Reset what what done in self.init_sys_modules if self._orig_sys_modules_main_mod is not None: sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
def restore_sys_module_state(self): """Restore the state of the sys module.""" try: for k, v in self._orig_sys_module_state.iteritems(): setattr(sys, k, v) except AttributeError: pass # Reset what what done in self.init_sys_modules if self._orig_sys_modules_main_mod is not None: sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
[ "Restore", "the", "state", "of", "the", "sys", "module", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L718-L727
[ "def", "restore_sys_module_state", "(", "self", ")", ":", "try", ":", "for", "k", ",", "v", "in", "self", ".", "_orig_sys_module_state", ".", "iteritems", "(", ")", ":", "setattr", "(", "sys", ",", "k", ",", "v", ")", "except", "AttributeError", ":", "pass", "# Reset what what done in self.init_sys_modules", "if", "self", ".", "_orig_sys_modules_main_mod", "is", "not", "None", ":", "sys", ".", "modules", "[", "self", ".", "_orig_sys_modules_main_name", "]", "=", "self", ".", "_orig_sys_modules_main_mod" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InteractiveShell.set_hook
set_hook(name,hook) -> sets an internal IPython hook. IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython's behavior to call at runtime your own routines.
environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): """set_hook(name,hook) -> sets an internal IPython hook. IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython's behavior to call at runtime your own routines.""" # At some point in the future, this should validate the hook before it # accepts it. Probably at least check that the hook takes the number # of args it's supposed to. f = types.MethodType(hook,self) # check if the hook is for strdispatcher first if str_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_s(str_key, f, priority ) self.strdispatchers[name] = sdp return if re_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_re(re.compile(re_key), f, priority ) self.strdispatchers[name] = sdp return dp = getattr(self.hooks, name, None) if name not in IPython.core.hooks.__all__: print "Warning! Hook '%s' is not one of %s" % \ (name, IPython.core.hooks.__all__ ) if not dp: dp = IPython.core.hooks.CommandChainDispatcher() try: dp.add(f,priority) except AttributeError: # it was not commandchain, plain old func - replace dp = f setattr(self.hooks,name, dp)
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): """set_hook(name,hook) -> sets an internal IPython hook. IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython's behavior to call at runtime your own routines.""" # At some point in the future, this should validate the hook before it # accepts it. Probably at least check that the hook takes the number # of args it's supposed to. f = types.MethodType(hook,self) # check if the hook is for strdispatcher first if str_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_s(str_key, f, priority ) self.strdispatchers[name] = sdp return if re_key is not None: sdp = self.strdispatchers.get(name, StrDispatch()) sdp.add_re(re.compile(re_key), f, priority ) self.strdispatchers[name] = sdp return dp = getattr(self.hooks, name, None) if name not in IPython.core.hooks.__all__: print "Warning! Hook '%s' is not one of %s" % \ (name, IPython.core.hooks.__all__ ) if not dp: dp = IPython.core.hooks.CommandChainDispatcher() try: dp.add(f,priority) except AttributeError: # it was not commandchain, plain old func - replace dp = f setattr(self.hooks,name, dp)
[ "set_hook", "(", "name", "hook", ")", "-", ">", "sets", "an", "internal", "IPython", "hook", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L746-L784
[ "def", "set_hook", "(", "self", ",", "name", ",", "hook", ",", "priority", "=", "50", ",", "str_key", "=", "None", ",", "re_key", "=", "None", ")", ":", "# At some point in the future, this should validate the hook before it", "# accepts it. Probably at least check that the hook takes the number", "# of args it's supposed to.", "f", "=", "types", ".", "MethodType", "(", "hook", ",", "self", ")", "# check if the hook is for strdispatcher first", "if", "str_key", "is", "not", "None", ":", "sdp", "=", "self", ".", "strdispatchers", ".", "get", "(", "name", ",", "StrDispatch", "(", ")", ")", "sdp", ".", "add_s", "(", "str_key", ",", "f", ",", "priority", ")", "self", ".", "strdispatchers", "[", "name", "]", "=", "sdp", "return", "if", "re_key", "is", "not", "None", ":", "sdp", "=", "self", ".", "strdispatchers", ".", "get", "(", "name", ",", "StrDispatch", "(", ")", ")", "sdp", ".", "add_re", "(", "re", ".", "compile", "(", "re_key", ")", ",", "f", ",", "priority", ")", "self", ".", "strdispatchers", "[", "name", "]", "=", "sdp", "return", "dp", "=", "getattr", "(", "self", ".", "hooks", ",", "name", ",", "None", ")", "if", "name", "not", "in", "IPython", ".", "core", ".", "hooks", ".", "__all__", ":", "print", "\"Warning! Hook '%s' is not one of %s\"", "%", "(", "name", ",", "IPython", ".", "core", ".", "hooks", ".", "__all__", ")", "if", "not", "dp", ":", "dp", "=", "IPython", ".", "core", ".", "hooks", ".", "CommandChainDispatcher", "(", ")", "try", ":", "dp", ".", "add", "(", "f", ",", "priority", ")", "except", "AttributeError", ":", "# it was not commandchain, plain old func - replace", "dp", "=", "f", "setattr", "(", "self", ".", "hooks", ",", "name", ",", "dp", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e