code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def update_details(profile_tree, details):
div = profile_tree.xpath("//div[@id = 'profile_details']")[0]
for dl in div.iter('dl'):
title = dl.find('dt').text
item = dl.find('dd')
if title == 'Last Online' and item.find('span') is not None:
details[title.lower()] = item.find('span').text.strip()
elif title.lower() in details and len(item.text):
details[title.lower()] = item.text.strip()
else:
continue
details[title.lower()] = replace_chars(details[title.lower()]) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none block expression_statement assignment subscript identifier call attribute identifier identifier argument_list call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list elif_clause boolean_operator comparison_operator call attribute identifier identifier argument_list identifier call identifier argument_list attribute identifier identifier block expression_statement assignment subscript identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list else_clause block continue_statement expression_statement assignment subscript identifier call attribute identifier identifier argument_list call identifier argument_list subscript identifier call attribute identifier identifier argument_list | Update details attribute of a Profile. |
def serialize(self):
data = {
'type': self.__class__.__name__,
'caption': self.caption.serialize(),
'headings': [[cell.serialize() for cell in hrow] for hrow in self.headings],
'rows': [[cell.serialize() for cell in row] for row in self.rows],
}
return data | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end list_comprehension list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier for_in_clause identifier attribute identifier identifier pair string string_start string_content string_end list_comprehension list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier for_in_clause identifier attribute identifier identifier return_statement identifier | Convert Table element to python dictionary. |
def a(self):
a = Point(self.center)
if self.xAxisIsMajor:
a.x += self.majorRadius
else:
a.y += self.majorRadius
return a | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement augmented_assignment attribute identifier identifier attribute identifier identifier else_clause block expression_statement augmented_assignment attribute identifier identifier attribute identifier identifier return_statement identifier | Positive antipodal point on the major axis, Point class. |
def completenames(self, text, *ignored):
return sorted(cmd.Cmd.completenames(self, text, *ignored) + self.argparse_names(text)) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block return_statement call identifier argument_list binary_operator call attribute attribute identifier identifier identifier argument_list identifier identifier list_splat identifier call attribute identifier identifier argument_list identifier | Patched to also return argparse commands |
def _precedence_parens(self, node, child, is_left=True):
if self._should_wrap(node, child, is_left):
return "(%s)" % child.accept(self)
return child.accept(self) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block if_statement call attribute identifier identifier argument_list identifier identifier identifier block return_statement binary_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Wrap child in parens only if required to keep same semantics |
def play(quiet, session_file, shell, speed, prompt, commentecho):
run(
session_file.readlines(),
shell=shell,
speed=speed,
quiet=quiet,
test_mode=TESTING,
prompt_template=prompt,
commentecho=commentecho,
) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Play a session file. |
def lnlike(self, theta):
params,loglike = self.params,self.loglike
kwargs = dict(list(zip(params,theta)))
try:
lnlike = loglike.value(**kwargs)
except ValueError as AssertionError:
lnlike = -np.inf
return lnlike | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier expression_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list call identifier argument_list identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier unary_operator attribute identifier identifier return_statement identifier | Logarithm of the likelihood |
def load_fits(self, filepath):
image = AstroImage.AstroImage(logger=self.logger)
image.load_file(filepath)
self.set_image(image) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Load a FITS file into the viewer. |
def slugify(text, sep='-'):
text = stringify(text)
if text is None:
return None
text = text.replace(sep, WS)
text = normalize(text, ascii=True)
if text is None:
return None
return text.replace(WS, sep) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier true if_statement comparison_operator identifier none block return_statement none return_statement call attribute identifier identifier argument_list identifier identifier | A simple slug generator. |
def other(wxcodes: typing.List[str]) -> str:
ret = []
for code in wxcodes:
item = translate.wxcode(code)
if item.startswith('Vicinity'):
item = item.lstrip('Vicinity ') + ' in the Vicinity'
ret.append(item)
return '. '.join(ret) | module function_definition identifier parameters typed_parameter identifier type subscript attribute identifier identifier identifier type identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Format wx codes into a spoken word string |
def visit_assign(self, node, parent):
type_annotation = self.check_type_comment(node)
newnode = nodes.Assign(node.lineno, node.col_offset, parent)
newnode.postinit(
targets=[self.visit(child, newnode) for child in node.targets],
value=self.visit(node.value, newnode),
type_annotation=type_annotation,
)
return newnode | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier return_statement identifier | visit a Assign node by returning a fresh instance of it |
def subscribe(self, topic, callback, qos):
if topic in self.topics:
return
def _message_callback(mqttc, userdata, msg):
callback(msg.topic, msg.payload.decode('utf-8'), msg.qos)
self._mqttc.subscribe(topic, qos)
self._mqttc.message_callback_add(topic, _message_callback)
self.topics[topic] = callback | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | Subscribe to an MQTT topic. |
def delegate(self, fn, *args, **kwargs):
callback = functools.partial(fn, *args, **kwargs)
coro = self.loop.run_in_executor(self.subexecutor, callback)
return asyncio.ensure_future(coro) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern 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 attribute identifier identifier identifier argument_list attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier | Return the given operation as an asyncio future. |
def visitTerminal(self, ctx):
text = ctx.getText()
return Terminal.from_text(text, ctx) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier | Converts case insensitive keywords and identifiers to lowercase |
def _time_reduce(self, arr, reduction):
if self.dtype_in_time == 'av' or not self.def_time:
return arr
reductions = {
'ts': lambda xarr: xarr,
'av': lambda xarr: xarr.mean(internal_names.YEAR_STR),
'std': lambda xarr: xarr.std(internal_names.YEAR_STR),
}
try:
return reductions[reduction](arr)
except KeyError:
raise ValueError("Specified time-reduction method '{}' is not "
"supported".format(reduction)) | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier string string_start string_content string_end not_operator attribute identifier identifier block return_statement identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end lambda lambda_parameters identifier identifier pair string string_start string_content string_end lambda lambda_parameters identifier call attribute identifier identifier argument_list attribute identifier identifier pair string string_start string_content string_end lambda lambda_parameters identifier call attribute identifier identifier argument_list attribute identifier identifier try_statement block return_statement call subscript identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier | Perform the specified time reduction on a local time-series. |
def reset(self):
self.domain = \
dns.name.Name(dns.name.from_text(socket.gethostname())[1:])
if len(self.domain) == 0:
self.domain = dns.name.root
self.nameservers = []
self.localhosts = set([
'localhost',
'loopback',
'127.0.0.1',
'0.0.0.0',
'::1',
'ip6-localhost',
'ip6-loopback',
])
self.interfaces = set()
self.search = set()
self.search_patterns = ['www.%s.com', 'www.%s.org', 'www.%s.net', ]
self.port = 53
self.timeout = 2.0
self.lifetime = 30.0
self.keyring = None
self.keyname = None
self.keyalgorithm = dns.tsig.default_algorithm
self.edns = -1
self.ednsflags = 0
self.payload = 0
self.cache = None | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier line_continuation call attribute attribute identifier identifier identifier argument_list subscript call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list slice integer if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier unary_operator integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier none | Reset all resolver configuration to the defaults. |
def update_last_sm_origin_meta_data(self):
self.meta['last_saved']['time'] = self.state_machine_model.state_machine.last_update
self.meta['last_saved']['file_system_path'] = self.state_machine_model.state_machine.file_system_path | module function_definition identifier parameters identifier block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier | Update the auto backup meta data with information of the state machine origin |
def list_alarms(self, limit=None, marker=None, return_next=False):
return self._alarm_manager.list(limit=limit, marker=marker,
return_next=return_next) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier false block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Returns a list of all the alarms created on this entity. |
def update(self, params=None, client=c):
uri = self.parent.uri
if not params or not self.res:
self.get_params()
return
d = self.payload
for k, v in params.items():
m = d["currentConfiguration"][self.parameter_map[k]]["message"]
if isinstance(v, bool) or isinstance(v, str):
m["value"] = v
else:
try:
m["expression"] = str(v)
except KeyError:
m["value"] = str(v)
res = client.update_configuration(uri.did, uri.wvm, uri.eid, json.dumps(d))
if res.status_code == 200:
self.res = res | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement boolean_operator not_operator identifier not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list return_statement expression_statement assignment identifier attribute identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end subscript attribute identifier identifier identifier string string_start string_content string_end if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block try_statement block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier except_clause identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment attribute identifier identifier identifier | Push params to OnShape and synchronize the local copy |
def wants(cls, *service_names):
def _decorator(cls_):
for service_name in service_names:
cls_._services_requested[service_name] = "want"
return cls_
return _decorator | module function_definition identifier parameters identifier list_splat_pattern identifier block function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier string string_start string_content string_end return_statement identifier return_statement identifier | A class decorator to indicate that an XBlock class wants particular services. |
def coerce_to_decimal(value):
if isinstance(value, decimal.Decimal):
return value
else:
try:
return decimal.Decimal(value)
except decimal.InvalidOperation as e:
raise GraphQLInvalidArgumentError(e) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement identifier else_clause block try_statement block return_statement call attribute identifier identifier argument_list identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier | Attempt to coerce the value to a Decimal, or raise an error if unable to do so. |
def execute(self):
r = self._s.execute()
r._faceted_search = self
return r | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier return_statement identifier | Execute the search and return the response. |
def limit_gen(limit, iterable):
limit = int(limit)
assert limit >= 0, 'negative limit'
for item in iterable:
if limit <= 0:
break
yield item
limit -= 1 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier assert_statement comparison_operator identifier integer string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator identifier integer block break_statement expression_statement yield identifier expression_statement augmented_assignment identifier integer | A generator that applies a count `limit`. |
def __install_eggs(self, config):
egg_carton = (self.directory.install_directory(self.feature_name),
'requirements.txt')
eggs = self.__gather_eggs(config)
self.logger.debug("Installing eggs %s..." % eggs)
self.__load_carton(egg_carton, eggs)
self.__prepare_eggs(egg_carton, config) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier tuple call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Install eggs for a particular configuration |
def shuffle(self, random=None):
random_.shuffle(self._list, random=random)
for i, elem in enumerate(self._list):
self._dict[elem] = i | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier | Shuffle all of the elements in self randomly. |
def prepare_data():
((x_train, y_train), (x_test, y_test)) = DATASET.load_data()
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255.0
x_test /= 255.0
return ((x_train, y_train), (x_test, y_test)) | module function_definition identifier parameters block expression_statement assignment tuple_pattern tuple_pattern identifier identifier tuple_pattern identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement augmented_assignment identifier float expression_statement augmented_assignment identifier float return_statement tuple tuple identifier identifier tuple identifier identifier | Load and normalize data. |
def dump_model_data(request, app_label, model_label):
return dump_to_response(request, '%s.%s' % (app_label, model_label),
[], '-'.join((app_label, model_label))) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list identifier binary_operator string string_start string_content string_end tuple identifier identifier list call attribute string string_start string_content string_end identifier argument_list tuple identifier identifier | Exports data from a model. |
def from_dict(cls, d):
o = super(Signature, cls).from_dict(d)
if 'content' in d:
try:
o._content = d['content']['_content']
o._contenttype = d['content']['type']
except TypeError:
o._content = d['content'][-1]['_content']
o._contenttype = d['content'][-1]['type']
return o | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block try_statement block expression_statement assignment attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end except_clause identifier block expression_statement assignment attribute identifier identifier subscript subscript subscript identifier string string_start string_content string_end unary_operator integer string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript subscript subscript identifier string string_start string_content string_end unary_operator integer string string_start string_content string_end return_statement identifier | Override default, adding the capture of content and contenttype. |
def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]:
result = tuple(self.visit(node=dim) for dim in node.dims)
self.recomputed_values[node] = result
return result | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier type generic_type identifier type_parameter type identifier type ellipsis block expression_statement assignment identifier call identifier generator_expression call attribute identifier identifier argument_list keyword_argument identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier | Visit each dimension of the advanced slicing and assemble the dimensions in a tuple. |
def append(self, row_dict):
entry = self.client.InsertRow(row_dict, self.key, self.worksheet)
self.feed.entry.append(entry)
return GDataRow(entry, sheet=self, deferred_save=self.deferred_save) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier return_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | Add a row to the spreadsheet, returns the new row |
def check_signature(signature, *args, **kwargs):
return hmac.compare_digest(signature, create_signature(*args, **kwargs)) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier call identifier argument_list list_splat identifier dictionary_splat identifier | Check for the signature is correct. |
def output(self, stream, disabletransferencoding = None):
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
self.outputstream = stream
try:
content_length = len(stream)
except Exception:
pass
else:
self.header(b'Content-Length', str(content_length).encode('ascii'))
if disabletransferencoding is not None:
self.disabledeflate = disabletransferencoding
self._startResponse() | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block pass_statement else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Set output stream and send response immediately |
def reorder_indices(self, indices_order):
'reorder all the indices'
indices_order, single = convert_index_to_keys(self.indices, indices_order)
old_indices = force_list(self.indices.keys())
if indices_order == old_indices:
return
if set(old_indices) != set(indices_order):
raise KeyError('Keys in the new order do not match existing keys')
new_idx = [old_indices.index(i) for i in indices_order]
items = [map(i.__getitem__, new_idx) for i in self.items()]
self.clear(True)
_MI_init(self, items, indices_order) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier identifier block return_statement if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension call identifier argument_list attribute identifier identifier identifier for_in_clause identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list true expression_statement call identifier argument_list identifier identifier identifier | reorder all the indices |
def inject(*injections):
def _decorate(func):
def _decorated(*args, **kwargs):
args = list(args)
keys_to_inject = [name for name in injections if name not in kwargs]
for key in keys_to_inject:
kwargs[key] = get_current_scope().container.get(key)
return func(*args, **kwargs)
return _decorated
return _decorate | module function_definition identifier parameters list_splat_pattern identifier block function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier identifier for_statement identifier identifier block expression_statement assignment subscript identifier identifier call attribute attribute call identifier argument_list identifier identifier argument_list identifier return_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier | Resolves dependencies using global container and passed it with optional parameters |
def Y(self, value):
if isinstance(value, (int, float,
long, types.NoneType)):
self._y = value | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier tuple identifier identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier identifier | sets the Y coordinate |
def __Finish(self, rootTable, sizePrefix):
N.enforce_number(rootTable, N.UOffsetTFlags)
prepSize = N.UOffsetTFlags.bytewidth
if sizePrefix:
prepSize += N.Int32Flags.bytewidth
self.Prep(self.minalign, prepSize)
self.PrependUOffsetTRelative(rootTable)
if sizePrefix:
size = len(self.Bytes) - self.Head()
N.enforce_number(size, N.Int32Flags)
self.PrependInt32(size)
self.finished = True
return self.Head() | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement identifier block expression_statement augmented_assignment identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier binary_operator call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier true return_statement call attribute identifier identifier argument_list | Finish finalizes a buffer, pointing to the given `rootTable`. |
def consume_keys_asynchronous_processes(self):
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
pool = multiprocessing.Pool(processes=jobs, maxtasksperchild=10)
for x in range(jobs):
pool.apply(self.data_worker, [], self.worker_args)
pool.close()
pool.join() | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator binary_operator binary_operator binary_operator string string_start string_content escape_sequence string_end call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end attribute identifier identifier string string_start string_content escape_sequence string_end expression_statement assignment identifier conditional_expression binary_operator call attribute identifier identifier argument_list integer parenthesized_expression comparison_operator binary_operator call attribute identifier identifier argument_list integer call attribute attribute identifier identifier identifier argument_list line_continuation call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier integer for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier list attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Work through the keys to look up asynchronously using multiple processes |
def build_attrs(self, *args, **kwargs):
attrs = super(HeavySelect2Mixin, self).build_attrs(*args, **kwargs)
self.widget_id = signing.dumps(id(self))
attrs['data-field_id'] = self.widget_id
attrs.setdefault('data-ajax--url', self.get_url())
attrs.setdefault('data-ajax--cache', "true")
attrs.setdefault('data-ajax--type', "GET")
attrs.setdefault('data-minimum-input-length', 2)
if self.dependent_fields:
attrs.setdefault('data-select2-dependent-fields', " ".join(self.dependent_fields))
attrs['class'] += ' django-select2-heavy'
return attrs | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement augmented_assignment subscript identifier string string_start string_content string_end string string_start string_content string_end return_statement identifier | Set select2's AJAX attributes. |
def compress(func):
def wrapper(*args, **kwargs):
ret = func(*args, **kwargs)
logger.debug('Receive {} {} request with header: {}'.format(
request.method,
request.url,
['{}: {}'.format(h, request.headers.get(h)) for h in request.headers.keys()]
))
if 'deflate' in request.headers.get('Accept-Encoding', ''):
response.headers['Content-Encoding'] = 'deflate'
ret = deflate_compress(ret)
else:
response.headers['Content-Encoding'] = 'identity'
return ret
def deflate_compress(data, compress_level=6):
zobj = zlib.compressobj(compress_level,
zlib.DEFLATED,
zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL,
zlib.Z_DEFAULT_STRATEGY)
return zobj.compress(b(data)) + zobj.flush()
return wrapper | module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier list_comprehension call attribute string string_start string_content string_end identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end return_statement identifier function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier return_statement binary_operator call attribute identifier identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list return_statement identifier | Compress result with deflate algorithm if the client ask for it. |
def suppress(self, email):
body = {
"EmailAddresses": [email] if isinstance(email, str) else email}
response = self._post(self.uri_for("suppress"), json.dumps(body)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end conditional_expression list identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier | Adds email addresses to a client's suppression list |
def maxCtxContextualRule(maxCtx, st, chain):
if not chain:
return max(maxCtx, st.GlyphCount)
elif chain == 'Reverse':
return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount)
return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyphCount) | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator identifier block return_statement call identifier argument_list identifier attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list identifier binary_operator attribute identifier identifier attribute identifier identifier return_statement call identifier argument_list identifier binary_operator attribute identifier identifier attribute identifier identifier | Calculate usMaxContext based on a contextual feature rule. |
def _from_string(cls, serialized):
library_key = LibraryLocator._from_string(serialized)
parsed_parts = LibraryLocator.parse_url(serialized)
block_id = parsed_parts.get('block_id', None)
if block_id is None:
raise InvalidKeyError(cls, serialized)
block_type = parsed_parts.get('block_type')
if block_type is None:
raise InvalidKeyError(cls, serialized)
return cls(library_key, parsed_parts.get('block_type'), block_id) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier none block raise_statement call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block raise_statement call identifier argument_list identifier identifier return_statement call identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier | Requests LibraryLocator to deserialize its part and then adds the local deserialization of block |
def exclusions(self):
exclusion_rules = [
r.strip()
for r in self.config.get("browser_exclude_rule", "").split(",")
if r.strip()
]
return exclusion_rules | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end if_clause call attribute identifier identifier argument_list return_statement identifier | Return list of browser exclusion rules defined in the Configuration. |
def verify(self, base_path, update=False):
return self.project.verify_submission(base_path, self, update=update) | module function_definition identifier parameters identifier identifier default_parameter identifier false block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier identifier | Verify the submission and return testables that can be executed. |
def updateRouterStatus(self):
print '%s call updateRouterStatus' % self.port
cmd = 'state'
while True:
state = self.__sendCommand(cmd)[0]
if state == 'detached':
continue
elif state == 'child':
break
else:
return False
cmd = 'state router'
return self.__sendCommand(cmd)[0] == 'Done' | module function_definition identifier parameters identifier block print_statement binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier string string_start string_content string_end while_statement true block expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer if_statement comparison_operator identifier string string_start string_content string_end block continue_statement elif_clause comparison_operator identifier string string_start string_content string_end block break_statement else_clause block return_statement false expression_statement assignment identifier string string_start string_content string_end return_statement comparison_operator subscript call attribute identifier identifier argument_list identifier integer string string_start string_content string_end | force update to router as if there is child id request |
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict | module function_definition identifier parameters identifier identifier identifier block import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier for_statement identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier identifier expression_statement assignment identifier call identifier argument_list function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier integer expression_statement assignment identifier call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier none none identifier integer expression_statement assignment identifier call attribute subscript attribute identifier identifier attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator list binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end identifier return_statement identifier | Run spellcheck-linter on matched_filenames. |
def update_view_state(self, view, state):
if view.name not in self:
self[view.name] = Bunch()
self[view.name].update(state) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment subscript identifier attribute identifier identifier call identifier argument_list expression_statement call attribute subscript identifier attribute identifier identifier identifier argument_list identifier | Update the state of a view. |
def _create_multi_buffer_action(self):
icon = resources_path('img', 'icons', 'show-multi-buffer.svg')
self.action_multi_buffer = QAction(
QIcon(icon),
self.tr('Multi Buffer'), self.iface.mainWindow())
self.action_multi_buffer.setStatusTip(self.tr(
'Open InaSAFE multi buffer'))
self.action_multi_buffer.setWhatsThis(self.tr(
'Open InaSAFE multi buffer'))
self.action_multi_buffer.triggered.connect(self.show_multi_buffer)
self.add_action(
self.action_multi_buffer,
add_to_toolbar=self.full_toolbar) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Create action for multi buffer dialog. |
def delete_intf_router(self, name, tenant_id, rout_id, subnet_lst):
try:
for subnet_id in subnet_lst:
body = {'subnet_id': subnet_id}
intf = self.neutronclient.remove_interface_router(rout_id,
body=body)
intf.get('id')
except Exception as exc:
LOG.error("Failed to delete router interface %(name)s, "
" Exc %(exc)s", {'name': name, 'exc': str(exc)})
return False
return True | module function_definition identifier parameters identifier identifier identifier identifier identifier block try_statement block for_statement identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call identifier argument_list identifier return_statement false return_statement true | Delete the openstack router and remove the interfaces attached. |
def debug_callback(event, *args, **kwds):
l = ['event %s' % (event.type,)]
if args:
l.extend(map(str, args))
if kwds:
l.extend(sorted('%s=%s' % t for t in kwds.items()))
print('Debug callback (%s)' % ', '.join(l)) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list binary_operator string string_start string_content string_end tuple attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call identifier generator_expression binary_operator string string_start string_content string_end identifier for_in_clause identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier | Example callback, useful for debugging. |
def increase_and_check_counter(self):
self.counter += 1
self.counter %= self.period
if not self.counter:
return True
else:
return False | module function_definition identifier parameters identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement augmented_assignment attribute identifier identifier attribute identifier identifier if_statement not_operator attribute identifier identifier block return_statement true else_clause block return_statement false | increase counter by one and check whether a period is end |
def add_epoch_number(batch: Batch, epoch: int) -> Batch:
for instance in batch.instances:
instance.fields['epoch_num'] = MetadataField(epoch)
return batch | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block for_statement identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list identifier return_statement identifier | Add the epoch number to the batch instances as a MetadataField. |
def _unicode_decode_extracted_tb(extracted_tb):
return [(_decode(file), line_number, _decode(function), _decode(text))
for file, line_number, function, text in extracted_tb] | module function_definition identifier parameters identifier block return_statement list_comprehension tuple call identifier argument_list identifier identifier call identifier argument_list identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier identifier identifier identifier | Return a traceback with the string elements translated into Unicode. |
def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate:
def inverse_predicate(graph: BELGraph, node: BaseEntity) -> bool:
return not node_predicate(graph, node)
return inverse_predicate | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block return_statement not_operator call identifier argument_list identifier identifier return_statement identifier | Build a node predicate that is the inverse of the given node predicate. |
def taxon_info(taxid, ncbi, outFH):
taxid = int(taxid)
tax_name = ncbi.get_taxid_translator([taxid])[taxid]
rank = list(ncbi.get_rank([taxid]).values())[0]
lineage = ncbi.get_taxid_translator(ncbi.get_lineage(taxid))
lineage = ['{}:{}'.format(k,v) for k,v in lineage.items()]
lineage = ';'.join(lineage)
x = [str(x) for x in [tax_name, taxid, rank, lineage]]
outFH.write('\t'.join(x) + '\n') | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list list identifier identifier expression_statement assignment identifier subscript call identifier argument_list call attribute call attribute identifier identifier argument_list list identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension call attribute string string_start string_content string_end identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier string string_start string_content escape_sequence string_end | Write info on taxid |
def pause_resume(self):
if self.is_paused():
urlopen(self.url + "&mode=resume")
else:
urlopen(self.url + "&mode=pause") | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement call identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end else_clause block expression_statement call identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end | Toggle between pausing or resuming downloading. |
def _DecodeUnrecognizedFields(message, pair_type):
new_values = []
codec = _ProtoJsonApiTools.Get()
for unknown_field in message.all_unrecognized_fields():
value, _ = message.get_unrecognized_field_info(unknown_field)
value_type = pair_type.field_by_name('value')
if isinstance(value_type, messages.MessageField):
decoded_value = DictToMessage(value, pair_type.value.message_type)
else:
decoded_value = codec.decode_field(
pair_type.value, value)
try:
new_pair_key = str(unknown_field)
except UnicodeEncodeError:
new_pair_key = protojson.ProtoJson().decode_field(
pair_type.key, unknown_field)
new_pair = pair_type(key=new_pair_key, value=decoded_value)
new_values.append(new_pair)
return new_values | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier attribute attribute identifier identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Process unrecognized fields in message. |
def update(self, cont):
self.max_time = max(self.max_time, cont.max_time)
if cont.items is not None:
if self.items is None:
self.items = cont.items
else:
self.items.update(cont.items) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Update this instance with the contextualize passed. |
def repo(name: str, owner: str) -> snug.Query[dict]:
return json.loads((yield f'/repos/{owner}/{name}').content) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type subscript attribute identifier identifier identifier block return_statement call attribute identifier identifier argument_list attribute parenthesized_expression yield string string_start string_content interpolation identifier string_content interpolation identifier string_end identifier | a repository lookup by owner and name |
def initStats(self):
url = "%s://%s:%d/%s" % (self._proto, self._host, self._port,
self._statuspath)
response = util.get_url(url, self._user, self._password)
self._statusDict = {}
for line in response.splitlines():
mobj = re.match('\s*(\d+)\s+(\d+)\s+(\d+)\s*$', line)
if mobj:
idx = 0
for key in ('accepts','handled','requests'):
idx += 1
self._statusDict[key] = util.parse_value(mobj.group(idx))
else:
for (key,val) in re.findall('(\w+):\s*(\d+)', line):
self._statusDict[key.lower()] = util.parse_value(val) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier integer for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement augmented_assignment identifier integer expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier else_clause block for_statement tuple_pattern identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier | Query and parse Nginx Web Server Status Page. |
def compare_config(self):
if self.config_session is None:
return ''
else:
commands = ['show session-config named %s diffs' % self.config_session]
result = self.device.run_commands(commands, encoding='text')[0]['output']
result = '\n'.join(result.splitlines()[2:])
return result.strip() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement string string_start string_end else_clause block expression_statement assignment identifier list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier subscript subscript call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end integer string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript call attribute identifier identifier argument_list slice integer return_statement call attribute identifier identifier argument_list | Implementation of NAPALM method compare_config. |
def rows(self):
for t in self.terms:
for row in t.rows:
term, value = row
if isinstance(value, dict):
term, args, remain = self._args(term, value)
yield term, args
for k, v in remain.items():
yield term.split('.')[-1] + '.' + k, v
else:
yield row | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier expression_statement yield expression_list identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement yield expression_list binary_operator binary_operator subscript call attribute identifier identifier argument_list string string_start string_content string_end unary_operator integer string string_start string_content string_end identifier identifier else_clause block expression_statement yield identifier | Yield rows for the section |
def rollback(self):
commands = []
commands.append('configure replace flash:rollback-0')
commands.append('write memory')
self.device.run_commands(commands) | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Implementation of NAPALM method rollback. |
def ssh(cls, vm_id, login, identity, args=None):
cmd = ['ssh']
if identity:
cmd.extend(('-i', identity,))
version, ip_addr = cls.vm_ip(vm_id)
if version == 6:
cmd.append('-6')
if not ip_addr:
cls.echo('No IP address found for vm %s, aborting.' % vm_id)
return
cmd.append('%s@%s' % (login, ip_addr,))
if args:
cmd.extend(args)
cls.echo('Requesting access using: %s ...' % ' '.join(cmd))
return cls.execute(cmd, False) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier list string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier false | Spawn an ssh session to virtual machine. |
def create_signaling(args):
if args.signaling == 'tcp-socket':
return TcpSocketSignaling(args.signaling_host, args.signaling_port)
elif args.signaling == 'unix-socket':
return UnixSocketSignaling(args.signaling_path)
else:
return CopyAndPasteSignaling() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call identifier argument_list attribute identifier identifier else_clause block return_statement call identifier argument_list | Create a signaling method based on command-line arguments. |
def delete_port_postcommit(self, context):
port = context.current
log_context("delete_port_postcommit: port", port)
self._delete_port_resources(port, context.host)
self._try_to_release_dynamic_segment(context) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Delete the port from CVX |
def exit_if_path_not_found(path):
if not os.path.exists(path):
ui.error(c.MESSAGES["path_missing"], path)
sys.exit(1) | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list integer | Exit if the path is not found. |
def __update(self):
width, height = self.size
super(BaseWidget, self).__setattr__("width", width)
super(BaseWidget, self).__setattr__("height", height)
super(BaseWidget, self).__setattr__(self.anchor, self.pos) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier | This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks. |
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
return conv_block_internal(conv1d, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list identifier identifier identifier identifier dictionary_splat identifier | A block of standard 1d convolutions. |
def load_registered_fixtures(context):
runner = context._runner
step_registry = getattr(runner, 'step_registry', None)
if not step_registry:
step_registry = module_step_registry.registry
for step in context.scenario.all_steps:
match = step_registry.find_match(step)
if match and hasattr(match.func, 'registered_fixtures'):
if not context.test.fixtures:
context.test.fixtures = []
context.test.fixtures.extend(match.func.registered_fixtures) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement not_operator identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end block if_statement not_operator attribute attribute identifier identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier | Apply fixtures that are registered with the @fixtures decorator. |
def citation_director(**kwargs):
qualifier = kwargs.get('qualifier', '')
content = kwargs.get('content', '')
if qualifier == 'publicationTitle':
return CitationJournalTitle(content=content)
elif qualifier == 'volume':
return CitationVolume(content=content)
elif qualifier == 'issue':
return CitationIssue(content=content)
elif qualifier == 'pageStart':
return CitationFirstpage(content=content)
elif qualifier == 'pageEnd':
return CitationLastpage(content=content)
else:
return None | module function_definition identifier parameters dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end if_statement comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier identifier else_clause block return_statement none | Direct the citation elements based on their qualifier. |
def filter_input(keys, raw):
if len(keys) == 1:
if keys[0] in UI.keys['up']:
keys[0] = 'up'
elif keys[0] in UI.keys['down']:
keys[0] = 'down'
elif len(keys[0]) == 4 and keys[0][0] == 'mouse press':
if keys[0][1] == 4:
keys[0] = 'up'
elif keys[0][1] == 5:
keys[0] = 'down'
return keys | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator subscript identifier integer subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment subscript identifier integer string string_start string_content string_end elif_clause comparison_operator subscript identifier integer subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment subscript identifier integer string string_start string_content string_end elif_clause boolean_operator comparison_operator call identifier argument_list subscript identifier integer integer comparison_operator subscript subscript identifier integer integer string string_start string_content string_end block if_statement comparison_operator subscript subscript identifier integer integer integer block expression_statement assignment subscript identifier integer string string_start string_content string_end elif_clause comparison_operator subscript subscript identifier integer integer integer block expression_statement assignment subscript identifier integer string string_start string_content string_end return_statement identifier | Adds fancy mouse wheel functionality and VI navigation to ListBox |
def get(cls, object_version, key):
return cls.query.filter_by(
version_id=as_object_version_id(object_version),
key=key,
).one_or_none() | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call identifier argument_list identifier keyword_argument identifier identifier identifier argument_list | Get the tag object. |
def resume(self):
with self._wake:
self._paused = False
self._wake.notifyAll() | module function_definition identifier parameters identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement assignment attribute identifier identifier false expression_statement call attribute attribute identifier identifier identifier argument_list | Resumes the response stream. |
def to_gpu(x, *args, **kwargs):
return x.cuda(*args, **kwargs) if USE_GPU else x | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement conditional_expression call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier identifier identifier | puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. |
def add_text(self, setting, width=300, height=100, multiline=False):
tab = self.panel(setting.tab)
if multiline:
ctrl = wx.TextCtrl(tab, -1, "", size=(width,height), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
else:
ctrl = wx.TextCtrl(tab, -1, "", size=(width,-1) )
self._add_input(setting, ctrl) | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier unary_operator integer string string_start string_end keyword_argument identifier tuple identifier identifier keyword_argument identifier binary_operator attribute identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier unary_operator integer string string_start string_end keyword_argument identifier tuple identifier unary_operator integer expression_statement call attribute identifier identifier argument_list identifier identifier | add a text input line |
def read_ical(self, ical_file_location):
with open(ical_file_location, 'r') as ical_file:
data = ical_file.read()
self.cal = Calendar.from_ical(data)
return self.cal | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement attribute identifier identifier | Read the ical file |
def asinh(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_asinh,
(BigFloat._implicit_convert(x),),
context,
) | module function_definition identifier parameters identifier default_parameter identifier none block return_statement call identifier argument_list identifier attribute identifier identifier tuple call attribute identifier identifier argument_list identifier identifier | Return the inverse hyperbolic sine of x. |
def visit_import(self, node, parent):
names = [(alias.name, alias.asname) for alias in node.names]
newnode = nodes.Import(
names,
getattr(node, "lineno", None),
getattr(node, "col_offset", None),
parent,
)
for (name, asname) in newnode.names:
name = asname or name
parent.set_local(name.split(".")[0], newnode)
return newnode | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list_comprehension tuple attribute identifier identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier string string_start string_content string_end none call identifier argument_list identifier string string_start string_content string_end none identifier for_statement tuple_pattern identifier identifier attribute identifier identifier block expression_statement assignment identifier boolean_operator identifier identifier expression_statement call attribute identifier identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end integer identifier return_statement identifier | visit a Import node by returning a fresh instance of it |
def _parse_complex_list(self, prop):
xpath_root = self._get_xroot_for(prop)
xpath_map = self._data_structures[prop]
return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier identifier return_statement call identifier argument_list attribute identifier identifier identifier identifier identifier | Default parsing operation for lists of complex structs |
def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]:
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return cursor.fetchone()
except:
log.exception("fetchone: SQL was: " + sql)
raise | module function_definition identifier parameters identifier typed_parameter identifier type identifier list_splat_pattern identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier list_splat identifier try_statement block return_statement call attribute identifier identifier argument_list except_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier raise_statement | Executes SQL; returns the first row, or None. |
def dependencies(source):
loader = ClassLoader(source, max_cache=-1)
all_dependencies = set()
for klass in loader.classes:
new_dependencies = loader.dependencies(klass) - all_dependencies
all_dependencies.update(new_dependencies)
for new_dep in new_dependencies:
click.echo(new_dep) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier unary_operator integer expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Output a list of all classes referenced by the given source. |
def move(self, dst):
if self.drive != dst.drive:
raise NotImplementedError(
"Moving between instances is not implemented yet")
self._accessor.move(self, dst) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier 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 identifier | Move artifact from this path to destinaiton. |
def copy(self):
params = {}
for key, val in self.__dict__.items():
if 'matrix' not in key:
k = key[1:] if key[0] == '_' else key
params[k] = val
return self.__class__(**params) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier conditional_expression subscript identifier slice integer comparison_operator subscript identifier integer string string_start string_content string_end identifier expression_statement assignment subscript identifier identifier identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Returns a copy of the projection matrix |
def render(self, name, value, attrs=None, renderer=None):
if django.VERSION >= (1, 11):
return super(BetterFileInput, self).render(name, value, attrs)
t = render_to_string(
template_name=self.template_name,
context=self.get_context(name, value, attrs),
)
return mark_safe(t) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator attribute identifier identifier tuple integer integer block return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier identifier identifier return_statement call identifier argument_list identifier | For django 1.10 compatibility |
def app_stop(device_id, app_id):
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].stop_app(app_id)
return jsonify(success=success) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier block expression_statement call identifier argument_list integer if_statement not_operator call identifier argument_list identifier block expression_statement call identifier argument_list integer if_statement comparison_operator identifier identifier block expression_statement call identifier argument_list integer expression_statement assignment identifier call attribute subscript identifier identifier identifier argument_list identifier return_statement call identifier argument_list keyword_argument identifier identifier | stops an app with corresponding package name |
async def read_frame(self, max_size: int) -> Frame:
frame = await Frame.read(
self.reader.readexactly,
mask=not self.is_client,
max_size=max_size,
extensions=self.extensions,
)
logger.debug("%s < %r", self.side, frame)
return frame | module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier not_operator attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier return_statement identifier | Read a single frame from the connection. |
def submit(self, *args, func=None, monitor=None):
monitor = monitor or self.monitor
func = func or self.task_func
if not hasattr(self, 'socket'):
self.__class__.running_tasks = self.tasks
self.socket = Socket(self.receiver, zmq.PULL, 'bind').__enter__()
monitor.backurl = 'tcp://%s:%s' % (
config.dbserver.host, self.socket.port)
assert not isinstance(args[-1], Monitor)
dist = 'no' if self.num_tasks == 1 else self.distribute
if dist != 'no':
args = pickle_sequence(args)
self.sent += numpy.array([len(p) for p in args])
res = submit[dist](self, func, args, monitor)
self.tasks.append(res) | module function_definition identifier parameters identifier list_splat_pattern identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier attribute identifier identifier expression_statement assignment identifier boolean_operator identifier attribute identifier identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute call identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_content string_end identifier argument_list expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier assert_statement not_operator call identifier argument_list subscript identifier unary_operator integer identifier expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator attribute identifier identifier integer attribute identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier call attribute identifier identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call subscript identifier identifier argument_list identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Submit the given arguments to the underlying task |
def visit_UnaryOperation(self, node):
if node.op.nature == Nature.PLUS:
return +self.visit(node.right)
elif node.op.nature == Nature.MINUS:
return -self.visit(node.right)
elif node.op.nature == Nature.NOT:
return Bool(not self.visit(node.right)) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier attribute identifier identifier block return_statement unary_operator call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator attribute attribute identifier identifier identifier attribute identifier identifier block return_statement unary_operator call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator attribute attribute identifier identifier identifier attribute identifier identifier block return_statement call identifier argument_list not_operator call attribute identifier identifier argument_list attribute identifier identifier | Visitor for `UnaryOperation` AST node. |
def _chunk(self, response, size=4096):
method = response.headers.get("content-encoding")
if method == "gzip":
d = zlib.decompressobj(16+zlib.MAX_WBITS)
b = response.read(size)
while b:
data = d.decompress(b)
yield data
b = response.read(size)
del data
else:
while True:
chunk = response.read(size)
if not chunk: break
yield chunk | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator integer attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier while_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement yield identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier delete_statement identifier else_clause block while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block break_statement expression_statement yield identifier | downloads a web response in pieces |
def _get_metadata_model(name=None):
if name is not None:
try:
return registry[name]
except KeyError:
if len(registry) == 1:
valid_names = 'Try using the name "%s" or simply leaving it '\
'out altogether.' % list(registry)[0]
else:
valid_names = "Valid names are " + ", ".join(
'"%s"' % k for k in list(registry))
raise Exception(
"Metadata definition with name \"%s\" does not exist.\n%s" % (
name, valid_names))
else:
assert len(registry) == 1, \
"You must have exactly one Metadata class, if using " \
"get_metadata() without a 'name' parameter."
return list(registry.values())[0] | module function_definition identifier parameters default_parameter identifier none block if_statement comparison_operator identifier none block try_statement block return_statement subscript identifier identifier except_clause identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end subscript call identifier argument_list identifier integer else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier generator_expression binary_operator string string_start string_content string_end identifier for_in_clause identifier call identifier argument_list identifier raise_statement call identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence escape_sequence string_end tuple identifier identifier else_clause block assert_statement comparison_operator call identifier argument_list identifier integer concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement subscript call identifier argument_list call attribute identifier identifier argument_list integer | Find registered Metadata object. |
def linebreaks_safe(value, autoescape=True):
if isinstance(value, string_types) and '\n' in value:
return linebreaks_filter(value, autoescape=autoescape)
return value | module function_definition identifier parameters identifier default_parameter identifier true block if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator string string_start string_content escape_sequence string_end identifier block return_statement call identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Adds linebreaks only for text that has a newline character. |
def _handle_tag_defineshape4(self):
obj = _make_object("DefineShape4")
obj.ShapeId = unpack_ui16(self._src)
obj.ShapeBounds = self._get_struct_rect()
obj.EdgeBounds = self._get_struct_rect()
bc = BitConsumer(self._src)
bc.u_get(5)
obj.UsesFillWindingRule = bc.u_get(1)
obj.UsesNonScalingStrokes = bc.u_get(1)
obj.UsesScalingStrokes = bc.u_get(1)
obj.Shapes = self._get_struct_shapewithstyle(4)
return obj | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer return_statement identifier | Handle the DefineShape4 tag. |
def clear(self):
self._config = configparser.RawConfigParser()
self._override_config = {}
self.read_config() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier dictionary expression_statement call attribute identifier identifier argument_list | Restart with a clean config |
def error_state(self):
self.buildstate.state.lasttime = time()
self.buildstate.commit()
return self.buildstate.state.error | module function_definition identifier parameters identifier block expression_statement assignment attribute attribute attribute identifier identifier identifier identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list return_statement attribute attribute attribute identifier identifier identifier identifier | Set the error condition |
def _parse_desc(node):
desc = ''
if len(node) == 0:
return '<p>' + node.text + '</p>'
for n in node:
if n.tag == 'p':
desc += '<p>' + _join_lines(n.text) + '</p>'
elif n.tag == 'ol' or n.tag == 'ul':
desc += '<ul>'
for c in n:
if c.tag == 'li':
desc += '<li>' + _join_lines(c.text) + '</li>'
else:
raise ParseError('Expected <li> in <%s>, got <%s>' % (n.tag, c.tag))
desc += '</ul>'
else:
raise ParseError('Expected <p>, <ul>, <ol> in <%s>, got <%s>' % (node.tag, n.tag))
return desc | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator call identifier argument_list identifier integer block return_statement binary_operator binary_operator string string_start string_content string_end attribute identifier identifier string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end elif_clause boolean_operator comparison_operator attribute identifier identifier string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment identifier string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier return_statement identifier | A quick'n'dirty description parser |
def parseFeed(filename, yesterday):
dom = xml.dom.minidom.parse(filename)
getText = lambda node, tag: node.getElementsByTagName(tag)[0].childNodes[0].data
getNode = lambda tag: dom.getElementsByTagName(tag)
content = getNode('channel')[0]
feedTitle = getText(content, 'title')
feedLink = getText(content, 'link')
feedDesc = getText(content, 'description')
feed = Feed(feedTitle, feedLink, feedDesc)
for item in getNode('item'):
itemDate = time.strptime(getText(item, 'pubDate'), '%a, %d %b %Y %H:%M:%S GMT')
if (itemDate > yesterday):
feed.addItem(getText(item, 'title'),
getText(item, 'link'),
getText(item, 'description'),
getText(item, 'pubDate'))
return feed | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment identifier lambda lambda_parameters identifier identifier attribute subscript attribute subscript call attribute identifier identifier argument_list identifier integer identifier integer identifier expression_statement assignment identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript call identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier identifier for_statement identifier call identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end if_statement parenthesized_expression comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end return_statement identifier | Parse an RSS feed and filter only entries that are newer than yesterday. |
def _set_allowed_services_and_actions(self, services):
for service in services:
self.services[service['name']] = {}
for action in service['actions']:
name = action.pop('name')
self.services[service['name']][name] = action | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment subscript attribute identifier identifier subscript identifier string string_start string_content string_end dictionary for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript subscript attribute identifier identifier subscript identifier string string_start string_content string_end identifier identifier | Expect services to be a list of service dictionaries, each with `name` and `actions` keys. |
async def update_trend_data(self, startdate, enddate):
url = '{}/users/{}/trends'.format(API_URL, self.userid)
params = {
'tz': self.device.tzone,
'from': startdate,
'to': enddate
}
trends = await self.device.api_get(url, params)
if trends is None:
_LOGGER.error('Unable to fetch eight trend data.')
else:
self.trends = trends['days'] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end | Update trends data json for specified time period. |
def extract_hosted_zip(data_url, save_dir, exclude_term=None):
zip_name = os.path.join(save_dir, 'temp.zip')
try:
print('Downloading %r to %r' % (data_url, zip_name))
zip_name, hdrs = urllib.request.urlretrieve(url=data_url, filename=zip_name)
print('Download successfully completed')
except IOError as e:
print("Could not successfully retrieve %r" % data_url)
raise e
extract_zip(zip_name=zip_name, exclude_term=exclude_term)
os.unlink(zip_name)
print("Extraction Complete") | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end try_statement block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier raise_statement identifier expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end | Downloads, then extracts a zip file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.