code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def close_compute_projects(self, compute):
for project in self._projects.values():
if compute in project.computes:
yield from project.close() | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block expression_statement yield call attribute identifier identifier argument_list | Close projects running on a compute |
def build(templates=None, schemes=None, base_output_dir=None):
template_dirs = templates or get_template_dirs()
scheme_files = get_scheme_files(schemes)
base_output_dir = base_output_dir or rel_to_cwd('output')
if not template_dirs or not scheme_files:
raise LookupError
try:
os.makedirs(base_output_dir)
except FileExistsError:
pass
if not os.access(base_output_dir, os.W_OK):
raise PermissionError
templates = [TemplateGroup(path) for path in template_dirs]
build_from_job_list(scheme_files, templates, base_output_dir)
print('Finished building process.') | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier call identifier argument_list string string_start string_content string_end if_statement boolean_operator not_operator identifier not_operator identifier block raise_statement identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block pass_statement if_statement not_operator call attribute identifier identifier argument_list identifier attribute identifier identifier block raise_statement identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list string string_start string_content string_end | Main build function to initiate building process. |
def selectis(table, field, value, complement=False):
return selectop(table, field, value, operator.is_, complement=complement) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block return_statement call identifier argument_list identifier identifier identifier attribute identifier identifier keyword_argument identifier identifier | Select rows where the given field `is` the given value. |
def getcoordinates(self, tree, location):
return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location)) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier generator_expression call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier | Gets coordinates from a specific element in PLIP XML |
def visit(self, node):
method = 'visit_' + type(node).__name__
return getattr(self, method, self.fallback)(node) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute call identifier argument_list identifier identifier return_statement call call identifier argument_list identifier identifier attribute identifier identifier argument_list identifier | Visit the right method of the child class according to the node. |
def register(cls, name):
def register_decorator(reg_cls):
def name_func(self):
return name
reg_cls.name = property(name_func)
assert issubclass(reg_cls, cls), \
"Must be subclass matching your NamedRegistry class"
cls.REGISTRY[name] = reg_cls
return reg_cls
return register_decorator | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block function_definition identifier parameters identifier block return_statement identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier assert_statement call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier return_statement identifier | Decorator to register a class. |
def run(self, b, compute, times=[], **kwargs):
self.run_checks(b, compute, times, **kwargs)
logger.debug("rank:{}/{} calling get_packet_and_syns".format(mpi.myrank, mpi.nprocs))
packet, new_syns = self.get_packet_and_syns(b, compute, times, **kwargs)
if mpi.enabled:
mpi.comm.bcast(packet, root=0)
packet['b'] = b
rpacketlists = self._run_chunk(**packet)
rpacketlists_per_worker = mpi.comm.gather(rpacketlists, root=0)
else:
rpacketlists_per_worker = [self._run_chunk(**packet)]
return self._fill_syns(new_syns, rpacketlists_per_worker) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier list dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier identifier dictionary_splat identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier integer expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier integer else_clause block expression_statement assignment identifier list call attribute identifier identifier argument_list dictionary_splat identifier return_statement call attribute identifier identifier argument_list identifier identifier | if within mpirun, workers should call _run_worker instead of run |
def print_with_pager(output):
if sys.stdout.isatty():
try:
pager = subprocess.Popen(
['less', '-F', '-r', '-S', '-X', '-K'],
stdin=subprocess.PIPE, stdout=sys.stdout)
except subprocess.CalledProcessError:
print(output)
return
else:
pager.stdin.write(output.encode('utf-8'))
pager.stdin.close()
pager.wait()
else:
print(output) | module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list block try_statement block expression_statement assignment identifier 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 string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier except_clause attribute identifier identifier block expression_statement call identifier argument_list identifier return_statement else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call identifier argument_list identifier | Print the output to `stdout` using less when in a tty. |
def __restore_selection(self, start_pos, end_pos):
cursor = self.textCursor()
cursor.setPosition(start_pos)
cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
self.setTextCursor(cursor) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Restore cursor selection from position bounds |
def full_name(self):
return "%s %s %s %s" % (self.get_title_display(),
self.first_name,
self.other_names.replace(",", ""),
self.last_name) | module function_definition identifier parameters identifier block return_statement binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end attribute identifier identifier | Return the title and full name |
def option_getter(type):
option_getters = {None: ConfigParser.get,
int: ConfigParser.getint,
float: ConfigParser.getfloat,
bool: ConfigParser.getboolean}
return option_getters.get(type, option_getters[None]) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair none attribute identifier identifier pair identifier attribute identifier identifier pair identifier attribute identifier identifier pair identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier subscript identifier none | Gets an unbound method to get a configuration option as the given type. |
def keyword(self, text):
cls = self.KEYWORDS[text]
self.push_token(cls(text, self.lineno, self.offset)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier attribute identifier identifier attribute identifier identifier | Push a keyword onto the token queue. |
def pixels(self, value: int) -> 'Gap':
raise_not_number(value)
self.gap = '{}px'.format(value)
return self | module function_definition identifier parameters identifier typed_parameter identifier type identifier type string string_start string_content string_end block expression_statement call identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Set the margin in pixels. |
def make_student(user):
tutor_group, owner_group = _get_user_groups()
user.is_staff = False
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.remove(user)
tutor_group.save() | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Makes the given user a student. |
def remove_sqlvm_from_aglistener(instance, sqlvm_resource_id):
if not is_valid_resource_id(sqlvm_resource_id):
raise CLIError("Invalid SQL virtual machine resource id.")
vm_list = instance.load_balancer_configurations[0].sql_virtual_machine_instances
if sqlvm_resource_id in vm_list:
instance.load_balancer_configurations[0].sql_virtual_machine_instances.remove(sqlvm_resource_id)
return instance | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute subscript attribute identifier identifier integer identifier if_statement comparison_operator identifier identifier block expression_statement call attribute attribute subscript attribute identifier identifier integer identifier identifier argument_list identifier return_statement identifier | Remove a SQL virtual machine from an availability group listener. |
def package(
files,
tag,
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
**extra_metadata
):
"Package specified SQLite files into a new datasette Docker container"
if not shutil.which("docker"):
click.secho(
' The package command requires "docker" to be installed and configured ',
bg="red",
fg="white",
bold=True,
err=True,
)
sys.exit(1)
with temporary_docker_directory(
files,
"datasette",
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
extra_metadata,
):
args = ["docker", "build"]
if tag:
args.append("-t")
args.append(tag)
args.append(".")
call(args) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end 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 string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier true keyword_argument identifier true expression_statement call attribute identifier identifier argument_list integer with_statement with_clause with_item call identifier argument_list identifier string string_start string_content string_end identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end if_statement identifier 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 string string_start string_content string_end expression_statement call identifier argument_list identifier | Package specified SQLite files into a new datasette Docker container |
def uri(self, value):
if value == self.__uri:
return
match = URI_REGEX.match(value)
if match is None:
raise ValueError('Unable to match URI from `{}`'.format(value))
for key, value in match.groupdict().items():
setattr(self, key, value) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier for_statement pattern_list identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list block expression_statement call identifier argument_list identifier identifier identifier | Attempt to validate URI and split into individual values |
def reset(self):
self.reached_limit = False
self.count = 0
self.seen.clear() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list | Resets state and uid set. To be called asap to free memory |
def data(self):
if self.sort:
xs = sorted(self.dataset, key=self.sort_key)
elif self.shuffle:
xs = [self.dataset[i] for i in self.random_shuffler(range(len(self.dataset)))]
else:
xs = self.dataset
return xs | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier elif_clause attribute identifier identifier block expression_statement assignment identifier list_comprehension subscript attribute identifier identifier identifier for_in_clause identifier call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier return_statement identifier | Return the examples in the dataset in order, sorted, or shuffled. |
def stddev(self):
if len(self) < 2:
return float('NaN')
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqrt(bigsum / (len(arr) - 1))
except ZeroDivisionError:
return float('NaN') | module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list identifier integer block return_statement call identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier float for_statement identifier identifier block expression_statement augmented_assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier integer return_statement call identifier argument_list binary_operator identifier parenthesized_expression binary_operator call identifier argument_list identifier integer except_clause identifier block return_statement call identifier argument_list string string_start string_content string_end | Return the sample standard deviation. |
def _handle_rate_exceeded(self, response):
waiting_time = int(response.headers.get("Retry-After", 10))
time.sleep(waiting_time) | module function_definition identifier parameters 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 integer expression_statement call attribute identifier identifier argument_list identifier | Handles rate exceeded errors |
def coincidents(self):
coincident_sites = []
for i, tag in enumerate(self.site_properties['grain_label']):
if 'incident' in tag:
coincident_sites.append(self.sites[i])
return coincident_sites | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier return_statement identifier | return the a list of coincident sites. |
def validate(self):
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format(
type(self.fold_scope_location), self.fold_scope_location))
if self.fold_scope_location.field is None:
raise ValueError(u'Expected FoldScopeLocation at a field, but got: {}'
.format(self.fold_scope_location))
if self.fold_scope_location.field == COUNT_META_FIELD_NAME:
if not GraphQLInt.is_same_type(self.field_type):
raise TypeError(u'Expected the _x_count meta-field to be of GraphQLInt type, but '
u'encountered type {} instead: {}'
.format(self.field_type, self.fold_scope_location))
else:
if not isinstance(self.field_type, GraphQLList):
raise ValueError(u'Invalid value of "field_type" for a field that is not '
u'a meta-field, expected a list type but got: {} {}'
.format(self.field_type, self.fold_scope_location))
inner_type = strip_non_null_from_type(self.field_type.of_type)
if isinstance(inner_type, GraphQLList):
raise GraphQLCompilationError(
u'Outputting list-valued fields in a @fold context is currently not supported: '
u'{} {}'.format(self.fold_scope_location, self.field_type.of_type)) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier none block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier identifier block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier block raise_statement call 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 else_clause block if_statement not_operator call identifier argument_list attribute identifier identifier identifier block raise_statement call 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 expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier if_statement call identifier argument_list identifier identifier block raise_statement call 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 attribute identifier identifier identifier | Validate that the FoldedContextField is correctly representable. |
def _check_update_(self):
try:
data = requests.get("https://pypi.python.org/pypi/jira/json", timeout=2.001).json()
released_version = data['info']['version']
if parse_version(released_version) > parse_version(__version__):
warnings.warn(
"You are running an outdated version of JIRA Python %s. Current version is %s. Do not file any bugs against older versions." % (
__version__, released_version))
except requests.RequestException:
pass
except Exception as e:
logging.warning(e) | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier float identifier argument_list expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier except_clause attribute identifier identifier block pass_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier | Check if the current version of the library is outdated. |
def update(self):
response = requests.get(self.update_url, timeout=timeout)
match = ip_pattern.search(response.content)
if not match:
raise ApiError("Couldn't parse the server's response",
response.content)
self.ip = match.group(0) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer | Updates remote DNS record by requesting its special endpoint URL |
def compute_rewards(self, scores):
for i in range(len(scores)):
if i >= self.k:
scores[i] = 0.
return scores | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list call identifier argument_list identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier float return_statement identifier | Retain the K most recent scores, and replace the rest with zeros |
def use_comparative_assessment_part_view(self):
self._object_views['assessment_part'] = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_assessment_part_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement | Pass through to provider AssessmentPartLookupSession.use_comparative_assessment_part_view |
def validate_number_attribute(self,
attribute: str,
value_type: Union[Type[int], Type[float]] = int,
minimum: Optional[Union[int, float]] = None,
maximum: Optional[Union[int, float]] = None) -> None:
self.add_errors(
validate_number_attribute(self.fully_qualified_name, self._spec, attribute, value_type,
minimum, maximum)) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier identifier typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier none typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier none type none block expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier identifier identifier identifier identifier | Validates that the attribute contains a numeric value within boundaries if specified |
def _select_features(example, feature_list=None):
feature_list = feature_list or ["inputs", "targets"]
return {f: example[f] for f in feature_list} | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier list string string_start string_content string_end string string_start string_content string_end return_statement dictionary_comprehension pair identifier subscript identifier identifier for_in_clause identifier identifier | Select a subset of features from the example dict. |
def begin_transaction(self, transaction_type, trace_parent=None):
return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent) | module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier | Register the start of a transaction on the client |
def merge(self, other):
assert self.attrs == other.attrs
self.tokens.extend(other.tokens)
self.spaces.extend(other.spaces)
self.strings.update(other.strings) | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Extend the annotations of this binder with the annotations from another. |
def _get_nics(vm_):
nics = []
if 'public_lan' in vm_:
firewall_rules = []
if 'public_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['public_firewall_rules'])
nic = NIC(lan=set_public_lan(int(vm_['public_lan'])),
name='public',
firewall_rules=firewall_rules)
if 'public_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['public_ips'])
nics.append(nic)
if 'private_lan' in vm_:
firewall_rules = []
if 'private_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['private_firewall_rules'])
nic = NIC(lan=int(vm_['private_lan']),
name='private',
firewall_rules=firewall_rules)
if 'private_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['private_ips'])
if 'nat' in vm_ and 'private_ips' not in vm_:
nic.nat = vm_['nat']
nics.append(nic)
return nics | module function_definition identifier parameters identifier block expression_statement assignment identifier list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier call identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Create network interfaces on appropriate LANs as defined in cloud profile. |
def population(self):
"Class containing the population and all the individuals generated"
try:
return self._p
except AttributeError:
self._p = self._population_class(base=self,
tournament_size=self._tournament_size,
classifier=self.classifier,
labels=self._labels,
es_extra_test=self.es_extra_test,
popsize=self._popsize,
random_generations=self._random_generations,
negative_selection=self._negative_selection)
return self._p | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end try_statement block return_statement attribute identifier identifier except_clause identifier block expression_statement assignment attribute identifier identifier 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 attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier return_statement attribute identifier identifier | Class containing the population and all the individuals generated |
def mul_block(self, index, val):
self._prepare_cache_slice(index)
self.msinds[self.cache_slice] *= val | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment subscript attribute identifier identifier attribute identifier identifier identifier | Multiply values in block |
def boxed_text_to_image_block(tag):
"covert boxed-text to an image block containing an inline-graphic"
tag_block = OrderedDict()
image_content = body_block_image_content(first(raw_parser.inline_graphic(tag)))
tag_block["type"] = "image"
set_if_value(tag_block, "doi", doi_uri_to_doi(object_id_doi(tag, tag.name)))
set_if_value(tag_block, "id", tag.get("id"))
set_if_value(tag_block, "image", image_content)
p_tags = raw_parser.paragraph(tag)
caption_content = []
for p_tag in p_tags:
if not raw_parser.inline_graphic(p_tag):
caption_content.append(body_block_content(p_tag))
set_if_value(tag_block, "caption", caption_content)
return tag_block | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list identifier string string_start string_content string_end call identifier argument_list call identifier argument_list identifier attribute identifier identifier expression_statement call identifier argument_list identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call identifier argument_list identifier string string_start string_content string_end identifier return_statement identifier | covert boxed-text to an image block containing an inline-graphic |
def server_online(self):
response = self._post(self.apiurl + '/v2/server/online', data={'apikey': self.apikey})
return self._raise_or_extract(response) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier | Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode. |
def convert_lat(Recs):
New = []
for rec in Recs:
if 'model_lat' in list(rec.keys()) and rec['model_lat'] != "":
New.append(rec)
elif 'average_age' in list(rec.keys()) and rec['average_age'] != "" and float(rec['average_age']) <= 5.:
if 'site_lat' in list(rec.keys()) and rec['site_lat'] != "":
rec['model_lat'] = rec['site_lat']
New.append(rec)
elif 'average_inc' in list(rec.keys()) and rec['average_inc'] != "":
rec['model_lat'] = '%7.1f' % (plat(float(rec['average_inc'])))
New.append(rec)
return New | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list comparison_operator subscript identifier string string_start string_content string_end string string_start string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause boolean_operator boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list comparison_operator subscript identifier string string_start string_content string_end string string_start string_end comparison_operator call identifier argument_list subscript identifier string string_start string_content string_end float block if_statement boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list comparison_operator subscript identifier string string_start string_content string_end string string_start string_end block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier elif_clause boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list comparison_operator subscript identifier string string_start string_content string_end string string_start string_end block expression_statement assignment subscript identifier string string_start string_content string_end binary_operator string string_start string_content string_end parenthesized_expression call identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | uses lat, for age<5Ma, model_lat if present, else tries to use average_inc to estimate plat. |
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
formatter_func = CONTEXT_FORMATTERS[formatter]
else:
raise ValueError(f'Invalid context format: "{formatter}"')
return formatter_func(context) | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type subscript attribute identifier identifier identifier identifier string string_start string_content string_end type identifier block if_statement not_operator identifier block return_statement string string_start string_end if_statement call identifier argument_list identifier block expression_statement assignment identifier identifier else_clause block if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content interpolation identifier string_content string_end return_statement call identifier argument_list identifier | Output the a context dictionary as a string. |
def Intersect(self, mask1, mask2):
_CheckFieldMaskMessage(mask1)
_CheckFieldMaskMessage(mask2)
tree = _FieldMaskTree(mask1)
intersection = _FieldMaskTree()
for path in mask2.paths:
tree.IntersectPath(path, intersection)
intersection.ToFieldMask(self) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Intersects mask1 and mask2 into this FieldMask. |
def clear_extensions(self, group=None):
if group is None:
ComponentRegistry._registered_extensions = {}
return
if group in self._registered_extensions:
self._registered_extensions[group] = [] | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier dictionary return_statement if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier list | Clear all previously registered extensions. |
def reverse_compl_with_name(old_seq):
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement identifier | Reverse a SeqIO sequence, but keep its name intact. |
def _construct_from_json(self, rec):
self.delete()
for required_key in ['dagobah_id', 'created_jobs']:
setattr(self, required_key, rec[required_key])
for job_json in rec.get('jobs', []):
self._add_job_from_spec(job_json)
self.commit(cascade=True) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier subscript identifier identifier for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end list block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier true | Construct this Dagobah instance from a JSON document. |
def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
instance_i = param_names.index("self")
if instance_i < len(args):
instance = args[instance_i]
else:
instance = kwargs["self"]
return instance | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type ellipsis typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier subscript identifier identifier else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement identifier | Find the instance of ``self`` in the arguments. |
def _get_template_dirs(type="plugin"):
template_dirs = [
os.path.expanduser(os.path.join(USER_CONFIG_DIR, "templates", type)),
os.path.join("rapport", "templates", type)
]
return template_dirs | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier return_statement identifier | Return a list of directories where templates may be located. |
def _sumterm(lexer):
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
else:
return ('or', xorterm, sumterm_prime) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block return_statement identifier else_clause block return_statement tuple string string_start string_content string_end identifier identifier | Return a sum term expresssion. |
def CheckClientApprovalRequest(approval_request):
_CheckExpired(approval_request)
_CheckHasEnoughGrants(approval_request)
if not client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.IsActive():
return True
token = access_control.ACLToken(username=approval_request.requestor_username)
approvers = set(g.grantor_username for g in approval_request.grants)
labels = sorted(
data_store.REL_DB.ReadClientLabels(approval_request.subject_id),
key=lambda l: l.name)
for label in labels:
client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.CheckApproversForLabel(
token, rdfvalue.RDFURN(approval_request.subject_id),
approval_request.requestor_username, approvers, label.name)
return True | module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list block return_statement true expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call identifier generator_expression attribute identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier lambda lambda_parameters identifier attribute identifier identifier for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier attribute identifier identifier return_statement true | Checks if a client approval request is granted. |
def _gap_progenitor_setup(self):
self._gap_progenitor= self._progenitor().flip()
self._gap_progenitor.turn_physical_off()
ts= numpy.linspace(0.,self._tdisrupt,1001)
self._gap_progenitor.integrate(ts,self._pot)
self._gap_progenitor._orb.orbit[:,1]= -self._gap_progenitor._orb.orbit[:,1]
self._gap_progenitor._orb.orbit[:,2]= -self._gap_progenitor._orb.orbit[:,2]
self._gap_progenitor._orb.orbit[:,4]= -self._gap_progenitor._orb.orbit[:,4]
return None | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list float attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment subscript attribute attribute attribute identifier identifier identifier identifier slice integer unary_operator subscript attribute attribute attribute identifier identifier identifier identifier slice integer expression_statement assignment subscript attribute attribute attribute identifier identifier identifier identifier slice integer unary_operator subscript attribute attribute attribute identifier identifier identifier identifier slice integer expression_statement assignment subscript attribute attribute attribute identifier identifier identifier identifier slice integer unary_operator subscript attribute attribute attribute identifier identifier identifier identifier slice integer return_statement none | Setup an Orbit instance that's the progenitor integrated backwards |
def _create_row_col_indices(ratings_df):
user_id_to_user_idx = _create_index(ratings_df, "userId")
item_id_to_item_idx = _create_index(ratings_df, "movieId")
ratings_df["row"] = ratings_df["userId"].apply(
lambda x: user_id_to_user_idx[x])
ratings_df["col"] = ratings_df["movieId"].apply(
lambda x: item_id_to_item_idx[x])
return ratings_df | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute subscript identifier string string_start string_content string_end identifier argument_list lambda lambda_parameters identifier subscript identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute subscript identifier string string_start string_content string_end identifier argument_list lambda lambda_parameters identifier subscript identifier identifier return_statement identifier | Maps user and items ids to their locations in the rating matrix. |
def outlierDetection_threaded(samples_x, samples_y_aggregation):
outliers = []
threads_inputs = [[samples_idx, samples_x, samples_y_aggregation]\
for samples_idx in range(0, len(samples_x))]
threads_pool = ThreadPool(min(4, len(threads_inputs)))
threads_results = threads_pool.map(_outlierDetection_threaded, threads_inputs)
threads_pool.close()
threads_pool.join()
for threads_result in threads_results:
if threads_result is not None:
outliers.append(threads_result)
else:
print("error here.")
outliers = None if len(outliers) == 0 else outliers
return outliers | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier list_comprehension list identifier identifier identifier line_continuation for_in_clause identifier call identifier argument_list integer call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list integer call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list for_statement identifier identifier block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier conditional_expression none comparison_operator call identifier argument_list identifier integer identifier return_statement identifier | Use Multi-thread to detect the outlier |
def _with_env(self, env):
res = self._browse(env, self._ids)
return res | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier return_statement identifier | As the `with_env` class method but for recordset. |
def _get_db_connect(dbSystem,db,user,password):
if dbSystem=='SYBASE':
import Sybase
try:
dbh = Sybase.connect(dbSystem,
user,
password,
database=db )
except:
dbh=None
elif dbSystem=='MYSQL':
import MySQLdb
try:
dbh = MySQLdb.connect(user=user,
passwd=password,
db=db ,
host='gimli')
except:
dbh=None
return dbh | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block import_statement dotted_name identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier identifier except_clause block expression_statement assignment identifier none elif_clause comparison_operator identifier string string_start string_content string_end block import_statement dotted_name identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end except_clause block expression_statement assignment identifier none return_statement identifier | Create a connection to the database specified on the command line |
def create(client, _type, **kwargs):
obj = client.factory.create("ns0:%s" % _type)
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list identifier identifier identifier return_statement identifier | Create a suds object of the requested _type. |
def list_mypasswords_search(self, searchstring):
log.debug('List MyPasswords with %s' % searchstring)
return self.collection('my_passwords/search/%s.json' %
quote_plus(searchstring)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier | List my passwords with searchstring. |
def _safe_readinto(self, b):
total_bytes = 0
mvb = memoryview(b)
while total_bytes < len(b):
if MAXAMOUNT < len(mvb):
temp_mvb = mvb[0:MAXAMOUNT]
n = self.fp.readinto(temp_mvb)
else:
n = self.fp.readinto(mvb)
if not n:
raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b))
mvb = mvb[n:]
total_bytes += n
return total_bytes | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list identifier while_statement comparison_operator identifier call identifier argument_list identifier block if_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier subscript identifier slice integer identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list call identifier argument_list subscript identifier slice integer identifier call identifier argument_list identifier expression_statement assignment identifier subscript identifier slice identifier expression_statement augmented_assignment identifier identifier return_statement identifier | Same as _safe_read, but for reading into a buffer. |
def main(handwriting_datasets_file, analyze_features):
logging.info("Start loading data '%s' ...", handwriting_datasets_file)
loaded = pickle.load(open(handwriting_datasets_file))
raw_datasets = loaded['handwriting_datasets']
logging.info("%i datasets loaded.", len(raw_datasets))
logging.info("Start analyzing...")
if analyze_features:
featurelist = [(features.AspectRatio(), "aspect_ratio.csv"),
(features.ReCurvature(1), "re_curvature.csv"),
(features.Height(), "height.csv"),
(features.Width(), "width.csv"),
(features.Time(), "time.csv"),
(features.Ink(), "ink.csv"),
(features.StrokeCount(), "stroke-count.csv")]
for feat, filename in featurelist:
logging.info("create %s...", filename)
analyze_feature(raw_datasets, feat, filename)
cfg = utils.get_project_configuration()
if 'data_analyzation_queue' in cfg:
metrics = dam.get_metrics(cfg['data_analyzation_queue'])
for metric in metrics:
logging.info("Start metric %s...", str(metric))
metric(raw_datasets)
else:
logging.info("No 'data_analyzation_queue' in ~/.hwrtrc") | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment identifier list tuple call attribute identifier identifier argument_list string string_start string_content string_end tuple call attribute identifier identifier argument_list integer string string_start string_content string_end tuple call attribute identifier identifier argument_list string string_start string_content string_end tuple call attribute identifier identifier argument_list string string_start string_content string_end tuple call attribute identifier identifier argument_list string string_start string_content string_end tuple call attribute identifier identifier argument_list string string_start string_content string_end tuple call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Start the creation of the wanted metric. |
def eval_str_to_list(input_str: str) -> List[str]:
inner_cast = ast.literal_eval(input_str)
if isinstance(inner_cast, list):
return inner_cast
else:
raise ValueError | module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block return_statement identifier else_clause block raise_statement identifier | Turn str into str or tuple. |
def _convert_and_assert_per_example_weights_compatible(
input_, per_example_weights, dtype):
per_example_weights = tf.convert_to_tensor(
per_example_weights, name='per_example_weights', dtype=dtype)
if input_.get_shape().ndims:
expected_length = input_.get_shape().dims[0]
message = ('per_example_weights must have rank 1 and length %s, but was: %s'
% (expected_length, per_example_weights.get_shape()))
else:
expected_length = None
message = ('per_example_weights must have rank 1 and length equal to the '
'first dimension of inputs (unknown), but was: %s'
% per_example_weights.get_shape())
if per_example_weights.get_shape().ndims not in (1, None):
raise ValueError(message)
if not per_example_weights.get_shape().is_compatible_with((expected_length,)):
raise ValueError(message)
return per_example_weights | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier if_statement attribute call attribute identifier identifier argument_list identifier block expression_statement assignment identifier subscript attribute call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier parenthesized_expression binary_operator string string_start string_content string_end tuple identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier none expression_statement assignment identifier parenthesized_expression binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list if_statement comparison_operator attribute call attribute identifier identifier argument_list identifier tuple integer none block raise_statement call identifier argument_list identifier if_statement not_operator call attribute call attribute identifier identifier argument_list identifier argument_list tuple identifier block raise_statement call identifier argument_list identifier return_statement identifier | Converts per_example_weights to a tensor and validates the shape. |
def all_active(cls):
prefix = context.get_current_config()["redis_prefix"]
queues = []
for key in context.connections.redis.keys():
if key.startswith(prefix):
queues.append(Queue(key[len(prefix) + 3:]))
return queues | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list subscript identifier slice binary_operator call identifier argument_list identifier integer return_statement identifier | List active queues, based on their lengths in Redis. Warning, uses the unscalable KEYS redis command |
def _dump(file_obj, options, out=sys.stdout):
total_count = 0
writer = None
keys = None
for row in DictReader(file_obj, options.col):
if not keys:
keys = row.keys()
if not writer:
writer = csv.DictWriter(out, keys, delimiter=u'\t', quotechar=u'\'', quoting=csv.QUOTE_MINIMAL) \
if options.format == 'csv' \
else JsonWriter(out) if options.format == 'json' \
else None
if total_count == 0 and options.format == "csv" and not options.no_headers:
writer.writeheader()
if options.limit != -1 and total_count >= options.limit:
return
row_unicode = {k: v.decode("utf-8") if isinstance(v, bytes) else v for k, v in row.items()}
writer.writerow(row_unicode)
total_count += 1 | module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier none expression_statement assignment identifier none for_statement identifier call identifier argument_list identifier attribute identifier identifier block if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content escape_sequence string_end keyword_argument identifier string string_start string_content escape_sequence string_end keyword_argument identifier attribute identifier identifier line_continuation comparison_operator attribute identifier identifier string string_start string_content string_end line_continuation conditional_expression call identifier argument_list identifier comparison_operator attribute identifier identifier string string_start string_content string_end line_continuation none if_statement boolean_operator boolean_operator comparison_operator identifier integer comparison_operator attribute identifier identifier string string_start string_content string_end not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator attribute identifier identifier unary_operator integer comparison_operator identifier attribute identifier identifier block return_statement expression_statement assignment identifier dictionary_comprehension pair identifier conditional_expression call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier integer | Dump to fo with given options. |
def app_size(self):
"Return the total apparent size, including children."
if self._nodes is None:
return self._app_size
return sum(i.app_size() for i in self._nodes) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block return_statement attribute identifier identifier return_statement call identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier attribute identifier identifier | Return the total apparent size, including children. |
def _hashes_match(self, a, b):
if len(a) != len(b):
return False
diff = 0
if six.PY2:
a = bytearray(a)
b = bytearray(b)
for x, y in zip(a, b):
diff |= x ^ y
return not diff | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block return_statement false expression_statement assignment identifier integer if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement augmented_assignment identifier binary_operator identifier identifier return_statement not_operator identifier | Constant time comparison of bytes for py3, strings for py2 |
def _column_resized(self, col, old_width, new_width):
self.dataTable.setColumnWidth(col, new_width)
self._update_layout() | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list | Update the column width. |
def _build_response(self, resp):
self.response.content = resp.content
self.response.status_code = resp.status_code
self.response.headers = resp.headers | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier | Build internal Response object from given response. |
def generate_security_hash(self, content_type, object_pk, timestamp):
info = (content_type, object_pk, timestamp)
key_salt = "django.contrib.forms.CommentSecurityForm"
value = "-".join(info)
return salted_hmac(key_salt, value).hexdigest() | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier tuple identifier identifier identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list | Generate a HMAC security hash from the provided info. |
def auto_scroll(self, thumbkey):
if not self.gui_up:
return
scrollp = self.w.auto_scroll.get_state()
if not scrollp:
return
bnch = self.thumb_dict[thumbkey]
pan_x, pan_y = self.c_view.get_pan()
self.c_view.panset_xy(pan_x, bnch.image.y) | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list if_statement not_operator identifier block return_statement expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier | Scroll the window to the thumb. |
def mx_page_trees(self, mx_page):
resp = dict()
for tree_name, tree in self.scheduler.timetable.trees.items():
if tree.mx_page == mx_page:
rest_tree = self._get_tree_details(tree_name)
resp[tree.tree_name] = rest_tree.document
return resp | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier attribute identifier identifier attribute identifier identifier return_statement identifier | return trees assigned to given MX Page |
def get(cls, parent, name):
return cls.query.filter_by(parent=parent, name=name).one_or_none() | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier identifier argument_list | Get an instance matching the parent and name |
def path_helper(self, operations, view, app=None, **kwargs):
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(view.view_class, MethodView):
for method in view.methods:
if method in rule.methods:
method_name = method.lower()
method = getattr(view.view_class, method_name)
operations[method_name] = yaml_utils.load_yaml_from_docstring(method.__doc__)
return self.flaskpath2openapi(rule.rule) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier | Path helper that allows passing a Flask view function. |
def create_tipo_rede(self):
return TipoRede(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Get an instance of tipo_rede services facade. |
def limiter(arr):
dyn_range = 32767.0 / 32767.0
lim_thresh = 30000.0 / 32767.0
lim_range = dyn_range - lim_thresh
new_arr = arr.copy()
inds = N.where(arr > lim_thresh)[0]
new_arr[inds] = (new_arr[inds] - lim_thresh) / lim_range
new_arr[inds] = (N.arctan(new_arr[inds]) * 2.0 / N.pi) *\
lim_range + lim_thresh
inds = N.where(arr < -lim_thresh)[0]
new_arr[inds] = -(new_arr[inds] + lim_thresh) / lim_range
new_arr[inds] = -(
N.arctan(new_arr[inds]) * 2.0 / N.pi * lim_range + lim_thresh)
return new_arr | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator float float expression_statement assignment identifier binary_operator float float expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript call attribute identifier identifier argument_list comparison_operator identifier identifier integer expression_statement assignment subscript identifier identifier binary_operator parenthesized_expression binary_operator subscript identifier identifier identifier identifier expression_statement assignment subscript identifier identifier binary_operator binary_operator parenthesized_expression binary_operator binary_operator call attribute identifier identifier argument_list subscript identifier identifier float attribute identifier identifier line_continuation identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list comparison_operator identifier unary_operator identifier integer expression_statement assignment subscript identifier identifier binary_operator unary_operator parenthesized_expression binary_operator subscript identifier identifier identifier identifier expression_statement assignment subscript identifier identifier unary_operator parenthesized_expression binary_operator binary_operator binary_operator binary_operator call attribute identifier identifier argument_list subscript identifier identifier float attribute identifier identifier identifier identifier return_statement identifier | Restrict the maximum and minimum values of arr |
def add_check(self, check_item):
self.checks.append(check_item)
for other in self.others:
other.add_check(check_item) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Adds a check universally. |
def _get_firefox_start_cmd(self):
start_cmd = ""
if platform.system() == "Darwin":
start_cmd = "/Applications/Firefox.app/Contents/MacOS/firefox-bin"
if not os.path.exists(start_cmd):
start_cmd = os.path.expanduser("~") + start_cmd
elif platform.system() == "Windows":
start_cmd = (self._find_exe_in_registry() or self._default_windows_location())
elif platform.system() == 'Java' and os._name == 'nt':
start_cmd = self._default_windows_location()
else:
for ffname in ["firefox", "iceweasel"]:
start_cmd = self.which(ffname)
if start_cmd is not None:
break
else:
raise RuntimeError(
"Could not find firefox in your system PATH." +
" Please specify the firefox binary location or install firefox")
return start_cmd | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier elif_clause comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier parenthesized_expression boolean_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list elif_clause boolean_operator comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block for_statement identifier list 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 if_statement comparison_operator identifier none block break_statement else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end return_statement identifier | Return the command to start firefox. |
def backward_step(self):
logger.debug("Executing backward step ...")
self.run_to_states = []
self.set_execution_mode(StateMachineExecutionStatus.BACKWARD) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier list expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Take a backward step for all active states in the state machine |
def create_session(self, ticket, payload=None, expires=None):
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
logging.debug('[CAS] Creating session for ticket {}'.format(ticket))
self.session_storage_adapter.create(
ticket,
payload=payload,
expires=expires,
) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block assert_statement call identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | Create a session record from a service ticket. |
def _ProcessSources(self, sources, parser_factory):
for source in sources:
for action, request in self._ParseSourceType(source):
yield self._RunClientAction(action, request, parser_factory,
source.path_type) | module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block expression_statement yield call attribute identifier identifier argument_list identifier identifier identifier attribute identifier identifier | Iterates through sources yielding action responses. |
def read_utf8(fh, byteorder, dtype, count, offsetsize):
return fh.read(count).decode('utf-8') | module function_definition identifier parameters identifier identifier identifier identifier identifier block return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end | Read tag data from file and return as unicode string. |
def _set_req_to_reinstall(self, req):
if not self.use_user_site or dist_in_usersite(req.satisfied_by):
req.conflicts_with = req.satisfied_by
req.satisfied_by = None | module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator attribute identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier none | Set a requirement to be installed. |
def patched(attrs, updates):
orig = patch(attrs, updates.items())
try:
yield orig
finally:
patch(attrs, orig.items()) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list try_statement block expression_statement yield identifier finally_clause block expression_statement call identifier argument_list identifier call attribute identifier identifier argument_list | A context in which some attributes temporarily have a modified value. |
def cdfout(data, file):
f = open(file, "w")
data.sort()
for j in range(len(data)):
y = old_div(float(j), float(len(data)))
out = str(data[j]) + ' ' + str(y) + '\n'
f.write(out)
f.close() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator binary_operator call identifier argument_list subscript identifier identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | spits out the cdf for data to file |
def _are_nearby_parallel_boxes(self, b1, b2):
"Are two boxes nearby, parallel, and similar in width?"
if not self._are_aligned_angles(b1.angle, b2.angle):
return False
angle = min(b1.angle, b2.angle)
return abs(np.dot(b1.center - b2.center, [-np.sin(angle), np.cos(angle)])) < self.lineskip_tol * (
b1.height + b2.height) and (b1.width > 0) and (b2.width > 0) and (0.5 < b1.width / b2.width < 2.0) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier block return_statement false expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier return_statement boolean_operator boolean_operator boolean_operator comparison_operator call identifier argument_list call attribute identifier identifier argument_list binary_operator attribute identifier identifier attribute identifier identifier list unary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier parenthesized_expression comparison_operator attribute identifier identifier integer parenthesized_expression comparison_operator attribute identifier identifier integer parenthesized_expression comparison_operator float binary_operator attribute identifier identifier attribute identifier identifier float | Are two boxes nearby, parallel, and similar in width? |
def ensure_a_list(data):
if not data:
return []
if isinstance(data, (list, tuple, set)):
return list(data)
if isinstance(data, str):
data = trimmed_split(data)
return data
return [data] | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement list if_statement call identifier argument_list identifier tuple identifier identifier identifier block return_statement call identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier return_statement list identifier | Ensure data is a list or wrap it in a list |
def save_csv(self):
self.results.sort_values(by=self.column_ids, inplace=True)
self.results.reindex(columns=self.column_ids).to_csv(
self.csv_filepath, index=False) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier true expression_statement call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier false | Dump all results to CSV. |
def cli(ctx, env):
env.out("Welcome to the SoftLayer shell.")
env.out("")
formatter = formatting.HelpFormatter()
commands = []
shell_commands = []
for name in cli_core.cli.list_commands(ctx):
command = cli_core.cli.get_command(ctx, name)
if command.short_help is None:
command.short_help = command.help
details = (name, command.short_help)
if name in dict(routes.ALL_ROUTES):
shell_commands.append(details)
else:
commands.append(details)
with formatter.section('Shell Commands'):
formatter.write_dl(shell_commands)
with formatter.section('Commands'):
formatter.write_dl(commands)
for line in formatter.buffer:
env.out(line, newline=False) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment identifier tuple identifier attribute identifier identifier if_statement comparison_operator identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false | Print shell help text. |
def adjust(color, attribute, percent):
r, g, b, a, type = parse_color(color)
r, g, b = hsl_to_rgb(*_adjust(rgb_to_hsl(r, g, b), attribute, percent))
return unparse_color(r, g, b, a, type) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list list_splat call identifier argument_list call identifier argument_list identifier identifier identifier identifier identifier return_statement call identifier argument_list identifier identifier identifier identifier identifier | Adjust an attribute of color by a percent |
def _logprior(self):
logj = self.logjacobian
logp = self.prior_distribution(**self.current_params) + logj
if numpy.isnan(logp):
logp = -numpy.inf
return logp | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list dictionary_splat attribute identifier identifier identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier unary_operator attribute identifier identifier return_statement identifier | Calculates the log prior at the current parameters. |
def __BitList_to_String(self, data):
result = []
pos = 0
c = 0
while pos < len(data):
c += data[pos] << (7 - (pos % 8))
if (pos % 8) == 7:
result.append(c)
c = 0
pos += 1
if _pythonMajorVersion < 3:
return ''.join([ chr(c) for c in result ])
else:
return bytes(result) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier integer expression_statement assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block expression_statement augmented_assignment identifier binary_operator subscript identifier identifier parenthesized_expression binary_operator integer parenthesized_expression binary_operator identifier integer if_statement comparison_operator parenthesized_expression binary_operator identifier integer integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier integer expression_statement augmented_assignment identifier integer if_statement comparison_operator identifier integer block return_statement call attribute string string_start string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier else_clause block return_statement call identifier argument_list identifier | Turn the list of bits -> data, into a string |
def _refresh_and_update(self):
if not self._operation.done:
self._operation = self._refresh()
self._set_result_from_operation() | module function_definition identifier parameters identifier block if_statement not_operator attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Refresh the operation and update the result if needed. |
def _lint(self):
command = self._get_command()
process = subprocess.run(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
LOG.info('Finished %s', ' '.join(command))
stdout, stderr = self._get_output_lines(process)
return self._linter.parse(stdout), self._parse_stderr(stderr) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement expression_list call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier | Run linter in a subprocess. |
def _write_docs(module_list, output_dir):
for module_meta in module_list:
directory = module_meta['directory']
if directory and not path.isdir(directory):
makedirs(directory)
file = open(module_meta['output'], 'w')
file.write(module_meta['content'])
file.close() | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement boolean_operator identifier not_operator call attribute identifier identifier argument_list identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list | Write the document meta to our output location. |
def lsmod(self):
lines = shell_out("lsmod", timeout=0).splitlines()
return [line.split()[0].strip() for line in lines] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list string string_start string_content string_end keyword_argument identifier integer identifier argument_list return_statement list_comprehension call attribute subscript call attribute identifier identifier argument_list integer identifier argument_list for_in_clause identifier identifier | Return a list of kernel module names as strings. |
def rlmb_tiny_sv2p():
hparams = rlmb_ppo_tiny()
hparams.generative_model = "next_frame_sv2p"
hparams.generative_model_params = "next_frame_sv2p_tiny"
hparams.grayscale = False
return hparams | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier false return_statement identifier | Tiny setting with a tiny sv2p model. |
def ping():
try:
response = salt.utils.http.query(
"{0}/ping".format(CONFIG[CONFIG_BASE_URL]),
decode_type='plain',
decode=True,
)
log.debug(
'marathon.info returned successfully: %s',
response,
)
if 'text' in response and response['text'].strip() == 'pong':
return True
except Exception as ex:
log.error(
'error calling marathon.info with base_url %s: %s',
CONFIG[CONFIG_BASE_URL],
ex,
)
return False | module function_definition identifier parameters block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end block return_statement true except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier identifier identifier return_statement false | Is the marathon api responding? |
def _rlmb_tiny_overrides():
return dict(
epochs=1,
num_real_env_frames=128,
model_train_steps=2,
max_num_noops=1,
eval_max_num_noops=1,
generative_model_params="next_frame_tiny",
stop_loop_early=True,
resize_height_factor=2,
resize_width_factor=2,
wm_eval_rollout_ratios=[1],
rl_env_max_episode_steps=7,
eval_rl_env_max_episode_steps=7,
simulated_rollout_length=2,
eval_sampling_temps=[0.0, 1.0],
) | module function_definition identifier parameters block return_statement call identifier argument_list keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier string string_start string_content string_end keyword_argument identifier true keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier list integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier list float float | Parameters to override for tiny setting excluding agent-related hparams. |
def tickets(self, extra_params=None):
tickets = []
for space in self.api.spaces():
tickets += filter(
lambda ticket: ticket.get('assigned_to_id', None) == self['id'],
space.tickets(extra_params=extra_params)
)
return tickets | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement augmented_assignment identifier call identifier argument_list lambda lambda_parameters identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement identifier | A User's tickets across all available spaces |
def _assemble_influence(stmt):
subj_str = _assemble_agent_str(stmt.subj.concept)
obj_str = _assemble_agent_str(stmt.obj.concept)
if stmt.subj.delta['polarity'] is not None:
subj_delta_str = ' decrease' if stmt.subj.delta['polarity'] == -1 \
else 'n increase'
subj_str = 'a%s in %s' % (subj_delta_str, subj_str)
if stmt.obj.delta['polarity'] is not None:
obj_delta_str = ' decrease' if stmt.obj.delta['polarity'] == -1 \
else 'n increase'
obj_str = 'a%s in %s' % (obj_delta_str, obj_str)
stmt_str = '%s causes %s' % (subj_str, obj_str)
return _make_sentence(stmt_str) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier if_statement comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end none block expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end unary_operator integer line_continuation string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier if_statement comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end none block expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end unary_operator integer line_continuation string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier return_statement call identifier argument_list identifier | Assemble an Influence statement into text. |
def built_datetime(self):
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.build_done)
except TypeError:
return None | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier try_statement block return_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier except_clause identifier block return_statement none | Return the built time as a datetime object |
def db_insert(self):
assert self.has_db
coll = self.manager.db_connector.get_collection()
print("Mongodb collection %s with count %d", coll, coll.count())
start = time.time()
for work in self:
for task in work:
results = task.get_results()
pprint(results)
results.update_collection(coll)
results = work.get_results()
pprint(results)
results.update_collection(coll)
print("MongoDb update done in %s [s]" % time.time() - start)
results = self.get_results()
pprint(results)
results.update_collection(coll)
self.pickle_dump()
for d in coll.find():
pprint(d) | module function_definition identifier parameters identifier block assert_statement attribute identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list binary_operator binary_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list identifier | Insert results in the `MongDB` database. |
def whowas(self, nick, max="", server=""):
self.send_items('WHOWAS', nick, max, server) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier | Send a WHOWAS command. |
def record_is_valid(record):
"Checks if a record is valid for processing."
if record.CHROM.startswith('GL'):
return False
if 'DP' in record.INFO and record.INFO['DP'] < 5:
return False
return True | module function_definition identifier parameters identifier block expression_statement 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 return_statement false if_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier comparison_operator subscript attribute identifier identifier string string_start string_content string_end integer block return_statement false return_statement true | Checks if a record is valid for processing. |
def append_onto_file(self, file_name, msg):
with open(file_name, "a") as heart_file:
heart_file.write(msg)
heart_file.close() | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Appends msg onto the Given File |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.