code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def userInvitations(self):
self.__init()
items = []
for n in self._userInvitations:
if "id" in n:
url = "%s/%s" % (self.root, n['id'])
items.append(self.Invitation(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initialize=True))
return items | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true return_statement identifier | gets all user invitations |
def render(template, context, partials={}, state=None):
state = state or State()
if isinstance(context, Context):
state.context = context
else:
state.context = Context(context)
if partials:
state.partials.push(partials)
return __render(make_unicode(template), state) | module function_definition identifier parameters identifier identifier default_parameter identifier dictionary default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier call identifier argument_list if_statement call identifier argument_list identifier identifier block expression_statement assignment attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list identifier identifier | Renders a given mustache template, with sane defaults. |
def create_key(self):
print("Creating key. Please input the following options:")
name = input("Key name (optional): ")
print("To make this key more secure, you should restrict the IP addresses that can use it. ")
print("To use with all IPs, leave blank or use 0.0.0.0/0.")
print("To use with a single IP, append '/32', such as 207.39.29.22/32. ")
print("See this reference on CIDR blocks: http://software77.net/cidr-101.html")
cidr = input("CIDR (optional): ")
key = self._curl_bitmex("/apiKey",
postdict={"name": name, "cidr": cidr, "enabled": True})
print("Key created. Details:\n")
print("API Key: " + key["id"])
print("Secret: " + key["secret"])
print("\nSafeguard your secret key! If somebody gets a hold of your API key and secret,")
print("your account can be taken over completely.")
print("\nKey generation complete.") | module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end true expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content escape_sequence string_end | Create an API key. |
def health_percentage(self) -> Union[int, float]:
if self._proto.health_max == 0:
return 0
return self._proto.health / self._proto.health_max | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier type identifier block if_statement comparison_operator attribute attribute identifier identifier identifier integer block return_statement integer return_statement binary_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier | Does not include shields |
def agm(x, y, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_agm,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call identifier argument_list identifier attribute identifier identifier tuple call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier | Return the arithmetic geometric mean of x and y. |
def options(argv=[]):
parser = HendrixOptionParser
parsed_args = parser.parse_args(argv)
return vars(parsed_args[0]) | module function_definition identifier parameters default_parameter identifier list block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list subscript identifier integer | A helper function that returns a dictionary of the default key-values pairs |
def cli(env, identifier):
mgr = SoftLayer.SshKeyManager(env.client)
key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
if not (env.skip_confirmations or formatting.no_going_back(key_id)):
raise exceptions.CLIAbort('Aborted')
mgr.delete_key(key_id) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier string string_start string_content string_end if_statement not_operator parenthesized_expression boolean_operator attribute identifier identifier call attribute identifier identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Permanently removes an SSH key. |
def probably_wkt(text):
valid = False
valid_types = set([
'POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT',
'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION',
])
matched = re.match(r'(\w+)\s*\([^)]+\)', text.strip())
if matched:
valid = matched.group(1).upper() in valid_types
return valid | module function_definition identifier parameters identifier block expression_statement assignment identifier false expression_statement assignment identifier call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier comparison_operator call attribute call attribute identifier identifier argument_list integer identifier argument_list identifier return_statement identifier | Quick check to determine if the provided text looks like WKT |
def listmetadataformats(**kwargs):
cfg = current_app.config
e_tree, e_listmetadataformats = verb(**kwargs)
if 'identifier' in kwargs:
OAIIDProvider.get(pid_value=kwargs['identifier'])
for prefix, metadata in cfg.get('OAISERVER_METADATA_FORMATS', {}).items():
e_metadataformat = SubElement(
e_listmetadataformats, etree.QName(NS_OAIPMH, 'metadataFormat')
)
e_metadataprefix = SubElement(
e_metadataformat, etree.QName(NS_OAIPMH, 'metadataPrefix')
)
e_metadataprefix.text = prefix
e_schema = SubElement(
e_metadataformat, etree.QName(NS_OAIPMH, 'schema')
)
e_schema.text = metadata['schema']
e_metadataNamespace = SubElement(
e_metadataformat, etree.QName(NS_OAIPMH, 'metadataNamespace')
)
e_metadataNamespace.text = metadata['namespace']
return e_tree | module function_definition identifier parameters dictionary_splat_pattern identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list dictionary_splat identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end for_statement pattern_list identifier identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end return_statement identifier | Create OAI-PMH response for ListMetadataFormats verb. |
def describe_group(record, region):
account_id = record['account']
group_name = cloudwatch.filter_request_parameters('groupName', record)
vpc_id = cloudwatch.filter_request_parameters('vpcId', record)
group_id = cloudwatch.filter_request_parameters('groupId', record, look_in_response=True)
if cloudwatch.get_collected_details(record):
LOG.debug(f"[<--] Received already collected security group data: {record['detail']['collected']}")
return [record['detail']['collected']]
try:
if group_id:
return describe_security_groups(
account_number=account_id,
assume_role=HISTORICAL_ROLE,
region=region,
GroupIds=[group_id]
)['SecurityGroups']
elif vpc_id and group_name:
return describe_security_groups(
account_number=account_id,
assume_role=HISTORICAL_ROLE,
region=region,
Filters=[
{
'Name': 'group-name',
'Values': [group_name]
},
{
'Name': 'vpc-id',
'Values': [vpc_id]
}
]
)['SecurityGroups']
else:
raise Exception('[X] Did not receive Group ID or VPC/Group Name pairs. '
f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.')
except ClientError as exc:
if exc.response['Error']['Code'] == 'InvalidGroup.NotFound':
return []
raise exc | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier true if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string_end return_statement list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end try_statement block if_statement identifier block return_statement subscript call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier list identifier string string_start string_content string_end elif_clause boolean_operator identifier identifier block return_statement subscript call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier list dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end list identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end list identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content interpolation identifier string_content interpolation identifier string_content interpolation identifier string_content string_end except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block return_statement list raise_statement identifier | Attempts to describe group ids. |
def casefold_parts(self, parts):
if self.filesystem.is_windows_fs:
return [p.lower() for p in parts]
return parts | module function_definition identifier parameters identifier identifier block if_statement attribute attribute identifier identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier return_statement identifier | Return the lower-case version of parts for a Windows filesystem. |
def noEmptyNests(node):
if type(node)==list:
for i in node:
noEmptyNests(i)
if type(node)==dict:
for i in node.values():
noEmptyNests(i)
if node["children"] == []:
node.pop("children")
return node | module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list identifier identifier block for_statement identifier identifier block expression_statement call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | recursively make sure that no dictionaries inside node contain empty children lists |
def instance(self, other):
assert '/' not in str(other)
return Key(str(self) + ':' + str(other)) | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator string string_start string_content string_end call identifier argument_list identifier return_statement call identifier argument_list binary_operator binary_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier | Returns an instance Key, by appending a name to the namespace. |
def iter_links_param_element(cls, element):
valuetype = element.attrib.get('valuetype', '')
if valuetype.lower() == 'ref' and 'value' in element.attrib:
link_type = identify_link_type(element.attrib.get('value'))
yield LinkInfo(
element=element, tag=element.tag, attrib='value',
link=element.attrib.get('value'),
inline=True, linked=False,
base_link=None,
value_type='plain',
link_type=link_type
) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end if_statement boolean_operator comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement yield call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true keyword_argument identifier false keyword_argument identifier none keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier | Iterate a ``param`` element. |
def cli_info(self, event):
self.log('Instance:', self.instance,
'Dev:', self.development,
'Host:', self.host,
'Port:', self.port,
'Insecure:', self.insecure,
'Frontend:', self.frontendtarget) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end attribute identifier identifier | Provides information about the running instance |
def table_mask(self):
margin = compress_pruned(
self._slice.margin(
axis=None,
weighted=False,
include_transforms_for_dims=self._hs_dims,
prune=self._prune,
)
)
mask = margin < self._size
if margin.shape == self._shape:
return mask
if self._slice.dim_types[0] == DT.MR:
return np.logical_or(np.zeros(self._shape, dtype=bool), mask[:, None])
return np.logical_or(np.zeros(self._shape, dtype=bool), mask) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier none keyword_argument identifier false keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier comparison_operator identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement identifier if_statement comparison_operator subscript attribute attribute identifier identifier identifier integer attribute identifier identifier block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier subscript identifier slice none return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier identifier | ndarray, True where table margin <= min_base_size, same shape as slice. |
def track_name_event(self, name):
l = self.int_to_varbyte(len(name))
return '\x00' + META_EVENT + TRACK_NAME + l + name | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier return_statement binary_operator binary_operator binary_operator binary_operator string string_start string_content escape_sequence string_end identifier identifier identifier identifier | Return the bytes for a track name meta event. |
def searchsorted(arr, N, x):
L = 0
R = N-1
done = False
m = (L+R)//2
while not done:
if arr[m] < x:
L = m + 1
elif arr[m] > x:
R = m - 1
elif arr[m] == x:
done = True
m = (L+R)//2
if L>R:
done = True
return L | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier false expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier integer while_statement not_operator identifier block if_statement comparison_operator subscript identifier identifier identifier block expression_statement assignment identifier binary_operator identifier integer elif_clause comparison_operator subscript identifier identifier identifier block expression_statement assignment identifier binary_operator identifier integer elif_clause comparison_operator subscript identifier identifier identifier block expression_statement assignment identifier true expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier integer if_statement comparison_operator identifier identifier block expression_statement assignment identifier true return_statement identifier | N is length of arr |
def extract_operations(self, migrations):
operations = []
for migration in migrations:
for operation in migration.operations:
if isinstance(operation, RunSQL):
statements = sqlparse.parse(dedent(operation.sql))
for statement in statements:
operation = SqlObjectOperation.parse(statement)
if operation:
operations.append(operation)
if self.verbosity >= 2:
self.stdout.write(" > % -100s (%s)" % (operation, migration))
return operations | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement identifier | Extract SQL operations from the given migrations |
def init_path():
sitedirs = getsyssitepackages()
for sitedir in sitedirs:
env_path = os.environ['PATH'].split(os.pathsep)
for module in allowed_modules:
p = join(sitedir, module)
if isdir(p) and not p in env_path:
os.environ['PATH'] += env_t(os.pathsep + p) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement boolean_operator call identifier argument_list identifier not_operator comparison_operator identifier identifier block expression_statement augmented_assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list binary_operator attribute identifier identifier identifier | Add any new modules that are directories to the PATH |
def open_pr(self, url):
if self.dry_run:
click.echo(f" dry-run: Create new PR: {url}")
else:
click.echo("Backport PR URL:")
click.echo(url)
webbrowser.open_new_tab(url) | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation identifier string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | open url in the web browser |
def _get_flowcell_id(in_file, require_single=True):
fc_ids = set([x[0] for x in _read_input_csv(in_file)])
if require_single and len(fc_ids) > 1:
raise ValueError("There are several FCIDs in the same samplesheet file: %s" % in_file)
else:
return fc_ids | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier call identifier argument_list list_comprehension subscript identifier integer for_in_clause identifier call identifier argument_list identifier if_statement boolean_operator identifier comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier else_clause block return_statement identifier | Retrieve the unique flowcell id represented in the SampleSheet. |
def update_vpc_entry(nexus_ips, vpc_id, learned, active):
LOG.debug("update_vpc_entry called")
session = bc.get_writer_session()
with session.begin():
for n_ip in nexus_ips:
flipit = not active
x = session.execute(
sa.update(nexus_models_v2.NexusVPCAlloc).values({
'learned': learned,
'active': active}).where(sa.and_(
nexus_models_v2.NexusVPCAlloc.switch_ip == n_ip,
nexus_models_v2.NexusVPCAlloc.vpc_id == vpc_id,
nexus_models_v2.NexusVPCAlloc.active == flipit
)))
if x.rowcount != 1:
raise c_exc.NexusVPCAllocNotFound(
switch_ip=n_ip, vpc_id=vpc_id, active=active) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list with_statement with_clause with_item call attribute identifier identifier argument_list block for_statement identifier identifier block expression_statement assignment identifier not_operator identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier identifier argument_list call attribute identifier identifier argument_list comparison_operator attribute attribute identifier identifier identifier identifier comparison_operator attribute attribute identifier identifier identifier identifier comparison_operator attribute attribute identifier identifier identifier identifier if_statement comparison_operator attribute identifier identifier integer block raise_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Change active state in vpc_allocate data base. |
def calc_oqparam(request, job_id):
job = logs.dbcmd('get_job', int(job_id))
if job is None:
return HttpResponseNotFound()
if not utils.user_has_permission(request, job.user_name):
return HttpResponseForbidden()
with datastore.read(job.ds_calc_dir + '.hdf5') as ds:
oq = ds['oqparam']
return HttpResponse(content=json.dumps(vars(oq)), content_type=JSON) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier if_statement comparison_operator identifier none block return_statement call identifier argument_list if_statement not_operator call attribute identifier identifier argument_list identifier attribute identifier identifier block return_statement call identifier argument_list with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list call identifier argument_list identifier keyword_argument identifier identifier | Return the calculation parameters as a JSON |
def check_field_cohesion(self, rec_write_fields, sig_write_fields):
if self.n_sig>0:
for f in sig_write_fields:
if len(getattr(self, f)) != self.n_sig:
raise ValueError('The length of field: '+f+' must match field n_sig.')
datfmts = {}
for ch in range(self.n_sig):
if self.file_name[ch] not in datfmts:
datfmts[self.file_name[ch]] = self.fmt[ch]
else:
if datfmts[self.file_name[ch]] != self.fmt[ch]:
raise ValueError('Each file_name (dat file) specified must have the same fmt')
datoffsets = {}
if self.byte_offset is not None:
for ch in range(self.n_sig):
if self.byte_offset[ch] is None:
continue
if self.file_name[ch] not in datoffsets:
datoffsets[self.file_name[ch]] = self.byte_offset[ch]
else:
if datoffsets[self.file_name[ch]] != self.byte_offset[ch]:
raise ValueError('Each file_name (dat file) specified must have the same byte offset') | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier integer block for_statement identifier identifier block if_statement comparison_operator call identifier argument_list call identifier argument_list identifier identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator subscript attribute identifier identifier identifier identifier block expression_statement assignment subscript identifier subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier else_clause block if_statement comparison_operator subscript identifier subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary if_statement comparison_operator attribute identifier identifier none block for_statement identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator subscript attribute identifier identifier identifier none block continue_statement if_statement comparison_operator subscript attribute identifier identifier identifier identifier block expression_statement assignment subscript identifier subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier else_clause block if_statement comparison_operator subscript identifier subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end | Check the cohesion of fields used to write the header |
def query_tracking_code(tracking_code, year=None):
payload = {
'Anio': year or datetime.now().year,
'Tracking': tracking_code,
}
response = _make_request(TRACKING_URL, payload)
if not response['d']:
return []
data = response['d'][0]
destination = data['RetornoCadena6']
payload.update({
'Destino': destination,
})
response = _make_request(TRACKING_DETAIL_URL, payload)
return _process_detail(response['d']) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end boolean_operator identifier attribute call attribute identifier identifier argument_list identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator subscript identifier string string_start string_content string_end block return_statement list expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end integer expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list subscript identifier string string_start string_content string_end | Given a tracking_code return a list of events related the tracking code |
def _passwd_opts(self):
options = ['ControlMaster=auto',
'StrictHostKeyChecking=no',
]
if self.opts['_ssh_version'] > (4, 9):
options.append('GSSAPIAuthentication=no')
options.append('ConnectTimeout={0}'.format(self.timeout))
if self.opts.get('ignore_host_keys'):
options.append('StrictHostKeyChecking=no')
if self.opts.get('no_host_keys'):
options.extend(['StrictHostKeyChecking=no',
'UserKnownHostsFile=/dev/null'])
if self.passwd:
options.extend(['PasswordAuthentication=yes',
'PubkeyAuthentication=yes'])
else:
options.extend(['PasswordAuthentication=no',
'PubkeyAuthentication=yes',
'KbdInteractiveAuthentication=no',
'ChallengeResponseAuthentication=no',
'BatchMode=yes'])
if self.port:
options.append('Port={0}'.format(self.port))
if self.user:
options.append('User={0}'.format(self.user))
if self.identities_only:
options.append('IdentitiesOnly=yes')
ret = []
for option in options:
ret.append('-o {0} '.format(option))
return ''.join(ret) | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator subscript attribute identifier identifier string string_start string_content string_end tuple integer integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute string string_start string_end identifier argument_list identifier | Return options to pass to ssh |
def _generate_barcode_ids(info_iter):
bc_type = "SampleSheet"
barcodes = list(set([x[-1] for x in info_iter]))
barcodes.sort()
barcode_ids = {}
for i, bc in enumerate(barcodes):
barcode_ids[bc] = (bc_type, i+1)
return barcode_ids | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call identifier argument_list list_comprehension subscript identifier unary_operator integer for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment subscript identifier identifier tuple identifier binary_operator identifier integer return_statement identifier | Create unique barcode IDs assigned to sequences |
def alphanumeric_hash(s: str, size=5):
import hashlib
import base64
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | module function_definition identifier parameters typed_parameter identifier type identifier default_parameter identifier integer block import_statement dotted_name identifier import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute subscript identifier slice identifier identifier argument_list string string_start string_content string_end identifier argument_list return_statement identifier | Short alphanumeric string derived from hash of given string |
def translate(self, text):
self.count = 0
return self._make_regex().sub(self, text) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier integer return_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier identifier | Translate text, returns the modified text. |
def delete_node_nto1(node_list, begin, node, end):
if begin is None:
assert node is not None
begin = node.precedence
elif not isinstance(begin, list):
begin = [begin]
if end.in_or_out:
for nb_ in begin:
nb_.out_redirect(node.single_input, node.single_output)
else:
for nb_ in begin:
target_var_name = node.single_input
assert target_var_name in nb_.output.values()
end.in_redirect(node.single_output, target_var_name)
for nb_ in begin:
nb_.successor = [end if v_ == node else v_ for v_ in nb_.successor]
end.precedence = [v_ for v_ in end.precedence if v_ != node] + node.precedence
node_list.remove(node)
return node_list | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier none block assert_statement comparison_operator identifier none expression_statement assignment identifier attribute identifier identifier elif_clause not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier if_statement attribute identifier identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier else_clause block for_statement identifier identifier block expression_statement assignment identifier attribute identifier identifier assert_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier for_statement identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension conditional_expression identifier comparison_operator identifier identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | delete the node which has n-input and 1-output |
def open(self):
self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.device.connect((self.host, self.port))
if self.device is None:
print "Could not open socket for %s" % self.host | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block print_statement binary_operator string string_start string_content string_end attribute identifier identifier | Open TCP socket and set it as escpos device |
def __check_deprecated(self):
if "SANIC_JWT_HANDLER_PAYLOAD_SCOPES" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_HANDLER_PAYLOAD_SCOPES has been deprecated. "
"Instead, pass your handler method (not an import path) as "
"initialize(add_scopes_to_payload=my_scope_extender)"
)
if "SANIC_JWT_PAYLOAD_HANDLER" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_PAYLOAD_HANDLER has been deprecated. "
"Instead, you will need to subclass Authentication. "
)
if "SANIC_JWT_HANDLER_PAYLOAD_EXTEND" in self.app.config:
raise exceptions.InvalidConfiguration(
"SANIC_JWT_HANDLER_PAYLOAD_EXTEND has been deprecated. "
"Instead, you will need to subclass Authentication. "
"Check out the documentation for more information."
) | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier block raise_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier block raise_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier block raise_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end | Checks for deprecated configuration keys |
def addComment(self, comment):
url = "%s/addComment" % self.root
params = {
"f" : "json",
"comment" : comment
}
return self._post(url, params, proxy_port=self._proxy_port,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | adds a comment to a given item. Must be authenticated |
def reset(self):
self._unionSDR = numpy.zeros(shape=(self._numInputs,))
self._activeCellsHistory = [] | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier tuple attribute identifier identifier expression_statement assignment attribute identifier identifier list | Reset Union Pooler, clear active cell history |
def clone_repo(pkg, dest, repo, repo_dest, branch):
git(['clone', '--recursive', '-b', branch, repo, repo_dest]) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier identifier identifier | Clone the Playdoh repo into a custom path. |
def macshim():
import subprocess, sys
subprocess.call([
sys.argv[0] + '32'
]+sys.argv[1:],
env={"VERSIONER_PYTHON_PREFER_32_BIT":"yes"}
) | module function_definition identifier parameters block import_statement dotted_name identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list binary_operator list binary_operator subscript attribute identifier identifier integer string string_start string_content string_end subscript attribute identifier identifier slice integer keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end | Shim to run 32-bit on 64-bit mac as a sub-process |
def split_window(pymux, variables):
executable = variables['<executable>']
start_directory = variables['<start-directory>']
pymux.add_process(executable, vsplit=variables['-h'],
start_directory=start_directory) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier identifier | Split horizontally or vertically. |
def do_help(self, args):
if args.command:
f = getattr(self, 'help_' + args.command, None)
if f:
f()
return
f = getattr(self, 'do_' + args.command, None)
if not f:
msg = self.nohelp % (args.command,)
self.stdout.write('{0}\n'.format(msg))
return
docstr = getattr(f, '__doc__', None)
f = getattr(self, 'args_' + args.command, None)
if f:
parser = argparse.ArgumentParser(
prog=args.command,
description=docstr)
f(parser)
parser.print_help(file=self.stdout)
else:
if not docstr:
docstr = self.nohelp % (args.command,)
self.stdout.write('{0}\n'.format(docstr))
else:
Cmd.do_help(self, '') | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier none if_statement identifier block expression_statement call identifier argument_list return_statement expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier none if_statement not_operator identifier block expression_statement assignment identifier binary_operator attribute identifier identifier tuple attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier return_statement expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier none if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier else_clause block if_statement not_operator identifier block expression_statement assignment identifier binary_operator attribute identifier identifier tuple attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier string string_start string_end | print help on a command |
def _srads2bt(self, data, channel_name):
a__, b__, c__ = BTFIT[channel_name]
wavenumber = CALIB[self.platform_id][channel_name]["VC"]
temp = self._tl15(data, wavenumber)
return a__ * temp * temp + b__ * temp + c__ | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier subscript identifier identifier expression_statement assignment identifier subscript subscript subscript identifier attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement binary_operator binary_operator binary_operator binary_operator identifier identifier identifier binary_operator identifier identifier identifier | Computation based on spectral radiance. |
def sign(self, signer: Signer):
message_data = self._data_to_sign()
self.signature = signer.sign(data=message_data) | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier identifier | Sign message using signer. |
def load_content(self):
rel_path = self.root_file_url.replace(os.path.basename(self.root_file_url), '')
self.toc_file_url = rel_path + self.root_file.find(id="ncx")['href']
self.toc_file_soup = bs(self.book_file.read(self.toc_file_url), 'xml')
for n, c in cross(self.toc_file_soup.find_all('navLabel'), self.toc_file_soup.find_all('content')):
content_soup = bs(self.book_file.read(rel_path + c.get('src')))
self.content.append({'part_name': c.text,
'source_url': c.get('src'),
'content_source': content_soup,
'content_source_body': content_soup.body,
'content_source_text': content_soup.body.text}) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_end expression_statement assignment attribute identifier identifier binary_operator identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list binary_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier | Load the book content |
def filter_short(terms):
return [term for i, term in enumerate(terms) if 26**(len(term)) > i] | module function_definition identifier parameters identifier block return_statement list_comprehension identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier if_clause comparison_operator binary_operator integer parenthesized_expression call identifier argument_list identifier identifier | only keep if brute-force possibilities are greater than this word's rank in the dictionary |
def trimmed_split(s, seps=(";", ",")):
for sep in seps:
if sep not in s:
continue
data = [item.strip() for item in s.strip().split(sep)]
return data
return [s] | module function_definition identifier parameters identifier default_parameter identifier tuple string string_start string_content string_end string string_start string_content string_end block for_statement identifier identifier block if_statement comparison_operator identifier identifier block continue_statement expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute call attribute identifier identifier argument_list identifier argument_list identifier return_statement identifier return_statement list identifier | Given a string s, split is by one of one of the seps. |
def getAceTypeText(self, t):
try:
return self.validAceTypes[t]['TEXT']
except KeyError:
raise CommandExecutionError((
'No ACE type "{0}". It should be one of the following: {1}'
).format(t, ', '.join(self.validAceTypes))) | module function_definition identifier parameters identifier identifier block try_statement block return_statement subscript subscript attribute identifier identifier identifier string string_start string_content string_end except_clause identifier block raise_statement call identifier argument_list call attribute parenthesized_expression string string_start string_content string_end identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | returns the textual representation of a acetype bit |
def process_on_event(self):
if not self._queue:
self._active = False
return
events = list(OrderedDict([(event.event_name, event)
for event in self._queue]).values())
self._queue = []
for event in events:
msg = {}
for attr, path in self.attributes.items():
model_obj = self.plot_handles.get(self.models[0])
msg[attr] = self.resolve_attr_spec(path, event, model_obj)
self.on_msg(msg)
self.plot.document.add_timeout_callback(self.process_on_event, 50) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier false return_statement expression_statement assignment identifier call identifier argument_list call attribute call identifier argument_list list_comprehension tuple attribute identifier identifier identifier for_in_clause identifier attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier list for_statement identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier integer expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier integer | Trigger callback change event and triggering corresponding streams. |
def find(self, path, all=False):
found = os.path.join(settings.STATIC_ROOT, path)
if all:
return [found]
else:
return found | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier if_statement identifier block return_statement list identifier else_clause block return_statement identifier | Looks for files in the app directories. |
def hasReaders(self, ulBuffer):
fn = self.function_table.hasReaders
result = fn(ulBuffer)
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes. |
def walk(self, into_past=0, into_future=0):
walked_range = []
for shift in range(-into_past, into_future):
kwargs = dict(drip_model=self.drip_model,
name=self.name,
now_shift_kwargs={'days': shift})
walked_range.append(self.__class__(**kwargs))
return walked_range | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier list for_statement identifier call identifier argument_list unary_operator identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list dictionary_splat identifier return_statement identifier | Walk over a date range and create new instances of self with new ranges. |
def tagged(self, tag):
return Scm(self.connection, self.developer_connection, self.url, tag=tag) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier keyword_argument identifier identifier | Creates a new `Scm` identical to this `Scm` but with the given `tag`. |
def create_add_on(self, add_on):
url = urljoin(self._url, '/add_ons')
return add_on.post(url) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier | Make the given `AddOn` available to subscribers on this plan. |
def _decode_ctrl_packet(self, version, packet):
for i in range(5):
input_bit = packet[i]
self._debug(PROP_LOGLEVEL_DEBUG, "Byte " + str(i) + ": " + str((input_bit >> 7) & 1) + str((input_bit >> 6) & 1) + str((input_bit >> 5) & 1) + str((input_bit >> 4) & 1) + str((input_bit >> 3) & 1) + str((input_bit >> 2) & 1) + str((input_bit >> 1) & 1) + str(input_bit & 1))
for sensor in self._ctrl_sensor:
if (sensor.sensor_type == PROP_SENSOR_FLAG):
sensor.value = (packet[sensor.index // 8] >> (sensor.index % 8)) & 1
elif (sensor.sensor_type == PROP_SENSOR_RAW):
sensor.value = packet | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call identifier argument_list integer block expression_statement assignment identifier subscript identifier identifier expression_statement call attribute identifier identifier argument_list identifier binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer call identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer call identifier argument_list binary_operator identifier integer for_statement identifier attribute identifier identifier block if_statement parenthesized_expression comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier binary_operator parenthesized_expression binary_operator subscript identifier binary_operator attribute identifier identifier integer parenthesized_expression binary_operator attribute identifier identifier integer integer elif_clause parenthesized_expression comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier | Decode a control packet into the list of sensors. |
def taskdir(self):
return os.path.join(self.BASE, self.TAG, self.task_family) | module function_definition identifier parameters identifier block return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier | Return the directory under which all artefacts are stored. |
def key(self):
return self.make_key(
self._instance._name,
self._instance.pk.get(),
self.name,
) | module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier | A property to return the key used in redis for the current field. |
def usage(self):
return u' '.join(u'<%s>' % pattern.usage for pattern in self.patterns) | module function_definition identifier parameters identifier block return_statement call attribute string string_start string_content string_end identifier generator_expression binary_operator string string_start string_content string_end attribute identifier identifier for_in_clause identifier attribute identifier identifier | A usage string that describes the signature. |
def _make_hyperparameter_decode_func(locked_values, meta_parameters):
def decode(solution):
hyperparameters = copy.deepcopy(locked_values)
index = 0
for name, parameters in meta_parameters.iteritems():
binary_size = parameters['binary_size']
binary = solution[index:index + binary_size]
index += binary_size
if parameters['type'] == 'discrete':
i = helpers.binary_to_int(
binary, upper_bound=len(parameters['values']) - 1)
value = parameters['values'][i]
elif parameters['type'] == 'int':
value = helpers.binary_to_int(
binary,
lower_bound=parameters['min'],
upper_bound=parameters['max'])
elif parameters['type'] == 'float':
value = helpers.binary_to_float(
binary,
lower_bound=parameters['min'],
upper_bound=parameters['max'])
else:
raise ValueError(
'Parameter type "{}" does not match known values'.format(
parameters['type']))
hyperparameters[name] = value
return hyperparameters
return decode | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier integer for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier slice identifier binary_operator identifier identifier expression_statement augmented_assignment identifier identifier if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier binary_operator call identifier argument_list subscript identifier string string_start string_content string_end integer expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end identifier elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier identifier identifier return_statement identifier return_statement identifier | Create a function that converts the binary solution to parameters. |
def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
fieldName = field.getName()
if fieldName + "_uid" in form:
uid = form.get(fieldName + "_uid", '')
if field.multiValued and\
(isinstance(uid, str) or isinstance(uid, unicode)):
uid = uid.split(",")
elif fieldName in form:
uid = form.get(fieldName, '')
if field.multiValued and\
(isinstance(uid, str) or isinstance(uid, unicode)):
uid = uid.split(",")
else:
uid = None
return uid, {} | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator binary_operator identifier string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end string string_start string_end if_statement boolean_operator attribute identifier identifier line_continuation parenthesized_expression boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end elif_clause comparison_operator identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_end if_statement boolean_operator attribute identifier identifier line_continuation parenthesized_expression boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier none return_statement expression_list identifier dictionary | Return a UID so that ReferenceField understands. |
def preprocess(cls, cat):
if isinstance(cat, str):
cat = intake.open_catalog(cat)
return cat | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Function to run on each cat input |
def rm(ctx, cluster_id):
session = create_session(ctx.obj['AWS_PROFILE_NAME'])
client = session.client('emr')
try:
result = client.describe_cluster(ClusterId=cluster_id)
target_dns = result['Cluster']['MasterPublicDnsName']
flag = click.prompt(
"Are you sure you want to terminate {0}: {1}? [y/Y]".format(
cluster_id, target_dns), type=str, default='n')
if flag.lower() == 'y':
result = client.terminate_job_flows(JobFlowIds=[cluster_id])
except ClientError as e:
click.echo(e, err=True) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true | Terminate a EMR cluster |
def build_basic_auth(username: str, password: str) -> str:
assert ":" not in username
user_pass = f"{username}:{password}"
basic_credentials = base64.b64encode(user_pass.encode()).decode()
return "Basic " + basic_credentials | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block assert_statement comparison_operator string string_start string_content string_end identifier expression_statement assignment identifier string string_start interpolation identifier string_content interpolation identifier string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier argument_list return_statement binary_operator string string_start string_content string_end identifier | Build an Authorization header for HTTP Basic Auth. |
def reward_bonus(self, assignment_id, amount, reason):
logger.info(
'Award ${} for assignment {}, with reason "{}"'.format(
amount, assignment_id, reason
)
) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier | Print out bonus info for the assignment |
def split_arg_string(string):
rv = []
for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
r'|"([^"\\]*(?:\\.[^"\\]*)*)"'
r'|\S+)\s*', string, re.S):
arg = match.group().strip()
if arg[:1] == arg[-1:] and arg[:1] in '"\'':
arg = arg[1:-1].encode('ascii', 'backslashreplace') \
.decode('unicode-escape')
try:
arg = type(string)(arg)
except UnicodeError:
pass
rv.append(arg)
return rv | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier attribute identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list if_statement boolean_operator comparison_operator subscript identifier slice integer subscript identifier slice unary_operator integer comparison_operator subscript identifier slice integer string string_start string_content escape_sequence string_end block expression_statement assignment identifier call attribute call attribute subscript identifier slice integer unary_operator integer identifier argument_list string string_start string_content string_end string string_start string_content string_end line_continuation identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call call identifier argument_list identifier argument_list identifier except_clause identifier block pass_statement expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Given an argument string this attempts to split it into small parts. |
def __struct_params_s(obj, separator=', ', f=repr, fmt='%s = %s'):
s = separator.join([__single_param(obj, n, f, fmt) for n in dir(obj) if __inc_param(obj, n)])
return s | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list list_comprehension call identifier argument_list identifier identifier identifier identifier for_in_clause identifier call identifier argument_list identifier if_clause call identifier argument_list identifier identifier return_statement identifier | method wrapper for printing all elements of a struct |
def iterprogress( sized_iterable ):
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list integer call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement yield identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier | Iterate something printing progress bar to stdout |
def his_from_sql(self, db_name, point):
his = self._read_from_sql('select * from "%s"' % "history", db_name)
his.index = his["index"].apply(Timestamp)
return his.set_index("index")[point] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier return_statement subscript call attribute identifier identifier argument_list string string_start string_content string_end identifier | Retrive point histories from SQL database |
def split_pubnote(pubnote_str):
pubnote = {}
parts = pubnote_str.split(',')
if len(parts) > 2:
pubnote['journal_title'] = parts[0]
pubnote['journal_volume'] = parts[1]
pubnote['page_start'], pubnote['page_end'], pubnote['artid'] = split_page_artid(parts[2])
return {key: val for (key, val) in six.iteritems(pubnote) if val is not None} | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier integer expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier integer expression_statement assignment pattern_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end call identifier argument_list subscript identifier integer return_statement dictionary_comprehension pair identifier identifier for_in_clause tuple_pattern identifier identifier call attribute identifier identifier argument_list identifier if_clause comparison_operator identifier none | Split pubnote into journal information. |
def ext_pillar(minion_id, pillar, function, **kwargs):
if function.startswith('_') or function not in globals():
return {}
return globals()[function](minion_id, pillar, **kwargs) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator identifier call identifier argument_list block return_statement dictionary return_statement call subscript call identifier argument_list identifier argument_list identifier identifier dictionary_splat identifier | Grabs external pillar data based on configured function |
def FilterArgsFromSemanticProtobuf(protobuf, kwargs):
for descriptor in protobuf.type_infos:
value = kwargs.pop(descriptor.name, None)
if value is not None:
setattr(protobuf, descriptor.name, value) | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier attribute identifier identifier identifier | Assign kwargs to the protobuf, and remove them from the kwargs dict. |
def check_user_by_name(user_name, u_pass):
the_query = TabMember.select().where(TabMember.user_name == user_name)
if the_query.count() == 0:
return -1
the_user = the_query.get()
if the_user.user_pass == tools.md5(u_pass):
return 1
return 0 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list comparison_operator attribute identifier identifier identifier if_statement comparison_operator call attribute identifier identifier argument_list integer block return_statement unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier call attribute identifier identifier argument_list identifier block return_statement integer return_statement integer | Checking the password by user's name. |
def _check_default_index(items, default_index):
num_items = len(items)
if default_index is not None and not isinstance(default_index, int):
raise TypeError("The default index ({}) is not an integer".format(default_index))
if default_index is not None and default_index >= num_items:
raise ValueError("The default index ({}) >= length of the list ({})".format(default_index, num_items))
if default_index is not None and default_index < 0:
raise ValueError("The default index ({}) < 0.".format(default_index))
if default_index is not None and not items[default_index]:
raise ValueError("The default index ({}) points to an empty item.".format(default_index)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none not_operator subscript identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Check that the default is in the list, and not empty |
def parse_multi_value_header(header_str):
parsed_parts = []
if header_str:
parts = header_str.split(',')
for part in parts:
match = re.search('\s*(W/)?\"?([^"]*)\"?\s*', part)
if match is not None:
parsed_parts.append(match.group(2))
return parsed_parts | module function_definition identifier parameters identifier block expression_statement assignment identifier list if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer return_statement identifier | Break apart an HTTP header string that is potentially a quoted, comma separated list as used in entity headers in RFC2616. |
def delete(self):
if not self.is_created():
LOG.debug("Container was not created. Skipping deletion")
return
try:
self.docker_client.containers\
.get(self.id)\
.remove(force=True)
except docker.errors.NotFound:
LOG.debug("Container with ID %s does not exist. Skipping deletion", self.id)
except docker.errors.APIError as ex:
msg = str(ex)
removal_in_progress = ("removal of container" in msg) and ("is already in progress" in msg)
if not removal_in_progress:
raise ex
self.id = None | module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement try_statement block expression_statement call attribute call attribute attribute attribute identifier identifier identifier line_continuation identifier argument_list attribute identifier identifier line_continuation identifier argument_list keyword_argument identifier true except_clause attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier boolean_operator parenthesized_expression comparison_operator string string_start string_content string_end identifier parenthesized_expression comparison_operator string string_start string_content string_end identifier if_statement not_operator identifier block raise_statement identifier expression_statement assignment attribute identifier identifier none | Removes a container that was created earlier. |
def location_path(cls, project, location):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}",
project=project,
location=location,
) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier | Return a fully-qualified location string. |
def setXr(self, Xr):
self.Xr = Xr
self.gp_block.covar.G = Xr | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute attribute attribute identifier identifier identifier identifier identifier | set genotype data of the set component |
def _state_table_name(environment=None, layer=None, stage=None):
if environment is None:
environment = os.environ.get("HUMILIS_ENVIRONMENT")
if layer is None:
layer = os.environ.get("HUMILIS_LAYER")
if stage is None:
stage = os.environ.get("HUMILIS_STAGE")
if environment:
if stage:
return "{environment}-{layer}-{stage}-state".format(
**locals())
else:
return "{environment}-{layer}-state".format(**locals()) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement identifier block if_statement identifier block return_statement call attribute string string_start string_content string_end identifier argument_list dictionary_splat call identifier argument_list else_clause block return_statement call attribute string string_start string_content string_end identifier argument_list dictionary_splat call identifier argument_list | The name of the state table associated to a humilis deployment. |
def preformatted_text(source: str) -> str:
environ.abort_thread()
if not source:
return ''
source = render_utils.html_escape(source)
return '<pre class="preformatted-textbox">{text}</pre>'.format(
text=str(textwrap.dedent(source))
) | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement call attribute identifier identifier argument_list if_statement not_operator identifier block return_statement string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call identifier argument_list call attribute identifier identifier argument_list identifier | Renders preformatted text box |
def end_element(self, tag):
if tag == u'form':
self.forms.append(self.form)
self.form = None | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier none | search for ending form values. |
def decode(self, name, as_map_key=False):
if is_cache_key(name) and (name in self.key_to_value):
return self.key_to_value[name]
return self.encache(name) if is_cacheable(name, as_map_key) else name | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement boolean_operator call identifier argument_list identifier parenthesized_expression comparison_operator identifier attribute identifier identifier block return_statement subscript attribute identifier identifier identifier return_statement conditional_expression call attribute identifier identifier argument_list identifier call identifier argument_list identifier identifier identifier | Always returns the name |
def colorize(occurence,maxoccurence,minoccurence):
if occurence == maxoccurence:
color = (255,0,0)
elif occurence == minoccurence:
color = (0,0,255)
else:
color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255))
return color | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment identifier tuple integer integer integer elif_clause comparison_operator identifier identifier block expression_statement assignment identifier tuple integer integer integer else_clause block expression_statement assignment identifier tuple call identifier argument_list parenthesized_expression binary_operator binary_operator call identifier argument_list identifier identifier integer integer call identifier argument_list binary_operator binary_operator call identifier argument_list identifier identifier integer return_statement identifier | A formula for determining colors. |
def point_lm(self, context):
(ls, us), _ = context.array_extents(context.name)
return np.asarray(lm_coords[ls:us], dtype=context.dtype) | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list tuple_pattern identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list subscript identifier slice identifier identifier keyword_argument identifier attribute identifier identifier | Supply point source lm coordinates to montblanc |
def cached_read(self, kind):
if not kind in self.cache:
self.pull_stats(kind)
if self.epochnow() - self.cache[kind]['lastcall'] > self.cache_timeout:
self.pull_stats(kind)
return self.cache[kind]['lastvalue'] | module function_definition identifier parameters identifier identifier block if_statement not_operator comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator binary_operator call attribute identifier identifier argument_list subscript subscript attribute identifier identifier identifier string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement subscript subscript attribute identifier identifier identifier string string_start string_content string_end | Cache stats calls to prevent hammering the API |
def follow_file(self, f, seen, trim):
return (f not in self.graph.nodes and
f not in seen and
(not trim or
not isinstance(self.provenance[f],
(resolve.Builtin, resolve.System)))) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement parenthesized_expression boolean_operator boolean_operator comparison_operator identifier attribute attribute identifier identifier identifier comparison_operator identifier identifier parenthesized_expression boolean_operator not_operator identifier not_operator call identifier argument_list subscript attribute identifier identifier identifier tuple attribute identifier identifier attribute identifier identifier | Whether to recurse into a file's dependencies. |
def bake(src):
src = os.path.realpath(src)
path = os.path.dirname(src)
filename = os.path.basename(src)
html = _load_file(src).read()
if imghdr.what("", html):
html = "<html><body><img src='{}'/></body></html>".format(cgi.escape(filename))
cwd = os.getcwd()
os.chdir(path)
bs_html = bs4.BeautifulSoup(html, "html.parser")
images = bs_html.find_all("img")
for image in images:
_image_to_data(image)
for link in bs_html.find_all("link"):
_bake_css(link)
for script in bs_html.find_all("script"):
_bake_script(script)
os.chdir(cwd)
return bs_html | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_end identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement call identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Runs the encoder on the given source file |
def OnDirectionChoice(self, event):
label = self.direction_choicectrl.GetItems()[event.GetSelection()]
param = self.choice_label2param[label]
self.attrs["direction"] = param
post_command_event(self, self.DrawChartMsg) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier attribute identifier identifier | Direction choice event handler |
def y_rotate(rotationAmt):
ma4 = Matrix4((math.cos(rotationAmt), 0, math.sin(rotationAmt), 0),
(0, 1, 0, 0),
(-math.sin(rotationAmt), 0, math.cos(rotationAmt), 0),
(0, 0, 0, 1))
return ma4 | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list tuple call attribute identifier identifier argument_list identifier integer call attribute identifier identifier argument_list identifier integer tuple integer integer integer integer tuple unary_operator call attribute identifier identifier argument_list identifier integer call attribute identifier identifier argument_list identifier integer tuple integer integer integer integer return_statement identifier | Create a matrix that rotates around the y axis. |
def gen_file_jinja(self, template_file, data, output, dest_path):
if not os.path.exists(dest_path):
os.makedirs(dest_path)
output = join(dest_path, output)
logger.debug("Generating: %s" % output)
env = Environment()
env.loader = FileSystemLoader(self.TEMPLATE_DIR)
template = env.get_template(template_file)
target_text = template.render(data)
open(output, "w").write(target_text)
return dirname(output), output | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list identifier return_statement expression_list call identifier argument_list identifier identifier | Fills data to the project template, using jinja2. |
async def commit_prepared(self, xid, *, is_prepared=True):
if not is_prepared:
await self.execute("XA END '%s'" % xid)
await self.execute("XA COMMIT '%s'" % xid) | module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier true block if_statement not_operator identifier block expression_statement await call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement await call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier | Commit prepared twophase transaction. |
def _objectdata_cache_key(func, obj):
uid = api.get_uid(obj)
modified = api.get_modification_date(obj).millis()
review_state = api.get_review_status(obj)
return "{}-{}-{}".format(uid, review_state, modified) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier | Cache Key for object data |
def validate_format(self, allowed_formats):
if self.format in allowed_formats:
return
ui.error("Export type '{0}' does not accept '{1}' format, only: "
"{2}".format(self.type, self.format, allowed_formats))
sys.exit(1) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list integer | Validate the allowed formats for a specific type. |
def _calculate_bounds(self):
first = self.coll_handle.find_one(None, sort=[("ts", ASCENDING)])
last = self.coll_handle.find_one(None, sort=[("ts", DESCENDING)])
self._start = first['ts']
if self._start.tzinfo is None:
self._start = self._start.replace(tzinfo=tzutc())
self._end = last['ts']
if self._end.tzinfo is None:
self._end = self._end.replace(tzinfo=tzutc())
return True | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list none keyword_argument identifier list tuple string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list none keyword_argument identifier list tuple string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call identifier argument_list expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call identifier argument_list return_statement true | Calculate beginning and end of log events. |
def process_csr(cls, common_name, csr=None, private_key=None,
country=None, state=None, city=None, organisation=None,
branch=None):
if csr:
if branch or organisation or city or state or country:
cls.echo('Following options are only used to generate'
' the CSR.')
else:
params = (('CN', common_name),
('OU', branch),
('O', organisation),
('L', city),
('ST', state),
('C', country))
params = [(key, val) for key, val in params if val]
csr = cls.create_csr(common_name, private_key, params)
if csr and os.path.exists(csr):
with open(csr) as fcsr:
csr = fcsr.read()
return csr | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement identifier block if_statement boolean_operator boolean_operator boolean_operator boolean_operator identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment identifier tuple tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier expression_statement assignment identifier list_comprehension tuple identifier identifier for_in_clause pattern_list identifier identifier identifier if_clause identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier if_statement boolean_operator identifier call attribute attribute identifier identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | Create a PK and a CSR if needed. |
def load_plugins(builtin=True, others=True):
for entry_point in pkg_resources.iter_entry_points('yolk.plugins'):
try:
plugin = entry_point.load()
except KeyboardInterrupt:
raise
except Exception as err_msg:
warn("Unable to load plugin %s: %s" % \
(entry_point, err_msg), RuntimeWarning)
continue
if plugin.__module__.startswith('yolk.plugins'):
if builtin:
yield plugin
elif others:
yield plugin | module function_definition identifier parameters default_parameter identifier true default_parameter identifier true block for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block raise_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end line_continuation tuple identifier identifier identifier continue_statement if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block if_statement identifier block expression_statement yield identifier elif_clause identifier block expression_statement yield identifier | Load plugins, either builtin, others, or both. |
def rset(self):
self._send('RSET\r\n')
resp = self._read()
if not resp.startswith('250'):
logger.warn('Unexpected server response at RSET: ' + resp)
self._recipients = []
self.results = {} | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier dictionary | Send LMTP RSET command and process the server response. |
def _slugify(path: Union[str, PurePath]) -> str:
if not isinstance(path, PurePath):
path = PurePath(path)
parts = list(path.parts)
if parts[0] == '/':
parts.pop(0)
elif len(parts[0]) == 3 and parts[0][1:] == ':\\':
parts[0] = parts[0][0]
filename = '-'.join(parts)
assert '/' not in filename, filename
assert not filename[1:].startswith(':'), filename
return filename | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier type identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list integer elif_clause boolean_operator comparison_operator call identifier argument_list subscript identifier integer integer comparison_operator subscript subscript identifier integer slice integer string string_start string_content escape_sequence string_end block expression_statement assignment subscript identifier integer subscript subscript identifier integer integer expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier assert_statement comparison_operator string string_start string_content string_end identifier identifier assert_statement not_operator call attribute subscript identifier slice integer identifier argument_list string string_start string_content string_end identifier return_statement identifier | Make a path into a filename. |
def fromseconds(cls, seconds):
try:
seconds = int(seconds)
except TypeError:
seconds = int(seconds.flatten()[0])
return cls(datetime.timedelta(0, int(seconds))) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block expression_statement assignment identifier call identifier argument_list subscript call attribute identifier identifier argument_list integer return_statement call identifier argument_list call attribute identifier identifier argument_list integer call identifier argument_list identifier | Return a |Period| instance based on a given number of seconds. |
def _get(self, pos):
res = None, None
if pos is not None:
try:
res = self[pos], pos
except (IndexError, KeyError):
pass
return res | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier expression_list none none if_statement comparison_operator identifier none block try_statement block expression_statement assignment identifier expression_list subscript identifier identifier identifier except_clause tuple identifier identifier block pass_statement return_statement identifier | loads widget at given position; handling invalid arguments |
def services(self):
"Returns a list of Service objects available in this folder"
return [self._get_subfolder("%s/%s/" %
(s['name'].rstrip('/').split('/')[-1], s['type']),
self._service_type_mapping.get(s['type'], Service)) for s
in self._json_struct.get('services', [])] | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end return_statement list_comprehension call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple subscript call attribute call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end unary_operator integer subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end list | Returns a list of Service objects available in this folder |
def _get_projection(self):
try:
proj_str = self.nc.attrs['gdal_projection']
except TypeError:
proj_str = self.nc.attrs['gdal_projection'].decode()
radius_a = proj_str.split('+a=')[-1].split()[0]
if float(radius_a) > 10e3:
units = 'm'
scale = 1.0
else:
units = 'km'
scale = 1e3
if 'units' not in proj_str:
proj_str = proj_str + ' +units=' + units
area_extent = (float(self.nc.attrs['gdal_xgeo_up_left']) / scale,
float(self.nc.attrs['gdal_ygeo_low_right']) / scale,
float(self.nc.attrs['gdal_xgeo_low_right']) / scale,
float(self.nc.attrs['gdal_ygeo_up_left']) / scale)
return proj_str, area_extent | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier call attribute subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier subscript call attribute subscript call attribute identifier identifier argument_list string string_start string_content string_end unary_operator integer identifier argument_list integer if_statement comparison_operator call identifier argument_list identifier float block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier float else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier float if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement assignment identifier tuple binary_operator call identifier argument_list subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier binary_operator call identifier argument_list subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier binary_operator call identifier argument_list subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier binary_operator call identifier argument_list subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier return_statement expression_list identifier identifier | Get projection from the NetCDF4 attributes |
def build_process_isolation_temp_dir(self):
path = tempfile.mkdtemp(prefix='ansible_runner_pi_', dir=self.process_isolation_path)
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
atexit.register(shutil.rmtree, path)
return path | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier return_statement identifier | Create a temporary directory for process isolation to use. |
def on_ok(self):
if self.dir_select.value:
npyscreen.notify_wait('In the process of restoring',
title='Restoring...')
status = self.restore(self.dirs[self.dir_select.value[0]])
if status[0]:
npyscreen.notify_confirm('Status of restore:\n' +
status[1])
else:
npyscreen.notify_confirm(status[1])
self.quit()
else:
npyscreen.notify_confirm('Choose a version to restore from') | module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier subscript attribute attribute identifier identifier identifier integer if_statement subscript identifier integer block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end subscript identifier integer else_clause block expression_statement call attribute identifier identifier argument_list subscript identifier integer expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Perform restoration on the backup file selected |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.