code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def transformArray(data, keysToSplit=[]):
transformed = [ ]
for item in data:
transformed.append(transform(item, keysToSplit))
return transformed | module function_definition identifier parameters identifier default_parameter identifier list block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier return_statement identifier | Transform a SPARQL json array based on the rules of transform |
def translate_state(self, s):
if not isinstance(s, basestring):
return s
s = s.capitalize().replace("_", " ")
return t(_(s)) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_content string_end return_statement call identifier argument_list call identifier argument_list identifier | Translate the given state string |
def connect_client_to_kernel(self, client, is_cython=False,
is_pylab=False, is_sympy=False):
connection_file = client.connection_file
stderr_handle = None if self.test_no_stderr else client.stderr_handle
km, kc = self.create_kernel_manager_and_kernel_client(
connection_file,
stderr_handle,
is_cython=is_cython,
is_pylab=is_pylab,
is_sympy=is_sympy)
if is_string(km) and kc is None:
client.shellwidget.kernel_manager = None
client.show_kernel_error(km)
return
if not self.testing:
kc.started_channels.connect(
lambda c=client: self.process_started(c))
kc.stopped_channels.connect(
lambda c=client: self.process_finished(c))
kc.start_channels(shell=True, iopub=True)
shellwidget = client.shellwidget
shellwidget.kernel_manager = km
shellwidget.kernel_client = kc | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier conditional_expression none attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement boolean_operator call identifier argument_list identifier comparison_operator identifier none block expression_statement assignment attribute attribute identifier identifier identifier none expression_statement call attribute identifier identifier argument_list identifier return_statement if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list lambda lambda_parameters default_parameter identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list lambda lambda_parameters default_parameter identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier true keyword_argument identifier true expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier | Connect a client to its kernel |
def update_org_owner(cls, module):
try:
cls.module_registry[module]["OrgOwnerModel"]._meta.get_field(
"organization_user"
)
except FieldDoesNotExist:
cls.module_registry[module]["OrgOwnerModel"].add_to_class(
"organization_user",
models.OneToOneField(
cls.module_registry[module]["OrgUserModel"],
on_delete=models.CASCADE,
),
)
try:
cls.module_registry[module]["OrgOwnerModel"]._meta.get_field("organization")
except FieldDoesNotExist:
cls.module_registry[module]["OrgOwnerModel"].add_to_class(
"organization",
models.OneToOneField(
cls.module_registry[module]["OrgModel"],
related_name="owner",
on_delete=models.CASCADE,
),
) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list subscript subscript attribute identifier identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier try_statement block expression_statement call attribute attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list subscript subscript attribute identifier identifier identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier | Creates the links to the organization and organization user for the owner. |
def _wire_events(self):
self._device.on_open += self._on_open
self._device.on_close += self._on_close
self._device.on_read += self._on_read
self._device.on_write += self._on_write
self._zonetracker.on_fault += self._on_zone_fault
self._zonetracker.on_restore += self._on_zone_restore | module function_definition identifier parameters identifier block expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute attribute identifier identifier identifier attribute identifier identifier | Wires up the internal device events. |
def tracker_class(clsname):
stats = server.stats
if not stats:
bottle.redirect('/tracker')
stats.annotate()
return dict(stats=stats, clsname=clsname) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement not_operator 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 return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Get class instance details. |
def _normalize_stack(graphobjs):
for operands, operator in graphobjs:
operator = str(operator)
if re.match(r'Q*q+$', operator):
for char in operator:
yield ([], char)
else:
yield (operands, operator) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier block for_statement identifier identifier block expression_statement yield tuple list identifier else_clause block expression_statement yield tuple identifier identifier | Convert runs of qQ's in the stack into single graphobjs |
def convert_to_duckling_language_id(cls, lang):
if lang is not None and cls.is_supported(lang):
return lang
elif lang is not None and cls.is_supported(lang + "$core"):
return lang + "$core"
else:
raise ValueError("Unsupported language '{}'. Supported languages: {}".format(
lang, ", ".join(cls.SUPPORTED_LANGUAGES))) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list identifier block return_statement identifier elif_clause boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end block return_statement binary_operator identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | Ensure a language identifier has the correct duckling format and is supported. |
def join_images(img_files, out_file):
images = [PIL.Image.open(f) for f in img_files]
joined = PIL.Image.new(
'RGB',
(sum(i.size[0] for i in images), max(i.size[1] for i in images))
)
left = 0
for img in images:
joined.paste(im=img, box=(left, 0))
left = left + img.size[0]
joined.save(out_file) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end tuple call identifier generator_expression subscript attribute identifier identifier integer for_in_clause identifier identifier call identifier generator_expression subscript attribute identifier identifier integer for_in_clause identifier identifier expression_statement assignment identifier integer for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier tuple identifier integer expression_statement assignment identifier binary_operator identifier subscript attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list identifier | Join the list of images into the out file |
def image_by_id(self, id):
if not id:
return None
return next((image for image in self.images() if image['Id'] == id),
None) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement none return_statement call identifier argument_list generator_expression identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator subscript identifier string string_start string_content string_end identifier none | Return image with given Id |
def cached(function):
cache_variable = '_cached_' + function.__name__
@wraps(function)
def function_wrapper(obj, *args, **kwargs):
try:
cache = getattr(obj, cache_variable)
except AttributeError:
cache = {}
setattr(obj, cache_variable, cache)
args_kwargs = args + tuple(kwargs.values())
try:
return cache[args_kwargs]
except KeyError:
cache_value = function(obj, *args, **kwargs)
cache[args_kwargs] = cache_value
return cache_value
return function_wrapper | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier except_clause identifier block expression_statement assignment identifier dictionary expression_statement call identifier argument_list identifier identifier identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list call attribute identifier identifier argument_list try_statement block return_statement subscript identifier identifier except_clause identifier block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier return_statement identifier | Method decorator caching a method's returned values. |
def symmetry_cycles(self):
result = set([])
for symmetry in self.symmetries:
result.add(symmetry.cycles)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | The cycle representations of the graph symmetries |
def confirm_user(query):
user = _query_to_user(query)
if click.confirm(f'Are you sure you want to confirm {user!r}?'):
if security_service.confirm_user(user):
click.echo(f'Successfully confirmed {user!r} at '
f'{user.confirmed_at.strftime("%Y-%m-%d %H:%M:%S%z")}')
user_manager.save(user, commit=True)
else:
click.echo(f'{user!r} has already been confirmed.')
else:
click.echo('Cancelled.') | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content interpolation identifier type_conversion string_content string_end block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content interpolation identifier type_conversion string_content string_end string string_start interpolation call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string_end expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true else_clause block expression_statement call attribute identifier identifier argument_list string string_start interpolation identifier type_conversion string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Confirm a user account. |
def follow_model(self, model):
if model:
self.models_by_name[model.__name__.lower()] = model
signals.post_save.connect(create_or_update, sender=model)
signals.post_delete.connect(self.remove_orphans, sender=model) | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment subscript attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier | Follow a particular model class, updating associated Activity objects automatically. |
def __set_premature_stop_codon_status(self, hgvs_string):
if re.search('.+\*(\d+)?$', hgvs_string):
self.is_premature_stop_codon = True
self.is_non_silent = True
if hgvs_string.endswith('*'):
self.is_nonsense_mutation = True
else:
self.is_nonsense_mutation = False
else:
self.is_premature_stop_codon = False
self.is_nonsense_mutation = False | module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier true if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment attribute identifier identifier true else_clause block expression_statement assignment attribute identifier identifier false else_clause block expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false | Set whether there is a premature stop codon. |
def median(self):
mu = self.mean()
ret_val = math.exp(mu)
if math.isnan(ret_val):
ret_val = float("inf")
return ret_val | 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 if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end return_statement identifier | Computes the median of a log-normal distribution built with the stats data. |
def _normalize_path(self, path):
if type(path) is str:
path = path.encode()
path = path.split(b'\0')[0]
if path[0:1] != self.pathsep:
path = self.cwd + self.pathsep + path
keys = path.split(self.pathsep)
i = 0
while i < len(keys):
if keys[i] == b'':
keys.pop(i)
elif keys[i] == b'.':
keys.pop(i)
elif keys[i] == b'..':
keys.pop(i)
if i != 0:
keys.pop(i-1)
i -= 1
else:
i += 1
return keys | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end integer if_statement comparison_operator subscript identifier slice integer integer attribute identifier identifier block expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block if_statement comparison_operator subscript identifier identifier string string_start string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator subscript identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator subscript identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list binary_operator identifier integer expression_statement augmented_assignment identifier integer else_clause block expression_statement augmented_assignment identifier integer return_statement identifier | Takes a path and returns a simple absolute path as a list of directories from the root |
def _createIndexRti(self, index, nodeName):
return PandasIndexRti(index=index, nodeName=nodeName, fileName=self.fileName,
iconColor=self._iconColor) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Auxiliary method that creates a PandasIndexRti. |
def cookies(self):
return (self.get_query()
.select(PageView.ip, PageView.headers['Cookie'])
.where(PageView.headers['Cookie'].is_null(False))
.tuples()) | module function_definition identifier parameters identifier block return_statement parenthesized_expression call attribute call attribute call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end identifier argument_list call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list false identifier argument_list | Retrieve the cookies header from all the users who visited. |
def removeReadGroupSet(self):
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
readGroupSet = dataset.getReadGroupSetByName(
self._args.readGroupSetName)
def func():
self._updateRepo(self._repo.removeReadGroupSet, readGroupSet)
self._confirmDelete("ReadGroupSet", readGroupSet.getLocalId(), func) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier | Removes a readGroupSet from the repo. |
def ensureFulltextIndex(self, fields, minLength = None) :
data = {
"type" : "fulltext",
"fields" : fields,
}
if minLength is not None :
data["minLength"] = minLength
ind = Index(self, creationData = data)
self.indexes["fulltext"][ind.infos["id"]] = ind
return ind | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end identifier return_statement identifier | Creates a fulltext index if it does not already exist, and returns it |
def generate_folder_names(name, project):
out_data_dir = prms.Paths.outdatadir
project_dir = os.path.join(out_data_dir, project)
batch_dir = os.path.join(project_dir, name)
raw_dir = os.path.join(batch_dir, "raw_data")
return out_data_dir, project_dir, batch_dir, raw_dir | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end return_statement expression_list identifier identifier identifier identifier | Creates sensible folder names. |
def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs):
if grouper is None:
self._set_binner()
grouper = self.grouper
obj = self._selected_obj
grouped = groupby(obj, by=None, grouper=grouper, axis=self.axis)
try:
if isinstance(obj, ABCDataFrame) and callable(how):
result = grouped._aggregate_item_by_item(how, *args, **kwargs)
else:
result = grouped.aggregate(how, *args, **kwargs)
except Exception:
result = grouped.apply(how, *args, **kwargs)
result = self._apply_loffset(result)
return self._wrap_result(result) | module function_definition identifier parameters identifier identifier default_parameter identifier none list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier try_statement block if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Re-evaluate the obj with a groupby aggregation. |
def save_sensors(self):
if not self.need_save:
return
fname = os.path.realpath(self.persistence_file)
exists = os.path.isfile(fname)
dirname = os.path.dirname(fname)
if (not os.access(dirname, os.W_OK) or exists and
not os.access(fname, os.W_OK)):
_LOGGER.error('Permission denied when writing to %s', fname)
return
split_fname = os.path.splitext(fname)
tmp_fname = '{}.tmp{}'.format(split_fname[0], split_fname[1])
_LOGGER.debug('Saving sensors to persistence file %s', fname)
self._perform_file_action(tmp_fname, 'save')
if exists:
os.rename(fname, self.persistence_bak)
os.rename(tmp_fname, fname)
if exists:
os.remove(self.persistence_bak)
self.need_save = False | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement parenthesized_expression boolean_operator not_operator call attribute identifier identifier argument_list identifier attribute identifier identifier boolean_operator identifier not_operator call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list subscript identifier integer subscript identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier false | Save sensors to file. |
def post(self, id):
model = self.model.objects.only('id').get_or_404(id=id)
follow, created = Follow.objects.get_or_create(
follower=current_user.id, following=model, until=None)
count = Follow.objects.followers(model).count()
if not current_app.config['TESTING']:
tracking.send_signal(on_new_follow, request, current_user)
return {'followers': count}, 201 if created else 200 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier none expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list if_statement not_operator subscript attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier identifier return_statement expression_list dictionary pair string string_start string_content string_end identifier conditional_expression integer identifier integer | Follow an object given its ID |
def change_user_password(self, ID, data):
log.info('Change user %s password' % ID)
self.put('users/%s/change_password.json' % ID, data) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier identifier | Change password of a User. |
def _delete_fields(self):
for key in self._json_dict.keys():
if not key.startswith("_"):
delattr(self, key)
self._json_dict = {}
self.id = None
self.name = None | module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none | Delete this object's attributes, including name and id |
def starting_expression(source_code, offset):
word_finder = worder.Worder(source_code, True)
expression, starting, starting_offset = \
word_finder.get_splitted_primary_before(offset)
if expression:
return expression + '.' + starting
return starting | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier true expression_statement assignment pattern_list identifier identifier identifier line_continuation call attribute identifier identifier argument_list identifier if_statement identifier block return_statement binary_operator binary_operator identifier string string_start string_content string_end identifier return_statement identifier | Return the expression to complete |
def current_values(self):
current_dict = {
'date': self.current_session_date,
'score': self.current_sleep_score,
'stage': self.current_sleep_stage,
'breakdown': self.current_sleep_breakdown,
'tnt': self.current_tnt,
'bed_temp': self.current_bed_temp,
'room_temp': self.current_room_temp,
'resp_rate': self.current_resp_rate,
'heart_rate': self.current_heart_rate,
'processing': self.current_session_processing,
}
return current_dict | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier return_statement identifier | Return a dict of all the 'current' parameters. |
def getObjectTypeBit(self, t):
if isinstance(t, string_types):
t = t.upper()
try:
return self.objectType[t]
except KeyError:
raise CommandExecutionError((
'Invalid object type "{0}". It should be one of the following: {1}'
).format(t, ', '.join(self.objectType)))
else:
return t | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block return_statement subscript attribute identifier identifier identifier except_clause identifier block raise_statement call identifier argument_list call attribute parenthesized_expression string string_start string_content string_end identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier else_clause block return_statement identifier | returns the bit value of the string object type |
def hide_auth(msg):
for pattern, repl in RE_HIDE_AUTH:
msg = pattern.sub(repl, msg)
return msg | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | Remove sensitive information from msg. |
def press_check(df):
new_df = df.copy()
press = new_df.copy().index.values
ref = press[0]
inversions = np.diff(np.r_[press, press[-1]]) < 0
mask = np.zeros_like(inversions)
for k, p in enumerate(inversions):
if p:
ref = press[k]
cut = press[k + 1 :] < ref
mask[k + 1 :][cut] = True
new_df[mask] = np.NaN
return new_df | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier attribute attribute call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list subscript attribute identifier identifier identifier subscript identifier unary_operator integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier comparison_operator subscript identifier slice binary_operator identifier integer identifier expression_statement assignment subscript subscript identifier slice binary_operator identifier integer identifier true expression_statement assignment subscript identifier identifier attribute identifier identifier return_statement identifier | Remove pressure reversals from the index. |
def fcs(bits):
fcs = FCS()
for bit in bits:
yield bit
fcs.update_bit(bit)
digest = bitarray(endian="little")
digest.frombytes(fcs.digest())
for bit in digest:
yield bit | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement yield identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement yield identifier | Append running bitwise FCS CRC checksum to end of generator |
def _WritePathInfo(self, client_id, path_info):
if client_id not in self.metadatas:
raise db.UnknownClientError(client_id)
path_record = self._GetPathRecord(client_id, path_info)
path_record.AddPathInfo(path_info)
parent_path_info = path_info.GetParent()
if parent_path_info is not None:
parent_path_record = self._GetPathRecord(client_id, parent_path_info)
parent_path_record.AddChild(path_info) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Writes a single path info record for given client. |
def split_none(self):
"Don't split the data and create an empty validation set."
val = self[[]]
val.ignore_empty = True
return self._split(self.path, self, val) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript identifier list expression_statement assignment attribute identifier identifier true return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier | Don't split the data and create an empty validation set. |
def proper_repr(value: Any) -> str:
if isinstance(value, sympy.Basic):
result = sympy.srepr(value)
fixed_tokens = [
'Symbol', 'pi', 'Mul', 'Add', 'Mod', 'Integer', 'Float', 'Rational'
]
for token in fixed_tokens:
result = result.replace(token, 'sympy.' + token)
return result
if isinstance(value, np.ndarray):
return 'np.array({!r})'.format(value.tolist())
return repr(value) | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier return_statement identifier if_statement call identifier argument_list identifier attribute identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list return_statement call identifier argument_list identifier | Overrides sympy and numpy returning repr strings that don't parse. |
def _vpc_peering_conn_id_for_name(name, conn):
log.debug('Retrieving VPC peering connection id')
ids = _get_peering_connection_ids(name, conn)
if not ids:
ids = [None]
elif len(ids) > 1:
raise SaltInvocationError('Found multiple VPC peering connections '
'with the same name!! '
'Please make sure you have only '
'one VPC peering connection named {0} '
'or invoke this function with a VPC '
'peering connection ID'.format(name))
return ids[0] | 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 assignment identifier call identifier argument_list identifier identifier if_statement not_operator identifier block expression_statement assignment identifier list none elif_clause comparison_operator call identifier argument_list identifier integer 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 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 identifier argument_list identifier return_statement subscript identifier integer | Get the ID associated with this name |
def symlink(source, link_name):
if os.path.islink(link_name) and os.readlink(link_name) == source:
return
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, link_name)
else:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
if csl(link_name, source, flags) == 0:
raise ctypes.WinError() | module function_definition identifier parameters identifier identifier block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier comparison_operator call attribute identifier identifier argument_list identifier identifier block return_statement expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement call identifier argument_list identifier block expression_statement call identifier argument_list identifier identifier else_clause block import_statement dotted_name identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment attribute identifier identifier tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment identifier conditional_expression integer call attribute attribute identifier identifier identifier argument_list identifier integer if_statement comparison_operator call identifier argument_list identifier identifier identifier integer block raise_statement call attribute identifier identifier argument_list | Method to allow creating symlinks on Windows |
def _get_jenks_config():
config_file = (get_configuration_file() or
os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME)))
if not os.path.exists(config_file):
open(config_file, 'w').close()
with open(config_file, 'r') as fh:
return JenksData(
yaml.load(fh.read()),
write_method=generate_write_yaml_to_file(config_file)
) | module function_definition identifier parameters block expression_statement assignment identifier parenthesized_expression boolean_operator call identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list 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 return_statement call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list identifier | retrieve the jenks configuration object |
def _list_paths(self, bucket, prefix):
s3 = self.s3
kwargs = {"Bucket": bucket, "Prefix": prefix}
if self.list_objects:
list_objects_api = "list_objects"
else:
list_objects_api = "list_objects_v2"
paginator = s3.get_paginator(list_objects_api)
for page in paginator.paginate(**kwargs):
contents = page.get("Contents", None)
if not contents:
continue
for item in contents:
yield item["Key"] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement attribute identifier identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list dictionary_splat identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement not_operator identifier block continue_statement for_statement identifier identifier block expression_statement yield subscript identifier string string_start string_content string_end | Read config for list object api, paginate through list objects. |
def read_writer_config(config_files, loader=UnsafeLoader):
conf = {}
LOG.debug('Reading %s', str(config_files))
for config_file in config_files:
with open(config_file) as fd:
conf.update(yaml.load(fd.read(), Loader=loader))
try:
writer_info = conf['writer']
except KeyError:
raise KeyError(
"Malformed config file {}: missing writer 'writer'".format(
config_files))
writer_info['config_files'] = config_files
return writer_info | module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier for_statement identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier try_statement block expression_statement assignment identifier subscript identifier string string_start string_content string_end except_clause identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Read the writer `config_files` and return the info extracted. |
def GetAnnotatedMethods(cls):
result = {}
for i_cls in reversed(inspect.getmro(cls)):
for name in compatibility.ListAttrs(i_cls):
cls_method = getattr(i_cls, name)
if not callable(cls_method):
continue
if not hasattr(cls_method, "__http_methods__"):
continue
result[name] = RouterMethodMetadata(
name=name,
doc=cls_method.__doc__,
args_type=getattr(cls_method, "__args_type__", None),
result_type=getattr(cls_method, "__result_type__", None),
category=getattr(cls_method, "__category__", None),
http_methods=getattr(cls_method, "__http_methods__", set()),
no_audit_log_required=getattr(cls_method,
"__no_audit_log_required__", False))
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list call attribute identifier identifier argument_list identifier block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator call identifier argument_list identifier block continue_statement if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block continue_statement expression_statement assignment subscript identifier identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list identifier string string_start string_content string_end none keyword_argument identifier call identifier argument_list identifier string string_start string_content string_end none keyword_argument identifier call identifier argument_list identifier string string_start string_content string_end none keyword_argument identifier call identifier argument_list identifier string string_start string_content string_end call identifier argument_list keyword_argument identifier call identifier argument_list identifier string string_start string_content string_end false return_statement identifier | Returns a dictionary of annotated router methods. |
def prepare_request(self, request):
try:
request_id = local.request_id
except AttributeError:
request_id = NO_REQUEST_ID
if self.request_id_header and request_id != NO_REQUEST_ID:
request.headers[self.request_id_header] = request_id
return super(Session, self).prepare_request(request) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block expression_statement assignment identifier identifier if_statement boolean_operator attribute identifier identifier comparison_operator identifier identifier block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Include the request ID, if available, in the outgoing request |
def store_snow_tweets_from_disk_to_mongodb(snow_tweets_folder):
client = pymongo.MongoClient("localhost", 27017)
db = client["snow_tweet_storage"]
collection = db["tweets"]
for tweet in extract_all_snow_tweets_from_disk_generator(snow_tweets_folder):
collection.insert(tweet) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier | Store all SNOW tweets in a mongodb collection. |
def to_bytes(s, encoding=None, errors='strict'):
encoding = encoding or 'utf-8'
if is_unicode(s):
return s.encode(encoding, errors)
elif is_strlike(s):
return s
else:
if six.PY2:
return str(s)
else:
return str(s).encode(encoding, errors) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier boolean_operator identifier string string_start string_content string_end if_statement call identifier argument_list identifier block return_statement call attribute identifier identifier argument_list identifier identifier elif_clause call identifier argument_list identifier block return_statement identifier else_clause block if_statement attribute identifier identifier block return_statement call identifier argument_list identifier else_clause block return_statement call attribute call identifier argument_list identifier identifier argument_list identifier identifier | Convert string to bytes. |
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer block try_statement block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end subscript subscript call identifier argument_list identifier identifier string string_start string_content string_end return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript call identifier argument_list identifier identifier identifier keyword_argument identifier identifier string string_start string_content string_end except_clause identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Simple command wrapper to commands that need only a path option |
def tag(name, tag_name):
with LOCK:
metric(name)
TAGS.setdefault(tag_name, set()).add(name) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item identifier block expression_statement call identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier call identifier argument_list identifier argument_list identifier | Tag the named metric with the given tag. |
def toggle_eventtype(self):
check = self.check_all_eventtype.isChecked()
for btn in self.idx_eventtype_list:
btn.setChecked(check) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Check or uncheck all event types in event type scroll. |
def reset_position(self):
self.pos = 0
self.col = 0
self.row = 1
self.eos = 0 | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer | Reset all current positions. |
def _evaluate_cut(transition, cut, unpartitioned_account,
direction=Direction.BIDIRECTIONAL):
cut_transition = transition.apply_cut(cut)
partitioned_account = account(cut_transition, direction)
log.debug("Finished evaluating %s.", cut)
alpha = account_distance(unpartitioned_account, partitioned_account)
return AcSystemIrreducibilityAnalysis(
alpha=round(alpha, config.PRECISION),
direction=direction,
account=unpartitioned_account,
partitioned_account=partitioned_account,
transition=transition,
cut=cut) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list keyword_argument identifier call identifier argument_list identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Find the |AcSystemIrreducibilityAnalysis| for a given cut. |
def clean(self):
super().clean()
if self.voter is None and self.anonymous_key is None:
raise ValidationError(_('A user id or an anonymous key must be used.'))
if self.voter and self.anonymous_key:
raise ValidationError(_('A user id or an anonymous key must be used, but not both.')) | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier argument_list if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list call identifier argument_list string string_start string_content string_end if_statement boolean_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call identifier argument_list string string_start string_content string_end | Validates the considered instance. |
def dashes(phone):
if isinstance(phone, str):
if phone.startswith("+1"):
return "1-" + "-".join((phone[2:5], phone[5:8], phone[8:]))
elif len(phone) == 10:
return "-".join((phone[:3], phone[3:6], phone[6:]))
else:
return phone
else:
return phone | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list tuple subscript identifier slice integer integer subscript identifier slice integer integer subscript identifier slice integer elif_clause comparison_operator call identifier argument_list identifier integer block return_statement call attribute string string_start string_content string_end identifier argument_list tuple subscript identifier slice integer subscript identifier slice integer integer subscript identifier slice integer else_clause block return_statement identifier else_clause block return_statement identifier | Returns the phone number formatted with dashes. |
def remove_env(environment):
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if not parser.remove_section(environment):
print("Unknown environment type '%s'" % environment)
return
write_config(parser)
print("Removed environment '%s'" % environment) | module function_definition identifier parameters identifier block if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call identifier argument_list if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement expression_statement call identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Remove an environment from the configuration. |
def return_value(self):
if self._raises:
if inspect.isclass(self._raises):
raise self._raises()
else:
raise self._raises
else:
if isinstance(self._returns, tuple):
return tuple([x.value if isinstance(x, Variable)
else x for x in self._returns])
return self._returns.value if isinstance(self._returns, Variable) \
else self._returns | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block if_statement call attribute identifier identifier argument_list attribute identifier identifier block raise_statement call attribute identifier identifier argument_list else_clause block raise_statement attribute identifier identifier else_clause block if_statement call identifier argument_list attribute identifier identifier identifier block return_statement call identifier argument_list list_comprehension conditional_expression attribute identifier identifier call identifier argument_list identifier identifier identifier for_in_clause identifier attribute identifier identifier return_statement conditional_expression attribute attribute identifier identifier identifier call identifier argument_list attribute identifier identifier identifier line_continuation attribute identifier identifier | Returns the value for this expectation or raises the proper exception. |
def direct_reply(self, text):
channel_id = self._client.open_dm_channel(self._get_user_id())
self._client.rtm_send_message(channel_id, text) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Send a reply via direct message using RTM API |
def parse_value(self, value_string: str):
self.value = Decimal(value_string)
return self.value | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment attribute identifier identifier call identifier argument_list identifier return_statement attribute identifier identifier | Parses the amount string. |
def jscanner(url):
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
matches = rendpoint.findall(response)
for match in matches:
match = match[0] + match[1]
if not re.search(r'[}{><"\']', match) and not match == '/':
verb('JS endpoint', match)
endpoints.add(match) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier binary_operator subscript identifier integer subscript identifier integer if_statement boolean_operator not_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier not_operator comparison_operator identifier string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier | Extract endpoints from JavaScript code. |
def make_mesh( coor, ngroups, conns, mesh_in ):
mat_ids = []
for ii, conn in enumerate( conns ):
mat_id = nm.empty( (conn.shape[0],), dtype = nm.int32 )
mat_id.fill( mesh_in.mat_ids[ii][0] )
mat_ids.append( mat_id )
mesh_out = Mesh.from_data( 'merged mesh', coor, ngroups, conns,
mat_ids, mesh_in.descs )
return mesh_out | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple subscript attribute identifier identifier integer keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list subscript subscript attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier identifier attribute identifier identifier return_statement identifier | Create a mesh reusing mat_ids and descs of mesh_in. |
def leaveoneout(self):
traintestfile = self.fileprefix + '.train'
options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out"
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
self.api = timblapi.TimblAPI(options, "")
if self.debug:
print("Enabling debug for timblapi",file=stderr)
self.api.enableDebug()
print("Calling Timbl API : " + options,file=stderr)
if sys.version < '3':
self.api.learn(b(traintestfile))
self.api.test(b(traintestfile), b(self.fileprefix + '.out'),b'')
else:
self.api.learn(u(traintestfile))
self.api.test(u(traintestfile), u(self.fileprefix + '.out'),'')
return self.api.getAccuracy() | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end attribute identifier identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call identifier argument_list identifier string string_start string_end else_clause block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier string string_start string_end if_statement attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier call identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end string string_start string_end else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier call identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end string string_start string_end return_statement call attribute attribute identifier identifier identifier argument_list | Train & Test using leave one out |
def next_frame_sampling():
hparams = next_frame_basic_deterministic()
hparams.scheduled_sampling_mode = "prob_inverse_exp"
hparams.scheduled_sampling_max_prob = 1.0
hparams.scheduled_sampling_decay_steps = 10000
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 float expression_statement assignment attribute identifier identifier integer return_statement identifier | Basic conv model with scheduled sampling. |
def send(self, data):
self._send_data(int_to_hex(len(data)))
self._send_data(data) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Send a formatted message to the ADB server |
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d):
zeta_a = satz_a
zeta_b = satz_b
phi_a = compute_phi(zeta_a)
phi_b = compute_phi(zeta_b)
theta_a = compute_theta(zeta_a, phi_a)
theta_b = compute_theta(zeta_b, phi_b)
phi = (phi_a + phi_b) / 2
zeta = compute_zeta(phi)
theta = compute_theta(zeta, phi)
c_expansion = 4 * (((theta_a + theta_b) / 2 - theta) / (theta_a - theta_b))
sin_beta_2 = scan_width / (2 * H)
d = ((R + H) / R * np.cos(phi) - np.cos(zeta)) * sin_beta_2
e = np.cos(zeta) - np.sqrt(np.cos(zeta) ** 2 - d ** 2)
c_alignment = 4 * e * np.sin(zeta) / (theta_a - theta_b)
return c_expansion, c_alignment | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier integer expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator integer parenthesized_expression binary_operator parenthesized_expression binary_operator binary_operator parenthesized_expression binary_operator identifier identifier integer identifier parenthesized_expression binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator integer identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator binary_operator binary_operator parenthesized_expression binary_operator identifier identifier identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list binary_operator binary_operator call attribute identifier identifier argument_list identifier integer binary_operator identifier integer expression_statement assignment identifier binary_operator binary_operator binary_operator integer identifier call attribute identifier identifier argument_list identifier parenthesized_expression binary_operator identifier identifier return_statement expression_list identifier identifier | All angles in radians. |
def __apf_cmd(cmd):
apf_cmd = '{0} {1}'.format(salt.utils.path.which('apf'), cmd)
out = __salt__['cmd.run_all'](apf_cmd)
if out['retcode'] != 0:
if not out['stderr']:
msg = out['stdout']
else:
msg = out['stderr']
raise CommandExecutionError(
'apf failed: {0}'.format(msg)
)
return out['stdout'] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end integer block if_statement not_operator subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement subscript identifier string string_start string_content string_end | Return the apf location |
def sorted_source_files(self):
assert self.final, 'Call build() before using the graph.'
out = []
for node in nx.topological_sort(self.graph):
if isinstance(node, NodeSet):
out.append(node.nodes)
else:
out.append([node])
return list(reversed(out)) | module function_definition identifier parameters identifier block assert_statement attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list list identifier return_statement call identifier argument_list call identifier argument_list identifier | Returns a list of targets in topologically sorted order. |
def save_current_figure_as(self):
if self.current_thumbnail is not None:
self.save_figure_as(self.current_thumbnail.canvas.fig,
self.current_thumbnail.canvas.fmt) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier attribute attribute attribute identifier identifier identifier identifier | Save the currently selected figure. |
def process_slice(self, b_rot90=None):
if b_rot90:
self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice)
if self.func == 'invertIntensities':
self.invert_slice_intensities() | module function_definition identifier parameters identifier default_parameter identifier none block if_statement identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list | Processes a single slice. |
def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs):
import sys
sys.stdout = IOQueue(q_stdout)
sys.stderr = IOQueue(q_stderr)
try:
target(*args, **kwargs)
except:
if not robust:
s = 'Error in tab\n' + traceback.format_exc()
logger = daiquiri.getLogger(name)
logger.error(s)
else:
raise
if not robust:
q_error.put(name)
raise | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block import_statement dotted_name identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier try_statement block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause block if_statement not_operator identifier block expression_statement assignment identifier binary_operator string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block raise_statement if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier raise_statement | Wraps a target with queues replacing stdout and stderr |
def _async_callable(func):
if isinstance(func, types.CoroutineType):
return func
@functools.wraps(func)
async def _async_def_wrapper(*args, **kwargs):
return func(*args, **kwargs)
return _async_def_wrapper | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement identifier decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier | Ensure the callable is an async def. |
def do_mute(self, sender, body, args):
if sender.get('MUTED'):
self.send_message('you are already muted', sender)
else:
self.broadcast('%s has muted this chatroom' % (sender['NICK'],))
sender['QUEUED_MESSAGES'] = []
sender['MUTED'] = True | module function_definition identifier parameters identifier identifier identifier identifier block if_statement 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 identifier else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end list expression_statement assignment subscript identifier string string_start string_content string_end true | Temporarily mutes chatroom for a user |
def run_checks(collector):
artifact = collector.configuration["dashmat"].artifact
chosen = artifact
if chosen in (None, "", NotSpecified):
chosen = None
dashmat = collector.configuration["dashmat"]
modules = collector.configuration["__active_modules__"]
config_root = collector.configuration["config_root"]
module_options = collector.configuration["modules"]
datastore = JsonDataStore(os.path.join(config_root, "data.json"))
if dashmat.redis_host:
datastore = RedisDataStore(redis.Redis(dashmat.redis_host))
scheduler = Scheduler(datastore)
for name, module in modules.items():
if chosen is None or name == chosen:
server = module.make_server(module_options[name].server_options)
scheduler.register(module, server, name)
scheduler.twitch(force=True) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier identifier if_statement comparison_operator identifier tuple none string string_start string_end identifier block expression_statement assignment identifier none expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier true | Just run the checks for our modules |
def cut_for_search(self, sentence, HMM=True):
words = self.cut(sentence, HMM=HMM)
for w in words:
if len(w) > 2:
for i in xrange(len(w) - 1):
gram2 = w[i:i + 2]
if self.FREQ.get(gram2):
yield gram2
if len(w) > 3:
for i in xrange(len(w) - 2):
gram3 = w[i:i + 3]
if self.FREQ.get(gram3):
yield gram3
yield w | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier for_statement identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block for_statement identifier call identifier argument_list binary_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier slice identifier binary_operator identifier integer if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement yield identifier if_statement comparison_operator call identifier argument_list identifier integer block for_statement identifier call identifier argument_list binary_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier slice identifier binary_operator identifier integer if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement yield identifier expression_statement yield identifier | Finer segmentation for search engines. |
def _wait_until_connectable(self, timeout=30):
count = 0
while not utils.is_connectable(self.profile.port):
if self.process.poll() is not None:
raise WebDriverException(
"The browser appears to have exited "
"before we could connect. If you specified a log_file in "
"the FirefoxBinary constructor, check it for details.")
if count >= timeout:
self.kill()
raise WebDriverException(
"Can't load the profile. Possible firefox version mismatch. "
"You must use GeckoDriver instead for Firefox 48+. Profile "
"Dir: %s If you specified a log_file in the "
"FirefoxBinary constructor, check it for details."
% (self.profile.path))
count += 1
time.sleep(1)
return True | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier integer while_statement not_operator call attribute identifier identifier argument_list attribute attribute identifier identifier identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list none block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list raise_statement call identifier argument_list binary_operator concatenated_string 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 parenthesized_expression attribute attribute identifier identifier identifier expression_statement augmented_assignment identifier integer expression_statement call attribute identifier identifier argument_list integer return_statement true | Blocks until the extension is connectable in the firefox. |
async def get_real_ext_ip(self):
while self._ip_hosts:
try:
timeout = aiohttp.ClientTimeout(total=self._timeout)
async with aiohttp.ClientSession(
timeout=timeout, loop=self._loop
) as session, session.get(self._pop_random_ip_host()) as resp:
ip = await resp.text()
except asyncio.TimeoutError:
pass
else:
ip = ip.strip()
if self.host_is_ip(ip):
log.debug('Real external IP: %s', ip)
break
else:
raise RuntimeError('Could not get the external IP')
return ip | module function_definition identifier parameters identifier block while_statement attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier as_pattern_target identifier with_item as_pattern call attribute identifier identifier argument_list call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list except_clause attribute identifier identifier block pass_statement else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier break_statement else_clause block raise_statement call identifier argument_list string string_start string_content string_end return_statement identifier | Return real external IP address. |
def time_logger(name):
start_time = time.time()
yield
end_time = time.time()
total_time = end_time - start_time
logging.info("%s; time: %ss", name, total_time) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement yield expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier | This logs the time usage of a code block |
def _round(ctx, number, num_digits):
number = conversions.to_decimal(number, ctx)
num_digits = conversions.to_integer(num_digits, ctx)
return decimal_round(number, num_digits, ROUND_HALF_UP) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement call identifier argument_list identifier identifier identifier | Rounds a number to a specified number of digits |
def adduser(app, username, password):
with app.app_context():
create_user(username=username, password=password)
click.echo('user created!') | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Add new user with admin access |
def setup(self, **kwargs):
for key in kwargs:
if key not in self.config.keys():
raise error.GrabMisuseError('Unknown option: %s' % key)
if 'url' in kwargs:
if self.config.get('url'):
kwargs['url'] = self.make_url_absolute(kwargs['url'])
self.config.update(kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block for_statement identifier identifier block if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier if_statement comparison_operator string string_start string_content string_end identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Setting up Grab instance configuration. |
def shutdown(self):
if not self._shutdown:
self._data_queue.put((None, None))
self._fetcher.join()
for _ in range(self._num_workers):
self._key_queue.put((None, None))
for w in self._workers:
if w.is_alive():
w.terminate()
self._shutdown = True | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list tuple none none expression_statement call attribute attribute identifier identifier identifier argument_list for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list tuple none none for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true | Shutdown internal workers by pushing terminate signals. |
def delete(self):
try:
self.revert()
except errors.ChangelistError:
pass
self._connection.run(['change', '-d', str(self._change)]) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list except_clause attribute identifier identifier block pass_statement expression_statement call attribute attribute identifier identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end call identifier argument_list attribute identifier identifier | Reverts all files in this changelist then deletes the changelist from perforce |
def bind(cls):
document["show_author_picker"].bind("click", lambda x: cls.show())
cls.storno_btn_el.bind("click", lambda x: cls.hide())
cls.pick_btn_el.bind("click", cls.on_pick_button_pressed) | module function_definition identifier parameters identifier block expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end lambda lambda_parameters identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end lambda lambda_parameters identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier | Bind the callbacks to the buttons. |
def PrintTags(self, file):
print >>file, '/* Tag definition for %s */' % self._name
print >>file, 'enum %s_ {' % self._name.lower()
for entry in self._entries:
print >>file, ' %s=%d,' % (self.EntryTagName(entry),
entry.Tag())
print >>file, ' %s_MAX_TAGS' % (self._name.upper())
print >>file, '};\n' | module function_definition identifier parameters identifier identifier block print_statement chevron identifier binary_operator string string_start string_content string_end attribute identifier identifier print_statement chevron identifier binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block print_statement chevron identifier binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list print_statement chevron identifier binary_operator string string_start string_content string_end parenthesized_expression call attribute attribute identifier identifier identifier argument_list print_statement chevron identifier string string_start string_content escape_sequence string_end | Prints the tag definitions for a structure. |
def form_node(cls):
assert issubclass(cls, FormNode)
res = attrs(init=False, slots=True)(cls)
res._args = []
res._required_args = 0
res._rest_arg = None
state = _FormArgMode.REQUIRED
for field in fields(res):
if 'arg_mode' in field.metadata:
if state is _FormArgMode.REST:
raise RuntimeError('rest argument must be last')
if field.metadata['arg_mode'] is _FormArgMode.REQUIRED:
if state is _FormArgMode.OPTIONAL:
raise RuntimeError('required arg after optional arg')
res._args.append(field)
res._required_args += 1
elif field.metadata['arg_mode'] is _FormArgMode.OPTIONAL:
state = _FormArgMode.OPTIONAL
res._args.append(field)
elif field.metadata['arg_mode'] is _FormArgMode.REST:
state = _FormArgMode.REST
res._rest_arg = field
else:
assert 0
return res | module function_definition identifier parameters identifier block assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier call call identifier argument_list keyword_argument identifier false keyword_argument identifier true argument_list identifier expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier none expression_statement assignment identifier attribute identifier identifier for_statement identifier call identifier argument_list identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier integer elif_clause comparison_operator subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier elif_clause comparison_operator subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier else_clause block assert_statement integer return_statement identifier | A class decorator to finalize fully derived FormNode subclasses. |
def compare_version(self, version_string, op):
from pkg_resources import parse_version
from monty.operator import operator_from_str
op = operator_from_str(op)
return op(parse_version(self.version), parse_version(version_string)) | module function_definition identifier parameters identifier identifier identifier block import_from_statement dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list attribute identifier identifier call identifier argument_list identifier | Compare Abinit version to `version_string` with operator `op` |
def clean(self):
if self.cleaners:
yield from asyncio.wait([x() for x in self.cleaners],
loop=self.loop) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement yield call attribute identifier identifier argument_list list_comprehension call identifier argument_list for_in_clause identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Run all of the cleaners added by the user. |
def _load_vocab_file(vocab_file, reserved_tokens=None):
if reserved_tokens is None:
reserved_tokens = RESERVED_TOKENS
subtoken_list = []
with tf.gfile.Open(vocab_file, mode="r") as f:
for line in f:
subtoken = _native_to_unicode(line.strip())
subtoken = subtoken[1:-1]
if subtoken in reserved_tokens:
continue
subtoken_list.append(_native_to_unicode(subtoken))
return reserved_tokens + subtoken_list | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement assignment identifier list with_statement with_clause with_item as_pattern call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier slice integer unary_operator integer if_statement comparison_operator identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement binary_operator identifier identifier | Load vocabulary while ensuring reserved tokens are at the top. |
def _do_scale(image, size):
shape = tf.cast(tf.shape(image), tf.float32)
w_greater = tf.greater(shape[0], shape[1])
shape = tf.cond(w_greater,
lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32),
lambda: tf.cast([size, shape[1] / shape[0] * size], tf.int32))
return tf.image.resize_bicubic([image], shape)[0] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier lambda call attribute identifier identifier argument_list list binary_operator binary_operator subscript identifier integer subscript identifier integer identifier identifier attribute identifier identifier lambda call attribute identifier identifier argument_list list identifier binary_operator binary_operator subscript identifier integer subscript identifier integer identifier attribute identifier identifier return_statement subscript call attribute attribute identifier identifier identifier argument_list list identifier identifier integer | Rescale the image by scaling the smaller spatial dimension to `size`. |
def __AddWorkers(self, num_to_add):
assert(self.__IsWebUiReady())
zone_to_ips = self.__GetZoneToWorkerIpsTable()
zone_old_new = []
for zone, ips in zone_to_ips.iteritems():
num_nodes_in_zone = len(ips)
num_nodes_to_add = 0
zone_old_new.append((zone, num_nodes_in_zone, num_nodes_to_add))
print 'num_to_add %s' % num_to_add
for _ in range(num_to_add):
zone_old_new.sort(key= lambda z : z[1]+z[2])
zt = zone_old_new[0]
zone_old_new[0] = (zt[0], zt[1], zt[2]+1)
zone_plan = [(zt[2], zt[0]) for zt in zone_old_new]
print 'resize plan'
if self.config.workers_on_spot_instances:
new_worker_instances = self.__LaunchSpotWorkerInstances(zone_plan)
else:
new_worker_instances = self.__LaunchOnDemandWorkerInstances(zone_plan)
self.__WaitForInstancesReachable(new_worker_instances)
self.__ConfigureWorkers(new_worker_instances)
return | module function_definition identifier parameters identifier identifier block assert_statement parenthesized_expression call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer expression_statement call attribute identifier identifier argument_list tuple identifier identifier identifier print_statement binary_operator string string_start string_content string_end identifier for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier lambda lambda_parameters identifier binary_operator subscript identifier integer subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment subscript identifier integer tuple subscript identifier integer subscript identifier integer binary_operator subscript identifier integer integer expression_statement assignment identifier list_comprehension tuple subscript identifier integer subscript identifier integer for_in_clause identifier identifier print_statement string string_start string_content string_end if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement | Adds workers evenly across all enabled zones. |
def _handshake(self, conn, addr):
msg = conn.recv(len(MAGIC_REQ))
log.debug('Received message %s from %s', msg, addr)
if msg != MAGIC_REQ:
log.warning('%s is not a valid REQ message from %s', msg, addr)
return
log.debug('Sending the private key')
conn.send(self.__key)
log.debug('Waiting for the client to confirm')
msg = conn.recv(len(MAGIC_ACK))
if msg != MAGIC_ACK:
return
log.debug('Sending the signature key')
conn.send(self.__sgn)
log.debug('Waiting for the client to confirm')
msg = conn.recv(len(MAGIC_ACK))
if msg != MAGIC_ACK:
return
log.info('%s is now authenticated', addr)
self.keep_alive(conn) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier | Ensures that the client receives the AES key. |
def update(d, e):
res = copy.copy(d)
res.update(e)
return res | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Return a copy of dict `d` updated with dict `e`. |
def create(self, verbose=None):
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
response = requests.post(
self.api_url,
auth=("api", self.api_key),
data={
"address": self.address,
"name": self.name,
"description": self.display_name,
},
)
if verbose:
sys.stdout.write(
f"Creating mailing list {self.address}. "
f"Got response={response.status_code}.\n"
)
return response | module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier tuple string string_start string_content string_end attribute identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list concatenated_string string string_start string_content interpolation attribute identifier identifier string_content string_end string string_start string_content interpolation attribute identifier identifier string_content escape_sequence string_end return_statement identifier | Returns a response after attempting to create the list. |
def delete(self) :
"deletes the document from the database"
if self.URL is None :
raise DeletionError("Can't delete a document that was not saved")
r = self.connection.session.delete(self.URL)
data = r.json()
if (r.status_code != 200 and r.status_code != 202) or 'error' in data :
raise DeletionError(data['errorMessage'], data)
self.reset(self.collection)
self.modified = True | 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 raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator parenthesized_expression boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier true | deletes the document from the database |
def cnn_learner(data:DataBunch, base_arch:Callable, cut:Union[int,Callable]=None, pretrained:bool=True,
lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None,
split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, init=nn.init.kaiming_normal_,
concat_pool:bool=True, **kwargs:Any)->Learner:
"Build convnet style learner."
meta = cnn_config(base_arch)
model = create_cnn_model(base_arch, data.c, cut, pretrained, lin_ftrs, ps=ps, custom_head=custom_head,
split_on=split_on, bn_final=bn_final, concat_pool=concat_pool)
learn = Learner(data, model, **kwargs)
learn.split(split_on or meta['split'])
if pretrained: learn.freeze()
if init: apply_init(model[1], init)
return learn | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier type identifier none typed_default_parameter identifier type identifier true typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier none typed_default_parameter identifier type identifier float typed_default_parameter identifier type generic_type identifier type_parameter type attribute identifier identifier none typed_default_parameter identifier type generic_type identifier type_parameter type identifier none typed_default_parameter identifier type identifier false default_parameter identifier attribute attribute identifier identifier identifier typed_default_parameter identifier type identifier true typed_parameter dictionary_splat_pattern identifier type identifier type identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list boolean_operator identifier subscript identifier string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement call identifier argument_list subscript identifier integer identifier return_statement identifier | Build convnet style learner. |
def stupid_hack(most=10, wait=None):
if wait is not None:
time.sleep(wait)
else:
time.sleep(random.randrange(1, most)) | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer identifier | Return a random time between 1 - 10 Seconds. |
def question_default_loader(self, pk):
try:
obj = Question.objects.get(pk=pk)
except Question.DoesNotExist:
return None
else:
self.question_default_add_related_pks(obj)
return obj | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier except_clause attribute identifier identifier block return_statement none else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Load a Question from the database. |
def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):
if not dry_run and any(r.import_type == RowResult.IMPORT_TYPE_NEW for r in result.rows):
connection = connections[DEFAULT_DB_ALIAS]
sequence_sql = connection.ops.sequence_reset_sql(no_style(), [self._meta.model])
if sequence_sql:
cursor = connection.cursor()
try:
for line in sequence_sql:
cursor.execute(line)
finally:
cursor.close() | module function_definition identifier parameters identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block if_statement boolean_operator not_operator identifier call identifier generator_expression comparison_operator attribute identifier identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list list attribute attribute identifier identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier finally_clause block expression_statement call attribute identifier identifier argument_list | Reset the SQL sequences after new objects are imported |
def isotime(s):
"Convert timestamps in ISO8661 format to and from Unix time."
if type(s) == type(1):
return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
elif type(s) == type(1.0):
date = int(s)
msec = s - date
date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
return date + "." + repr(msec)[3:]
elif type(s) == type("") or type(s) == type(u""):
if s[-1] == "Z":
s = s[:-1]
if "." in s:
(date, msec) = s.split(".")
else:
date = s
msec = "0"
return calendar.timegm(time.strptime(date, "%Y-%m-%dT%H:%M:%S")) + float("0." + msec)
else:
raise TypeError | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier call identifier argument_list integer block return_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier elif_clause comparison_operator call identifier argument_list identifier call identifier argument_list float block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier return_statement binary_operator binary_operator identifier string string_start string_content string_end subscript call identifier argument_list identifier slice integer elif_clause boolean_operator comparison_operator call identifier argument_list identifier call identifier argument_list string string_start string_end comparison_operator call identifier argument_list identifier call identifier argument_list string string_start string_end block if_statement comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice unary_operator integer if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier string string_start string_content string_end return_statement binary_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end call identifier argument_list binary_operator string string_start string_content string_end identifier else_clause block raise_statement identifier | Convert timestamps in ISO8661 format to and from Unix time. |
def executable_exists(executable):
for directory in os.getenv("PATH").split(":"):
if os.path.exists(os.path.join(directory, executable)):
return True
return False | module function_definition identifier parameters identifier block for_statement identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end block if_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier block return_statement true return_statement false | Test if an executable is available on the system. |
def git_sha_metadata(content, git_content):
if not content.settings['GIT_SHA_METADATA']:
return
if not git_content.is_committed():
return
content.metadata['gitsha_newest'] = str(git_content.get_newest_commit())
content.metadata['gitsha_oldest'] = str(git_content.get_oldest_commit()) | module function_definition identifier parameters identifier identifier block if_statement not_operator subscript attribute identifier identifier string string_start string_content string_end block return_statement if_statement not_operator call attribute identifier identifier argument_list block return_statement expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list | Add sha metadata to content |
def convert_kv(key, val, attr_type, attr={}, cdata=False):
LOG.info('Inside convert_kv(): key="%s", val="%s", type(val) is: "%s"' % (
unicode_me(key), unicode_me(val), type(val).__name__)
)
key, attr = make_valid_xml_name(key, attr)
if attr_type:
attr['type'] = get_xml_type(val)
attrstring = make_attrstring(attr)
return '<%s%s>%s</%s>' % (
key, attrstring,
wrap_cdata(val) if cdata == True else escape_xml(val),
key
) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier dictionary default_parameter identifier false block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple call identifier argument_list identifier call identifier argument_list identifier attribute call identifier argument_list identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement binary_operator string string_start string_content string_end tuple identifier identifier conditional_expression call identifier argument_list identifier comparison_operator identifier true call identifier argument_list identifier identifier | Converts a number or string into an XML element |
def _inspectArguments(self, args):
if args:
self.exec_path = PathStr(args[0])
else:
self.exec_path = None
session_name = None
args = args[1:]
openSession = False
for arg in args:
if arg in ('-h', '--help'):
self._showHelp()
elif arg in ('-d', '--debug'):
print('RUNNGING IN DEBUG-MODE')
self.opts['debugMode'] = True
elif arg in ('-l', '--log'):
print('CREATE LOG')
self.opts['createLog'] = True
elif arg in ('-s', '--server'):
self.opts['server'] = True
elif arg in ('-o', '--open'):
openSession = True
elif openSession:
session_name = arg
else:
print("Argument '%s' not known." % arg)
return self._showHelp()
return session_name | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier integer else_clause block expression_statement assignment attribute identifier identifier none expression_statement assignment identifier none expression_statement assignment identifier subscript identifier slice integer expression_statement assignment identifier false for_statement identifier identifier block if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end true elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end true elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end true elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier true elif_clause identifier block expression_statement assignment identifier identifier else_clause block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list return_statement identifier | inspect the command-line-args and give them to appBase |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.