id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
27,981 | def _RuleInputsAndOutputs(rule, trigger_file):
raw_inputs = _FixPaths(rule.get('inputs', []))
raw_outputs = _FixPaths(rule.get('outputs', []))
inputs = OrderedSet()
outputs = OrderedSet()
inputs.add(trigger_file)
for i in raw_inputs:
inputs.add(_RuleExpandPath(i, trigger_file))
for o in raw_outputs:
outputs.add(_RuleExpandPath(o, trigger_file))
return (inputs, outputs)
| [
"def",
"_RuleInputsAndOutputs",
"(",
"rule",
",",
"trigger_file",
")",
":",
"raw_inputs",
"=",
"_FixPaths",
"(",
"rule",
".",
"get",
"(",
"'inputs'",
",",
"[",
"]",
")",
")",
"raw_outputs",
"=",
"_FixPaths",
"(",
"rule",
".",
"get",
"(",
"'outputs'",
","... | find the inputs and outputs generated by a rule . | train | false |
27,982 | def print_actions(actions):
sys.stdout.write((_dumps(actions).encode('utf-8') + '\n'))
| [
"def",
"print_actions",
"(",
"actions",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"_dumps",
"(",
"actions",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"+",
"'\\n'",
")",
")"
] | serialize all the actions and print to stdout . | train | false |
27,984 | def _mediafile_image(image_path, maxwidth=None):
with open(syspath(image_path), 'rb') as f:
data = f.read()
return mediafile.Image(data, type=mediafile.ImageType.front)
| [
"def",
"_mediafile_image",
"(",
"image_path",
",",
"maxwidth",
"=",
"None",
")",
":",
"with",
"open",
"(",
"syspath",
"(",
"image_path",
")",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"return",
"mediafile",
".",
"Imag... | return a mediafile . | train | false |
27,985 | def _rc_path():
rc_file = '.fabricrc'
rc_path = ('~/' + rc_file)
expanded_rc_path = os.path.expanduser(rc_path)
if ((expanded_rc_path == rc_path) and win32):
from win32com.shell.shell import SHGetSpecialFolderPath
from win32com.shell.shellcon import CSIDL_PROFILE
expanded_rc_path = ('%s/%s' % (SHGetSpecialFolderPath(0, CSIDL_PROFILE), rc_file))
return expanded_rc_path
| [
"def",
"_rc_path",
"(",
")",
":",
"rc_file",
"=",
"'.fabricrc'",
"rc_path",
"=",
"(",
"'~/'",
"+",
"rc_file",
")",
"expanded_rc_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_path",
")",
"if",
"(",
"(",
"expanded_rc_path",
"==",
"rc_path",
")... | return platform-specific default file path for $home/ . | train | false |
27,986 | def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
info = conn.get_user_policy(user_name, policy_name)
log.debug('Info for user policy is : {0}.'.format(info))
if (not info):
return False
info = info.get_user_policy_response.get_user_policy_result.policy_document
info = _unquote(info)
info = json.loads(info, object_pairs_hook=odict.OrderedDict)
return info
except boto.exception.BotoServerError as e:
log.debug(e)
msg = 'Failed to get user {0} policy.'
log.error(msg.format(user_name))
return False
| [
"def",
"get_user_policy",
"(",
"user_name",
",",
"policy_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
... | retrieves the specified policy document for the specified user . | train | true |
27,987 | def _duplicate_hits_generator(timestamps, **kwargs):
while True:
(yield generate_hits(timestamps, **kwargs))
| [
"def",
"_duplicate_hits_generator",
"(",
"timestamps",
",",
"**",
"kwargs",
")",
":",
"while",
"True",
":",
"(",
"yield",
"generate_hits",
"(",
"timestamps",
",",
"**",
"kwargs",
")",
")"
] | generator repeatedly returns identical hits dictionaries . | train | false |
27,988 | def parse_date(string):
return get_i18n().parse_date(string)
| [
"def",
"parse_date",
"(",
"string",
")",
":",
"return",
"get_i18n",
"(",
")",
".",
"parse_date",
"(",
"string",
")"
] | parses a string and return a datetime . | train | false |
27,989 | def getGeometryDictionary(folderName):
geometryDictionary = {}
geometryDirectory = getGeometryPath()
addToNamePathDictionary(os.path.join(geometryDirectory, folderName), geometryDictionary)
geometryPluginsDirectory = getFabmetheusUtilitiesPath('geometry_plugins')
addToNamePathDictionary(os.path.join(geometryPluginsDirectory, folderName), geometryDictionary)
return geometryDictionary
| [
"def",
"getGeometryDictionary",
"(",
"folderName",
")",
":",
"geometryDictionary",
"=",
"{",
"}",
"geometryDirectory",
"=",
"getGeometryPath",
"(",
")",
"addToNamePathDictionary",
"(",
"os",
".",
"path",
".",
"join",
"(",
"geometryDirectory",
",",
"folderName",
")... | get to the geometry name path dictionary . | train | false |
27,990 | def new_token(*args, **kwargs):
return uuid.uuid4().hex
| [
"def",
"new_token",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex"
] | generator for new random tokens for now . | train | false |
27,991 | def collections_endpoint(**lookup):
resource = _resource()
response = None
method = request.method
if (method in ('GET', 'HEAD')):
response = get(resource, lookup)
elif (method == 'POST'):
response = post(resource)
elif (method == 'DELETE'):
response = delete(resource, lookup)
elif (method == 'OPTIONS'):
send_response(resource, response)
else:
abort(405)
return send_response(resource, response)
| [
"def",
"collections_endpoint",
"(",
"**",
"lookup",
")",
":",
"resource",
"=",
"_resource",
"(",
")",
"response",
"=",
"None",
"method",
"=",
"request",
".",
"method",
"if",
"(",
"method",
"in",
"(",
"'GET'",
",",
"'HEAD'",
")",
")",
":",
"response",
"... | resource endpoint handler . | train | false |
27,992 | def sync_table(model, keyspaces=None, connections=None):
context = _get_context(keyspaces, connections)
for (connection, keyspace) in context:
with query.ContextQuery(model, keyspace=keyspace) as m:
_sync_table(m, connection=connection)
| [
"def",
"sync_table",
"(",
"model",
",",
"keyspaces",
"=",
"None",
",",
"connections",
"=",
"None",
")",
":",
"context",
"=",
"_get_context",
"(",
"keyspaces",
",",
"connections",
")",
"for",
"(",
"connection",
",",
"keyspace",
")",
"in",
"context",
":",
... | inspects the model and creates / updates the corresponding table and columns . | train | true |
27,994 | def getCurrentThreadName():
return threading.current_thread().getName()
| [
"def",
"getCurrentThreadName",
"(",
")",
":",
"return",
"threading",
".",
"current_thread",
"(",
")",
".",
"getName",
"(",
")"
] | returns currents thread name . | train | false |
27,995 | def getNewMouseTool():
return ViewpointRotate()
| [
"def",
"getNewMouseTool",
"(",
")",
":",
"return",
"ViewpointRotate",
"(",
")"
] | get a new mouse tool . | train | false |
27,997 | def glob_list(obj, *args, **kwargs):
return obj.__glob_list__(*args, **kwargs)
| [
"def",
"glob_list",
"(",
"obj",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"obj",
".",
"__glob_list__",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | creates a list of paths in which all special glob characters in all the parent directories of all paths in the given setting are properly escaped . | train | false |
27,998 | def prepare_embed_request():
is_embed = request.GET.get('embed')
if (not is_embed):
return None
if (request.host != g.media_domain):
abort(404)
c.allow_framing = True
return is_embed
| [
"def",
"prepare_embed_request",
"(",
")",
":",
"is_embed",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'embed'",
")",
"if",
"(",
"not",
"is_embed",
")",
":",
"return",
"None",
"if",
"(",
"request",
".",
"host",
"!=",
"g",
".",
"media_domain",
")",
... | given a request . | train | false |
27,999 | def get_tree_details(nodes):
if hasattr(nodes, u'order_by'):
nodes = list(nodes.order_by(u'tree_id', u'lft', u'pk'))
nodes = list(nodes)
opts = nodes[0]._mptt_meta
return u'\n'.join([(u'%s %s %s %s %s %s' % (n.pk, (getattr(n, (u'%s_id' % opts.parent_attr)) or u'-'), getattr(n, opts.tree_id_attr), getattr(n, opts.level_attr), getattr(n, opts.left_attr), getattr(n, opts.right_attr))) for n in nodes])
| [
"def",
"get_tree_details",
"(",
"nodes",
")",
":",
"if",
"hasattr",
"(",
"nodes",
",",
"u'order_by'",
")",
":",
"nodes",
"=",
"list",
"(",
"nodes",
".",
"order_by",
"(",
"u'tree_id'",
",",
"u'lft'",
",",
"u'pk'",
")",
")",
"nodes",
"=",
"list",
"(",
... | creates pertinent tree details for the given list of nodes . | train | false |
28,001 | def get_bound_method(obj, method_name):
method = getattr(obj, method_name, None)
if (method is not None):
if (six.get_method_self(method) is None):
msg = '{0} must be a bound method'.format(method)
raise AttributeError(msg)
return method
| [
"def",
"get_bound_method",
"(",
"obj",
",",
"method_name",
")",
":",
"method",
"=",
"getattr",
"(",
"obj",
",",
"method_name",
",",
"None",
")",
"if",
"(",
"method",
"is",
"not",
"None",
")",
":",
"if",
"(",
"six",
".",
"get_method_self",
"(",
"method"... | get a bound method of the given object by name . | train | false |
28,002 | def get_editable_fields(cc_content, context):
ret = {'abuse_flagged'}
if ((cc_content['type'] == 'thread') and cc_content['closed']):
ret |= {'read'}
return ret
if ((cc_content['type'] == 'comment') and context['thread']['closed']):
return ret
ret |= {'voted'}
if _is_author_or_privileged(cc_content, context):
ret |= {'raw_body'}
if (cc_content['type'] == 'thread'):
ret |= {'following', 'read'}
if _is_author_or_privileged(cc_content, context):
ret |= {'topic_id', 'type', 'title'}
if (context['is_requester_privileged'] and context['course'].is_cohorted):
ret |= {'group_id'}
if ((cc_content['type'] == 'comment') and (context['is_requester_privileged'] or (_is_author(context['thread'], context) and (context['thread']['thread_type'] == 'question')))):
ret |= {'endorsed'}
return ret
| [
"def",
"get_editable_fields",
"(",
"cc_content",
",",
"context",
")",
":",
"ret",
"=",
"{",
"'abuse_flagged'",
"}",
"if",
"(",
"(",
"cc_content",
"[",
"'type'",
"]",
"==",
"'thread'",
")",
"and",
"cc_content",
"[",
"'closed'",
"]",
")",
":",
"ret",
"|=",... | return the set of fields that the requester can edit on the given content . | train | false |
28,003 | @register.as_tag
def tweets_default(*args):
query_type = settings.TWITTER_DEFAULT_QUERY_TYPE
args = (settings.TWITTER_DEFAULT_QUERY, settings.TWITTER_DEFAULT_NUM_TWEETS)
per_user = None
if (query_type == QUERY_TYPE_LIST):
per_user = 1
return tweets_for(query_type, args, per_user=per_user)
| [
"@",
"register",
".",
"as_tag",
"def",
"tweets_default",
"(",
"*",
"args",
")",
":",
"query_type",
"=",
"settings",
".",
"TWITTER_DEFAULT_QUERY_TYPE",
"args",
"=",
"(",
"settings",
".",
"TWITTER_DEFAULT_QUERY",
",",
"settings",
".",
"TWITTER_DEFAULT_NUM_TWEETS",
"... | tweets for the default settings . | train | true |
28,004 | def analyze_company_name(name, stripNotes=False):
if stripNotes:
name = split_company_name_notes(name)[0]
o_name = name
name = name.strip()
country = None
if name.startswith('['):
name = re.sub('[!@#$\\(\\)\\[\\]]', '', name)
elif name.endswith(']'):
idx = name.rfind('[')
if (idx != (-1)):
country = name[idx:]
name = name[:idx].rstrip()
if (not name):
raise IMDbParserError(('invalid name: "%s"' % o_name))
result = {'name': name}
if country:
result['country'] = country
return result
| [
"def",
"analyze_company_name",
"(",
"name",
",",
"stripNotes",
"=",
"False",
")",
":",
"if",
"stripNotes",
":",
"name",
"=",
"split_company_name_notes",
"(",
"name",
")",
"[",
"0",
"]",
"o_name",
"=",
"name",
"name",
"=",
"name",
".",
"strip",
"(",
")",
... | return a dictionary with the name and the optional country keys . | train | false |
28,005 | @verbose
def set_eeg_reference(inst, ref_channels=None, copy=True, verbose=None):
if (ref_channels is None):
if _has_eeg_average_ref_proj(inst.info['projs']):
warn('An average reference projection was already added. The data has been left untouched.')
return (inst, None)
else:
custom_ref_applied = inst.info['custom_ref_applied']
try:
inst.info['custom_ref_applied'] = False
inst.add_proj(make_eeg_average_ref_proj(inst.info, activate=False))
except:
inst.info['custom_ref_applied'] = custom_ref_applied
raise
return (inst, None)
else:
logger.info('Applying a custom EEG reference.')
inst = (inst.copy() if copy else inst)
return _apply_reference(inst, ref_channels)
| [
"@",
"verbose",
"def",
"set_eeg_reference",
"(",
"inst",
",",
"ref_channels",
"=",
"None",
",",
"copy",
"=",
"True",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"(",
"ref_channels",
"is",
"None",
")",
":",
"if",
"_has_eeg_average_ref_proj",
"(",
"inst",
... | rereference eeg channels to new reference channel(s) . | train | false |
28,006 | def converge(service, strategy=ConvergenceStrategy.changed):
plan = service.convergence_plan(strategy)
return service.execute_convergence_plan(plan, timeout=1)
| [
"def",
"converge",
"(",
"service",
",",
"strategy",
"=",
"ConvergenceStrategy",
".",
"changed",
")",
":",
"plan",
"=",
"service",
".",
"convergence_plan",
"(",
"strategy",
")",
"return",
"service",
".",
"execute_convergence_plan",
"(",
"plan",
",",
"timeout",
... | create a converge plan from a strategy and execute the plan . | train | false |
28,007 | def get_filters(getter_func):
if getter_func('none'):
return [u'none']
filters = collections.OrderedDict()
for slug in FilterGroup.objects.values_list('slug', flat=True):
for filters_slug in getter_func(slug, []):
filters[filters_slug] = None
if filters:
return filters.keys()
else:
return [x[1] for x in Filter.objects.default_filters()]
| [
"def",
"get_filters",
"(",
"getter_func",
")",
":",
"if",
"getter_func",
"(",
"'none'",
")",
":",
"return",
"[",
"u'none'",
"]",
"filters",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"slug",
"in",
"FilterGroup",
".",
"objects",
".",
"values_l... | returns the values of all filter groups . | train | false |
28,009 | @frappe.whitelist()
def get_item_details(args):
args = process_args(args)
item_doc = frappe.get_doc(u'Item', args.item_code)
item = item_doc
validate_item_details(args, item)
out = get_basic_details(args, item)
get_party_item_code(args, item_doc, out)
if frappe.db.exists(u'Product Bundle', args.item_code):
valuation_rate = 0.0
bundled_items = frappe.get_doc(u'Product Bundle', args.item_code)
for bundle_item in bundled_items.items:
valuation_rate += flt((get_valuation_rate(bundle_item.item_code, out.get(u'warehouse')).get(u'valuation_rate') * bundle_item.qty))
out.update({u'valuation_rate': valuation_rate})
else:
out.update(get_valuation_rate(args.item_code, out.get(u'warehouse')))
get_price_list_rate(args, item_doc, out)
if (args.customer and cint(args.is_pos)):
out.update(get_pos_profile_item_details(args.company, args))
if out.get(u'warehouse'):
out.update(get_bin_details(args.item_code, out.warehouse))
for (key, value) in out.iteritems():
if (args.get(key) is None):
args[key] = value
out.update(get_pricing_rule_for_item(args))
if (args.get(u'doctype') in (u'Sales Invoice', u'Delivery Note')):
out.serial_no = get_serial_no(out)
if (args.transaction_date and item.lead_time_days):
out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days)
if (args.get(u'is_subcontracted') == u'Yes'):
out.bom = get_default_bom(args.item_code)
get_gross_profit(out)
return out
| [
"@",
"frappe",
".",
"whitelist",
"(",
")",
"def",
"get_item_details",
"(",
"args",
")",
":",
"args",
"=",
"process_args",
"(",
"args",
")",
"item_doc",
"=",
"frappe",
".",
"get_doc",
"(",
"u'Item'",
",",
"args",
".",
"item_code",
")",
"item",
"=",
"ite... | returns all items details . | train | false |
28,012 | def db_add_group(**kwargs):
name = kwargs.get('name')
group = get_object(AssetGroup, name=name)
asset_id_list = kwargs.pop('asset_select')
if (not group):
group = AssetGroup(**kwargs)
group.save()
for asset_id in asset_id_list:
group_add_asset(group, asset_id)
| [
"def",
"db_add_group",
"(",
"**",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"get",
"(",
"'name'",
")",
"group",
"=",
"get_object",
"(",
"AssetGroup",
",",
"name",
"=",
"name",
")",
"asset_id_list",
"=",
"kwargs",
".",
"pop",
"(",
"'asset_select'",
... | add a asset group in database . | train | false |
28,013 | def volume_types_encryption_changed(context, vol_type_id1, vol_type_id2):
def _get_encryption(enc):
enc = dict(enc)
for param in ENCRYPTION_IGNORED_FIELDS:
enc.pop(param, None)
return enc
enc1 = get_volume_type_encryption(context, vol_type_id1)
enc2 = get_volume_type_encryption(context, vol_type_id2)
enc1_filtered = (_get_encryption(enc1) if enc1 else None)
enc2_filtered = (_get_encryption(enc2) if enc2 else None)
return (enc1_filtered != enc2_filtered)
| [
"def",
"volume_types_encryption_changed",
"(",
"context",
",",
"vol_type_id1",
",",
"vol_type_id2",
")",
":",
"def",
"_get_encryption",
"(",
"enc",
")",
":",
"enc",
"=",
"dict",
"(",
"enc",
")",
"for",
"param",
"in",
"ENCRYPTION_IGNORED_FIELDS",
":",
"enc",
".... | return whether encryptions of two volume types are same . | train | false |
28,014 | def print_(*strings, **kwargs):
if (not strings):
strings = [u'']
assert isinstance(strings[0], six.text_type)
txt = u' '.join(strings)
txt += kwargs.get('end', u'\n')
if six.PY2:
txt = txt.encode(_out_encoding(), 'replace')
sys.stdout.write(txt)
| [
"def",
"print_",
"(",
"*",
"strings",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"strings",
")",
":",
"strings",
"=",
"[",
"u''",
"]",
"assert",
"isinstance",
"(",
"strings",
"[",
"0",
"]",
",",
"six",
".",
"text_type",
")",
"txt",
"=",
"u'... | like print . | train | false |
28,015 | def strordict_fullname(item, key='fullname'):
try:
d = pickle.loads(item)
except:
d = {key: item}
if ((not isinstance(d, dict)) or (key not in d) or (not isinstance(d[key], str))):
raise ValueError(('Error trying to migrate %r (%r)' % (item, d)))
return d
| [
"def",
"strordict_fullname",
"(",
"item",
",",
"key",
"=",
"'fullname'",
")",
":",
"try",
":",
"d",
"=",
"pickle",
".",
"loads",
"(",
"item",
")",
"except",
":",
"d",
"=",
"{",
"key",
":",
"item",
"}",
"if",
"(",
"(",
"not",
"isinstance",
"(",
"d... | sometimes we migrate amqp queues from simple strings to pickled dictionaries . | train | false |
28,017 | def init_save_csr(privkey, names, path, csrname='csr-certbot.pem'):
config = zope.component.getUtility(interfaces.IConfig)
(csr_pem, csr_der) = make_csr(privkey.pem, names, must_staple=config.must_staple)
util.make_or_verify_dir(path, 493, os.geteuid(), config.strict_permissions)
(csr_f, csr_filename) = util.unique_file(os.path.join(path, csrname), 420, 'wb')
csr_f.write(csr_pem)
csr_f.close()
logger.info('Creating CSR: %s', csr_filename)
return util.CSR(csr_filename, csr_der, 'der')
| [
"def",
"init_save_csr",
"(",
"privkey",
",",
"names",
",",
"path",
",",
"csrname",
"=",
"'csr-certbot.pem'",
")",
":",
"config",
"=",
"zope",
".",
"component",
".",
"getUtility",
"(",
"interfaces",
".",
"IConfig",
")",
"(",
"csr_pem",
",",
"csr_der",
")",
... | initialize a csr with the given private key . | train | false |
28,019 | def TrimmedMeanVar(t, p=0.01):
t = Trim(t, p)
(mu, var) = MeanVar(t)
return (mu, var)
| [
"def",
"TrimmedMeanVar",
"(",
"t",
",",
"p",
"=",
"0.01",
")",
":",
"t",
"=",
"Trim",
"(",
"t",
",",
"p",
")",
"(",
"mu",
",",
"var",
")",
"=",
"MeanVar",
"(",
"t",
")",
"return",
"(",
"mu",
",",
"var",
")"
] | computes the trimmed mean and variance of a sequence of numbers . | train | false |
28,020 | def ip2int(ipstr):
return struct.unpack('!I', socket.inet_aton(ipstr))[0]
| [
"def",
"ip2int",
"(",
"ipstr",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
"'!I'",
",",
"socket",
".",
"inet_aton",
"(",
"ipstr",
")",
")",
"[",
"0",
"]"
] | converts the classical decimal . | train | false |
28,021 | def _filter_ticks(lims, fscale):
if (fscale == 'linear'):
return (None, None)
lims = np.array(lims)
ticks = list()
for exp in range(int(np.floor(np.log10(lims[0]))), (int(np.floor(np.log10(lims[1]))) + 1)):
ticks += (np.array([1, 2, 4]) * (10 ** exp)).tolist()
ticks = np.array(ticks)
ticks = ticks[((ticks >= lims[0]) & (ticks <= lims[1]))]
ticklabels = [(('%g' if (t < 1) else '%d') % t) for t in ticks]
return (ticks, ticklabels)
| [
"def",
"_filter_ticks",
"(",
"lims",
",",
"fscale",
")",
":",
"if",
"(",
"fscale",
"==",
"'linear'",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"lims",
"=",
"np",
".",
"array",
"(",
"lims",
")",
"ticks",
"=",
"list",
"(",
")",
"for",
"exp... | create approximately spaced ticks between lims . | train | false |
28,022 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | create a new cast-128 cipher . | train | false |
28,023 | def format_histogram_one_count(counts, bin_edges):
lines = []
lines.append('Length DCTB Count')
for (edge, count) in zip(bin_edges, counts):
lines.append(' DCTB '.join(map(str, [edge, count])))
return '\n'.join(lines)
| [
"def",
"format_histogram_one_count",
"(",
"counts",
",",
"bin_edges",
")",
":",
"lines",
"=",
"[",
"]",
"lines",
".",
"append",
"(",
"'Length DCTB Count'",
")",
"for",
"(",
"edge",
",",
"count",
")",
"in",
"zip",
"(",
"bin_edges",
",",
"counts",
")",
":"... | returns text-formatted histogram with only one count . | train | false |
28,024 | def _set_argv(process_name):
if (Py_GetArgcArgv is None):
return
global _PROCESS_NAME
current_name = get_process_name()
(argv, argc) = (ctypes.c_int(0), argc_t())
Py_GetArgcArgv(argv, ctypes.pointer(argc))
if (len(process_name) > _MAX_NAME_LENGTH):
raise IOError("Can't rename process to something longer than our initial name (this would overwrite memory used for the env)")
zero_size = max(len(current_name), len(process_name))
ctypes.memset(argc.contents, 0, (zero_size + 1))
process_name_encoded = process_name.encode('utf8')
ctypes.memmove(argc.contents, process_name_encoded, len(process_name))
_PROCESS_NAME = process_name
| [
"def",
"_set_argv",
"(",
"process_name",
")",
":",
"if",
"(",
"Py_GetArgcArgv",
"is",
"None",
")",
":",
"return",
"global",
"_PROCESS_NAME",
"current_name",
"=",
"get_process_name",
"(",
")",
"(",
"argv",
",",
"argc",
")",
"=",
"(",
"ctypes",
".",
"c_int",... | overwrites our argv in a similar fashion to how its done in c with: strcpy; . | train | false |
28,025 | def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None):
where_clause = ("where keyspace_name = '{0}'".format(keyspace) if keyspace else '')
query = 'select columnfamily_name\n from system.schema_columnfamilies\n {0};'.format(where_clause)
ret = {}
try:
ret = cql_query(query, contact_points, port, cql_user, cql_pass)
except CommandExecutionError:
log.critical('Could not list column families.')
raise
except BaseException as e:
log.critical('Unexpected error while listing column families: {0}'.format(str(e)))
raise
return ret
| [
"def",
"list_column_families",
"(",
"keyspace",
"=",
"None",
",",
"contact_points",
"=",
"None",
",",
"port",
"=",
"None",
",",
"cql_user",
"=",
"None",
",",
"cql_pass",
"=",
"None",
")",
":",
"where_clause",
"=",
"(",
"\"where keyspace_name = '{0}'\"",
".",
... | list column families in a cassandra cluster for all keyspaces or just the provided one . | train | true |
28,026 | def get_nova_v2_client(session, region):
return NovaClient(session=session, region_name=region, version=2)
| [
"def",
"get_nova_v2_client",
"(",
"session",
",",
"region",
")",
":",
"return",
"NovaClient",
"(",
"session",
"=",
"session",
",",
"region_name",
"=",
"region",
",",
"version",
"=",
"2",
")"
] | create a nova client from a keystone session . | train | false |
28,027 | def build_options(gens, args=None):
if (args is None):
(gens, args) = ((), gens)
if ((len(args) != 1) or ('opt' not in args) or gens):
return Options(gens, args)
else:
return args['opt']
| [
"def",
"build_options",
"(",
"gens",
",",
"args",
"=",
"None",
")",
":",
"if",
"(",
"args",
"is",
"None",
")",
":",
"(",
"gens",
",",
"args",
")",
"=",
"(",
"(",
")",
",",
"gens",
")",
"if",
"(",
"(",
"len",
"(",
"args",
")",
"!=",
"1",
")"... | construct options from keyword arguments or . | train | false |
28,028 | def reset():
_runtime.reset()
| [
"def",
"reset",
"(",
")",
":",
"_runtime",
".",
"reset",
"(",
")"
] | reset a development environment . | train | false |
28,029 | def get_all_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
marker = False
profiles = []
while (marker is not None):
marker = (marker if marker else None)
p = conn.list_instance_profiles(path_prefix=path_prefix, marker=marker)
res = p.list_instance_profiles_response.list_instance_profiles_result
profiles += res.instance_profiles
marker = getattr(res, 'marker', None)
return profiles
| [
"def",
"get_all_instance_profiles",
"(",
"path_prefix",
"=",
"'/'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key... | get and return all iam instance profiles . | train | true |
28,030 | @requires_csrf_token
def bad_request(request, template_name='400.html'):
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
return http.HttpResponseBadRequest(template.render(Context({})))
| [
"@",
"requires_csrf_token",
"def",
"bad_request",
"(",
"request",
",",
"template_name",
"=",
"'400.html'",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"return",
"http",
"... | raise 400 httpbadrequest error . | train | false |
28,031 | def patched_get_children(self, usage_key_filter=None):
def iter_children():
'skip children not visible to students'
for child in GET_CHILDREN(self, usage_key_filter=usage_key_filter):
child._field_data_cache = {}
if (not child.visible_to_staff_only):
(yield child)
return list(iter_children())
| [
"def",
"patched_get_children",
"(",
"self",
",",
"usage_key_filter",
"=",
"None",
")",
":",
"def",
"iter_children",
"(",
")",
":",
"for",
"child",
"in",
"GET_CHILDREN",
"(",
"self",
",",
"usage_key_filter",
"=",
"usage_key_filter",
")",
":",
"child",
".",
"_... | emulate system tools that mask courseware not visible to students . | train | false |
28,032 | def qemu_img_info(path, format=None):
if ((not os.path.exists(path)) and (CONF.libvirt.images_type != 'rbd')):
raise exception.DiskNotFound(location=path)
try:
if (os.path.isdir(path) and os.path.exists(os.path.join(path, 'DiskDescriptor.xml'))):
path = os.path.join(path, 'root.hds')
cmd = ('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info', path)
if (format is not None):
cmd = (cmd + ('-f', format))
(out, err) = utils.execute(prlimit=QEMU_IMG_LIMITS, *cmd)
except processutils.ProcessExecutionError as exp:
if (exp.exit_code == (-9)):
msg = (_('qemu-img aborted by prlimits when inspecting %(path)s : %(exp)s') % {'path': path, 'exp': exp})
else:
msg = (_('qemu-img failed to execute on %(path)s : %(exp)s') % {'path': path, 'exp': exp})
raise exception.InvalidDiskInfo(reason=msg)
if (not out):
msg = (_('Failed to run qemu-img info on %(path)s : %(error)s') % {'path': path, 'error': err})
raise exception.InvalidDiskInfo(reason=msg)
return imageutils.QemuImgInfo(out)
| [
"def",
"qemu_img_info",
"(",
"path",
",",
"format",
"=",
"None",
")",
":",
"if",
"(",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
"and",
"(",
"CONF",
".",
"libvirt",
".",
"images_type",
"!=",
"'rbd'",
")",
")",
":",
"rais... | return an object containing the parsed output from qemu-img info . | train | false |
28,033 | def is_writable(path):
if os.path.exists(path):
return os.access(path, os.W_OK)
else:
return os.access(os.path.dirname(path), os.W_OK)
| [
"def",
"is_writable",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"W_OK",
")",
"else",
":",
"return",
"os",
".",
"access",
"(",
"os",
".",
"pa... | predicate that returns true if the sheet is writeable . | train | false |
28,035 | def wait_for_ajax_or_reload(browser):
def _is_ajax_finished():
' Wait for jQuery to finish all AJAX calls, if it is present. '
return browser.execute_script("return typeof(jQuery) == 'undefined' || jQuery.active == 0")
EmptyPromise(_is_ajax_finished, 'Finished waiting for ajax requests.').fulfill()
| [
"def",
"wait_for_ajax_or_reload",
"(",
"browser",
")",
":",
"def",
"_is_ajax_finished",
"(",
")",
":",
"return",
"browser",
".",
"execute_script",
"(",
"\"return typeof(jQuery) == 'undefined' || jQuery.active == 0\"",
")",
"EmptyPromise",
"(",
"_is_ajax_finished",
",",
"'... | wait for all ajax requests to finish . | train | false |
28,036 | def bzr(registry, xml_parent, data):
mapping = [('url', 'source', None), ('clean-tree', 'cleantree', False), ('lightweight-checkout', 'checkout', False)]
scm_element = XML.SubElement(xml_parent, 'scm', {'class': 'hudson.plugins.bazaar.BazaarSCM'})
convert_mapping_to_xml(scm_element, data, mapping, fail_required=True)
browser_name_to_class = {'loggerhead': 'Loggerhead', 'opengrok': 'OpenGrok'}
browser = data.get('browser', 'auto')
if (browser == 'auto'):
return
if (browser not in browser_name_to_class):
raise InvalidAttributeError('browser', browser, browser_name_to_class.keys())
browser_element = XML.SubElement(scm_element, 'browser', {'class': 'hudson.plugins.bazaar.browsers.{0}'.format(browser_name_to_class[browser])})
XML.SubElement(browser_element, 'url').text = data['browser-url']
if (browser == 'opengrok'):
XML.SubElement(browser_element, 'rootModule').text = data['opengrok-root-module']
| [
"def",
"bzr",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"mapping",
"=",
"[",
"(",
"'url'",
",",
"'source'",
",",
"None",
")",
",",
"(",
"'clean-tree'",
",",
"'cleantree'",
",",
"False",
")",
",",
"(",
"'lightweight-checkout'",
",",
"'c... | yaml: bzr specifies the bzr scm repository for this job . | train | false |
28,037 | def fac_multiplicity(n, p):
if (p > n):
return 0
if (p > (n // 2)):
return 1
(q, m) = (n, 0)
while (q >= p):
q //= p
m += q
return m
| [
"def",
"fac_multiplicity",
"(",
"n",
",",
"p",
")",
":",
"if",
"(",
"p",
">",
"n",
")",
":",
"return",
"0",
"if",
"(",
"p",
">",
"(",
"n",
"//",
"2",
")",
")",
":",
"return",
"1",
"(",
"q",
",",
"m",
")",
"=",
"(",
"n",
",",
"0",
")",
... | return the power of the prime number p in the factorization of n! . | train | false |
28,038 | def teardown_container(container_dir):
try:
img = _DiskImage(image=None, mount_dir=container_dir)
img.teardown()
except Exception as exn:
LOG.exception(_('Failed to teardown ntainer filesystem: %s'), exn)
| [
"def",
"teardown_container",
"(",
"container_dir",
")",
":",
"try",
":",
"img",
"=",
"_DiskImage",
"(",
"image",
"=",
"None",
",",
"mount_dir",
"=",
"container_dir",
")",
"img",
".",
"teardown",
"(",
")",
"except",
"Exception",
"as",
"exn",
":",
"LOG",
"... | teardown the container rootfs mounting once it is spawned . | train | false |
28,039 | def LINEARREG_ANGLE(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.LINEARREG_ANGLE, timeperiod)
| [
"def",
"LINEARREG_ANGLE",
"(",
"ds",
",",
"count",
",",
"timeperiod",
"=",
"(",
"-",
"(",
"2",
"**",
"31",
")",
")",
")",
":",
"return",
"call_talib_with_ds",
"(",
"ds",
",",
"count",
",",
"talib",
".",
"LINEARREG_ANGLE",
",",
"timeperiod",
")"
] | linear regression angle . | train | false |
28,040 | def load_vint(buf, pos):
limit = min((pos + 11), len(buf))
res = ofs = 0
while (pos < limit):
b = _byte_code(buf[pos])
res += ((b & 127) << ofs)
pos += 1
ofs += 7
if (b < 128):
return (res, pos)
raise BadRarFile('cannot load vint')
| [
"def",
"load_vint",
"(",
"buf",
",",
"pos",
")",
":",
"limit",
"=",
"min",
"(",
"(",
"pos",
"+",
"11",
")",
",",
"len",
"(",
"buf",
")",
")",
"res",
"=",
"ofs",
"=",
"0",
"while",
"(",
"pos",
"<",
"limit",
")",
":",
"b",
"=",
"_byte_code",
... | load variable-size int . | train | true |
28,041 | def sync_ldap_users_groups(request):
if (not request.user.is_superuser):
request.audit = {'operation': 'SYNC_LDAP_USERS_GROUPS', 'operationText': _get_failed_operation_text(request.user.username, 'SYNC_LDAP_USERS_GROUPS'), 'allowed': False}
raise PopupException(_('You must be a superuser to sync the LDAP users/groups.'), error_code=401)
if (request.method == 'POST'):
form = SyncLdapUsersGroupsForm(request.POST)
if form.is_valid():
is_ensuring_home_directory = form.cleaned_data['ensure_home_directory']
server = form.cleaned_data.get('server')
connection = ldap_access.get_connection_from_server(server)
failed_ldap_users = []
sync_ldap_users_and_groups(connection, is_ensuring_home_directory, request.fs, failed_users=failed_ldap_users)
request.audit = {'operation': 'SYNC_LDAP_USERS_GROUPS', 'operationText': 'Successfully synced LDAP users/groups'}
if failed_ldap_users:
unique_users = set(failed_ldap_users)
request.warn((_('Failed to import following users: %s') % ', '.join(unique_users)))
return redirect(reverse(list_users))
else:
form = SyncLdapUsersGroupsForm()
return render('sync_ldap_users_groups.mako', request, dict(path=request.path, form=form))
| [
"def",
"sync_ldap_users_groups",
"(",
"request",
")",
":",
"if",
"(",
"not",
"request",
".",
"user",
".",
"is_superuser",
")",
":",
"request",
".",
"audit",
"=",
"{",
"'operation'",
":",
"'SYNC_LDAP_USERS_GROUPS'",
",",
"'operationText'",
":",
"_get_failed_opera... | handler for syncing the hue database with ldap users and groups . | train | false |
28,042 | def profile_detail(request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs):
user = get_object_or_404(get_user_model(), username__iexact=username)
profile = get_user_profile(user=user)
if (not profile.can_view_profile(request.user)):
raise PermissionDenied
if (not extra_context):
extra_context = dict()
extra_context['profile'] = profile
extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
| [
"def",
"profile_detail",
"(",
"request",
",",
"username",
",",
"template_name",
"=",
"userena_settings",
".",
"USERENA_PROFILE_DETAIL_TEMPLATE",
",",
"extra_context",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"user",
"=",
"get_object_or_404",
"(",
"get_user_model"... | detailed view of an user . | train | true |
28,043 | def test_append_empty_history(hist, config_stub):
config_stub.data = CONFIG_NOT_PRIVATE
hist.history = []
hist.append('item')
assert (hist[0] == 'item')
| [
"def",
"test_append_empty_history",
"(",
"hist",
",",
"config_stub",
")",
":",
"config_stub",
".",
"data",
"=",
"CONFIG_NOT_PRIVATE",
"hist",
".",
"history",
"=",
"[",
"]",
"hist",
".",
"append",
"(",
"'item'",
")",
"assert",
"(",
"hist",
"[",
"0",
"]",
... | test append when . | train | false |
28,044 | @pytest.yield_fixture
def dir_with_hooks(tmpdir):
hooks_dir = tmpdir.mkdir('hooks')
pre_hook_content = textwrap.dedent(u"\n #!/usr/bin/env python\n # -*- coding: utf-8 -*-\n print('pre_gen_project.py~')\n ")
pre_gen_hook_file = (hooks_dir / 'pre_gen_project.py~')
pre_gen_hook_file.write_text(pre_hook_content, encoding='utf8')
post_hook_content = textwrap.dedent(u"\n #!/usr/bin/env python\n # -*- coding: utf-8 -*-\n print('post_gen_project.py~')\n ")
post_gen_hook_file = (hooks_dir / 'post_gen_project.py~')
post_gen_hook_file.write_text(post_hook_content, encoding='utf8')
(yield str(tmpdir))
pre_gen_hook_file.remove()
post_gen_hook_file.remove()
| [
"@",
"pytest",
".",
"yield_fixture",
"def",
"dir_with_hooks",
"(",
"tmpdir",
")",
":",
"hooks_dir",
"=",
"tmpdir",
".",
"mkdir",
"(",
"'hooks'",
")",
"pre_hook_content",
"=",
"textwrap",
".",
"dedent",
"(",
"u\"\\n #!/usr/bin/env python\\n # -*- coding: ... | yield a directory that contains hook backup files . | train | false |
28,045 | @skip('multiple_execute')
def test_register():
def garbage_func0():
pass
def garbage_func1(param1):
pass
codecs.register(garbage_func0)
codecs.register(garbage_func1)
AssertError(TypeError, codecs.register)
AssertError(TypeError, codecs.register, None)
AssertError(TypeError, codecs.register, ())
AssertError(TypeError, codecs.register, [])
AssertError(TypeError, codecs.register, 1)
AssertError(TypeError, codecs.register, 'abc')
AssertError(TypeError, codecs.register, 3.14)
| [
"@",
"skip",
"(",
"'multiple_execute'",
")",
"def",
"test_register",
"(",
")",
":",
"def",
"garbage_func0",
"(",
")",
":",
"pass",
"def",
"garbage_func1",
"(",
"param1",
")",
":",
"pass",
"codecs",
".",
"register",
"(",
"garbage_func0",
")",
"codecs",
".",... | make sure registering works . | train | false |
28,047 | def test_unknown(enum):
with pytest.raises(AttributeError):
_ = enum.three
| [
"def",
"test_unknown",
"(",
"enum",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"AttributeError",
")",
":",
"_",
"=",
"enum",
".",
"three"
] | test invalid values which should raise an attributeerror . | train | false |
28,048 | def makeleaf(expr):
name = (expr._name or '_')
if (expr in _leaf_cache):
return _leaf_cache[expr]
if isinstance(expr, Symbol):
_used_tokens[name].add(expr._token)
_leaf_cache[expr] = expr
return expr
used_for_name = _used_tokens[name]
for token in itertools.count():
if (token not in used_for_name):
break
result = symbol(name, expr.dshape, token)
used_for_name.add(token)
_leaf_cache[expr] = result
return result
| [
"def",
"makeleaf",
"(",
"expr",
")",
":",
"name",
"=",
"(",
"expr",
".",
"_name",
"or",
"'_'",
")",
"if",
"(",
"expr",
"in",
"_leaf_cache",
")",
":",
"return",
"_leaf_cache",
"[",
"expr",
"]",
"if",
"isinstance",
"(",
"expr",
",",
"Symbol",
")",
":... | name of a new leaf replacement for this expression . | train | false |
28,052 | @require_POST
@csrf_protect
def generic_copy(request, what, obj_name=None, obj_newname=None):
if (not test_user_authenticated(request)):
return login(request, next=('/cobbler_web/%s/copy/%s/%s' % (what, obj_name, obj_newname)), expired=True)
if (obj_name is None):
return error_page(request, ('You must specify a %s to rename' % what))
if (not remote.has_item(what, obj_name)):
return error_page(request, ('Unknown %s specified' % what))
elif (not remote.check_access_no_fail(request.session['token'], ('modify_%s' % what), obj_name)):
return error_page(request, ('You do not have permission to copy this %s' % what))
else:
obj_id = remote.get_item_handle(what, obj_name, request.session['token'])
remote.copy_item(what, obj_id, obj_newname, request.session['token'])
return HttpResponseRedirect(('/cobbler_web/%s/list' % what))
| [
"@",
"require_POST",
"@",
"csrf_protect",
"def",
"generic_copy",
"(",
"request",
",",
"what",
",",
"obj_name",
"=",
"None",
",",
"obj_newname",
"=",
"None",
")",
":",
"if",
"(",
"not",
"test_user_authenticated",
"(",
"request",
")",
")",
":",
"return",
"lo... | copies an object . | train | false |
28,053 | def _select_options(pat):
if (pat in _registered_options):
return [pat]
keys = sorted(_registered_options.keys())
if (pat == 'all'):
return keys
return [k for k in keys if re.search(pat, k, re.I)]
| [
"def",
"_select_options",
"(",
"pat",
")",
":",
"if",
"(",
"pat",
"in",
"_registered_options",
")",
":",
"return",
"[",
"pat",
"]",
"keys",
"=",
"sorted",
"(",
"_registered_options",
".",
"keys",
"(",
")",
")",
"if",
"(",
"pat",
"==",
"'all'",
")",
"... | returns a list of keys matching pat if pat=="all" . | train | true |
28,056 | def replace_ext(path, ext):
ext_dot = ('.' + ext)
return (os.path.splitext(path)[0] + ext_dot)
| [
"def",
"replace_ext",
"(",
"path",
",",
"ext",
")",
":",
"ext_dot",
"=",
"(",
"'.'",
"+",
"ext",
")",
"return",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"0",
"]",
"+",
"ext_dot",
")"
] | return the path with its extension replaced by ext . | train | false |
28,057 | def filterStringValue(value, charRegex, replacement=''):
retVal = value
if value:
retVal = re.sub((charRegex.replace('[', '[^') if ('[^' not in charRegex) else charRegex.replace('[^', '[')), replacement, value)
return retVal
| [
"def",
"filterStringValue",
"(",
"value",
",",
"charRegex",
",",
"replacement",
"=",
"''",
")",
":",
"retVal",
"=",
"value",
"if",
"value",
":",
"retVal",
"=",
"re",
".",
"sub",
"(",
"(",
"charRegex",
".",
"replace",
"(",
"'['",
",",
"'[^'",
")",
"if... | returns string value consisting only of chars satisfying supplied regular expression . | train | false |
28,058 | def mock_cast_as_call(obj=None):
orig_prepare = obj.prepare
def prepare(*args, **kwargs):
cctxt = orig_prepare(*args, **kwargs)
mock_cast_as_call(obj=cctxt)
return cctxt
prepare_patch = mock.patch.object(obj, 'prepare').start()
prepare_patch.side_effect = prepare
cast_patch = mock.patch.object(obj, 'cast').start()
cast_patch.side_effect = obj.call
| [
"def",
"mock_cast_as_call",
"(",
"obj",
"=",
"None",
")",
":",
"orig_prepare",
"=",
"obj",
".",
"prepare",
"def",
"prepare",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"cctxt",
"=",
"orig_prepare",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"m... | use this to mock cast as calls . | train | false |
28,059 | @receiver(post_save, sender=CourseTeam, dispatch_uid='teams.signals.course_team_post_save_callback')
def course_team_post_save_callback(**kwargs):
try:
CourseTeamIndexer.index(kwargs['instance'])
except ElasticSearchConnectionError:
pass
| [
"@",
"receiver",
"(",
"post_save",
",",
"sender",
"=",
"CourseTeam",
",",
"dispatch_uid",
"=",
"'teams.signals.course_team_post_save_callback'",
")",
"def",
"course_team_post_save_callback",
"(",
"**",
"kwargs",
")",
":",
"try",
":",
"CourseTeamIndexer",
".",
"index",... | reindex object after save . | train | false |
28,060 | def load_tool_sources_from_path(path, load_exception_handler=load_exception_handler, recursive=False, register_load_errors=False):
return _load_tools_from_path(path, load_exception_handler=load_exception_handler, recursive=recursive, register_load_errors=register_load_errors, loader_func=get_tool_source, enable_beta_formats=True)
| [
"def",
"load_tool_sources_from_path",
"(",
"path",
",",
"load_exception_handler",
"=",
"load_exception_handler",
",",
"recursive",
"=",
"False",
",",
"register_load_errors",
"=",
"False",
")",
":",
"return",
"_load_tools_from_path",
"(",
"path",
",",
"load_exception_han... | walk a directory and toolsource objects . | train | false |
28,061 | def serializePath(pathObj, options):
return ''.join([(cmd + scourCoordinates(data, options, (cmd == 'a'))) for (cmd, data) in pathObj])
| [
"def",
"serializePath",
"(",
"pathObj",
",",
"options",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"(",
"cmd",
"+",
"scourCoordinates",
"(",
"data",
",",
"options",
",",
"(",
"cmd",
"==",
"'a'",
")",
")",
")",
"for",
"(",
"cmd",
",",
"data",
... | reserializes the path data with some cleanups . | train | false |
28,062 | def get_specific_user():
user = get_user()
if is_windows():
if _win_current_user_is_admin():
return 'sudo_{0}'.format(user)
else:
env_vars = ('SUDO_USER',)
if (user == 'root'):
for evar in env_vars:
if (evar in os.environ):
return 'sudo_{0}'.format(os.environ[evar])
return user
| [
"def",
"get_specific_user",
"(",
")",
":",
"user",
"=",
"get_user",
"(",
")",
"if",
"is_windows",
"(",
")",
":",
"if",
"_win_current_user_is_admin",
"(",
")",
":",
"return",
"'sudo_{0}'",
".",
"format",
"(",
"user",
")",
"else",
":",
"env_vars",
"=",
"("... | get a user name for publishing . | train | false |
28,063 | def _list_designs(user, querydict, page_size, prefix='', is_trashed=False):
DEFAULT_SORT = ('-', 'date')
SORT_ATTR_TRANSLATION = dict(date='last_modified', name='name', desc='description', type='extra')
if is_trashed:
db_queryset = Document.objects.trashed_docs(SavedQuery, user)
else:
db_queryset = Document.objects.available_docs(SavedQuery, user)
filter_username = querydict.get((prefix + 'user'))
if filter_username:
try:
db_queryset = db_queryset.filter(owner=User.objects.get(username=filter_username))
except User.DoesNotExist:
pass
d_type = querydict.get((prefix + 'type'))
if (d_type and (d_type in SavedQuery.TYPES_MAPPING.keys())):
db_queryset = db_queryset.filter(extra=str(SavedQuery.TYPES_MAPPING[d_type]))
frag = querydict.get((prefix + 'text'))
if frag:
db_queryset = db_queryset.filter((Q(name__icontains=frag) | Q(description__icontains=frag)))
sort_key = querydict.get((prefix + 'sort'))
if sort_key:
if (sort_key[0] == '-'):
(sort_dir, sort_attr) = ('-', sort_key[1:])
else:
(sort_dir, sort_attr) = ('', sort_key)
if (not SORT_ATTR_TRANSLATION.has_key(sort_attr)):
LOG.warn(('Bad parameter to list_designs: sort=%s' % (sort_key,)))
(sort_dir, sort_attr) = DEFAULT_SORT
else:
(sort_dir, sort_attr) = DEFAULT_SORT
db_queryset = db_queryset.order_by((sort_dir + SORT_ATTR_TRANSLATION[sort_attr]))
designs = [job.content_object for job in db_queryset.all() if (job.content_object and (job.content_object.is_auto == False))]
pagenum = int(querydict.get((prefix + 'page'), 1))
paginator = Paginator(designs, page_size)
page = paginator.page(pagenum)
keys_to_copy = [(prefix + key) for key in ('user', 'type', 'sort', 'text')]
filter_params = copy_query_dict(querydict, keys_to_copy)
return (page, filter_params)
| [
"def",
"_list_designs",
"(",
"user",
",",
"querydict",
",",
"page_size",
",",
"prefix",
"=",
"''",
",",
"is_trashed",
"=",
"False",
")",
":",
"DEFAULT_SORT",
"=",
"(",
"'-'",
",",
"'date'",
")",
"SORT_ATTR_TRANSLATION",
"=",
"dict",
"(",
"date",
"=",
"'l... | fetch all workflow designs . | train | false |
28,065 | def get_transport_and_path_from_url(url, config=None, **kwargs):
parsed = urlparse.urlparse(url)
if (parsed.scheme == 'git'):
return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path)
elif (parsed.scheme in ('git+ssh', 'ssh')):
path = parsed.path
if path.startswith('/'):
path = parsed.path[1:]
return (SSHGitClient.from_parsedurl(parsed, **kwargs), path)
elif (parsed.scheme in ('http', 'https')):
return (HttpGitClient.from_parsedurl(parsed, config=config, **kwargs), parsed.path)
elif (parsed.scheme == 'file'):
return (default_local_git_client_cls.from_parsedurl(parsed, **kwargs), parsed.path)
raise ValueError(("unknown scheme '%s'" % parsed.scheme))
| [
"def",
"get_transport_and_path_from_url",
"(",
"url",
",",
"config",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"if",
"(",
"parsed",
".",
"scheme",
"==",
"'git'",
")",
":",
"return",
"(",
"T... | obtain a git client from a url . | train | false |
28,066 | def _get_subnetname_id(subnetname):
params = {'Action': 'DescribeSubnets'}
for subnet in aws.query(params, location=get_location(), provider=get_provider(), opts=__opts__, sigver='4'):
tags = subnet.get('tagSet', {}).get('item', {})
if (not isinstance(tags, list)):
tags = [tags]
for tag in tags:
if ((tag['key'] == 'Name') and (tag['value'] == subnetname)):
log.debug('AWS Subnet ID of {0} is {1}'.format(subnetname, subnet['subnetId']))
return subnet['subnetId']
return None
| [
"def",
"_get_subnetname_id",
"(",
"subnetname",
")",
":",
"params",
"=",
"{",
"'Action'",
":",
"'DescribeSubnets'",
"}",
"for",
"subnet",
"in",
"aws",
".",
"query",
"(",
"params",
",",
"location",
"=",
"get_location",
"(",
")",
",",
"provider",
"=",
"get_p... | returns the subnetid of a subnetname to use . | train | true |
28,067 | def split_at_single(text, sep, not_before=[], not_after=[]):
n = 0
(lt, s) = (len(text), len(sep))
last = 0
while (n < lt):
if (not ((s + n) > lt)):
if (sep == text[n:(n + s)]):
if any((text[last:n].endswith(e) for e in not_before)):
pass
elif any((text[(n + s):].startswith(e) for e in not_after)):
pass
else:
(yield text[last:n])
last = (n + s)
n += (s - 1)
n += 1
(yield text[last:])
| [
"def",
"split_at_single",
"(",
"text",
",",
"sep",
",",
"not_before",
"=",
"[",
"]",
",",
"not_after",
"=",
"[",
"]",
")",
":",
"n",
"=",
"0",
"(",
"lt",
",",
"s",
")",
"=",
"(",
"len",
"(",
"text",
")",
",",
"len",
"(",
"sep",
")",
")",
"l... | works like text . | train | true |
28,068 | def build_logger():
return log
| [
"def",
"build_logger",
"(",
")",
":",
"return",
"log"
] | build a logger for test driver script . | train | false |
28,069 | def _ping_listener(dbapi_conn, connection_rec, connection_proxy):
try:
dbapi_conn.cursor().execute('select 1')
except dbapi_conn.OperationalError as ex:
if (ex.args[0] in (2006, 2013, 2014, 2045, 2055)):
LOG.warn(_('Got mysql server has gone away: %s'), ex)
raise sqla_exc.DisconnectionError('Database server went away')
else:
raise
| [
"def",
"_ping_listener",
"(",
"dbapi_conn",
",",
"connection_rec",
",",
"connection_proxy",
")",
":",
"try",
":",
"dbapi_conn",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"'select 1'",
")",
"except",
"dbapi_conn",
".",
"OperationalError",
"as",
"ex",
":",
... | ensures that mysql connections checked out of the pool are alive . | train | false |
28,070 | def get_encoding_from_headers(headers):
content_type = headers.get('content-type')
if (not content_type):
return None
(content_type, params) = cgi.parse_header(content_type)
if ('charset' in params):
return params['charset'].strip('\'"')
if ('text' in content_type):
return 'ISO-8859-1'
| [
"def",
"get_encoding_from_headers",
"(",
"headers",
")",
":",
"content_type",
"=",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"if",
"(",
"not",
"content_type",
")",
":",
"return",
"None",
"(",
"content_type",
",",
"params",
")",
"=",
"cgi",
".",
"p... | returns encoding from given http header dict . | train | true |
28,071 | def pauseUnpause(n):
d = defer.Deferred()
def f(result):
return result
d.callback(1)
d.pause()
for i in xrange(n):
d.addCallback(f)
d.addErrback(f)
d.addBoth(f)
d.addCallbacks(f)
d.unpause()
| [
"def",
"pauseUnpause",
"(",
"n",
")",
":",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"def",
"f",
"(",
"result",
")",
":",
"return",
"result",
"d",
".",
"callback",
"(",
"1",
")",
"d",
".",
"pause",
"(",
")",
"for",
"i",
"in",
"xrange",
"(",... | adds the given number of callbacks/errbacks/both to a deferred while it is paused . | train | false |
28,072 | def MIDPOINT(ds, count, timeperiod=(- (2 ** 31))):
return call_talib_with_ds(ds, count, talib.MIDPOINT, timeperiod)
| [
"def",
"MIDPOINT",
"(",
"ds",
",",
"count",
",",
"timeperiod",
"=",
"(",
"-",
"(",
"2",
"**",
"31",
")",
")",
")",
":",
"return",
"call_talib_with_ds",
"(",
"ds",
",",
"count",
",",
"talib",
".",
"MIDPOINT",
",",
"timeperiod",
")"
] | midpoint over period . | train | false |
28,074 | def exchange_shared(a, b):
raise NotImplementedError('TODO: implement the function')
| [
"def",
"exchange_shared",
"(",
"a",
",",
"b",
")",
":",
"raise",
"NotImplementedError",
"(",
"'TODO: implement the function'",
")"
] | a: a theano shared variable b: a theano shared variable uses get_value and set_value to swap the values stored in a and b . | train | false |
28,075 | def load_dictionary(filename):
filename = osp.abspath(filename)
old_cwd = getcwd()
os.chdir(osp.dirname(filename))
data = None
error_message = None
try:
tar = tarfile.open(filename, 'r')
tar.extractall()
pickle_filename = (osp.splitext(filename)[0] + '.pickle')
try:
with open(pickle_filename, 'U') as fdesc:
data = pickle.loads(fdesc.read())
except (pickle.PickleError, TypeError, UnicodeDecodeError):
with open(pickle_filename, 'rb') as fdesc:
data = pickle.loads(fdesc.read())
saved_arrays = {}
if (load_array is not None):
try:
saved_arrays = data.pop('__saved_arrays__')
for ((name, index), fname) in list(saved_arrays.items()):
arr = np.load(osp.join(osp.dirname(filename), fname))
if (index is None):
data[name] = arr
elif isinstance(data[name], dict):
data[name][index] = arr
else:
data[name].insert(index, arr)
except KeyError:
pass
for fname in ([pickle_filename] + [fn for fn in list(saved_arrays.values())]):
os.remove(fname)
except (EOFError, ValueError) as error:
error_message = to_text_string(error)
os.chdir(old_cwd)
return (data, error_message)
| [
"def",
"load_dictionary",
"(",
"filename",
")",
":",
"filename",
"=",
"osp",
".",
"abspath",
"(",
"filename",
")",
"old_cwd",
"=",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"osp",
".",
"dirname",
"(",
"filename",
")",
")",
"data",
"=",
"None",
"er... | load a dictionary . | train | false |
28,076 | @register.filter(name='as_crispy_errors')
def as_crispy_errors(form, template_pack=TEMPLATE_PACK):
if isinstance(form, BaseFormSet):
template = get_template(('%s/errors_formset.html' % template_pack))
c = Context({'formset': form}).flatten()
else:
template = get_template(('%s/errors.html' % template_pack))
c = Context({'form': form}).flatten()
return template.render(c)
| [
"@",
"register",
".",
"filter",
"(",
"name",
"=",
"'as_crispy_errors'",
")",
"def",
"as_crispy_errors",
"(",
"form",
",",
"template_pack",
"=",
"TEMPLATE_PACK",
")",
":",
"if",
"isinstance",
"(",
"form",
",",
"BaseFormSet",
")",
":",
"template",
"=",
"get_te... | renders only form errors the same way as django-crispy-forms:: {% load crispy_forms_tags %} {{ form|as_crispy_errors }} or:: {{ form|as_crispy_errors:"bootstrap" }} . | train | true |
28,077 | def is_overlapping(t):
(memlen, itemsize, ndim, shape, strides, offset) = t
visited = (1 << memlen)
for ind in indices(shape):
i = memory_index(ind, t)
bit = (1 << i)
if (visited & bit):
return True
visited |= bit
return False
| [
"def",
"is_overlapping",
"(",
"t",
")",
":",
"(",
"memlen",
",",
"itemsize",
",",
"ndim",
",",
"shape",
",",
"strides",
",",
"offset",
")",
"=",
"t",
"visited",
"=",
"(",
"1",
"<<",
"memlen",
")",
"for",
"ind",
"in",
"indices",
"(",
"shape",
")",
... | the structure t is overlapping if at least one memory location is visited twice while iterating through all possible tuples of indices . | train | false |
28,078 | def _udp(src, dst, payload):
udpHeader = (((_H(src) + _H(dst)) + _H((len(payload) + 8))) + _H(0))
return (udpHeader + payload)
| [
"def",
"_udp",
"(",
"src",
",",
"dst",
",",
"payload",
")",
":",
"udpHeader",
"=",
"(",
"(",
"(",
"_H",
"(",
"src",
")",
"+",
"_H",
"(",
"dst",
")",
")",
"+",
"_H",
"(",
"(",
"len",
"(",
"payload",
")",
"+",
"8",
")",
")",
")",
"+",
"_H",... | construct a udp datagram with the given source . | train | false |
28,079 | def set_precision_provider(precision_provider):
assert callable(precision_provider)
global _precision_provider
_precision_provider = precision_provider
| [
"def",
"set_precision_provider",
"(",
"precision_provider",
")",
":",
"assert",
"callable",
"(",
"precision_provider",
")",
"global",
"_precision_provider",
"_precision_provider",
"=",
"precision_provider"
] | set precision provider for money instances . | train | false |
28,080 | def ParseRangeHeader(range_header):
if (not range_header):
return (None, None)
try:
(range_type, ranges) = range_header.split('=', 1)
if (range_type != 'bytes'):
return (None, None)
ranges = ranges.lstrip()
if (',' in ranges):
return (None, None)
end = None
if ranges.startswith('-'):
start = int(ranges)
if (start == 0):
return (None, None)
else:
split_range = ranges.split('-', 1)
start = int(split_range[0])
if ((len(split_range) == 2) and split_range[1].strip()):
end = (int(split_range[1]) + 1)
if (start > end):
return (None, None)
return (start, end)
except ValueError:
return (None, None)
| [
"def",
"ParseRangeHeader",
"(",
"range_header",
")",
":",
"if",
"(",
"not",
"range_header",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"try",
":",
"(",
"range_type",
",",
"ranges",
")",
"=",
"range_header",
".",
"split",
"(",
"'='",
",",
"1",
... | parse http range header . | train | false |
28,081 | def _get_pool_key(conf):
return (conf.klass, conf.host, conf.port)
| [
"def",
"_get_pool_key",
"(",
"conf",
")",
":",
"return",
"(",
"conf",
".",
"klass",
",",
"conf",
".",
"host",
",",
"conf",
".",
"port",
")"
] | given a connectionconfig . | train | false |
28,083 | def svd_timing(X, n_comps, n_iter, n_oversamples, power_iteration_normalizer='auto', method=None):
print '... running SVD ...'
if (method is not 'fbpca'):
gc.collect()
t0 = time()
(U, mu, V) = randomized_svd(X, n_comps, n_oversamples, n_iter, power_iteration_normalizer, random_state=random_state, transpose=False)
call_time = (time() - t0)
else:
gc.collect()
t0 = time()
(U, mu, V) = fbpca.pca(X, n_comps, raw=True, n_iter=n_iter, l=(n_oversamples + n_comps))
call_time = (time() - t0)
return (U, mu, V, call_time)
| [
"def",
"svd_timing",
"(",
"X",
",",
"n_comps",
",",
"n_iter",
",",
"n_oversamples",
",",
"power_iteration_normalizer",
"=",
"'auto'",
",",
"method",
"=",
"None",
")",
":",
"print",
"'... running SVD ...'",
"if",
"(",
"method",
"is",
"not",
"'fbpca'",
")",
":... | measure time for decomposition . | train | false |
28,084 | def _list_items(queue):
con = _conn(queue)
with con:
cur = con.cursor()
cmd = 'SELECT name FROM {0}'.format(queue)
log.debug('SQL Query: {0}'.format(cmd))
cur.execute(cmd)
contents = cur.fetchall()
return contents
| [
"def",
"_list_items",
"(",
"queue",
")",
":",
"con",
"=",
"_conn",
"(",
"queue",
")",
"with",
"con",
":",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"cmd",
"=",
"'SELECT name FROM {0}'",
".",
"format",
"(",
"queue",
")",
"log",
".",
"debug",
"(",
... | list items belonging to an api call . | train | true |
28,085 | def list_nodes_select(call=None):
if (call == 'action'):
raise SaltCloudSystemExit('The list_nodes_select function must be called with -f or --function.')
ret = {}
vm_properties = []
selection = __opts__.get('query.selection')
if (not selection):
raise SaltCloudSystemExit('query.selection not found in /etc/salt/cloud')
if ('id' in selection):
vm_properties.append('name')
if ('image' in selection):
vm_properties.append('config.guestFullName')
if ('size' in selection):
vm_properties.extend(['config.hardware.numCPU', 'config.hardware.memoryMB'])
if ('state' in selection):
vm_properties.append('summary.runtime.powerState')
if (('private_ips' in selection) or ('networks' in selection)):
vm_properties.append('guest.net')
if (('devices' in selection) or ('mac_address' in selection) or ('mac_addresses' in selection)):
vm_properties.append('config.hardware.device')
if ('storage' in selection):
vm_properties.extend(['config.hardware.device', 'summary.storage.committed', 'summary.storage.uncommitted', 'summary.storage.unshared'])
if ('files' in selection):
vm_properties.append('layoutEx.file')
if ('guest_id' in selection):
vm_properties.append('config.guestId')
if ('hostname' in selection):
vm_properties.append('guest.hostName')
if ('path' in selection):
vm_properties.append('config.files.vmPathName')
if ('tools_status' in selection):
vm_properties.append('guest.toolsStatus')
if (not vm_properties):
return {}
elif ('name' not in vm_properties):
vm_properties.append('name')
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
for vm in vm_list:
ret[vm['name']] = _format_instance_info_select(vm, selection)
return ret
| [
"def",
"list_nodes_select",
"(",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"==",
"'action'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_select function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"vm_properties",
... | return a list of the vms that are on the provider . | train | true |
28,086 | def get_sharing_strategy():
return _sharing_strategy
| [
"def",
"get_sharing_strategy",
"(",
")",
":",
"return",
"_sharing_strategy"
] | returns the current strategy for sharing cpu tensors . | train | false |
28,088 | def get_user_info_cookie_data(request):
user = request.user
header_urls = {u'logout': reverse(u'logout')}
try:
header_urls[u'account_settings'] = reverse(u'account_settings')
header_urls[u'learner_profile'] = reverse(u'learner_profile', kwargs={u'username': user.username})
except NoReverseMatch:
pass
for (url_name, url_path) in six.iteritems(header_urls):
header_urls[url_name] = request.build_absolute_uri(url_path)
user_info = {u'version': settings.EDXMKTG_USER_INFO_COOKIE_VERSION, u'username': user.username, u'header_urls': header_urls, u'enrollmentStatusHash': CourseEnrollment.generate_enrollment_status_hash(user)}
return user_info
| [
"def",
"get_user_info_cookie_data",
"(",
"request",
")",
":",
"user",
"=",
"request",
".",
"user",
"header_urls",
"=",
"{",
"u'logout'",
":",
"reverse",
"(",
"u'logout'",
")",
"}",
"try",
":",
"header_urls",
"[",
"u'account_settings'",
"]",
"=",
"reverse",
"... | returns information that wil populate the user info cookie . | train | false |
28,089 | def toposort_rules(rules):
graph = {}
class_dict = {}
for rule in rules:
if (rule.__class__ in class_dict):
raise ValueError(('Duplicate class rules are not allowed: %s' % rule.__class__))
class_dict[rule.__class__] = rule
for rule in rules:
if ((not is_iterable(rule.dependency)) and rule.dependency):
rule_dependencies = [rule.dependency]
else:
rule_dependencies = rule.dependency
dependencies = set()
if rule_dependencies:
for dependency in rule_dependencies:
if inspect.isclass(dependency):
dependency = class_dict.get(dependency)
if dependency:
dependencies.add(dependency)
graph[rule] = dependencies
return toposort(graph)
| [
"def",
"toposort_rules",
"(",
"rules",
")",
":",
"graph",
"=",
"{",
"}",
"class_dict",
"=",
"{",
"}",
"for",
"rule",
"in",
"rules",
":",
"if",
"(",
"rule",
".",
"__class__",
"in",
"class_dict",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Duplicate cla... | sort given rules using toposort with dependency parameter . | train | true |
28,090 | def setup_log_file_handler(config, logfile, fmt):
log_file_path = os.path.join(config.logs_dir, logfile)
try:
handler = logging.handlers.RotatingFileHandler(log_file_path, maxBytes=(2 ** 20), backupCount=1000)
except IOError as error:
raise errors.Error(_PERM_ERR_FMT.format(error))
handler.doRollover()
handler.setLevel(logging.DEBUG)
handler_formatter = logging.Formatter(fmt=fmt)
handler_formatter.converter = time.gmtime
handler.setFormatter(handler_formatter)
return (handler, log_file_path)
| [
"def",
"setup_log_file_handler",
"(",
"config",
",",
"logfile",
",",
"fmt",
")",
":",
"log_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"logs_dir",
",",
"logfile",
")",
"try",
":",
"handler",
"=",
"logging",
".",
"handlers",
".",
... | setup file debug logging . | train | false |
28,091 | def quotify_list(words):
wordout = []
for word in words:
qtype = q
if (word and (not re.search('[\\s\\"\\\']', word))):
qtype = ''
elif ((q in word) and (qq not in word)):
qtype = qq
wordout.append(quotify(qtype, word, True))
return ' '.join(wordout)
| [
"def",
"quotify_list",
"(",
"words",
")",
":",
"wordout",
"=",
"[",
"]",
"for",
"word",
"in",
"words",
":",
"qtype",
"=",
"q",
"if",
"(",
"word",
"and",
"(",
"not",
"re",
".",
"search",
"(",
"'[\\\\s\\\\\"\\\\\\']'",
",",
"word",
")",
")",
")",
":"... | return a minimally-quoted string produced by quoting each word . | train | false |
28,092 | @command('(?:q|quit|exit)')
def quits(showlogo=True):
if has_readline:
readline.write_history_file(g.READLINE_FILE)
util.dbg('Saved history file')
cache.save()
screen.clear()
msg = (logo(c.r, version=__version__) if showlogo else '')
msg += util.F('exitmsg', 2)
if (config.CHECKUPDATE.get and showlogo):
try:
url = 'https://raw.githubusercontent.com/mps-youtube/mps-youtube/master/VERSION'
v = urlopen(url, timeout=1).read().decode()
v = re.search('^version\\s*([\\d\\.]+)\\s*$', v, re.MULTILINE)
if v:
v = v.group(1)
if (v > __version__):
msg += ('\n\nA newer version is available (%s)\n' % v)
except (URLError, HTTPError, socket.timeout):
util.dbg('check update timed out')
screen.msgexit(msg)
| [
"@",
"command",
"(",
"'(?:q|quit|exit)'",
")",
"def",
"quits",
"(",
"showlogo",
"=",
"True",
")",
":",
"if",
"has_readline",
":",
"readline",
".",
"write_history_file",
"(",
"g",
".",
"READLINE_FILE",
")",
"util",
".",
"dbg",
"(",
"'Saved history file'",
")"... | exit the program . | train | false |
28,093 | def is_loopback_ip_address(ip=None, addrinfo=None):
if addrinfo:
if ((addrinfo[0] == socket.AF_INET) or (addrinfo[0] == socket.AF_INET6)):
ip = addrinfo[4]
if (not isinstance(ip, basestring)):
return False
if (ip.count('.') == 3):
return ip.lower().startswith(('127', '::127', '0:0:0:0:0:0:127', '::ffff:127', '0:0:0:0:0:ffff:127'))
return ((ip == '::1') or (ip == '0:0:0:0:0:0:0:1'))
| [
"def",
"is_loopback_ip_address",
"(",
"ip",
"=",
"None",
",",
"addrinfo",
"=",
"None",
")",
":",
"if",
"addrinfo",
":",
"if",
"(",
"(",
"addrinfo",
"[",
"0",
"]",
"==",
"socket",
".",
"AF_INET",
")",
"or",
"(",
"addrinfo",
"[",
"0",
"]",
"==",
"soc... | determines whether the address appears to be a loopback address . | train | false |
28,094 | def E1(z):
return expint(1, z)
| [
"def",
"E1",
"(",
"z",
")",
":",
"return",
"expint",
"(",
"1",
",",
"z",
")"
] | classical case of the generalized exponential integral . | train | false |
28,095 | def rollback():
connection._rollback()
set_clean()
| [
"def",
"rollback",
"(",
")",
":",
"connection",
".",
"_rollback",
"(",
")",
"set_clean",
"(",
")"
] | this function does the rollback itself and resets the dirty flag . | train | false |
28,097 | def pkcs_os2ip(x):
return int(x.encode('hex'), 16)
| [
"def",
"pkcs_os2ip",
"(",
"x",
")",
":",
"return",
"int",
"(",
"x",
".",
"encode",
"(",
"'hex'",
")",
",",
"16",
")"
] | accepts a byte string as input parameter and return the associated long value: input : x octet string to be converted output: x corresponding nonnegative integer reverse function is pkcs_i2osp() . | train | false |
28,098 | def init_journalist(is_admin=False):
username = crypto_util.genrandomid()
user_pw = crypto_util.genrandomid()
user = db.Journalist(username, user_pw, is_admin)
db.db_session.add(user)
db.db_session.commit()
return (user, user_pw)
| [
"def",
"init_journalist",
"(",
"is_admin",
"=",
"False",
")",
":",
"username",
"=",
"crypto_util",
".",
"genrandomid",
"(",
")",
"user_pw",
"=",
"crypto_util",
".",
"genrandomid",
"(",
")",
"user",
"=",
"db",
".",
"Journalist",
"(",
"username",
",",
"user_... | initialize a journalist into the database . | train | false |
28,099 | def select_array_wrapper(inputs):
max_prio = float('-inf')
selected_input = None
selected_index = None
for (index, ty) in enumerate(inputs):
if (isinstance(ty, types.ArrayCompatible) and (ty.array_priority > max_prio)):
selected_input = ty
selected_index = index
max_prio = ty.array_priority
assert (selected_index is not None)
return selected_index
| [
"def",
"select_array_wrapper",
"(",
"inputs",
")",
":",
"max_prio",
"=",
"float",
"(",
"'-inf'",
")",
"selected_input",
"=",
"None",
"selected_index",
"=",
"None",
"for",
"(",
"index",
",",
"ty",
")",
"in",
"enumerate",
"(",
"inputs",
")",
":",
"if",
"("... | given the array-compatible input types to an operation . | train | false |
28,100 | def dmp_from_dict(f, u, K):
if (not u):
return dup_from_dict(f, K)
if (not f):
return dmp_zero(u)
coeffs = {}
for (monom, coeff) in f.items():
(head, tail) = (monom[0], monom[1:])
if (head in coeffs):
coeffs[head][tail] = coeff
else:
coeffs[head] = {tail: coeff}
(n, v, h) = (max(coeffs.keys()), (u - 1), [])
for k in range(n, (-1), (-1)):
coeff = coeffs.get(k)
if (coeff is not None):
h.append(dmp_from_dict(coeff, v, K))
else:
h.append(dmp_zero(v))
return dmp_strip(h, u)
| [
"def",
"dmp_from_dict",
"(",
"f",
",",
"u",
",",
"K",
")",
":",
"if",
"(",
"not",
"u",
")",
":",
"return",
"dup_from_dict",
"(",
"f",
",",
"K",
")",
"if",
"(",
"not",
"f",
")",
":",
"return",
"dmp_zero",
"(",
"u",
")",
"coeffs",
"=",
"{",
"}"... | create a k[x] polynomial from a dict . | train | false |
28,101 | def _isfloat(x):
try:
float(x)
except:
return False
return True
| [
"def",
"_isfloat",
"(",
"x",
")",
":",
"try",
":",
"float",
"(",
"x",
")",
"except",
":",
"return",
"False",
"return",
"True"
] | returns true if x is a float . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.