labNo
float64
1
10
taskNo
float64
0
4
questioner
stringclasses
2 values
question
stringlengths
9
201
code
stringlengths
18
30.3k
startLine
float64
0
192
endLine
float64
0
196
questionType
stringclasses
4 values
answer
stringlengths
2
905
src
stringclasses
3 values
code_processed
stringlengths
12
28.3k
id
stringlengths
2
5
raw_code
stringlengths
20
30.3k
raw_comment
stringlengths
10
242
comment
stringlengths
9
207
q_code
stringlengths
66
30.3k
null
null
null
What does this function do?
def check_timeout(start_time, timeout): return timeutils.is_older_than(start_time, timeout)
null
null
null
Return True if the specified time has passed, False otherwise.
pcsd
def check timeout start time timeout return timeutils is older than start time timeout
15337
def check_timeout(start_time, timeout): return timeutils.is_older_than(start_time, timeout)
Return True if the specified time has passed, False otherwise.
return true if the specified time has passed , false otherwise .
Question: What does this function do? Code: def check_timeout(start_time, timeout): return timeutils.is_older_than(start_time, timeout)
null
null
null
What does this function do?
def remove_record(module, gcdns, record): overwrite = module.boolean(module.params['overwrite']) ttl = module.params['ttl'] record_data = module.params['record_data'] if (record is None): return False if (not overwrite): if (not _records_match(record.data['ttl'], record.data['rrdatas'], ttl, record_data)): ...
null
null
null
Remove a resource record.
pcsd
def remove record module gcdns record overwrite = module boolean module params['overwrite'] ttl = module params['ttl'] record data = module params['record data'] if record is None return False if not overwrite if not records match record data['ttl'] record data['rrdatas'] ttl record data module fail json msg= 'cannot d...
15340
def remove_record(module, gcdns, record): overwrite = module.boolean(module.params['overwrite']) ttl = module.params['ttl'] record_data = module.params['record_data'] if (record is None): return False if (not overwrite): if (not _records_match(record.data['ttl'], record.data['rrdatas'], ttl, record_data)): ...
Remove a resource record.
remove a resource record .
Question: What does this function do? Code: def remove_record(module, gcdns, record): overwrite = module.boolean(module.params['overwrite']) ttl = module.params['ttl'] record_data = module.params['record_data'] if (record is None): return False if (not overwrite): if (not _records_match(record.data['ttl'], ...
null
null
null
What does this function do?
def getProfileBaseName(repository): return getProfileName(repository.baseName, repository)
null
null
null
Get the profile base file name.
pcsd
def get Profile Base Name repository return get Profile Name repository base Name repository
15343
def getProfileBaseName(repository): return getProfileName(repository.baseName, repository)
Get the profile base file name.
get the profile base file name .
Question: What does this function do? Code: def getProfileBaseName(repository): return getProfileName(repository.baseName, repository)
null
null
null
What does this function do?
def ext_pillar(minion_id, pillar, key=None, only=()): url = __opts__['foreman.url'] user = __opts__['foreman.user'] password = __opts__['foreman.password'] api = __opts__['foreman.api'] verify = __opts__['foreman.verifyssl'] certfile = __opts__['foreman.certfile'] keyfile = __opts__['foreman.keyfile'] cafile = ...
null
null
null
Read pillar data from Foreman via its API.
pcsd
def ext pillar minion id pillar key=None only= url = opts ['foreman url'] user = opts ['foreman user'] password = opts ['foreman password'] api = opts ['foreman api'] verify = opts ['foreman verifyssl'] certfile = opts ['foreman certfile'] keyfile = opts ['foreman keyfile'] cafile = opts ['foreman cafile'] lookup param...
15351
def ext_pillar(minion_id, pillar, key=None, only=()): url = __opts__['foreman.url'] user = __opts__['foreman.user'] password = __opts__['foreman.password'] api = __opts__['foreman.api'] verify = __opts__['foreman.verifyssl'] certfile = __opts__['foreman.certfile'] keyfile = __opts__['foreman.keyfile'] cafile = ...
Read pillar data from Foreman via its API.
read pillar data from foreman via its api .
Question: What does this function do? Code: def ext_pillar(minion_id, pillar, key=None, only=()): url = __opts__['foreman.url'] user = __opts__['foreman.user'] password = __opts__['foreman.password'] api = __opts__['foreman.api'] verify = __opts__['foreman.verifyssl'] certfile = __opts__['foreman.certfile'] k...
null
null
null
What does this function do?
def json_decode(value): return json.loads(to_basestring(value))
null
null
null
Returns Python objects for the given JSON string.
pcsd
def json decode value return json loads to basestring value
15353
def json_decode(value): return json.loads(to_basestring(value))
Returns Python objects for the given JSON string.
returns python objects for the given json string .
Question: What does this function do? Code: def json_decode(value): return json.loads(to_basestring(value))
null
null
null
What does this function do?
def _process_mass_form(f): def wrap(request, *args, **kwargs): 'Wrap' if ('massform' in request.POST): for key in request.POST: if ('mass-item' in key): try: item = Item.objects.get(pk=request.POST[key]) form = MassActionForm(request.user.profile, request.POST, instance=item) if (form...
null
null
null
Pre-process request to handle mass action form for Tasks and Milestones
pcsd
def process mass form f def wrap request *args **kwargs 'Wrap' if 'massform' in request POST for key in request POST if 'mass-item' in key try item = Item objects get pk=request POST[key] form = Mass Action Form request user profile request POST instance=item if form is valid and request user profile has permission ite...
15354
def _process_mass_form(f): def wrap(request, *args, **kwargs): 'Wrap' if ('massform' in request.POST): for key in request.POST: if ('mass-item' in key): try: item = Item.objects.get(pk=request.POST[key]) form = MassActionForm(request.user.profile, request.POST, instance=item) if (form...
Pre-process request to handle mass action form for Tasks and Milestones
pre - process request to handle mass action form for tasks and milestones
Question: What does this function do? Code: def _process_mass_form(f): def wrap(request, *args, **kwargs): 'Wrap' if ('massform' in request.POST): for key in request.POST: if ('mass-item' in key): try: item = Item.objects.get(pk=request.POST[key]) form = MassActionForm(request.user.profi...
null
null
null
What does this function do?
def add_new_user_history(user_profile, streams): one_week_ago = (now() - datetime.timedelta(weeks=1)) recipients = Recipient.objects.filter(type=Recipient.STREAM, type_id__in=[stream.id for stream in streams if (not stream.invite_only)]) recent_messages = Message.objects.filter(recipient_id__in=recipients, pub_date_...
null
null
null
Give you the last 100 messages on your public streams, so you have something to look at in your home view once you finish the tutorial.
pcsd
def add new user history user profile streams one week ago = now - datetime timedelta weeks=1 recipients = Recipient objects filter type=Recipient STREAM type id in=[stream id for stream in streams if not stream invite only ] recent messages = Message objects filter recipient id in=recipients pub date gt=one week ago o...
15375
def add_new_user_history(user_profile, streams): one_week_ago = (now() - datetime.timedelta(weeks=1)) recipients = Recipient.objects.filter(type=Recipient.STREAM, type_id__in=[stream.id for stream in streams if (not stream.invite_only)]) recent_messages = Message.objects.filter(recipient_id__in=recipients, pub_date_...
Give you the last 100 messages on your public streams, so you have something to look at in your home view once you finish the tutorial.
give you the last 100 messages on your public streams , so you have something to look at in your home view once you finish the tutorial .
Question: What does this function do? Code: def add_new_user_history(user_profile, streams): one_week_ago = (now() - datetime.timedelta(weeks=1)) recipients = Recipient.objects.filter(type=Recipient.STREAM, type_id__in=[stream.id for stream in streams if (not stream.invite_only)]) recent_messages = Message.object...
null
null
null
What does this function do?
def _CheckQuery(query): _ValidateString(query, 'query', MAXIMUM_QUERY_LENGTH, empty_ok=True) if (query is None): raise TypeError('query must be unicode, got None') if query.strip(): try: query_parser.Parse(query) except query_parser.QueryException as e: raise QueryError(('Failed to parse query "%s"' % qu...
null
null
null
Checks a query is a valid query string.
pcsd
def Check Query query Validate String query 'query' MAXIMUM QUERY LENGTH empty ok=True if query is None raise Type Error 'query must be unicode got None' if query strip try query parser Parse query except query parser Query Exception as e raise Query Error 'Failed to parse query "%s"' % query return query
15384
def _CheckQuery(query): _ValidateString(query, 'query', MAXIMUM_QUERY_LENGTH, empty_ok=True) if (query is None): raise TypeError('query must be unicode, got None') if query.strip(): try: query_parser.Parse(query) except query_parser.QueryException as e: raise QueryError(('Failed to parse query "%s"' % qu...
Checks a query is a valid query string.
checks a query is a valid query string .
Question: What does this function do? Code: def _CheckQuery(query): _ValidateString(query, 'query', MAXIMUM_QUERY_LENGTH, empty_ok=True) if (query is None): raise TypeError('query must be unicode, got None') if query.strip(): try: query_parser.Parse(query) except query_parser.QueryException as e: rais...
null
null
null
What does this function do?
def getargsfromtext(text, objname): signature = getsignaturefromtext(text, objname) if signature: argtxt = signature[(signature.find('(') + 1):(-1)] return argtxt.split(',')
null
null
null
Get arguments from text (object documentation)
pcsd
def getargsfromtext text objname signature = getsignaturefromtext text objname if signature argtxt = signature[ signature find ' ' + 1 -1 ] return argtxt split ' '
15392
def getargsfromtext(text, objname): signature = getsignaturefromtext(text, objname) if signature: argtxt = signature[(signature.find('(') + 1):(-1)] return argtxt.split(',')
Get arguments from text (object documentation)
get arguments from text
Question: What does this function do? Code: def getargsfromtext(text, objname): signature = getsignaturefromtext(text, objname) if signature: argtxt = signature[(signature.find('(') + 1):(-1)] return argtxt.split(',')
null
null
null
What does this function do?
@testing.requires_testing_data @requires_mayavi def test_plot_evoked_field(): evoked = read_evokeds(evoked_fname, condition='Left Auditory', baseline=((-0.2), 0.0)) evoked = pick_channels_evoked(evoked, evoked.ch_names[::10]) for t in ['meg', None]: with warnings.catch_warnings(record=True): maps = make_field_m...
null
null
null
Test plotting evoked field.
pcsd
@testing requires testing data @requires mayavi def test plot evoked field evoked = read evokeds evoked fname condition='Left Auditory' baseline= -0 2 0 0 evoked = pick channels evoked evoked evoked ch names[ 10] for t in ['meg' None] with warnings catch warnings record=True maps = make field map evoked trans fname sub...
15399
@testing.requires_testing_data @requires_mayavi def test_plot_evoked_field(): evoked = read_evokeds(evoked_fname, condition='Left Auditory', baseline=((-0.2), 0.0)) evoked = pick_channels_evoked(evoked, evoked.ch_names[::10]) for t in ['meg', None]: with warnings.catch_warnings(record=True): maps = make_field_m...
Test plotting evoked field.
test plotting evoked field .
Question: What does this function do? Code: @testing.requires_testing_data @requires_mayavi def test_plot_evoked_field(): evoked = read_evokeds(evoked_fname, condition='Left Auditory', baseline=((-0.2), 0.0)) evoked = pick_channels_evoked(evoked, evoked.ch_names[::10]) for t in ['meg', None]: with warnings.catc...
null
null
null
What does this function do?
def set_exception_context(e, s): e._context = s
null
null
null
Set the context of a given exception.
pcsd
def set exception context e s e context = s
15400
def set_exception_context(e, s): e._context = s
Set the context of a given exception.
set the context of a given exception .
Question: What does this function do? Code: def set_exception_context(e, s): e._context = s
null
null
null
What does this function do?
def get(args=None): if (not args): args = frappe.local.form_dict get_docinfo(frappe.get_doc(args.get(u'doctype'), args.get(u'name'))) return frappe.db.sql(u'select owner, description from `tabToDo`\n DCTB DCTB where reference_type=%(doctype)s and reference_name=%(name)s and status="Open"\n DCTB DCTB order by mod...
null
null
null
get assigned to
pcsd
def get args=None if not args args = frappe local form dict get docinfo frappe get doc args get u'doctype' args get u'name' return frappe db sql u'select owner description from `tab To Do` DCTB DCTB where reference type=% doctype s and reference name=% name s and status="Open" DCTB DCTB order by modified desc limit 5' ...
15416
def get(args=None): if (not args): args = frappe.local.form_dict get_docinfo(frappe.get_doc(args.get(u'doctype'), args.get(u'name'))) return frappe.db.sql(u'select owner, description from `tabToDo`\n DCTB DCTB where reference_type=%(doctype)s and reference_name=%(name)s and status="Open"\n DCTB DCTB order by mod...
get assigned to
get assigned to
Question: What does this function do? Code: def get(args=None): if (not args): args = frappe.local.form_dict get_docinfo(frappe.get_doc(args.get(u'doctype'), args.get(u'name'))) return frappe.db.sql(u'select owner, description from `tabToDo`\n DCTB DCTB where reference_type=%(doctype)s and reference_name=%(nam...
null
null
null
What does this function do?
def makepairs(x, y): xy = array([[a, b] for a in asarray(x) for b in asarray(y)]) return xy.T
null
null
null
Helper function to create an array of pairs of x and y.
pcsd
def makepairs x y xy = array [[a b] for a in asarray x for b in asarray y ] return xy T
15419
def makepairs(x, y): xy = array([[a, b] for a in asarray(x) for b in asarray(y)]) return xy.T
Helper function to create an array of pairs of x and y.
helper function to create an array of pairs of x and y .
Question: What does this function do? Code: def makepairs(x, y): xy = array([[a, b] for a in asarray(x) for b in asarray(y)]) return xy.T
null
null
null
What does this function do?
def setup_platform(hass, config, add_devices, discovery_info=None): if ((discovery_info is None) or (zwave.NETWORK is None)): return node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]] value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]] if ((value.command_class == zwave.const.COMMAND_C...
null
null
null
Find and return Z-Wave covers.
pcsd
def setup platform hass config add devices discovery info=None if discovery info is None or zwave NETWORK is None return node = zwave NETWORK nodes[discovery info[zwave const ATTR NODE ID]] value = node values[discovery info[zwave const ATTR VALUE ID]] if value command class == zwave const COMMAND CLASS SWITCH MULTILEV...
15427
def setup_platform(hass, config, add_devices, discovery_info=None): if ((discovery_info is None) or (zwave.NETWORK is None)): return node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]] value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]] if ((value.command_class == zwave.const.COMMAND_C...
Find and return Z-Wave covers.
find and return z - wave covers .
Question: What does this function do? Code: def setup_platform(hass, config, add_devices, discovery_info=None): if ((discovery_info is None) or (zwave.NETWORK is None)): return node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]] value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]] if...
null
null
null
What does this function do?
def setupApp(root, flist): if (not runningAsOSXApp()): return hideTkConsole(root) overrideRootMenu(root, flist) addOpenEventSupport(root, flist)
null
null
null
Perform setup for the OSX application bundle.
pcsd
def setup App root flist if not running As OSX App return hide Tk Console root override Root Menu root flist add Open Event Support root flist
15430
def setupApp(root, flist): if (not runningAsOSXApp()): return hideTkConsole(root) overrideRootMenu(root, flist) addOpenEventSupport(root, flist)
Perform setup for the OSX application bundle.
perform setup for the osx application bundle .
Question: What does this function do? Code: def setupApp(root, flist): if (not runningAsOSXApp()): return hideTkConsole(root) overrideRootMenu(root, flist) addOpenEventSupport(root, flist)
null
null
null
What does this function do?
def sort_from_strings(model_cls, sort_parts): if (not sort_parts): return query.NullSort() else: sort = query.MultipleSort() for part in sort_parts: sort.add_sort(construct_sort_part(model_cls, part)) return sort
null
null
null
Create a `Sort` from a list of sort criteria (strings).
pcsd
def sort from strings model cls sort parts if not sort parts return query Null Sort else sort = query Multiple Sort for part in sort parts sort add sort construct sort part model cls part return sort
15438
def sort_from_strings(model_cls, sort_parts): if (not sort_parts): return query.NullSort() else: sort = query.MultipleSort() for part in sort_parts: sort.add_sort(construct_sort_part(model_cls, part)) return sort
Create a `Sort` from a list of sort criteria (strings).
create a sort from a list of sort criteria .
Question: What does this function do? Code: def sort_from_strings(model_cls, sort_parts): if (not sort_parts): return query.NullSort() else: sort = query.MultipleSort() for part in sort_parts: sort.add_sort(construct_sort_part(model_cls, part)) return sort
null
null
null
What does this function do?
def image_property_delete(context, prop_ref, session=None): prop_ref.delete(session=session) return prop_ref
null
null
null
Used internally by image_property_create and image_property_update
pcsd
def image property delete context prop ref session=None prop ref delete session=session return prop ref
15446
def image_property_delete(context, prop_ref, session=None): prop_ref.delete(session=session) return prop_ref
Used internally by image_property_create and image_property_update
used internally by image _ property _ create and image _ property _ update
Question: What does this function do? Code: def image_property_delete(context, prop_ref, session=None): prop_ref.delete(session=session) return prop_ref
null
null
null
What does this function do?
def map_url_in(request, env, app=False): THREAD_LOCAL.routes = params map = MapUrlIn(request=request, env=env) map.sluggify() map.map_prefix() map.map_app() if params.routes_app: THREAD_LOCAL.routes = params_apps.get(app, params) if app: return map.application (root_static_file, version) = map.map_root_stat...
null
null
null
Routes incoming URL
pcsd
def map url in request env app=False THREAD LOCAL routes = params map = Map Url In request=request env=env map sluggify map map prefix map map app if params routes app THREAD LOCAL routes = params apps get app params if app return map application root static file version = map map root static if root static file map up...
15452
def map_url_in(request, env, app=False): THREAD_LOCAL.routes = params map = MapUrlIn(request=request, env=env) map.sluggify() map.map_prefix() map.map_app() if params.routes_app: THREAD_LOCAL.routes = params_apps.get(app, params) if app: return map.application (root_static_file, version) = map.map_root_stat...
Routes incoming URL
routes incoming url
Question: What does this function do? Code: def map_url_in(request, env, app=False): THREAD_LOCAL.routes = params map = MapUrlIn(request=request, env=env) map.sluggify() map.map_prefix() map.map_app() if params.routes_app: THREAD_LOCAL.routes = params_apps.get(app, params) if app: return map.application ...
null
null
null
What does this function do?
def render(tmplname, data): here = os.path.dirname(__file__) tmpl = os.path.join(here, 'templates', tmplname) data['env'] = os.environ data['shell_ok'] = recording.config.SHELL_OK data['multithread'] = os.getenv('wsgi.multithread') try: return _template.render(tmpl, data) except Exception as err: logging.exc...
null
null
null
Helper function to render a template.
pcsd
def render tmplname data here = os path dirname file tmpl = os path join here 'templates' tmplname data['env'] = os environ data['shell ok'] = recording config SHELL OK data['multithread'] = os getenv 'wsgi multithread' try return template render tmpl data except Exception as err logging exception 'Failed to render %s'...
15460
def render(tmplname, data): here = os.path.dirname(__file__) tmpl = os.path.join(here, 'templates', tmplname) data['env'] = os.environ data['shell_ok'] = recording.config.SHELL_OK data['multithread'] = os.getenv('wsgi.multithread') try: return _template.render(tmpl, data) except Exception as err: logging.exc...
Helper function to render a template.
helper function to render a template .
Question: What does this function do? Code: def render(tmplname, data): here = os.path.dirname(__file__) tmpl = os.path.join(here, 'templates', tmplname) data['env'] = os.environ data['shell_ok'] = recording.config.SHELL_OK data['multithread'] = os.getenv('wsgi.multithread') try: return _template.render(tmpl...
null
null
null
What does this function do?
def submodule_update(git_path, module, dest, track_submodules, force=False): params = get_submodule_update_params(module, git_path, dest) if (not os.path.exists(os.path.join(dest, '.gitmodules'))): return (0, '', '') cmd = [git_path, 'submodule', 'sync'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd...
null
null
null
init and update any submodules
pcsd
def submodule update git path module dest track submodules force=False params = get submodule update params module git path dest if not os path exists os path join dest ' gitmodules' return 0 '' '' cmd = [git path 'submodule' 'sync'] rc out err = module run command cmd check rc=True cwd=dest if 'remote' in params and t...
15462
def submodule_update(git_path, module, dest, track_submodules, force=False): params = get_submodule_update_params(module, git_path, dest) if (not os.path.exists(os.path.join(dest, '.gitmodules'))): return (0, '', '') cmd = [git_path, 'submodule', 'sync'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd...
init and update any submodules
init and update any submodules
Question: What does this function do? Code: def submodule_update(git_path, module, dest, track_submodules, force=False): params = get_submodule_update_params(module, git_path, dest) if (not os.path.exists(os.path.join(dest, '.gitmodules'))): return (0, '', '') cmd = [git_path, 'submodule', 'sync'] (rc, out, er...
null
null
null
What does this function do?
def chop(seq, size): return [seq[i:(i + size)] for i in range(0, len(seq), size)]
null
null
null
Chop a sequence into chunks of the given size.
pcsd
def chop seq size return [seq[i i + size ] for i in range 0 len seq size ]
15469
def chop(seq, size): return [seq[i:(i + size)] for i in range(0, len(seq), size)]
Chop a sequence into chunks of the given size.
chop a sequence into chunks of the given size .
Question: What does this function do? Code: def chop(seq, size): return [seq[i:(i + size)] for i in range(0, len(seq), size)]
null
null
null
What does this function do?
def check(a, exclude=[], check_attr=True): protocols = [0, 1, 2, copy.copy, copy.deepcopy] if (sys.version_info >= (3,)): protocols.extend([3]) if (sys.version_info >= (3, 4)): protocols.extend([4]) if cloudpickle: protocols.extend([cloudpickle]) for protocol in protocols: if (protocol in exclude): cont...
null
null
null
Check that pickling and copying round-trips.
pcsd
def check a exclude=[] check attr=True protocols = [0 1 2 copy copy copy deepcopy] if sys version info >= 3 protocols extend [3] if sys version info >= 3 4 protocols extend [4] if cloudpickle protocols extend [cloudpickle] for protocol in protocols if protocol in exclude continue if callable protocol if isinstance a Ba...
15470
def check(a, exclude=[], check_attr=True): protocols = [0, 1, 2, copy.copy, copy.deepcopy] if (sys.version_info >= (3,)): protocols.extend([3]) if (sys.version_info >= (3, 4)): protocols.extend([4]) if cloudpickle: protocols.extend([cloudpickle]) for protocol in protocols: if (protocol in exclude): cont...
Check that pickling and copying round-trips.
check that pickling and copying round - trips .
Question: What does this function do? Code: def check(a, exclude=[], check_attr=True): protocols = [0, 1, 2, copy.copy, copy.deepcopy] if (sys.version_info >= (3,)): protocols.extend([3]) if (sys.version_info >= (3, 4)): protocols.extend([4]) if cloudpickle: protocols.extend([cloudpickle]) for protocol in...
null
null
null
What does this function do?
def get_tensor_with_parent_name(tensor): tensor_name = tensor.name if (tensor.op.inputs[0].name is not None): return ((tensor.op.inputs[0].name + '_') + tensor_name) return tensor_name
null
null
null
Get a tensor name with its parent tensor\'s name as prefix.
pcsd
def get tensor with parent name tensor tensor name = tensor name if tensor op inputs[0] name is not None return tensor op inputs[0] name + ' ' + tensor name return tensor name
15473
def get_tensor_with_parent_name(tensor): tensor_name = tensor.name if (tensor.op.inputs[0].name is not None): return ((tensor.op.inputs[0].name + '_') + tensor_name) return tensor_name
Get a tensor name with its parent tensor\'s name as prefix.
get a tensor name with its parent tensors name as prefix .
Question: What does this function do? Code: def get_tensor_with_parent_name(tensor): tensor_name = tensor.name if (tensor.op.inputs[0].name is not None): return ((tensor.op.inputs[0].name + '_') + tensor_name) return tensor_name
null
null
null
What does this function do?
@disable_signal_for_loaddata def update_simple_plugins(**kwargs): instance = kwargs[u'instance'] if kwargs.get(u'created', False): p_revisions = SimplePlugin.objects.filter(article=instance.article, deleted=False) p_revisions.update(article_revision=instance)
null
null
null
Every time a new article revision is created, we update all active plugins to match this article revision
pcsd
@disable signal for loaddata def update simple plugins **kwargs instance = kwargs[u'instance'] if kwargs get u'created' False p revisions = Simple Plugin objects filter article=instance article deleted=False p revisions update article revision=instance
15477
@disable_signal_for_loaddata def update_simple_plugins(**kwargs): instance = kwargs[u'instance'] if kwargs.get(u'created', False): p_revisions = SimplePlugin.objects.filter(article=instance.article, deleted=False) p_revisions.update(article_revision=instance)
Every time a new article revision is created, we update all active plugins to match this article revision
every time a new article revision is created , we update all active plugins to match this article revision
Question: What does this function do? Code: @disable_signal_for_loaddata def update_simple_plugins(**kwargs): instance = kwargs[u'instance'] if kwargs.get(u'created', False): p_revisions = SimplePlugin.objects.filter(article=instance.article, deleted=False) p_revisions.update(article_revision=instance)
null
null
null
What does this function do?
def dataset_map_from_iterable(iterable): return {dataset.dataset_id: dataset for dataset in iterable}
null
null
null
Turn a list of datasets into a map from their IDs to the datasets.
pcsd
def dataset map from iterable iterable return {dataset dataset id dataset for dataset in iterable}
15499
def dataset_map_from_iterable(iterable): return {dataset.dataset_id: dataset for dataset in iterable}
Turn a list of datasets into a map from their IDs to the datasets.
turn a list of datasets into a map from their ids to the datasets .
Question: What does this function do? Code: def dataset_map_from_iterable(iterable): return {dataset.dataset_id: dataset for dataset in iterable}
null
null
null
What does this function do?
def describe_token_expr(expr): if (':' in expr): (type, value) = expr.split(':', 1) if (type == 'name'): return value else: type = expr return _describe_token_type(type)
null
null
null
Like `describe_token` but for token expressions.
pcsd
def describe token expr expr if ' ' in expr type value = expr split ' ' 1 if type == 'name' return value else type = expr return describe token type type
15502
def describe_token_expr(expr): if (':' in expr): (type, value) = expr.split(':', 1) if (type == 'name'): return value else: type = expr return _describe_token_type(type)
Like `describe_token` but for token expressions.
like describe _ token but for token expressions .
Question: What does this function do? Code: def describe_token_expr(expr): if (':' in expr): (type, value) = expr.split(':', 1) if (type == 'name'): return value else: type = expr return _describe_token_type(type)
null
null
null
What does this function do?
def email_inbox(): if (not auth.s3_logged_in()): session.error = T('Requires Login!') redirect(URL(c='default', f='user', args='login')) s3.filter = (FS('inbound') == True) from s3 import S3SQLCustomForm, S3SQLInlineComponent crud_form = S3SQLCustomForm('date', 'subject', 'from_address', 'body', S3SQLInlineComp...
null
null
null
RESTful CRUD controller for the Email Inbox - all Inbound Email Messages are visible here
pcsd
def email inbox if not auth s3 logged in session error = T 'Requires Login!' redirect URL c='default' f='user' args='login' s3 filter = FS 'inbound' == True from s3 import S3SQL Custom Form S3SQL Inline Component crud form = S3SQL Custom Form 'date' 'subject' 'from address' 'body' S3SQL Inline Component 'attachment' na...
15506
def email_inbox(): if (not auth.s3_logged_in()): session.error = T('Requires Login!') redirect(URL(c='default', f='user', args='login')) s3.filter = (FS('inbound') == True) from s3 import S3SQLCustomForm, S3SQLInlineComponent crud_form = S3SQLCustomForm('date', 'subject', 'from_address', 'body', S3SQLInlineComp...
RESTful CRUD controller for the Email Inbox - all Inbound Email Messages are visible here
restful crud controller for the email inbox - all inbound email messages are visible here
Question: What does this function do? Code: def email_inbox(): if (not auth.s3_logged_in()): session.error = T('Requires Login!') redirect(URL(c='default', f='user', args='login')) s3.filter = (FS('inbound') == True) from s3 import S3SQLCustomForm, S3SQLInlineComponent crud_form = S3SQLCustomForm('date', 'su...
null
null
null
What does this function do?
def delete_system_info(key, default=None): obj = meta.Session.query(SystemInfo).filter_by(key=key).first() if obj: meta.Session.delete(obj) meta.Session.commit()
null
null
null
delete data from system_info table
pcsd
def delete system info key default=None obj = meta Session query System Info filter by key=key first if obj meta Session delete obj meta Session commit
15516
def delete_system_info(key, default=None): obj = meta.Session.query(SystemInfo).filter_by(key=key).first() if obj: meta.Session.delete(obj) meta.Session.commit()
delete data from system_info table
delete data from system _ info table
Question: What does this function do? Code: def delete_system_info(key, default=None): obj = meta.Session.query(SystemInfo).filter_by(key=key).first() if obj: meta.Session.delete(obj) meta.Session.commit()
null
null
null
What does this function do?
def dist_string(dist): out = ('%.1f%%' % ((1 - dist) * 100)) if (dist <= config['match']['strong_rec_thresh'].as_number()): out = ui.colorize('green', out) elif (dist <= config['match']['medium_rec_thresh'].as_number()): out = ui.colorize('yellow', out) else: out = ui.colorize('red', out) return out
null
null
null
Formats a distance (a float) as a colorized similarity percentage string.
pcsd
def dist string dist out = '% 1f%%' % 1 - dist * 100 if dist <= config['match']['strong rec thresh'] as number out = ui colorize 'green' out elif dist <= config['match']['medium rec thresh'] as number out = ui colorize 'yellow' out else out = ui colorize 'red' out return out
15518
def dist_string(dist): out = ('%.1f%%' % ((1 - dist) * 100)) if (dist <= config['match']['strong_rec_thresh'].as_number()): out = ui.colorize('green', out) elif (dist <= config['match']['medium_rec_thresh'].as_number()): out = ui.colorize('yellow', out) else: out = ui.colorize('red', out) return out
Formats a distance (a float) as a colorized similarity percentage string.
formats a distance as a colorized similarity percentage string .
Question: What does this function do? Code: def dist_string(dist): out = ('%.1f%%' % ((1 - dist) * 100)) if (dist <= config['match']['strong_rec_thresh'].as_number()): out = ui.colorize('green', out) elif (dist <= config['match']['medium_rec_thresh'].as_number()): out = ui.colorize('yellow', out) else: out...
null
null
null
What does this function do?
def addToCraftMenu(menu): settings.ToolDialog().addPluginToMenu(menu, archive.getUntilDot(archive.getSkeinforgePluginsPath('craft.py'))) menu.add_separator() directoryPath = skeinforge_craft.getPluginsDirectoryPath() directoryFolders = settings.getFolders(directoryPath) pluginFileNames = skeinforge_craft.getPlugin...
null
null
null
Add a craft plugin menu.
pcsd
def add To Craft Menu menu settings Tool Dialog add Plugin To Menu menu archive get Until Dot archive get Skeinforge Plugins Path 'craft py' menu add separator directory Path = skeinforge craft get Plugins Directory Path directory Folders = settings get Folders directory Path plugin File Names = skeinforge craft get Pl...
15522
def addToCraftMenu(menu): settings.ToolDialog().addPluginToMenu(menu, archive.getUntilDot(archive.getSkeinforgePluginsPath('craft.py'))) menu.add_separator() directoryPath = skeinforge_craft.getPluginsDirectoryPath() directoryFolders = settings.getFolders(directoryPath) pluginFileNames = skeinforge_craft.getPlugin...
Add a craft plugin menu.
add a craft plugin menu .
Question: What does this function do? Code: def addToCraftMenu(menu): settings.ToolDialog().addPluginToMenu(menu, archive.getUntilDot(archive.getSkeinforgePluginsPath('craft.py'))) menu.add_separator() directoryPath = skeinforge_craft.getPluginsDirectoryPath() directoryFolders = settings.getFolders(directoryPath...
null
null
null
What does this function do?
@use_clip_fps_by_default def find_video_period(clip, fps=None, tmin=0.3): frame = (lambda t: clip.get_frame(t).flatten()) tt = np.arange(tmin, clip.duration, (1.0 / fps))[1:] ref = frame(0) corrs = [np.corrcoef(ref, frame(t))[(0, 1)] for t in tt] return tt[np.argmax(corrs)]
null
null
null
Finds the period of a video based on frames correlation
pcsd
@use clip fps by default def find video period clip fps=None tmin=0 3 frame = lambda t clip get frame t flatten tt = np arange tmin clip duration 1 0 / fps [1 ] ref = frame 0 corrs = [np corrcoef ref frame t [ 0 1 ] for t in tt] return tt[np argmax corrs ]
15525
@use_clip_fps_by_default def find_video_period(clip, fps=None, tmin=0.3): frame = (lambda t: clip.get_frame(t).flatten()) tt = np.arange(tmin, clip.duration, (1.0 / fps))[1:] ref = frame(0) corrs = [np.corrcoef(ref, frame(t))[(0, 1)] for t in tt] return tt[np.argmax(corrs)]
Finds the period of a video based on frames correlation
finds the period of a video based on frames correlation
Question: What does this function do? Code: @use_clip_fps_by_default def find_video_period(clip, fps=None, tmin=0.3): frame = (lambda t: clip.get_frame(t).flatten()) tt = np.arange(tmin, clip.duration, (1.0 / fps))[1:] ref = frame(0) corrs = [np.corrcoef(ref, frame(t))[(0, 1)] for t in tt] return tt[np.argmax(c...
null
null
null
What does this function do?
def map_string2func(funcname, clss, compute_capability): if (('_get_' + funcname) not in globals()): raise AttributeError((("kernel type '" + funcname) + "' not understood")) return globals()[('_get_' + funcname)](clss, compute_capability)
null
null
null
Helper function that converts string function names to function calls
pcsd
def map string2func funcname clss compute capability if ' get ' + funcname not in globals raise Attribute Error "kernel type '" + funcname + "' not understood" return globals [ ' get ' + funcname ] clss compute capability
15527
def map_string2func(funcname, clss, compute_capability): if (('_get_' + funcname) not in globals()): raise AttributeError((("kernel type '" + funcname) + "' not understood")) return globals()[('_get_' + funcname)](clss, compute_capability)
Helper function that converts string function names to function calls
helper function that converts string function names to function calls
Question: What does this function do? Code: def map_string2func(funcname, clss, compute_capability): if (('_get_' + funcname) not in globals()): raise AttributeError((("kernel type '" + funcname) + "' not understood")) return globals()[('_get_' + funcname)](clss, compute_capability)
null
null
null
What does this function do?
def enumerate_projects(): src_path = os.path.join(_DEFAULT_APP_DIR, 'src') projects = {} for project in os.listdir(src_path): projects[project] = [] project_path = os.path.join(src_path, project) for file in os.listdir(project_path): if file.endswith('.gwt.xml'): projects[project].append(file[:(-8)]) r...
null
null
null
List projects in _DEFAULT_APP_DIR.
pcsd
def enumerate projects src path = os path join DEFAULT APP DIR 'src' projects = {} for project in os listdir src path projects[project] = [] project path = os path join src path project for file in os listdir project path if file endswith ' gwt xml' projects[project] append file[ -8 ] return projects
15529
def enumerate_projects(): src_path = os.path.join(_DEFAULT_APP_DIR, 'src') projects = {} for project in os.listdir(src_path): projects[project] = [] project_path = os.path.join(src_path, project) for file in os.listdir(project_path): if file.endswith('.gwt.xml'): projects[project].append(file[:(-8)]) r...
List projects in _DEFAULT_APP_DIR.
list projects in _ default _ app _ dir .
Question: What does this function do? Code: def enumerate_projects(): src_path = os.path.join(_DEFAULT_APP_DIR, 'src') projects = {} for project in os.listdir(src_path): projects[project] = [] project_path = os.path.join(src_path, project) for file in os.listdir(project_path): if file.endswith('.gwt.xml'...
null
null
null
What does this function do?
def encode_string(v, encoding=u'utf-8'): if isinstance(encoding, basestring): encoding = (((encoding,),) + ((u'windows-1252',), (u'utf-8', u'ignore'))) if isinstance(v, unicode): for e in encoding: try: return v.encode(*e) except: pass return v return str(v)
null
null
null
Returns the given value as a Python byte string (if possible).
pcsd
def encode string v encoding=u'utf-8' if isinstance encoding basestring encoding = encoding + u'windows-1252' u'utf-8' u'ignore' if isinstance v unicode for e in encoding try return v encode *e except pass return v return str v
15535
def encode_string(v, encoding=u'utf-8'): if isinstance(encoding, basestring): encoding = (((encoding,),) + ((u'windows-1252',), (u'utf-8', u'ignore'))) if isinstance(v, unicode): for e in encoding: try: return v.encode(*e) except: pass return v return str(v)
Returns the given value as a Python byte string (if possible).
returns the given value as a python byte string .
Question: What does this function do? Code: def encode_string(v, encoding=u'utf-8'): if isinstance(encoding, basestring): encoding = (((encoding,),) + ((u'windows-1252',), (u'utf-8', u'ignore'))) if isinstance(v, unicode): for e in encoding: try: return v.encode(*e) except: pass return v retur...
null
null
null
What does this function do?
def regex_replace(value='', pattern='', replacement='', ignorecase=False): value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr') if ignorecase: flags = re.I else: flags = 0 _re = re.compile(pattern, flags=flags) return _re.sub(replacement, value)
null
null
null
Perform a `re.sub` returning a string
pcsd
def regex replace value='' pattern='' replacement='' ignorecase=False value = to text value errors='surrogate or strict' nonstring='simplerepr' if ignorecase flags = re I else flags = 0 re = re compile pattern flags=flags return re sub replacement value
15536
def regex_replace(value='', pattern='', replacement='', ignorecase=False): value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr') if ignorecase: flags = re.I else: flags = 0 _re = re.compile(pattern, flags=flags) return _re.sub(replacement, value)
Perform a `re.sub` returning a string
perform a re . sub returning a string
Question: What does this function do? Code: def regex_replace(value='', pattern='', replacement='', ignorecase=False): value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr') if ignorecase: flags = re.I else: flags = 0 _re = re.compile(pattern, flags=flags) return _re.sub(replacement, v...
null
null
null
What does this function do?
@handle_response_format @treeio_login_required def folder_add_typed(request, folder_id=None, response_format='html'): folder = None if folder_id: folder = get_object_or_404(Folder, pk=folder_id) if (not request.user.profile.has_permission(folder, mode='x')): folder = None if request.POST: if ('cancel' not i...
null
null
null
Folder add to preselected folder
pcsd
@handle response format @treeio login required def folder add typed request folder id=None response format='html' folder = None if folder id folder = get object or 404 Folder pk=folder id if not request user profile has permission folder mode='x' folder = None if request POST if 'cancel' not in request POST folder = Fo...
15557
@handle_response_format @treeio_login_required def folder_add_typed(request, folder_id=None, response_format='html'): folder = None if folder_id: folder = get_object_or_404(Folder, pk=folder_id) if (not request.user.profile.has_permission(folder, mode='x')): folder = None if request.POST: if ('cancel' not i...
Folder add to preselected folder
folder add to preselected folder
Question: What does this function do? Code: @handle_response_format @treeio_login_required def folder_add_typed(request, folder_id=None, response_format='html'): folder = None if folder_id: folder = get_object_or_404(Folder, pk=folder_id) if (not request.user.profile.has_permission(folder, mode='x')): folde...
null
null
null
What does this function do?
def jacobi(a, b): if ((a % b) == 0): return 0 result = 1 while (a > 1): if (a & 1): if ((((a - 1) * (b - 1)) >> 2) & 1): result = (- result) (b, a) = (a, (b % a)) else: if ((((b ** 2) - 1) >> 3) & 1): result = (- result) a = (a >> 1) return result
null
null
null
Calculates the value of the Jacobi symbol (a/b)
pcsd
def jacobi a b if a % b == 0 return 0 result = 1 while a > 1 if a & 1 if a - 1 * b - 1 >> 2 & 1 result = - result b a = a b % a else if b ** 2 - 1 >> 3 & 1 result = - result a = a >> 1 return result
15563
def jacobi(a, b): if ((a % b) == 0): return 0 result = 1 while (a > 1): if (a & 1): if ((((a - 1) * (b - 1)) >> 2) & 1): result = (- result) (b, a) = (a, (b % a)) else: if ((((b ** 2) - 1) >> 3) & 1): result = (- result) a = (a >> 1) return result
Calculates the value of the Jacobi symbol (a/b)
calculates the value of the jacobi symbol
Question: What does this function do? Code: def jacobi(a, b): if ((a % b) == 0): return 0 result = 1 while (a > 1): if (a & 1): if ((((a - 1) * (b - 1)) >> 2) & 1): result = (- result) (b, a) = (a, (b % a)) else: if ((((b ** 2) - 1) >> 3) & 1): result = (- result) a = (a >> 1) return re...
null
null
null
What does this function do?
def _recursive_flatten(cell, dtype): while (not isinstance(cell[0], dtype)): cell = [c for d in cell for c in d] return cell
null
null
null
Helper to unpack mat files in Python.
pcsd
def recursive flatten cell dtype while not isinstance cell[0] dtype cell = [c for d in cell for c in d] return cell
15568
def _recursive_flatten(cell, dtype): while (not isinstance(cell[0], dtype)): cell = [c for d in cell for c in d] return cell
Helper to unpack mat files in Python.
helper to unpack mat files in python .
Question: What does this function do? Code: def _recursive_flatten(cell, dtype): while (not isinstance(cell[0], dtype)): cell = [c for d in cell for c in d] return cell
null
null
null
What does this function do?
def atomic_open(filename, mode='w'): if (mode in ('r', 'rb', 'r+', 'rb+', 'a', 'ab')): raise TypeError("Read or append modes don't work with atomic_open") ntf = tempfile.NamedTemporaryFile(mode, prefix='.___atomic_write', dir=os.path.dirname(filename), delete=False) return _AtomicWFile(ntf, ntf.name, filename)
null
null
null
Works like a regular `open()` but writes updates into a temporary file instead of the given file and moves it over when the file is closed. The file returned behaves as if it was a regular Python
pcsd
def atomic open filename mode='w' if mode in 'r' 'rb' 'r+' 'rb+' 'a' 'ab' raise Type Error "Read or append modes don't work with atomic open" ntf = tempfile Named Temporary File mode prefix=' atomic write' dir=os path dirname filename delete=False return Atomic W File ntf ntf name filename
15569
def atomic_open(filename, mode='w'): if (mode in ('r', 'rb', 'r+', 'rb+', 'a', 'ab')): raise TypeError("Read or append modes don't work with atomic_open") ntf = tempfile.NamedTemporaryFile(mode, prefix='.___atomic_write', dir=os.path.dirname(filename), delete=False) return _AtomicWFile(ntf, ntf.name, filename)
Works like a regular `open()` but writes updates into a temporary file instead of the given file and moves it over when the file is closed. The file returned behaves as if it was a regular Python
works like a regular open ( ) but writes updates into a temporary file instead of the given file and moves it over when the file is closed .
Question: What does this function do? Code: def atomic_open(filename, mode='w'): if (mode in ('r', 'rb', 'r+', 'rb+', 'a', 'ab')): raise TypeError("Read or append modes don't work with atomic_open") ntf = tempfile.NamedTemporaryFile(mode, prefix='.___atomic_write', dir=os.path.dirname(filename), delete=False) r...
null
null
null
What does this function do?
def _send_textmetrics(metrics): data = ([' '.join(map(str, metric)) for metric in metrics] + ['']) return '\n'.join(data)
null
null
null
Format metrics for the carbon plaintext protocol
pcsd
def send textmetrics metrics data = [' ' join map str metric for metric in metrics] + [''] return ' ' join data
15576
def _send_textmetrics(metrics): data = ([' '.join(map(str, metric)) for metric in metrics] + ['']) return '\n'.join(data)
Format metrics for the carbon plaintext protocol
format metrics for the carbon plaintext protocol
Question: What does this function do? Code: def _send_textmetrics(metrics): data = ([' '.join(map(str, metric)) for metric in metrics] + ['']) return '\n'.join(data)
null
null
null
What does this function do?
def describe_form(label, fields=None): from django.db.models.loading import get_model try: (app_name, model_name) = label.split('.')[(-2):] except (IndexError, ValueError): raise CommandError('Need application and model name in the form: appname.model') model = get_model(app_name, model_name) opts = model._met...
null
null
null
Returns a string describing a form based on the model
pcsd
def describe form label fields=None from django db models loading import get model try app name model name = label split ' ' [ -2 ] except Index Error Value Error raise Command Error 'Need application and model name in the form appname model' model = get model app name model name opts = model meta field list = [] for f...
15585
def describe_form(label, fields=None): from django.db.models.loading import get_model try: (app_name, model_name) = label.split('.')[(-2):] except (IndexError, ValueError): raise CommandError('Need application and model name in the form: appname.model') model = get_model(app_name, model_name) opts = model._met...
Returns a string describing a form based on the model
returns a string describing a form based on the model
Question: What does this function do? Code: def describe_form(label, fields=None): from django.db.models.loading import get_model try: (app_name, model_name) = label.split('.')[(-2):] except (IndexError, ValueError): raise CommandError('Need application and model name in the form: appname.model') model = get...
null
null
null
What does this function do?
def get_pkg_name(args, pkg_path): recipes_dir = args.recipes_dir input_dir = os.path.dirname(os.path.join(recipes_dir, pkg_path)) recipe_meta = MetaData(input_dir) return recipe_meta.get_value('package/name')
null
null
null
Extract the package name from a given meta.yaml file.
pcsd
def get pkg name args pkg path recipes dir = args recipes dir input dir = os path dirname os path join recipes dir pkg path recipe meta = Meta Data input dir return recipe meta get value 'package/name'
15586
def get_pkg_name(args, pkg_path): recipes_dir = args.recipes_dir input_dir = os.path.dirname(os.path.join(recipes_dir, pkg_path)) recipe_meta = MetaData(input_dir) return recipe_meta.get_value('package/name')
Extract the package name from a given meta.yaml file.
extract the package name from a given meta . yaml file .
Question: What does this function do? Code: def get_pkg_name(args, pkg_path): recipes_dir = args.recipes_dir input_dir = os.path.dirname(os.path.join(recipes_dir, pkg_path)) recipe_meta = MetaData(input_dir) return recipe_meta.get_value('package/name')
null
null
null
What does this function do?
@register.function def license_link(license): from olympia.versions.models import License if isinstance(license, (long, int)): if (license in PERSONA_LICENSES_IDS): license = PERSONA_LICENSES_IDS[license] else: license = License.objects.filter(id=license) if (not license.exists()): return '' licen...
null
null
null
Link to a code license, including icon where applicable.
pcsd
@register function def license link license from olympia versions models import License if isinstance license long int if license in PERSONA LICENSES IDS license = PERSONA LICENSES IDS[license] else license = License objects filter id=license if not license exists return '' license = license[0] elif not license return ...
15587
@register.function def license_link(license): from olympia.versions.models import License if isinstance(license, (long, int)): if (license in PERSONA_LICENSES_IDS): license = PERSONA_LICENSES_IDS[license] else: license = License.objects.filter(id=license) if (not license.exists()): return '' licen...
Link to a code license, including icon where applicable.
link to a code license , including icon where applicable .
Question: What does this function do? Code: @register.function def license_link(license): from olympia.versions.models import License if isinstance(license, (long, int)): if (license in PERSONA_LICENSES_IDS): license = PERSONA_LICENSES_IDS[license] else: license = License.objects.filter(id=license) if...
null
null
null
What does this function do?
@command(('(%s{0,3})(?:\\*|all)\\s*(%s{0,3})' % (RS, RS))) def play_all(pre, choice, post=''): options = ((pre + choice) + post) play(options, ('1-' + str(len(g.model))))
null
null
null
Play all tracks in model (last displayed). shuffle/repeat if req\'d.
pcsd
@command ' %s{0 3} ? \\*|all \\s* %s{0 3} ' % RS RS def play all pre choice post='' options = pre + choice + post play options '1-' + str len g model
15588
@command(('(%s{0,3})(?:\\*|all)\\s*(%s{0,3})' % (RS, RS))) def play_all(pre, choice, post=''): options = ((pre + choice) + post) play(options, ('1-' + str(len(g.model))))
Play all tracks in model (last displayed). shuffle/repeat if req\'d.
play all tracks in model .
Question: What does this function do? Code: @command(('(%s{0,3})(?:\\*|all)\\s*(%s{0,3})' % (RS, RS))) def play_all(pre, choice, post=''): options = ((pre + choice) + post) play(options, ('1-' + str(len(g.model))))
null
null
null
What does this function do?
def _get_child_text(parent, tag, construct=unicode): child = parent.find(_ns(tag)) if ((child is not None) and child.text): return construct(child.text)
null
null
null
Find a child node by tag; pass its text through a constructor. Returns None if no matching child is found.
pcsd
def get child text parent tag construct=unicode child = parent find ns tag if child is not None and child text return construct child text
15595
def _get_child_text(parent, tag, construct=unicode): child = parent.find(_ns(tag)) if ((child is not None) and child.text): return construct(child.text)
Find a child node by tag; pass its text through a constructor. Returns None if no matching child is found.
find a child node by tag ; pass its text through a constructor .
Question: What does this function do? Code: def _get_child_text(parent, tag, construct=unicode): child = parent.find(_ns(tag)) if ((child is not None) and child.text): return construct(child.text)
null
null
null
What does this function do?
def resource(name): def make_responder(retriever): def responder(ids): entities = [retriever(id) for id in ids] entities = [entity for entity in entities if entity] if (len(entities) == 1): return flask.jsonify(_rep(entities[0], expand=is_expand())) elif entities: return app.response_class(json_g...
null
null
null
Decorates a function to handle RESTful HTTP requests for a resource.
pcsd
def resource name def make responder retriever def responder ids entities = [retriever id for id in ids] entities = [entity for entity in entities if entity] if len entities == 1 return flask jsonify rep entities[0] expand=is expand elif entities return app response class json generator entities root=name mimetype='app...
15596
def resource(name): def make_responder(retriever): def responder(ids): entities = [retriever(id) for id in ids] entities = [entity for entity in entities if entity] if (len(entities) == 1): return flask.jsonify(_rep(entities[0], expand=is_expand())) elif entities: return app.response_class(json_g...
Decorates a function to handle RESTful HTTP requests for a resource.
decorates a function to handle restful http requests for a resource .
Question: What does this function do? Code: def resource(name): def make_responder(retriever): def responder(ids): entities = [retriever(id) for id in ids] entities = [entity for entity in entities if entity] if (len(entities) == 1): return flask.jsonify(_rep(entities[0], expand=is_expand())) elif...
null
null
null
What does this function do?
@contextlib.contextmanager def check_remains_sorted(X): if ((not hasattr(X, 'has_sorted_indices')) or (not X.has_sorted_indices)): (yield) return (yield) indices = X.indices.copy() X.has_sorted_indices = False X.sort_indices() assert_array_equal(indices, X.indices, 'Expected sorted indices, found unsorted')
null
null
null
Checks that sorted indices property is retained through an operation
pcsd
@contextlib contextmanager def check remains sorted X if not hasattr X 'has sorted indices' or not X has sorted indices yield return yield indices = X indices copy X has sorted indices = False X sort indices assert array equal indices X indices 'Expected sorted indices found unsorted'
15597
@contextlib.contextmanager def check_remains_sorted(X): if ((not hasattr(X, 'has_sorted_indices')) or (not X.has_sorted_indices)): (yield) return (yield) indices = X.indices.copy() X.has_sorted_indices = False X.sort_indices() assert_array_equal(indices, X.indices, 'Expected sorted indices, found unsorted')
Checks that sorted indices property is retained through an operation
checks that sorted indices property is retained through an operation
Question: What does this function do? Code: @contextlib.contextmanager def check_remains_sorted(X): if ((not hasattr(X, 'has_sorted_indices')) or (not X.has_sorted_indices)): (yield) return (yield) indices = X.indices.copy() X.has_sorted_indices = False X.sort_indices() assert_array_equal(indices, X.indice...
null
null
null
What does this function do?
def basePost(base, a, b): base.calledBasePost = (base.calledBasePost + 1)
null
null
null
a post-hook for the base class
pcsd
def base Post base a b base called Base Post = base called Base Post + 1
15603
def basePost(base, a, b): base.calledBasePost = (base.calledBasePost + 1)
a post-hook for the base class
a post - hook for the base class
Question: What does this function do? Code: def basePost(base, a, b): base.calledBasePost = (base.calledBasePost + 1)
null
null
null
What does this function do?
def decrypt(cypher, key): return gluechops(cypher, key['d'], (key['p'] * key['q']), decrypt_int)
null
null
null
Decrypts a cypher with the private key \'key\'
pcsd
def decrypt cypher key return gluechops cypher key['d'] key['p'] * key['q'] decrypt int
15606
def decrypt(cypher, key): return gluechops(cypher, key['d'], (key['p'] * key['q']), decrypt_int)
Decrypts a cypher with the private key \'key\'
decrypts a cypher with the private key key
Question: What does this function do? Code: def decrypt(cypher, key): return gluechops(cypher, key['d'], (key['p'] * key['q']), decrypt_int)
null
null
null
What does this function do?
def get_dummy_vm_create_spec(client_factory, name, data_store_name): config_spec = client_factory.create('ns0:VirtualMachineConfigSpec') config_spec.name = name config_spec.guestId = 'otherGuest' vm_file_info = client_factory.create('ns0:VirtualMachineFileInfo') vm_file_info.vmPathName = (('[' + data_store_name) +...
null
null
null
Builds the dummy VM create spec.
pcsd
def get dummy vm create spec client factory name data store name config spec = client factory create 'ns0 Virtual Machine Config Spec' config spec name = name config spec guest Id = 'other Guest' vm file info = client factory create 'ns0 Virtual Machine File Info' vm file info vm Path Name = '[' + data store name + ']'...
15609
def get_dummy_vm_create_spec(client_factory, name, data_store_name): config_spec = client_factory.create('ns0:VirtualMachineConfigSpec') config_spec.name = name config_spec.guestId = 'otherGuest' vm_file_info = client_factory.create('ns0:VirtualMachineFileInfo') vm_file_info.vmPathName = (('[' + data_store_name) +...
Builds the dummy VM create spec.
builds the dummy vm create spec .
Question: What does this function do? Code: def get_dummy_vm_create_spec(client_factory, name, data_store_name): config_spec = client_factory.create('ns0:VirtualMachineConfigSpec') config_spec.name = name config_spec.guestId = 'otherGuest' vm_file_info = client_factory.create('ns0:VirtualMachineFileInfo') vm_fi...
null
null
null
What does this function do?
@pytest.fixture(scope='function') def remove_additional_dirs(request): def fin_remove_additional_dirs(): if os.path.isdir('fake-project'): utils.rmtree('fake-project') if os.path.isdir('fake-project-input-extra'): utils.rmtree('fake-project-input-extra') request.addfinalizer(fin_remove_additional_dirs)
null
null
null
Remove special directories which are created during the tests.
pcsd
@pytest fixture scope='function' def remove additional dirs request def fin remove additional dirs if os path isdir 'fake-project' utils rmtree 'fake-project' if os path isdir 'fake-project-input-extra' utils rmtree 'fake-project-input-extra' request addfinalizer fin remove additional dirs
15610
@pytest.fixture(scope='function') def remove_additional_dirs(request): def fin_remove_additional_dirs(): if os.path.isdir('fake-project'): utils.rmtree('fake-project') if os.path.isdir('fake-project-input-extra'): utils.rmtree('fake-project-input-extra') request.addfinalizer(fin_remove_additional_dirs)
Remove special directories which are created during the tests.
remove special directories which are created during the tests .
Question: What does this function do? Code: @pytest.fixture(scope='function') def remove_additional_dirs(request): def fin_remove_additional_dirs(): if os.path.isdir('fake-project'): utils.rmtree('fake-project') if os.path.isdir('fake-project-input-extra'): utils.rmtree('fake-project-input-extra') reques...
null
null
null
What does this function do?
def readNonWhitespace(stream): tok = WHITESPACES[0] while (tok in WHITESPACES): tok = stream.read(1) return tok
null
null
null
Finds and reads the next non-whitespace character (ignores whitespace).
pcsd
def read Non Whitespace stream tok = WHITESPACES[0] while tok in WHITESPACES tok = stream read 1 return tok
15618
def readNonWhitespace(stream): tok = WHITESPACES[0] while (tok in WHITESPACES): tok = stream.read(1) return tok
Finds and reads the next non-whitespace character (ignores whitespace).
finds and reads the next non - whitespace character .
Question: What does this function do? Code: def readNonWhitespace(stream): tok = WHITESPACES[0] while (tok in WHITESPACES): tok = stream.read(1) return tok
null
null
null
What does this function do?
def create_resource(): deserializer = wsgi.JSONRequestDeserializer() serializer = wsgi.JSONResponseSerializer() return wsgi.Resource(Controller(), deserializer, serializer)
null
null
null
Image members resource factory method.
pcsd
def create resource deserializer = wsgi JSON Request Deserializer serializer = wsgi JSON Response Serializer return wsgi Resource Controller deserializer serializer
15627
def create_resource(): deserializer = wsgi.JSONRequestDeserializer() serializer = wsgi.JSONResponseSerializer() return wsgi.Resource(Controller(), deserializer, serializer)
Image members resource factory method.
image members resource factory method .
Question: What does this function do? Code: def create_resource(): deserializer = wsgi.JSONRequestDeserializer() serializer = wsgi.JSONResponseSerializer() return wsgi.Resource(Controller(), deserializer, serializer)
null
null
null
What does this function do?
def get_msvcr(): msc_pos = sys.version.find('MSC v.') if (msc_pos != (-1)): msc_ver = sys.version[(msc_pos + 6):(msc_pos + 10)] if (msc_ver == '1300'): return ['msvcr70'] elif (msc_ver == '1310'): return ['msvcr71'] elif (msc_ver == '1400'): return ['msvcr80'] elif (msc_ver == '1500'): return ['...
null
null
null
Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later.
pcsd
def get msvcr msc pos = sys version find 'MSC v ' if msc pos != -1 msc ver = sys version[ msc pos + 6 msc pos + 10 ] if msc ver == '1300' return ['msvcr70'] elif msc ver == '1310' return ['msvcr71'] elif msc ver == '1400' return ['msvcr80'] elif msc ver == '1500' return ['msvcr90'] else raise Value Error 'Unknown MS Co...
15628
def get_msvcr(): msc_pos = sys.version.find('MSC v.') if (msc_pos != (-1)): msc_ver = sys.version[(msc_pos + 6):(msc_pos + 10)] if (msc_ver == '1300'): return ['msvcr70'] elif (msc_ver == '1310'): return ['msvcr71'] elif (msc_ver == '1400'): return ['msvcr80'] elif (msc_ver == '1500'): return ['...
Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later.
include the appropriate msvc runtime library if python was built with msvc 7 . 0 or later .
Question: What does this function do? Code: def get_msvcr(): msc_pos = sys.version.find('MSC v.') if (msc_pos != (-1)): msc_ver = sys.version[(msc_pos + 6):(msc_pos + 10)] if (msc_ver == '1300'): return ['msvcr70'] elif (msc_ver == '1310'): return ['msvcr71'] elif (msc_ver == '1400'): return ['msv...
null
null
null
What does this function do?
def getSegmentPath(center, loop, path, pointIndex): centerBegin = loop[pointIndex] centerEnd = loop[((pointIndex + 1) % len(loop))] centerEndMinusBegin = (centerEnd - centerBegin) if (abs(centerEndMinusBegin) <= 0.0): return [centerBegin] if (center != None): return getRadialPath(centerBegin, center, centerEnd...
null
null
null
Get segment path.
pcsd
def get Segment Path center loop path point Index center Begin = loop[point Index] center End = loop[ point Index + 1 % len loop ] center End Minus Begin = center End - center Begin if abs center End Minus Begin <= 0 0 return [center Begin] if center != None return get Radial Path center Begin center center End path be...
15634
def getSegmentPath(center, loop, path, pointIndex): centerBegin = loop[pointIndex] centerEnd = loop[((pointIndex + 1) % len(loop))] centerEndMinusBegin = (centerEnd - centerBegin) if (abs(centerEndMinusBegin) <= 0.0): return [centerBegin] if (center != None): return getRadialPath(centerBegin, center, centerEnd...
Get segment path.
get segment path .
Question: What does this function do? Code: def getSegmentPath(center, loop, path, pointIndex): centerBegin = loop[pointIndex] centerEnd = loop[((pointIndex + 1) % len(loop))] centerEndMinusBegin = (centerEnd - centerBegin) if (abs(centerEndMinusBegin) <= 0.0): return [centerBegin] if (center != None): retu...
null
null
null
What does this function do?
@pytest.mark.network def test_pip_wheel_builds_editable(script, data): script.pip('install', 'wheel') editable_path = os.path.join(data.src, 'simplewheel-1.0') result = script.pip('wheel', '--no-index', '-e', editable_path) wheel_file_name = ('simplewheel-1.0-py%s-none-any.whl' % pyversion[0]) wheel_file_path = (s...
null
null
null
Test \'pip wheel\' builds an editable package
pcsd
@pytest mark network def test pip wheel builds editable script data script pip 'install' 'wheel' editable path = os path join data src 'simplewheel-1 0' result = script pip 'wheel' '--no-index' '-e' editable path wheel file name = 'simplewheel-1 0-py%s-none-any whl' % pyversion[0] wheel file path = script scratch / whe...
15637
@pytest.mark.network def test_pip_wheel_builds_editable(script, data): script.pip('install', 'wheel') editable_path = os.path.join(data.src, 'simplewheel-1.0') result = script.pip('wheel', '--no-index', '-e', editable_path) wheel_file_name = ('simplewheel-1.0-py%s-none-any.whl' % pyversion[0]) wheel_file_path = (s...
Test \'pip wheel\' builds an editable package
test pip wheel builds an editable package
Question: What does this function do? Code: @pytest.mark.network def test_pip_wheel_builds_editable(script, data): script.pip('install', 'wheel') editable_path = os.path.join(data.src, 'simplewheel-1.0') result = script.pip('wheel', '--no-index', '-e', editable_path) wheel_file_name = ('simplewheel-1.0-py%s-none...
null
null
null
What does this function do?
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=1e-05): if ((mu != 0) or (sigma != 1)): return (mu + (sigma * inverse_normal_cdf(p, tolerance=tolerance))) (low_z, low_p) = ((-10.0), 0) (hi_z, hi_p) = (10.0, 1) while ((hi_z - low_z) > tolerance): mid_z = ((low_z + hi_z) / 2) mid_p = normal_cdf(mid_z) if (...
null
null
null
find approximate inverse using binary search
pcsd
def inverse normal cdf p mu=0 sigma=1 tolerance=1e-05 if mu != 0 or sigma != 1 return mu + sigma * inverse normal cdf p tolerance=tolerance low z low p = -10 0 0 hi z hi p = 10 0 1 while hi z - low z > tolerance mid z = low z + hi z / 2 mid p = normal cdf mid z if mid p < p low z low p = mid z mid p elif mid p > p hi z...
15643
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=1e-05): if ((mu != 0) or (sigma != 1)): return (mu + (sigma * inverse_normal_cdf(p, tolerance=tolerance))) (low_z, low_p) = ((-10.0), 0) (hi_z, hi_p) = (10.0, 1) while ((hi_z - low_z) > tolerance): mid_z = ((low_z + hi_z) / 2) mid_p = normal_cdf(mid_z) if (...
find approximate inverse using binary search
find approximate inverse using binary search
Question: What does this function do? Code: def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=1e-05): if ((mu != 0) or (sigma != 1)): return (mu + (sigma * inverse_normal_cdf(p, tolerance=tolerance))) (low_z, low_p) = ((-10.0), 0) (hi_z, hi_p) = (10.0, 1) while ((hi_z - low_z) > tolerance): mid_z = ((low_z ...
null
null
null
What does this function do?
def _limited_traceback(excinfo): tb = extract_tb(excinfo.tb) try: idx = [(__file__ in e) for e in tb].index(True) return format_list(tb[(idx + 1):]) except ValueError: return format_list(tb)
null
null
null
Return a formatted traceback with all the stack from this frame (i.e __file__) up removed
pcsd
def limited traceback excinfo tb = extract tb excinfo tb try idx = [ file in e for e in tb] index True return format list tb[ idx + 1 ] except Value Error return format list tb
15654
def _limited_traceback(excinfo): tb = extract_tb(excinfo.tb) try: idx = [(__file__ in e) for e in tb].index(True) return format_list(tb[(idx + 1):]) except ValueError: return format_list(tb)
Return a formatted traceback with all the stack from this frame (i.e __file__) up removed
return a formatted traceback with all the stack from this frame up removed
Question: What does this function do? Code: def _limited_traceback(excinfo): tb = extract_tb(excinfo.tb) try: idx = [(__file__ in e) for e in tb].index(True) return format_list(tb[(idx + 1):]) except ValueError: return format_list(tb)
null
null
null
What does this function do?
def _is_internal_request(domain, referer): return ((referer is not None) and re.match(('^https?://%s/' % re.escape(domain)), referer))
null
null
null
Return true if the referring URL is the same domain as the current request
pcsd
def is internal request domain referer return referer is not None and re match '^https? //%s/' % re escape domain referer
15665
def _is_internal_request(domain, referer): return ((referer is not None) and re.match(('^https?://%s/' % re.escape(domain)), referer))
Return true if the referring URL is the same domain as the current request
return true if the referring url is the same domain as the current request
Question: What does this function do? Code: def _is_internal_request(domain, referer): return ((referer is not None) and re.match(('^https?://%s/' % re.escape(domain)), referer))
null
null
null
What does this function do?
def main(the_map): treelist = [] if VERBOSE: print 'Planting new trees' planttrees(the_map, treelist) if VERBOSE: print 'Processing tree changes' processtrees(the_map, treelist) if FOLIAGE: if VERBOSE: print 'Generating foliage ' for i in treelist: i.makefoliage(the_map) if VERBOSE: print ' com...
null
null
null
create the trees
pcsd
def main the map treelist = [] if VERBOSE print 'Planting new trees' planttrees the map treelist if VERBOSE print 'Processing tree changes' processtrees the map treelist if FOLIAGE if VERBOSE print 'Generating foliage ' for i in treelist i makefoliage the map if VERBOSE print ' completed' if WOOD if VERBOSE print 'Gene...
15678
def main(the_map): treelist = [] if VERBOSE: print 'Planting new trees' planttrees(the_map, treelist) if VERBOSE: print 'Processing tree changes' processtrees(the_map, treelist) if FOLIAGE: if VERBOSE: print 'Generating foliage ' for i in treelist: i.makefoliage(the_map) if VERBOSE: print ' com...
create the trees
create the trees
Question: What does this function do? Code: def main(the_map): treelist = [] if VERBOSE: print 'Planting new trees' planttrees(the_map, treelist) if VERBOSE: print 'Processing tree changes' processtrees(the_map, treelist) if FOLIAGE: if VERBOSE: print 'Generating foliage ' for i in treelist: i.ma...
null
null
null
What does this function do?
def _image_get(context, image_id, session=None, force_show_deleted=False): _check_image_id(image_id) session = (session or get_session()) try: query = session.query(models.Image).options(sa_orm.joinedload(models.Image.properties)).options(sa_orm.joinedload(models.Image.locations)).filter_by(id=image_id) if ((not...
null
null
null
Get an image or raise if it does not exist.
pcsd
def image get context image id session=None force show deleted=False check image id image id session = session or get session try query = session query models Image options sa orm joinedload models Image properties options sa orm joinedload models Image locations filter by id=image id if not force show deleted and not ...
15683
def _image_get(context, image_id, session=None, force_show_deleted=False): _check_image_id(image_id) session = (session or get_session()) try: query = session.query(models.Image).options(sa_orm.joinedload(models.Image.properties)).options(sa_orm.joinedload(models.Image.locations)).filter_by(id=image_id) if ((not...
Get an image or raise if it does not exist.
get an image or raise if it does not exist .
Question: What does this function do? Code: def _image_get(context, image_id, session=None, force_show_deleted=False): _check_image_id(image_id) session = (session or get_session()) try: query = session.query(models.Image).options(sa_orm.joinedload(models.Image.properties)).options(sa_orm.joinedload(models.Imag...
null
null
null
What does this function do?
def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None, pycompile=True, scheme=None): if (not scheme): scheme = distutils_scheme(name, user=user, home=home, root=root) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_dir = scheme['platlib'] info_dir = [] data_dirs...
null
null
null
Install a wheel
pcsd
def move wheel files name req wheeldir user=False home=None root=None pycompile=True scheme=None if not scheme scheme = distutils scheme name user=user home=home root=root if root is purelib name wheeldir lib dir = scheme['purelib'] else lib dir = scheme['platlib'] info dir = [] data dirs = [] source = wheeldir rstrip ...
15684
def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None, pycompile=True, scheme=None): if (not scheme): scheme = distutils_scheme(name, user=user, home=home, root=root) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_dir = scheme['platlib'] info_dir = [] data_dirs...
Install a wheel
install a wheel
Question: What does this function do? Code: def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None, pycompile=True, scheme=None): if (not scheme): scheme = distutils_scheme(name, user=user, home=home, root=root) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_di...
null
null
null
What does this function do?
def getBracketEvaluators(bracketBeginIndex, bracketEndIndex, evaluators): return getEvaluatedExpressionValueEvaluators(evaluators[(bracketBeginIndex + 1):bracketEndIndex])
null
null
null
Get the bracket evaluators.
pcsd
def get Bracket Evaluators bracket Begin Index bracket End Index evaluators return get Evaluated Expression Value Evaluators evaluators[ bracket Begin Index + 1 bracket End Index]
15708
def getBracketEvaluators(bracketBeginIndex, bracketEndIndex, evaluators): return getEvaluatedExpressionValueEvaluators(evaluators[(bracketBeginIndex + 1):bracketEndIndex])
Get the bracket evaluators.
get the bracket evaluators .
Question: What does this function do? Code: def getBracketEvaluators(bracketBeginIndex, bracketEndIndex, evaluators): return getEvaluatedExpressionValueEvaluators(evaluators[(bracketBeginIndex + 1):bracketEndIndex])
null
null
null
What does this function do?
def presence(label): return (lambda x, y: (1.0 * ((label in x) == (label in y))))
null
null
null
Higher-order function to test presence of a given label
pcsd
def presence label return lambda x y 1 0 * label in x == label in y
15714
def presence(label): return (lambda x, y: (1.0 * ((label in x) == (label in y))))
Higher-order function to test presence of a given label
higher - order function to test presence of a given label
Question: What does this function do? Code: def presence(label): return (lambda x, y: (1.0 * ((label in x) == (label in y))))
null
null
null
What does this function do?
def extra_padding_x(original_size, padding): return _resize(original_size, 0, padding=padding)
null
null
null
Reduce the width of `original_size` by `padding`
pcsd
def extra padding x original size padding return resize original size 0 padding=padding
15715
def extra_padding_x(original_size, padding): return _resize(original_size, 0, padding=padding)
Reduce the width of `original_size` by `padding`
reduce the width of original _ size by padding
Question: What does this function do? Code: def extra_padding_x(original_size, padding): return _resize(original_size, 0, padding=padding)
null
null
null
What does this function do?
@utils.no_4byte_params def metadef_namespace_create(context, values, session=None): session = (session or get_session()) return metadef_namespace_api.create(context, values, session)
null
null
null
Create a namespace or raise if it already exists.
pcsd
@utils no 4byte params def metadef namespace create context values session=None session = session or get session return metadef namespace api create context values session
15721
@utils.no_4byte_params def metadef_namespace_create(context, values, session=None): session = (session or get_session()) return metadef_namespace_api.create(context, values, session)
Create a namespace or raise if it already exists.
create a namespace or raise if it already exists .
Question: What does this function do? Code: @utils.no_4byte_params def metadef_namespace_create(context, values, session=None): session = (session or get_session()) return metadef_namespace_api.create(context, values, session)
null
null
null
What does this function do?
def _get_name_and_version(name, version, for_filename=False): if for_filename: name = _FILESAFE.sub(u'-', name) version = _FILESAFE.sub(u'-', version.replace(u' ', u'.')) return (u'%s-%s' % (name, version))
null
null
null
Return the distribution name with version. If for_filename is true, return a filename-escaped form.
pcsd
def get name and version name version for filename=False if for filename name = FILESAFE sub u'-' name version = FILESAFE sub u'-' version replace u' ' u' ' return u'%s-%s' % name version
15722
def _get_name_and_version(name, version, for_filename=False): if for_filename: name = _FILESAFE.sub(u'-', name) version = _FILESAFE.sub(u'-', version.replace(u' ', u'.')) return (u'%s-%s' % (name, version))
Return the distribution name with version. If for_filename is true, return a filename-escaped form.
return the distribution name with version .
Question: What does this function do? Code: def _get_name_and_version(name, version, for_filename=False): if for_filename: name = _FILESAFE.sub(u'-', name) version = _FILESAFE.sub(u'-', version.replace(u' ', u'.')) return (u'%s-%s' % (name, version))
null
null
null
What does this function do?
def domain(url): return urlsplit(url)[1].split(u':')[0]
null
null
null
Return the domain part of a URL.
pcsd
def domain url return urlsplit url [1] split u' ' [0]
15723
def domain(url): return urlsplit(url)[1].split(u':')[0]
Return the domain part of a URL.
return the domain part of a url .
Question: What does this function do? Code: def domain(url): return urlsplit(url)[1].split(u':')[0]
null
null
null
What does this function do?
def _libvirt_creds(): g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = s...
null
null
null
Returns the user and group that the disk images should be owned by
pcsd
def libvirt creds g cmd = 'grep ^\\s*group /etc/libvirt/qemu conf' u cmd = 'grep ^\\s*user /etc/libvirt/qemu conf' try stdout = subprocess Popen g cmd shell=True stdout=subprocess PIPE communicate [0] group = salt utils to str stdout split '"' [1] except Index Error group = 'root' try stdout = subprocess Popen u cmd sh...
15724
def _libvirt_creds(): g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = s...
Returns the user and group that the disk images should be owned by
returns the user and group that the disk images should be owned by
Question: What does this function do? Code: def _libvirt_creds(): g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.to_str(stdout).split('"')[1] except ...
null
null
null
What does this function do?
def writeFeatureFile(font, path): fout = open(path, 'w') fout.write(font.features.text) fout.close()
null
null
null
Write the font\'s features to an external file.
pcsd
def write Feature File font path fout = open path 'w' fout write font features text fout close
15726
def writeFeatureFile(font, path): fout = open(path, 'w') fout.write(font.features.text) fout.close()
Write the font\'s features to an external file.
write the fonts features to an external file .
Question: What does this function do? Code: def writeFeatureFile(font, path): fout = open(path, 'w') fout.write(font.features.text) fout.close()
null
null
null
What does this function do?
def _convert_image(prefix, source, dest, out_format, run_as_root=True): cmd = (prefix + ('qemu-img', 'convert', '-O', out_format, source, dest)) if (utils.is_blk_device(dest) and volume_utils.check_for_odirect_support(source, dest, 'oflag=direct')): cmd = (prefix + ('qemu-img', 'convert', '-t', 'none', '-O', out_fo...
null
null
null
Convert image to other format.
pcsd
def convert image prefix source dest out format run as root=True cmd = prefix + 'qemu-img' 'convert' '-O' out format source dest if utils is blk device dest and volume utils check for odirect support source dest 'oflag=direct' cmd = prefix + 'qemu-img' 'convert' '-t' 'none' '-O' out format source dest start time = time...
15731
def _convert_image(prefix, source, dest, out_format, run_as_root=True): cmd = (prefix + ('qemu-img', 'convert', '-O', out_format, source, dest)) if (utils.is_blk_device(dest) and volume_utils.check_for_odirect_support(source, dest, 'oflag=direct')): cmd = (prefix + ('qemu-img', 'convert', '-t', 'none', '-O', out_fo...
Convert image to other format.
convert image to other format .
Question: What does this function do? Code: def _convert_image(prefix, source, dest, out_format, run_as_root=True): cmd = (prefix + ('qemu-img', 'convert', '-O', out_format, source, dest)) if (utils.is_blk_device(dest) and volume_utils.check_for_odirect_support(source, dest, 'oflag=direct')): cmd = (prefix + ('q...
null
null
null
What does this function do?
def _magnetic_dipole_field_vec(rrs, coils): if isinstance(coils, tuple): (rmags, cosmags, ws, bins) = coils else: (rmags, cosmags, ws, bins) = _concatenate_coils(coils) del coils fwd = np.empty(((3 * len(rrs)), (bins[(-1)] + 1))) for (ri, rr) in enumerate(rrs): diff = (rmags - rr) dist2 = np.sum((diff * di...
null
null
null
Compute an MEG forward solution for a set of magnetic dipoles.
pcsd
def magnetic dipole field vec rrs coils if isinstance coils tuple rmags cosmags ws bins = coils else rmags cosmags ws bins = concatenate coils coils del coils fwd = np empty 3 * len rrs bins[ -1 ] + 1 for ri rr in enumerate rrs diff = rmags - rr dist2 = np sum diff * diff axis=1 [ np newaxis] dist = np sqrt dist2 if di...
15734
def _magnetic_dipole_field_vec(rrs, coils): if isinstance(coils, tuple): (rmags, cosmags, ws, bins) = coils else: (rmags, cosmags, ws, bins) = _concatenate_coils(coils) del coils fwd = np.empty(((3 * len(rrs)), (bins[(-1)] + 1))) for (ri, rr) in enumerate(rrs): diff = (rmags - rr) dist2 = np.sum((diff * di...
Compute an MEG forward solution for a set of magnetic dipoles.
compute an meg forward solution for a set of magnetic dipoles .
Question: What does this function do? Code: def _magnetic_dipole_field_vec(rrs, coils): if isinstance(coils, tuple): (rmags, cosmags, ws, bins) = coils else: (rmags, cosmags, ws, bins) = _concatenate_coils(coils) del coils fwd = np.empty(((3 * len(rrs)), (bins[(-1)] + 1))) for (ri, rr) in enumerate(rrs): ...
null
null
null
What does this function do?
def tmpdir(): global _tmpdir if (not _tmpdir): def cleanup(): shutil.rmtree(_tmpdir) import atexit atexit.register(cleanup) _tmpdir = os.path.join(tempfile.gettempdir(), 'anki_temp') if (not os.path.exists(_tmpdir)): os.mkdir(_tmpdir) return _tmpdir
null
null
null
A reusable temp folder which we clean out on each program invocation.
pcsd
def tmpdir global tmpdir if not tmpdir def cleanup shutil rmtree tmpdir import atexit atexit register cleanup tmpdir = os path join tempfile gettempdir 'anki temp' if not os path exists tmpdir os mkdir tmpdir return tmpdir
15742
def tmpdir(): global _tmpdir if (not _tmpdir): def cleanup(): shutil.rmtree(_tmpdir) import atexit atexit.register(cleanup) _tmpdir = os.path.join(tempfile.gettempdir(), 'anki_temp') if (not os.path.exists(_tmpdir)): os.mkdir(_tmpdir) return _tmpdir
A reusable temp folder which we clean out on each program invocation.
a reusable temp folder which we clean out on each program invocation .
Question: What does this function do? Code: def tmpdir(): global _tmpdir if (not _tmpdir): def cleanup(): shutil.rmtree(_tmpdir) import atexit atexit.register(cleanup) _tmpdir = os.path.join(tempfile.gettempdir(), 'anki_temp') if (not os.path.exists(_tmpdir)): os.mkdir(_tmpdir) return _tmpdir
null
null
null
What does this function do?
def largest_factor_relatively_prime(a, b): while 1: d = gcd(a, b) if (d <= 1): break b = d while 1: (q, r) = divmod(a, d) if (r > 0): break a = q return a
null
null
null
Return the largest factor of a relatively prime to b.
pcsd
def largest factor relatively prime a b while 1 d = gcd a b if d <= 1 break b = d while 1 q r = divmod a d if r > 0 break a = q return a
15749
def largest_factor_relatively_prime(a, b): while 1: d = gcd(a, b) if (d <= 1): break b = d while 1: (q, r) = divmod(a, d) if (r > 0): break a = q return a
Return the largest factor of a relatively prime to b.
return the largest factor of a relatively prime to b .
Question: What does this function do? Code: def largest_factor_relatively_prime(a, b): while 1: d = gcd(a, b) if (d <= 1): break b = d while 1: (q, r) = divmod(a, d) if (r > 0): break a = q return a
null
null
null
What does this function do?
def deactivate_all(): _active.value = gettext_module.NullTranslations() _active.value.to_language = (lambda *args: None)
null
null
null
Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.
pcsd
def deactivate all active value = gettext module Null Translations active value to language = lambda *args None
15751
def deactivate_all(): _active.value = gettext_module.NullTranslations() _active.value.to_language = (lambda *args: None)
Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.
makes the active translation object a nulltranslations ( ) instance .
Question: What does this function do? Code: def deactivate_all(): _active.value = gettext_module.NullTranslations() _active.value.to_language = (lambda *args: None)
null
null
null
What does this function do?
def is_dir(path, use_sudo=False): func = ((use_sudo and run_as_root) or run) with settings(hide('running', 'warnings'), warn_only=True): return func(('[ -d "%(path)s" ]' % locals())).succeeded
null
null
null
Check if a path exists, and is a directory.
pcsd
def is dir path use sudo=False func = use sudo and run as root or run with settings hide 'running' 'warnings' warn only=True return func '[ -d "% path s" ]' % locals succeeded
15752
def is_dir(path, use_sudo=False): func = ((use_sudo and run_as_root) or run) with settings(hide('running', 'warnings'), warn_only=True): return func(('[ -d "%(path)s" ]' % locals())).succeeded
Check if a path exists, and is a directory.
check if a path exists , and is a directory .
Question: What does this function do? Code: def is_dir(path, use_sudo=False): func = ((use_sudo and run_as_root) or run) with settings(hide('running', 'warnings'), warn_only=True): return func(('[ -d "%(path)s" ]' % locals())).succeeded
null
null
null
What does this function do?
def compare_chemical_expression(s1, s2, ignore_state=False): return (divide_chemical_expression(s1, s2, ignore_state) == 1)
null
null
null
It does comparison between two expressions. It uses divide_chemical_expression and check if division is 1
pcsd
def compare chemical expression s1 s2 ignore state=False return divide chemical expression s1 s2 ignore state == 1
15755
def compare_chemical_expression(s1, s2, ignore_state=False): return (divide_chemical_expression(s1, s2, ignore_state) == 1)
It does comparison between two expressions. It uses divide_chemical_expression and check if division is 1
it does comparison between two expressions .
Question: What does this function do? Code: def compare_chemical_expression(s1, s2, ignore_state=False): return (divide_chemical_expression(s1, s2, ignore_state) == 1)
null
null
null
What does this function do?
def create_backup(ctxt, volume_id=fake.VOLUME_ID, display_name='test_backup', display_description='This is a test backup', status=fields.BackupStatus.CREATING, parent_id=None, temp_volume_id=None, temp_snapshot_id=None, snapshot_id=None, data_timestamp=None, **kwargs): values = {'user_id': (ctxt.user_id or fake.USER_I...
null
null
null
Create a backup object.
pcsd
def create backup ctxt volume id=fake VOLUME ID display name='test backup' display description='This is a test backup' status=fields Backup Status CREATING parent id=None temp volume id=None temp snapshot id=None snapshot id=None data timestamp=None **kwargs values = {'user id' ctxt user id or fake USER ID 'project id'...
15769
def create_backup(ctxt, volume_id=fake.VOLUME_ID, display_name='test_backup', display_description='This is a test backup', status=fields.BackupStatus.CREATING, parent_id=None, temp_volume_id=None, temp_snapshot_id=None, snapshot_id=None, data_timestamp=None, **kwargs): values = {'user_id': (ctxt.user_id or fake.USER_I...
Create a backup object.
create a backup object .
Question: What does this function do? Code: def create_backup(ctxt, volume_id=fake.VOLUME_ID, display_name='test_backup', display_description='This is a test backup', status=fields.BackupStatus.CREATING, parent_id=None, temp_volume_id=None, temp_snapshot_id=None, snapshot_id=None, data_timestamp=None, **kwargs): va...
null
null
null
What does this function do?
def relpath(path, start=curdir): if (not path): raise ValueError('no path specified') start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) if (start_list[0].lower() != path_list[0].lower()): (unc_path, rest) = splitunc(path) (unc_start, rest) = splitunc(start) if (bool(unc_path) ^ boo...
null
null
null
Return a relative version of a path
pcsd
def relpath path start=curdir if not path raise Value Error 'no path specified' start list = abspath start split sep path list = abspath path split sep if start list[0] lower != path list[0] lower unc path rest = splitunc path unc start rest = splitunc start if bool unc path ^ bool unc start raise Value Error 'Cannot m...
15771
def relpath(path, start=curdir): if (not path): raise ValueError('no path specified') start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) if (start_list[0].lower() != path_list[0].lower()): (unc_path, rest) = splitunc(path) (unc_start, rest) = splitunc(start) if (bool(unc_path) ^ boo...
Return a relative version of a path
return a relative version of a path
Question: What does this function do? Code: def relpath(path, start=curdir): if (not path): raise ValueError('no path specified') start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) if (start_list[0].lower() != path_list[0].lower()): (unc_path, rest) = splitunc(path) (unc_start, res...
null
null
null
What does this function do?
def csv_header(): print_('Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,Upload') sys.exit(0)
null
null
null
Print the CSV Headers
pcsd
def csv header print 'Server ID Sponsor Server Name Timestamp Distance Ping Download Upload' sys exit 0
15773
def csv_header(): print_('Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,Upload') sys.exit(0)
Print the CSV Headers
print the csv headers
Question: What does this function do? Code: def csv_header(): print_('Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,Upload') sys.exit(0)
null
null
null
What does this function do?
def get_fun(fun): serv = _get_serv(ret=None) sql = "select first(id) as fid, first(full_ret) as fret\n from returns\n where fun = '{0}'\n group by fun, id\n ".format(fun) data = serv.query(sql) ret = {} if data: points = data[0]['points'] for point in points: ret[po...
null
null
null
Return a dict of the last function called for all minions
pcsd
def get fun fun serv = get serv ret=None sql = "select first id as fid first full ret as fret from returns where fun = '{0}' group by fun id " format fun data = serv query sql ret = {} if data points = data[0]['points'] for point in points ret[point[1]] = json loads point[2] return ret
15774
def get_fun(fun): serv = _get_serv(ret=None) sql = "select first(id) as fid, first(full_ret) as fret\n from returns\n where fun = '{0}'\n group by fun, id\n ".format(fun) data = serv.query(sql) ret = {} if data: points = data[0]['points'] for point in points: ret[po...
Return a dict of the last function called for all minions
return a dict of the last function called for all minions
Question: What does this function do? Code: def get_fun(fun): serv = _get_serv(ret=None) sql = "select first(id) as fid, first(full_ret) as fret\n from returns\n where fun = '{0}'\n group by fun, id\n ".format(fun) data = serv.query(sql) ret = {} if data: points = dat...
null
null
null
What does this function do?
def check_directory_tree(base_path, file_check, exclusions=set(), pattern='*.py'): if (not base_path): return for (root, dirs, files) in walk(base_path): check_files(glob(join(root, pattern)), file_check, exclusions)
null
null
null
Checks all files in the directory tree (with base_path as starting point) with the file_check function provided, skipping files that contain any of the strings in the set provided by exclusions.
pcsd
def check directory tree base path file check exclusions=set pattern='* py' if not base path return for root dirs files in walk base path check files glob join root pattern file check exclusions
15785
def check_directory_tree(base_path, file_check, exclusions=set(), pattern='*.py'): if (not base_path): return for (root, dirs, files) in walk(base_path): check_files(glob(join(root, pattern)), file_check, exclusions)
Checks all files in the directory tree (with base_path as starting point) with the file_check function provided, skipping files that contain any of the strings in the set provided by exclusions.
checks all files in the directory tree with the file _ check function provided , skipping files that contain any of the strings in the set provided by exclusions .
Question: What does this function do? Code: def check_directory_tree(base_path, file_check, exclusions=set(), pattern='*.py'): if (not base_path): return for (root, dirs, files) in walk(base_path): check_files(glob(join(root, pattern)), file_check, exclusions)
null
null
null
What does this function do?
def resolve(thing, forceload=0): if isinstance(thing, str): object = locate(thing, forceload) if (not object): raise ImportError, ('no Python documentation found for %r' % thing) return (object, thing) else: name = getattr(thing, '__name__', None) return (thing, (name if isinstance(name, str) else None))...
null
null
null
Given an object or a path to an object, get the object and its name.
pcsd
def resolve thing forceload=0 if isinstance thing str object = locate thing forceload if not object raise Import Error 'no Python documentation found for %r' % thing return object thing else name = getattr thing ' name ' None return thing name if isinstance name str else None
15787
def resolve(thing, forceload=0): if isinstance(thing, str): object = locate(thing, forceload) if (not object): raise ImportError, ('no Python documentation found for %r' % thing) return (object, thing) else: name = getattr(thing, '__name__', None) return (thing, (name if isinstance(name, str) else None))...
Given an object or a path to an object, get the object and its name.
given an object or a path to an object , get the object and its name .
Question: What does this function do? Code: def resolve(thing, forceload=0): if isinstance(thing, str): object = locate(thing, forceload) if (not object): raise ImportError, ('no Python documentation found for %r' % thing) return (object, thing) else: name = getattr(thing, '__name__', None) return (th...
null
null
null
What does this function do?
def send_event_publish(email, event_name, link): message_settings = MessageSettings.query.filter_by(action=NEXT_EVENT).first() if ((not message_settings) or (message_settings.mail_status == 1)): send_email(to=email, action=NEXT_EVENT, subject=MAILS[EVENT_PUBLISH]['subject'].format(event_name=event_name), html=MAILS...
null
null
null
Send email on publishing event
pcsd
def send event publish email event name link message settings = Message Settings query filter by action=NEXT EVENT first if not message settings or message settings mail status == 1 send email to=email action=NEXT EVENT subject=MAILS[EVENT PUBLISH]['subject'] format event name=event name html=MAILS[EVENT PUBLISH]['mess...
15790
def send_event_publish(email, event_name, link): message_settings = MessageSettings.query.filter_by(action=NEXT_EVENT).first() if ((not message_settings) or (message_settings.mail_status == 1)): send_email(to=email, action=NEXT_EVENT, subject=MAILS[EVENT_PUBLISH]['subject'].format(event_name=event_name), html=MAILS...
Send email on publishing event
send email on publishing event
Question: What does this function do? Code: def send_event_publish(email, event_name, link): message_settings = MessageSettings.query.filter_by(action=NEXT_EVENT).first() if ((not message_settings) or (message_settings.mail_status == 1)): send_email(to=email, action=NEXT_EVENT, subject=MAILS[EVENT_PUBLISH]['subj...
null
null
null
What does this function do?
def get_hmm(): return 'hmmm...'
null
null
null
Get a thought.
pcsd
def get hmm return 'hmmm '
15804
def get_hmm(): return 'hmmm...'
Get a thought.
get a thought .
Question: What does this function do? Code: def get_hmm(): return 'hmmm...'
null
null
null
What does this function do?
def is_reduced(exp): return _contains(exp, Reduced)
null
null
null
Does `exp` contain a `Reduced` node.
pcsd
def is reduced exp return contains exp Reduced
15809
def is_reduced(exp): return _contains(exp, Reduced)
Does `exp` contain a `Reduced` node.
does exp contain a reduced node .
Question: What does this function do? Code: def is_reduced(exp): return _contains(exp, Reduced)
null
null
null
What does this function do?
def unbox_usecase(x): res = 0 for v in x: res += v return res
null
null
null
Expect a list of numbers
pcsd
def unbox usecase x res = 0 for v in x res += v return res
15816
def unbox_usecase(x): res = 0 for v in x: res += v return res
Expect a list of numbers
expect a list of numbers
Question: What does this function do? Code: def unbox_usecase(x): res = 0 for v in x: res += v return res
null
null
null
What does this function do?
def preprocess_roots(poly): coeff = S.One try: (_, poly) = poly.clear_denoms(convert=True) except DomainError: return (coeff, poly) poly = poly.primitive()[1] poly = poly.retract() if (poly.get_domain().is_Poly and all((c.is_term for c in poly.rep.coeffs()))): poly = poly.inject() strips = list(zip(*poly....
null
null
null
Try to get rid of symbolic coefficients from ``poly``.
pcsd
def preprocess roots poly coeff = S One try poly = poly clear denoms convert=True except Domain Error return coeff poly poly = poly primitive [1] poly = poly retract if poly get domain is Poly and all c is term for c in poly rep coeffs poly = poly inject strips = list zip *poly monoms gens = list poly gens[1 ] base str...
15817
def preprocess_roots(poly): coeff = S.One try: (_, poly) = poly.clear_denoms(convert=True) except DomainError: return (coeff, poly) poly = poly.primitive()[1] poly = poly.retract() if (poly.get_domain().is_Poly and all((c.is_term for c in poly.rep.coeffs()))): poly = poly.inject() strips = list(zip(*poly....
Try to get rid of symbolic coefficients from ``poly``.
try to get rid of symbolic coefficients from poly .
Question: What does this function do? Code: def preprocess_roots(poly): coeff = S.One try: (_, poly) = poly.clear_denoms(convert=True) except DomainError: return (coeff, poly) poly = poly.primitive()[1] poly = poly.retract() if (poly.get_domain().is_Poly and all((c.is_term for c in poly.rep.coeffs()))): ...
null
null
null
What does this function do?
def ask_for_port(): sys.stderr.write('\n--- Available ports:\n') ports = [] for (n, (port, desc, hwid)) in enumerate(sorted(comports()), 1): sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc)) ports.append(port) while True: port = raw_input('--- Enter port index or full name: ') try: index = (...
null
null
null
Show a list of ports and ask the user for a choice. To make selection easier on systems with long device names, also allow the input of an index.
pcsd
def ask for port sys stderr write ' --- Available ports ' ports = [] for n port desc hwid in enumerate sorted comports 1 sys stderr write '--- { 2} { 20} {} ' format n port desc ports append port while True port = raw input '--- Enter port index or full name ' try index = int port - 1 if not 0 <= index < len ports sys ...
15818
def ask_for_port(): sys.stderr.write('\n--- Available ports:\n') ports = [] for (n, (port, desc, hwid)) in enumerate(sorted(comports()), 1): sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc)) ports.append(port) while True: port = raw_input('--- Enter port index or full name: ') try: index = (...
Show a list of ports and ask the user for a choice. To make selection easier on systems with long device names, also allow the input of an index.
show a list of ports and ask the user for a choice .
Question: What does this function do? Code: def ask_for_port(): sys.stderr.write('\n--- Available ports:\n') ports = [] for (n, (port, desc, hwid)) in enumerate(sorted(comports()), 1): sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc)) ports.append(port) while True: port = raw_input('--- Enter ...
null
null
null
What does this function do?
def main(argv): (opts, args) = parse_args(argv) setup_logging(opts.log, opts.log_facility, opts.log_level) params = {'min_poll_seconds': 5, 'host': 'asu101', 'port': 8053} descriptors = metric_init(params) try: while True: for d in descriptors: v = d['call_back'](d['name']) if (v is None): print ...
null
null
null
used for testing
pcsd
def main argv opts args = parse args argv setup logging opts log opts log facility opts log level params = {'min poll seconds' 5 'host' 'asu101' 'port' 8053} descriptors = metric init params try while True for d in descriptors v = d['call back'] d['name'] if v is None print 'got None for %s' % d['name'] else print 'val...
15819
def main(argv): (opts, args) = parse_args(argv) setup_logging(opts.log, opts.log_facility, opts.log_level) params = {'min_poll_seconds': 5, 'host': 'asu101', 'port': 8053} descriptors = metric_init(params) try: while True: for d in descriptors: v = d['call_back'](d['name']) if (v is None): print ...
used for testing
used for testing
Question: What does this function do? Code: def main(argv): (opts, args) = parse_args(argv) setup_logging(opts.log, opts.log_facility, opts.log_level) params = {'min_poll_seconds': 5, 'host': 'asu101', 'port': 8053} descriptors = metric_init(params) try: while True: for d in descriptors: v = d['call_ba...
null
null
null
What does this function do?
@profiler.trace def roles_for_user(request, user, project=None, domain=None): manager = keystoneclient(request, admin=True).roles if (VERSIONS.active < 3): return manager.roles_for_user(user, project) else: return manager.list(user=user, domain=domain, project=project)
null
null
null
Returns a list of user roles scoped to a project or domain.
pcsd
@profiler trace def roles for user request user project=None domain=None manager = keystoneclient request admin=True roles if VERSIONS active < 3 return manager roles for user user project else return manager list user=user domain=domain project=project
15821
@profiler.trace def roles_for_user(request, user, project=None, domain=None): manager = keystoneclient(request, admin=True).roles if (VERSIONS.active < 3): return manager.roles_for_user(user, project) else: return manager.list(user=user, domain=domain, project=project)
Returns a list of user roles scoped to a project or domain.
returns a list of user roles scoped to a project or domain .
Question: What does this function do? Code: @profiler.trace def roles_for_user(request, user, project=None, domain=None): manager = keystoneclient(request, admin=True).roles if (VERSIONS.active < 3): return manager.roles_for_user(user, project) else: return manager.list(user=user, domain=domain, project=proje...
null
null
null
What does this function do?
def build_recursive_traversal_spec(client_factory): visit_folders_select_spec = build_selection_spec(client_factory, 'visitFolders') dc_to_hf = build_traversal_spec(client_factory, 'dc_to_hf', 'Datacenter', 'hostFolder', False, [visit_folders_select_spec]) dc_to_vmf = build_traversal_spec(client_factory, 'dc_to_vmf'...
null
null
null
Builds the Recursive Traversal Spec to traverse the object managed object hierarchy.
pcsd
def build recursive traversal spec client factory visit folders select spec = build selection spec client factory 'visit Folders' dc to hf = build traversal spec client factory 'dc to hf' 'Datacenter' 'host Folder' False [visit folders select spec] dc to vmf = build traversal spec client factory 'dc to vmf' 'Datacenter...
15829
def build_recursive_traversal_spec(client_factory): visit_folders_select_spec = build_selection_spec(client_factory, 'visitFolders') dc_to_hf = build_traversal_spec(client_factory, 'dc_to_hf', 'Datacenter', 'hostFolder', False, [visit_folders_select_spec]) dc_to_vmf = build_traversal_spec(client_factory, 'dc_to_vmf'...
Builds the Recursive Traversal Spec to traverse the object managed object hierarchy.
builds the recursive traversal spec to traverse the object managed object hierarchy .
Question: What does this function do? Code: def build_recursive_traversal_spec(client_factory): visit_folders_select_spec = build_selection_spec(client_factory, 'visitFolders') dc_to_hf = build_traversal_spec(client_factory, 'dc_to_hf', 'Datacenter', 'hostFolder', False, [visit_folders_select_spec]) dc_to_vmf = b...
null
null
null
What does this function do?
def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'gogrid'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), ar...
null
null
null
Create a single VM from a data dict
pcsd
def create vm try if vm ['profile'] and config is profile configured opts active provider name or 'gogrid' vm ['profile'] vm =vm is False return False except Attribute Error pass utils ['cloud fire event'] 'event' 'starting create' 'salt/cloud/{0}/creating' format vm ['name'] args={'name' vm ['name'] 'profile' vm ['pro...
15835
def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'gogrid'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), ar...
Create a single VM from a data dict
create a single vm from a data dict
Question: What does this function do? Code: def create(vm_): try: if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'gogrid'), vm_['profile'], vm_=vm_) is False)): return False except AttributeError: pass __utils__['cloud.fire_event']('event', 'starting create', 's...
null
null
null
What does this function do?
def dailymotion_download(url, output_dir='.', merge=True, info_only=False, **kwargs): html = get_content(url) info = json.loads(match1(html, 'qualities":({.+?}),"')) title = (match1(html, '"video_title"\\s*:\\s*"([^"]+)"') or match1(html, '"title"\\s*:\\s*"([^"]+)"')) for quality in ['1080', '720', '480', '380', '2...
null
null
null
Downloads Dailymotion videos by URL.
pcsd
def dailymotion download url output dir=' ' merge=True info only=False **kwargs html = get content url info = json loads match1 html 'qualities" { +?} "' title = match1 html '"video title"\\s* \\s*" [^"]+ "' or match1 html '"title"\\s* \\s*" [^"]+ "' for quality in ['1080' '720' '480' '380' '240' 'auto'] try real url =...
15839
def dailymotion_download(url, output_dir='.', merge=True, info_only=False, **kwargs): html = get_content(url) info = json.loads(match1(html, 'qualities":({.+?}),"')) title = (match1(html, '"video_title"\\s*:\\s*"([^"]+)"') or match1(html, '"title"\\s*:\\s*"([^"]+)"')) for quality in ['1080', '720', '480', '380', '2...
Downloads Dailymotion videos by URL.
downloads dailymotion videos by url .
Question: What does this function do? Code: def dailymotion_download(url, output_dir='.', merge=True, info_only=False, **kwargs): html = get_content(url) info = json.loads(match1(html, 'qualities":({.+?}),"')) title = (match1(html, '"video_title"\\s*:\\s*"([^"]+)"') or match1(html, '"title"\\s*:\\s*"([^"]+)"')) ...
null
null
null
What does this function do?
def _noop(object): return object
null
null
null
Return the passed object unmodified. This private function is intended to be used as the identity decorator.
pcsd
def noop object return object
15858
def _noop(object): return object
Return the passed object unmodified. This private function is intended to be used as the identity decorator.
return the passed object unmodified .
Question: What does this function do? Code: def _noop(object): return object
null
null
null
What does this function do?
def resource_query(name): def make_responder(query_func): def responder(queries): return app.response_class(json_generator(query_func(queries), root='results', expand=is_expand()), mimetype='application/json') responder.__name__ = 'query_{0}'.format(name) return responder return make_responder
null
null
null
Decorates a function to handle RESTful HTTP queries for resources.
pcsd
def resource query name def make responder query func def responder queries return app response class json generator query func queries root='results' expand=is expand mimetype='application/json' responder name = 'query {0}' format name return responder return make responder
15875
def resource_query(name): def make_responder(query_func): def responder(queries): return app.response_class(json_generator(query_func(queries), root='results', expand=is_expand()), mimetype='application/json') responder.__name__ = 'query_{0}'.format(name) return responder return make_responder
Decorates a function to handle RESTful HTTP queries for resources.
decorates a function to handle restful http queries for resources .
Question: What does this function do? Code: def resource_query(name): def make_responder(query_func): def responder(queries): return app.response_class(json_generator(query_func(queries), root='results', expand=is_expand()), mimetype='application/json') responder.__name__ = 'query_{0}'.format(name) return ...
null
null
null
What does this function do?
@register.function @jinja2.contextfunction def collection_widgets(context, collection, condensed=False): c = dict(context.items()) if collection: c.update({'condensed': condensed, 'c': collection}) template = get_env().get_template('bandwagon/collection_widgets.html') return jinja2.Markup(template.render(c))
null
null
null
Displays collection widgets
pcsd
@register function @jinja2 contextfunction def collection widgets context collection condensed=False c = dict context items if collection c update {'condensed' condensed 'c' collection} template = get env get template 'bandwagon/collection widgets html' return jinja2 Markup template render c
15880
@register.function @jinja2.contextfunction def collection_widgets(context, collection, condensed=False): c = dict(context.items()) if collection: c.update({'condensed': condensed, 'c': collection}) template = get_env().get_template('bandwagon/collection_widgets.html') return jinja2.Markup(template.render(c))
Displays collection widgets
displays collection widgets
Question: What does this function do? Code: @register.function @jinja2.contextfunction def collection_widgets(context, collection, condensed=False): c = dict(context.items()) if collection: c.update({'condensed': condensed, 'c': collection}) template = get_env().get_template('bandwagon/collection_widgets.html'...
null
null
null
What does this function do?
def deprecated(use_instead=None): def deco(func): @wraps(func) def wrapped(*args, **kwargs): message = ('Call to deprecated function %s.' % func.__name__) if use_instead: message += (' Use %s instead.' % use_instead) warnings.warn(message, category=ScrapyDeprecationWarning, stacklevel=2) return fun...
null
null
null
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
pcsd
def deprecated use instead=None def deco func @wraps func def wrapped *args **kwargs message = 'Call to deprecated function %s ' % func name if use instead message += ' Use %s instead ' % use instead warnings warn message category=Scrapy Deprecation Warning stacklevel=2 return func *args **kwargs return wrapped if call...
15888
def deprecated(use_instead=None): def deco(func): @wraps(func) def wrapped(*args, **kwargs): message = ('Call to deprecated function %s.' % func.__name__) if use_instead: message += (' Use %s instead.' % use_instead) warnings.warn(message, category=ScrapyDeprecationWarning, stacklevel=2) return fun...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
this is a decorator which can be used to mark functions as deprecated .
Question: What does this function do? Code: def deprecated(use_instead=None): def deco(func): @wraps(func) def wrapped(*args, **kwargs): message = ('Call to deprecated function %s.' % func.__name__) if use_instead: message += (' Use %s instead.' % use_instead) warnings.warn(message, category=Scrapy...
null
null
null
What does this function do?
def no_vtk(): global _vtk_version return (_vtk_version is None)
null
null
null
Checks if VTK is installed and the python wrapper is functional
pcsd
def no vtk global vtk version return vtk version is None
15894
def no_vtk(): global _vtk_version return (_vtk_version is None)
Checks if VTK is installed and the python wrapper is functional
checks if vtk is installed and the python wrapper is functional
Question: What does this function do? Code: def no_vtk(): global _vtk_version return (_vtk_version is None)
null
null
null
What does this function do?
def log_events(klass): old_event = klass.event @functools.wraps(old_event) def new_event(self, e, *args, **kwargs): 'Wrapper for event() which logs events.' log.misc.debug('Event in {}: {}'.format(utils.qualname(klass), qenum_key(QEvent, e.type()))) return old_event(self, e, *args, **kwargs) klass.event = new...
null
null
null
Class decorator to log Qt events.
pcsd
def log events klass old event = klass event @functools wraps old event def new event self e *args **kwargs 'Wrapper for event which logs events ' log misc debug 'Event in {} {}' format utils qualname klass qenum key Q Event e type return old event self e *args **kwargs klass event = new event return klass
15897
def log_events(klass): old_event = klass.event @functools.wraps(old_event) def new_event(self, e, *args, **kwargs): 'Wrapper for event() which logs events.' log.misc.debug('Event in {}: {}'.format(utils.qualname(klass), qenum_key(QEvent, e.type()))) return old_event(self, e, *args, **kwargs) klass.event = new...
Class decorator to log Qt events.
class decorator to log qt events .
Question: What does this function do? Code: def log_events(klass): old_event = klass.event @functools.wraps(old_event) def new_event(self, e, *args, **kwargs): 'Wrapper for event() which logs events.' log.misc.debug('Event in {}: {}'.format(utils.qualname(klass), qenum_key(QEvent, e.type()))) return old_eve...