code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def pair(self):
if self.set_val is not None:
return self.env_name, self.set_val
elif self.default_val is not None:
return self.env_name, os.environ.get(self.env_name, self.default_val)
else:
return self.env_name, os.environ[self.env_name] | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_list attribute identifier identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier none block return_statement expression_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier else_clause block return_statement expression_list attribute identifier identifier subscript attribute identifier identifier attribute identifier identifier | Get the name and value for this environment variable |
def reject(self):
self.canvas.unsetMapTool(self.tool)
if self.previous_map_tool != self.tool:
self.canvas.setMapTool(self.previous_map_tool)
self.tool.reset()
self.extent_selector_closed.emit()
super(ExtentSelectorDialog, self).reject() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list | User rejected the rectangle. |
def _Decode(self, codec_name, data):
try:
return data.decode(codec_name, "replace")
except LookupError:
raise RuntimeError("Codec could not be found.")
except AssertionError:
raise RuntimeError("Codec failed to decode") | module function_definition identifier parameters identifier identifier identifier block try_statement block return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end | Decode data with the given codec name. |
def decode(var, encoding):
if PY2:
if isinstance(var, unicode):
ret = var
elif isinstance(var, str):
if encoding:
ret = var.decode(encoding)
else:
ret = unicode(var)
else:
ret = unicode(var)
else:
ret = str(var)
return ret | module function_definition identifier parameters identifier identifier block if_statement identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | If not already unicode, decode it. |
def to_tzolkin(jd):
lcount = trunc(jd) + 0.5 - EPOCH
day = amod(lcount + 4, 13)
name = amod(lcount + 20, 20)
return int(day), TZOLKIN_NAMES[int(name) - 1] | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator call identifier argument_list identifier float identifier expression_statement assignment identifier call identifier argument_list binary_operator identifier integer integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer integer return_statement expression_list call identifier argument_list identifier subscript identifier binary_operator call identifier argument_list identifier integer | Determine Mayan Tzolkin "month" and day from Julian day |
def emit(self, *args, **kwargs):
if self._block:
return
for slot in self._slots:
if not slot:
continue
elif isinstance(slot, partial):
slot()
elif isinstance(slot, weakref.WeakKeyDictionary):
for obj, method in slot.items():
method(obj, *args, **kwargs)
elif isinstance(slot, weakref.ref):
if (slot() is not None):
slot()(*args, **kwargs)
else:
slot(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement attribute identifier identifier block return_statement for_statement identifier attribute identifier identifier block if_statement not_operator identifier block continue_statement elif_clause call identifier argument_list identifier identifier block expression_statement call identifier argument_list elif_clause call identifier argument_list identifier attribute identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier elif_clause call identifier argument_list identifier attribute identifier identifier block if_statement parenthesized_expression comparison_operator call identifier argument_list none block expression_statement call call identifier argument_list argument_list list_splat identifier dictionary_splat identifier else_clause block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier | Calls all the connected slots with the provided args and kwargs unless block is activated |
def output_sshkey(gandi, sshkey, output_keys, justify=12):
output_generic(gandi, sshkey, output_keys, justify) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement call identifier argument_list identifier identifier identifier identifier | Helper to output an ssh key information. |
def match(self, objects: List[Any]) -> bool:
s = self._make_string(objects)
m = self._compiled_expression.match(s)
return m is not None | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement comparison_operator identifier none | Return True if the list of objects matches the expression. |
def setCurrentRegItem(self, regItem):
check_class(regItem, ClassRegItem, allow_none=True)
self.tableView.setCurrentRegItem(regItem) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier identifier keyword_argument identifier true expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Sets the current item to the regItem |
def _handle_entity(self, token):
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityNumeric):
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityHex):
text = self._tokens.pop()
self._tokens.pop()
return HTMLEntity(text.text, named=False, hexadecimal=True,
hex_char=token.char)
self._tokens.pop()
return HTMLEntity(token.text, named=False, hexadecimal=False)
self._tokens.pop()
return HTMLEntity(token.text, named=True, hexadecimal=False) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier false keyword_argument identifier true keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier false keyword_argument identifier false expression_statement call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier true keyword_argument identifier false | Handle a case where an HTML entity is at the head of the tokens. |
def Kgrad_param_num(self,i,h=1e-4):
params = self.getParams()
e = sp.zeros_like(params); e[i] = 1
self.setParams(params-h*e)
C_L = self.K()
self.setParams(params+h*e)
C_R = self.K()
self.setParams(params)
RV = (C_R-C_L)/(2*h)
return RV | module function_definition identifier parameters identifier identifier default_parameter identifier float block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier integer expression_statement call attribute identifier identifier argument_list binary_operator identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator integer identifier return_statement identifier | check discrepancies between numerical and analytical gradients |
def reset(self):
self.num_inst = 0
self.sum_metric = 0.0
self.global_num_inst = 0
self.global_sum_metric = 0.0 | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier float | Resets the internal evaluation result to initial state. |
def assignQuery(self):
self.uiRecordTREE.setQuery(self._queryWidget.query(), autoRefresh=True) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true | Assigns the query from the query widget to the edit. |
def load_global_settings():
with open(settings_path, 'r') as settings_f:
global global_settings
settings_json = json.loads(settings_f.read())
if global_settings is None:
global_settings = settings_json
global_settings[u'package_path'] = package_dir
else:
for k, v in settings_json.items():
if type(v) == dict:
global_settings[k].update(v)
else:
global_settings[k] = v | module function_definition identifier parameters 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 global_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier identifier identifier | Loads settings file containing paths to dependencies and other optional configuration elements. |
def to(self, unit):
if not _has_astropy:
raise ImportError("astropy must be installed for unit/quantity support")
if self.unit is None:
raise ValueError("no units currently set")
if not is_unit_or_unitstring(unit)[0]:
raise ValueError("unit not recognized")
mult_factor = self.unit.to(unit)
copy = self.copy() * mult_factor
copy.unit = unit
return copy | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator subscript call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | convert between units. Returns a new nparray object with the new units |
def grok_ttl(secret):
ttl_obj = {}
lease_msg = ''
if 'lease' in secret:
ttl_obj['lease'] = secret['lease']
lease_msg = "lease:%s" % (ttl_obj['lease'])
if 'lease_max' in secret:
ttl_obj['lease_max'] = secret['lease_max']
elif 'lease' in ttl_obj:
ttl_obj['lease_max'] = ttl_obj['lease']
if 'lease_max' in ttl_obj:
lease_msg = "%s lease_max:%s" % (lease_msg, ttl_obj['lease_max'])
return ttl_obj, lease_msg | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier string string_start string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier subscript identifier string string_start string_content string_end return_statement expression_list identifier identifier | Parses the TTL information |
def _hammer_function_precompute(self,x0, L, Min, model):
if x0 is None: return None, None
if len(x0.shape)==1: x0 = x0[None,:]
m = model.predict(x0)[0]
pred = model.predict(x0)[1].copy()
pred[pred<1e-16] = 1e-16
s = np.sqrt(pred)
r_x0 = (m-Min)/L
s_x0 = s/L
r_x0 = r_x0.flatten()
s_x0 = s_x0.flatten()
return r_x0, s_x0 | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier none block return_statement expression_list none none if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier subscript identifier none slice expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute subscript call attribute identifier identifier argument_list identifier integer identifier argument_list expression_statement assignment subscript identifier comparison_operator identifier float float expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list return_statement expression_list identifier identifier | Pre-computes the parameters of a penalizer centered at x0. |
def _load_account(self, acct_id, acct_dir_path):
self._config[acct_id] = {
'name': None,
'role_name': DEFAULT_ROLE_NAME,
'regions': {}
}
with open(os.path.join(acct_dir_path, 'config.json'), 'r') as fh:
acct_conf = json.loads(fh.read())
self._config[acct_id].update(acct_conf)
for region_name in os.listdir(acct_dir_path):
path = os.path.join(acct_dir_path, region_name)
if not os.path.isdir(path):
continue
self._load_region(acct_id, region_name, path) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier dictionary pair string string_start string_content string_end none pair string string_start string_content string_end identifier pair string string_start string_content string_end dictionary with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block continue_statement expression_statement call attribute identifier identifier argument_list identifier identifier identifier | load configuration from one per-account subdirectory |
def render_exception_js(self, exception):
from .http import JsonResponse
response = {}
response["error"] = exception.error
response["error_description"] = exception.reason
return JsonResponse(response, status=getattr(exception, 'code', 400)) | module function_definition identifier parameters identifier identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier string string_start string_content string_end integer | Return a response with the body containing a JSON-formatter version of the exception. |
def ipopo_instances(self):
try:
with use_ipopo(self.__context) as ipopo:
return {
instance[0]: ipopo.get_instance_details(instance[0])
for instance in ipopo.get_instances()
}
except BundleException:
return None | module function_definition identifier parameters identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier as_pattern_target identifier block return_statement dictionary_comprehension pair subscript identifier integer call attribute identifier identifier argument_list subscript identifier integer for_in_clause identifier call attribute identifier identifier argument_list except_clause identifier block return_statement none | List of iPOPO instances |
def copy(self, klass=None):
chain = (
klass if klass else self.__class__
)(*self._args, **self._kwargs)
chain._tokens = self._tokens.copy()
return chain | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call parenthesized_expression conditional_expression identifier identifier attribute identifier identifier argument_list list_splat attribute identifier identifier dictionary_splat attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list return_statement identifier | Create a new instance of the current chain. |
def score_for_task(properties, category, result):
assert result is not None
if properties and Property.create_from_names(properties).is_svcomp:
return _svcomp_score(category, result)
return None | module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator identifier none if_statement boolean_operator identifier attribute call attribute identifier identifier argument_list identifier identifier block return_statement call identifier argument_list identifier identifier return_statement none | Return the possible score of task, depending on whether the result is correct or not. |
def mpool(self,
k_height,
k_width,
d_height=2,
d_width=2,
mode="VALID",
input_layer=None,
num_channels_in=None):
return self._pool("mpool", pooling_layers.max_pooling2d, k_height,
k_width, d_height, d_width, mode, input_layer,
num_channels_in) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier identifier identifier identifier identifier identifier identifier | Construct a max pooling layer. |
def configure_cmake(self):
cmake = CMake(self)
cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False
cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared
cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared
cmake.configure()
return cmake | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end false expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end not_operator attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Create CMake instance and execute configure step |
def profiles(self):
limit = []
if self.is_admin():
limit.append(_("Administrator"))
limit.sort()
return limit | module function_definition identifier parameters identifier block expression_statement assignment identifier list if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list return_statement identifier | return the rolls this people is related with |
def action_aggregate(reader, *args):
all_aggregated = aggregated_records(reader)
first_row = next(all_aggregated)
keys = sorted(first_row.keys())
print(*keys, sep='\t')
iterable = chain([first_row], all_aggregated)
for item in iterable:
print(*[item[k] for k in keys], sep='\t') | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list list_splat identifier keyword_argument identifier string string_start string_content escape_sequence string_end expression_statement assignment identifier call identifier argument_list list identifier identifier for_statement identifier identifier block expression_statement call identifier argument_list list_splat list_comprehension subscript identifier identifier for_in_clause identifier identifier keyword_argument identifier string string_start string_content escape_sequence string_end | Aggregate flow records by 5-tuple and print a tab-separated stream |
def save_location(self, filename: str, location: PostLocation, mtime: datetime) -> None:
filename += '_location.txt'
location_string = (location.name + "\n" +
"https://maps.google.com/maps?q={0},{1}&ll={0},{1}\n".format(location.lat,
location.lng))
with open(filename, 'wb') as text_file:
shutil.copyfileobj(BytesIO(location_string.encode()), text_file)
os.utime(filename, (datetime.now().timestamp(), mtime.timestamp()))
self.context.log('geo', end=' ', flush=True) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement assignment identifier parenthesized_expression binary_operator binary_operator attribute identifier identifier string string_start string_content escape_sequence string_end call attribute string string_start string_content escape_sequence string_end identifier argument_list attribute identifier identifier attribute identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier tuple call attribute call attribute identifier identifier argument_list identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier true | Save post location name and Google Maps link. |
def body_block_image_content(tag):
"format a graphic or inline-graphic into a body block json format"
image_content = OrderedDict()
if tag:
copy_attribute(tag.attrs, 'xlink:href', image_content, 'uri')
if "uri" in image_content:
set_if_value(image_content, "alt", "")
return image_content | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list if_statement identifier block expression_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list identifier string string_start string_content string_end string string_start string_end return_statement identifier | format a graphic or inline-graphic into a body block json format |
def write_display(self):
for i, value in enumerate(self.buffer):
self._device.write8(i, value) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Write display buffer to display hardware. |
def _validate_edges_do_not_have_extra_links(class_name, properties):
for property_name, property_descriptor in six.iteritems(properties):
if property_name in {EDGE_SOURCE_PROPERTY_NAME, EDGE_DESTINATION_PROPERTY_NAME}:
continue
if property_descriptor.type_id == PROPERTY_TYPE_LINK_ID:
raise IllegalSchemaStateError(u'Edge class "{}" has a property of type Link that is '
u'not an edge endpoint, this is not allowed: '
u'{}'.format(class_name, property_name)) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator identifier set identifier identifier block continue_statement if_statement comparison_operator attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier | Validate that edges do not have properties of Link type that aren't the edge endpoints. |
def clear(self) -> None:
self._headers = httputil.HTTPHeaders(
{
"Server": "TornadoServer/%s" % tornado.version,
"Content-Type": "text/html; charset=UTF-8",
"Date": httputil.format_timestamp(time.time()),
}
)
self.set_default_headers()
self._write_buffer = []
self._status_code = 200
self._reason = httputil.responses[200] | module function_definition identifier parameters identifier type none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier subscript attribute identifier identifier integer | Resets all headers and content for this response. |
def _parse_quoted_key(self):
quote_style = self._current
key_type = None
dotted = False
for t in KeyType:
if t.value == quote_style:
key_type = t
break
if key_type is None:
raise RuntimeError("Should not have entered _parse_quoted_key()")
self.inc()
self.mark()
while self._current != quote_style and self.inc():
pass
key = self.extract()
if self._current == ".":
self.inc()
dotted = True
key += "." + self._parse_key().as_string()
key_type = KeyType.Bare
else:
self.inc()
return Key(key, key_type, "", dotted) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier none expression_statement assignment identifier false for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier identifier break_statement if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list while_statement boolean_operator comparison_operator attribute identifier identifier identifier call attribute identifier identifier argument_list block pass_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier true expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier identifier string string_start string_end identifier | Parses a key enclosed in either single or double quotes. |
def myreplace(astr, thefind, thereplace):
alist = astr.split(thefind)
new_s = alist.split(thereplace)
return new_s | 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 identifier return_statement identifier | in string astr replace all occurences of thefind with thereplace |
def remove_subreddit(self, subreddit, *args, **kwargs):
return self.add_subreddit(subreddit, True, *args, **kwargs) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier true list_splat identifier dictionary_splat identifier | Remove a subreddit from the user's multireddit. |
def __get_float(section, name):
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | module function_definition identifier parameters identifier identifier block try_statement block return_statement call identifier argument_list subscript identifier identifier except_clause tuple identifier identifier identifier block return_statement call identifier argument_list integer | Get the forecasted float from json section. |
def ConsultarTipoDeduccion(self, sep="||"):
"Consulta de tipos de Deducciones"
ret = self.client.tipoDeduccionConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipoDeduccionReturn']
self.__analizar_errores(ret)
array = ret.get('tiposDeduccion', [])
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigoDescripcion']['codigo'],
it['codigoDescripcion']['descripcion'])
for it in array] | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list return_statement list_comprehension binary_operator parenthesized_expression binary_operator string string_start string_content string_end tuple identifier identifier identifier tuple subscript subscript identifier string string_start string_content string_end string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end for_in_clause identifier identifier | Consulta de tipos de Deducciones |
def ensure_params(kty, provided, required):
if not required <= provided:
missing = required - provided
raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(missing)))) | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator comparison_operator identifier identifier block expression_statement assignment identifier binary_operator identifier identifier raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list call identifier argument_list identifier | Ensure all required parameters are present in dictionary |
def remove_duplicate_edges_undirected(udg):
lookup = {}
edges = sorted(udg.get_all_edge_ids())
for edge_id in edges:
e = udg.get_edge(edge_id)
tpl_a = e['vertices']
tpl_b = (tpl_a[1], tpl_a[0])
if tpl_a in lookup or tpl_b in lookup:
udg.delete_edge_by_id(edge_id)
else:
lookup[tpl_a] = edge_id
lookup[tpl_b] = edge_id | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier tuple subscript identifier integer subscript identifier integer if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier identifier identifier expression_statement assignment subscript identifier identifier identifier | Removes duplicate edges from an undirected graph. |
def sign_ssh_challenge(self, blob, identity):
msg = _parse_ssh_blob(blob)
log.debug('%s: user %r via %r (%r)',
msg['conn'], msg['user'], msg['auth'], msg['key_type'])
log.debug('nonce: %r', msg['nonce'])
fp = msg['public_key']['fingerprint']
log.debug('fingerprint: %s', fp)
log.debug('hidden challenge size: %d bytes', len(blob))
log.info('please confirm user "%s" login to "%s" using %s...',
msg['user'].decode('ascii'), identity.to_string(),
self.device)
with self.device:
return self.device.sign(blob=blob, identity=identity) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript subscript identifier 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 identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier with_statement with_clause with_item attribute identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Sign given blob using a private key on the device. |
def account(self):
from ambry.util import parse_url_to_dict
d = parse_url_to_dict(self.url)
return self._bundle.library.account(d['netloc']) | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list subscript identifier string string_start string_content string_end | Return an account record, based on the host in the url |
def plotGenCost(generators):
figure()
plots = []
for generator in generators:
if generator.pcost_model == PW_LINEAR:
x = [x for x, _ in generator.p_cost]
y = [y for _, y in generator.p_cost]
elif generator.pcost_model == POLYNOMIAL:
x = scipy.arange(generator.p_min, generator.p_max, 5)
y = scipy.polyval(scipy.array(generator.p_cost), x)
else:
raise
plots.append(plot(x, y))
xlabel("P (MW)")
ylabel("Cost ($)")
legend(plots, [g.name for g in generators])
show() | module function_definition identifier parameters identifier block expression_statement call identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block raise_statement expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier expression_statement call identifier argument_list | Plots the costs of the given generators. |
def exclude_package(self, package):
pfx = package + '.'
if self.packages:
self.packages = [
p for p in self.packages
if p != package and not p.startswith(pfx)
]
if self.py_modules:
self.py_modules = [
p for p in self.py_modules
if p != package and not p.startswith(pfx)
]
if self.ext_modules:
self.ext_modules = [
p for p in self.ext_modules
if p.name != package and not p.name.startswith(pfx)
] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause boolean_operator comparison_operator identifier identifier not_operator call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause boolean_operator comparison_operator identifier identifier not_operator call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause boolean_operator comparison_operator attribute identifier identifier identifier not_operator call attribute attribute identifier identifier identifier argument_list identifier | Remove packages, modules, and extensions in named package |
def move_to_result(self, lst_idx):
self.in_result_idx.add(lst_idx)
if lst_idx in self.not_in_result_root_match_idx:
self.not_in_result_root_match_idx.remove(lst_idx) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Moves element from lst available at lst_idx. |
def _validate_label(self, label):
letter_pattern = compile("^[a-z]{1}$")
number_pattern = compile("^[0]{1}$|^[1-9]{1,2}$")
icon_pattern = compile("^[a-zA-Z ]{1,}$")
if not match(letter_pattern, label)\
and not match(number_pattern, label)\
and not match(icon_pattern, label):
raise InvalidLabelError(
"{} is not a valid label".format(label)
)
return label | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement boolean_operator boolean_operator not_operator call identifier argument_list identifier identifier line_continuation not_operator call identifier argument_list identifier identifier line_continuation not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Validates label, raising error if invalid. |
def request_uplink_info(self, context, agent):
LOG.debug('request_uplink_info from %(agent)s', {'agent': agent})
event_type = 'agent.request.uplink'
payload = {'agent': agent}
timestamp = time.ctime()
data = (event_type, payload)
pri = self.obj.PRI_LOW_START + 1
self.obj.pqueue.put((pri, timestamp, data))
LOG.debug('Added request uplink info into queue.')
return 0 | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier tuple identifier identifier expression_statement assignment identifier binary_operator attribute attribute identifier identifier identifier integer expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list tuple identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement integer | Process uplink message from an agent. |
def rebase_opt(self):
if not hasattr(self, '_rebase_opt'):
out, err = Popen(
['cleancss', '--version'], stdout=PIPE).communicate()
ver = int(out[:out.index(b'.')])
self._rebase_opt = ['--root', self.root] if ver == 3 else []
return self._rebase_opt | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute call identifier argument_list list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list subscript identifier slice call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier conditional_expression list string string_start string_content string_end attribute identifier identifier comparison_operator identifier integer list return_statement attribute identifier identifier | Determine which option name to use. |
def _api_response(response):
if response.status_code == 404:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Element doesn\'t exists')
if response.status_code == 401:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('Bad username or password')
elif response.status_code == 200 or response.status_code == 500:
try:
data = salt.utils.json.loads(response.content)
if data['exit_code'] != 'SUCCESS':
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError(data['message'])
return data
except ValueError:
__context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError('The server returned no data')
else:
response.raise_for_status() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier raise_statement call identifier argument_list string string_start string_content escape_sequence string_end if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier raise_statement call identifier argument_list string string_start string_content string_end elif_clause boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier raise_statement call identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier except_clause identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list | Check response status code + success_code returned by glassfish |
def enable_proxy(self, host, port):
self.proxy = [host, _number(port)]
self.proxy_enabled = True | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier list identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier true | Enable a default web proxy |
def _execute_example_group(self):
"Handles the execution of Example Group"
for example in self.example:
runner = self.__class__(example, self.formatter)
runner.is_root_runner = False
successes, failures, skipped = runner.run(self.context)
self.num_successes += successes
self.num_failures += failures
self.num_skipped += skipped | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment attribute identifier identifier false expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier | Handles the execution of Example Group |
def init_widget(self):
super(QtKeyEvent, self).init_widget()
d = self.declaration
widget = self.widget
self._keyPressEvent = widget.keyPressEvent
self._keyReleaseEvent = widget.keyReleaseEvent
self.set_enabled(d.enabled)
self.set_keys(d.keys) | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | The KeyEvent uses the parent_widget as it's widget |
def _populate_warcinfo(self, extra_fields=None):
self._warcinfo_record.set_common_fields(
WARCRecord.WARCINFO, WARCRecord.WARC_FIELDS)
info_fields = NameValueRecord(wrap_width=1024)
info_fields['Software'] = self._params.software_string \
or self.DEFAULT_SOFTWARE_STRING
info_fields['format'] = 'WARC File Format 1.0'
info_fields['conformsTo'] = \
'http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf'
if extra_fields:
for name, value in extra_fields:
info_fields.add(name, value)
self._warcinfo_record.block_file = io.BytesIO(
bytes(info_fields) + b'\r\n')
self._warcinfo_record.compute_checksum() | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier integer expression_statement assignment subscript identifier string string_start string_content string_end boolean_operator attribute attribute identifier identifier identifier line_continuation attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement identifier block for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment attribute attribute identifier identifier identifier call attribute identifier identifier argument_list binary_operator call identifier argument_list identifier string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute attribute identifier identifier identifier argument_list | Add the metadata to the Warcinfo record. |
def make_basic_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
model = make_basic_cnn()
layers = model.layers
model = MLPnGPU(nb_classes, layers, input_shape)
return model | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier tuple none integer integer integer dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier return_statement identifier | Create a multi-GPU model similar to the basic cnn in the tutorials. |
def getMedia(self, uri):
r = self.doQuery('media/' + uri)
if r.status_code == 200:
content_type = 'application/octet-stream'
if 'content-type' in r.headers:
content_type = r.headers['content-type']
cache_control = None
if 'cache-control' in r.headers:
cache_control = r.headers['cache-control']
return (r.content, content_type, cache_control)
else:
return (None, None, None) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier none if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end return_statement tuple attribute identifier identifier identifier identifier else_clause block return_statement tuple none none none | Return a tuple with a media and his content-type. Don't cache anything ! |
def render_to_string(self, *args, **kwargs):
try:
template_name, args = args[0], args[1:]
except IndexError:
raise TypeError('name of template required')
return self.get_template(template_name).render(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment pattern_list identifier identifier expression_list subscript identifier integer subscript identifier slice integer except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list list_splat identifier dictionary_splat identifier | Load and render a template into a unicode string. |
def local_check (self):
log.debug(LOG_CHECK, "Checking %s", unicode(self))
assert not self.extern[1], 'checking strict extern URL'
log.debug(LOG_CHECK, "checking connection")
try:
self.check_connection()
self.set_content_type()
self.add_size_info()
self.aggregate.plugin_manager.run_connection_plugins(self)
except tuple(ExcList) as exc:
value = self.handle_exception()
if isinstance(exc, socket.error) and exc.args[0] == -2:
value = _('Hostname not found')
elif isinstance(exc, UnicodeError):
value = _('Bad hostname %(host)r: %(msg)s') % {'host': self.host, 'msg': str(value)}
self.set_result(unicode_safe(value), valid=False) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier assert_statement not_operator subscript attribute identifier identifier integer string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier except_clause as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier comparison_operator subscript attribute identifier identifier integer unary_operator integer block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier keyword_argument identifier false | Local check function can be overridden in subclasses. |
def about_action(self):
name = self.action.metavar or self.action.dest
type_name = self.action.type.__name__ if self.action.type else ''
if self.action.help or type_name:
extra = ' (%s)' % (self.action.help or 'type: %s' % type_name)
else:
extra = ''
return name + extra | module function_definition identifier parameters identifier block expression_statement assignment identifier boolean_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier conditional_expression attribute attribute attribute identifier identifier identifier identifier attribute attribute identifier identifier identifier string string_start string_end if_statement boolean_operator attribute attribute identifier identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression boolean_operator attribute attribute identifier identifier identifier binary_operator string string_start string_content string_end identifier else_clause block expression_statement assignment identifier string string_start string_end return_statement binary_operator identifier identifier | Simple string describing the action. |
def load_modules(self):
if self.INTERFACES_MODULE is None:
raise NotImplementedError("A module containing interfaces modules "
"should be setup in INTERFACES_MODULE !")
else:
for module, permission in self.modules.items():
i = getattr(self.INTERFACES_MODULE,
module).Interface(self, permission)
self.interfaces[module] = i | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end else_clause block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute call identifier argument_list attribute identifier identifier identifier identifier argument_list identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | Should instance interfaces and set them to interface, following `modules` |
def write_file(self, name, path=None):
if path is None:
path = name
self.zf.write(path, name) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Write the contents of a file from the disk to the XPI. |
def _make_chunk_iter(stream, limit, buffer_size):
if isinstance(stream, (bytes, bytearray, text_type)):
raise TypeError('Passed a string or byte object instead of '
'true iterator or stream.')
if not hasattr(stream, 'read'):
for item in stream:
if item:
yield item
return
if not isinstance(stream, LimitedStream) and limit is not None:
stream = LimitedStream(stream, limit)
_read = stream.read
while 1:
item = _read(buffer_size)
if not item:
break
yield item | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier tuple identifier identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block for_statement identifier identifier block if_statement identifier block expression_statement yield identifier return_statement if_statement boolean_operator not_operator call identifier argument_list identifier identifier comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier attribute identifier identifier while_statement integer block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block break_statement expression_statement yield identifier | Helper for the line and chunk iter functions. |
def parse_rule(rule: str, raise_error=False):
parser = Parser(raise_error)
return parser.parse(rule) | module function_definition identifier parameters typed_parameter identifier type identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Parses policy to a tree of Check objects. |
def CheckLineLength(filename, linenumber, clean_lines, errors):
line = clean_lines.raw_lines[linenumber]
if len(line) > _lint_state.linelength:
return errors(
filename,
linenumber,
'linelength',
'Lines should be <= %d characters long' %
(_lint_state.linelength)) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block return_statement call identifier argument_list identifier identifier string string_start string_content string_end binary_operator string string_start string_content string_end parenthesized_expression attribute identifier identifier | Check for lines longer than the recommended length |
def rpy_matrix(roll, pitch, yaw):
return np.dot(Rz_matrix(yaw), np.dot(Ry_matrix(pitch), Rx_matrix(roll))) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list call identifier argument_list identifier call identifier argument_list identifier | Returns a rotation matrix described by the extrinsinc roll, pitch, yaw coordinates |
def _get_contract_exception_dict(contract_msg):
start_token = "[START CONTRACT MSG: "
stop_token = "[STOP CONTRACT MSG]"
if contract_msg.find(start_token) == -1:
return {
"num": 0,
"msg": "Argument `*[argument_name]*` is not valid",
"type": RuntimeError,
"field": "argument_name",
}
msg_start = contract_msg.find(start_token) + len(start_token)
contract_msg = contract_msg[msg_start:]
contract_name = contract_msg[: contract_msg.find("]")]
contract_msg = contract_msg[
contract_msg.find("]") + 1 : contract_msg.find(stop_token)
]
exdict = _CUSTOM_CONTRACTS[contract_name]
for exvalue in exdict.values():
if exvalue["msg"] == contract_msg:
return exvalue | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator call attribute identifier identifier argument_list identifier unary_operator integer block return_statement dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment identifier subscript identifier slice call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier slice binary_operator call attribute identifier identifier argument_list string string_start string_content string_end integer call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier identifier for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator subscript identifier string string_start string_content string_end identifier block return_statement identifier | Generate message for exception. |
def context(self):
"Internal property that returns the stylus compiler"
if self._context is None:
with io.open(path.join(path.abspath(path.dirname(__file__)), "compiler.js")) as compiler_file:
compiler_source = compiler_file.read()
self._context = self.backend.compile(compiler_source)
return self._context | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier 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 attribute identifier identifier identifier argument_list identifier return_statement attribute identifier identifier | Internal property that returns the stylus compiler |
def _formatinfo(format):
size = struct.calcsize(format)
return size, len(struct.unpack(format, B('\x00') * size)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier call identifier argument_list call attribute identifier identifier argument_list identifier binary_operator call identifier argument_list string string_start string_content escape_sequence string_end identifier | Calculate the size and number of items in a struct format. |
def parse_dos_time(stamp):
sec, stamp = stamp & 0x1F, stamp >> 5
mn, stamp = stamp & 0x3F, stamp >> 6
hr, stamp = stamp & 0x1F, stamp >> 5
day, stamp = stamp & 0x1F, stamp >> 5
mon, stamp = stamp & 0x0F, stamp >> 4
yr = (stamp & 0x7F) + 1980
return (yr, mon, day, hr, mn, sec * 2) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier expression_list binary_operator identifier integer binary_operator identifier integer expression_statement assignment pattern_list identifier identifier expression_list binary_operator identifier integer binary_operator identifier integer expression_statement assignment pattern_list identifier identifier expression_list binary_operator identifier integer binary_operator identifier integer expression_statement assignment pattern_list identifier identifier expression_list binary_operator identifier integer binary_operator identifier integer expression_statement assignment pattern_list identifier identifier expression_list binary_operator identifier integer binary_operator identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier integer integer return_statement tuple identifier identifier identifier identifier identifier binary_operator identifier integer | Parse standard 32-bit DOS timestamp. |
def on_close_grid(self, event):
if self.parent.grid_frame:
self.parent.grid_frame.onSave(None)
self.parent.grid_frame.Destroy() | module function_definition identifier parameters identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list none expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list | If there is an open grid, save its data and close it. |
def _read_data(self, count):
frame = bytearray(count)
frame[0] = PN532_SPI_DATAREAD
self._gpio.set_low(self._cs)
self._busy_wait_ms(2)
response = self._spi.transfer(frame)
self._gpio.set_high(self._cs)
return response | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier integer identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement identifier | Read a specified count of bytes from the PN532. |
def accept(self, pub):
try:
with salt.utils.files.fopen(self.path, 'r') as fp_:
expiry = int(fp_.read())
except (OSError, IOError):
log.error(
'Request to sign key for minion \'%s\' on hyper \'%s\' '
'denied: no authorization', self.id, self.hyper
)
return False
except ValueError:
log.error('Invalid expiry data in %s', self.path)
return False
if (time.time() - expiry) > 600:
log.warning(
'Request to sign key for minion "%s" on hyper "%s" denied: '
'authorization expired', self.id, self.hyper
)
return False
pubfn = os.path.join(self.opts['pki_dir'],
'minions',
self.id)
with salt.utils.files.fopen(pubfn, 'w+') as fp_:
fp_.write(pub)
self.void()
return True | module function_definition identifier parameters identifier identifier block try_statement block with_statement with_clause with_item as_pattern call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list except_clause tuple identifier identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end string string_start string_content string_end attribute identifier identifier attribute identifier identifier return_statement false except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier return_statement false if_statement comparison_operator parenthesized_expression binary_operator call attribute identifier identifier argument_list identifier integer 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 attribute identifier identifier attribute identifier identifier return_statement false expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier with_statement with_clause with_item as_pattern call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement true | Accept the provided key |
def cli_certify_core_integer(
config, min_value, max_value, value,
):
def parser(v):
try:
v = load_json_pickle(v, config)
except Exception:
pass
try:
return int(v)
except Exception as err:
six.raise_from(
CertifierTypeError(
message='Not integer: {x}'.format(
x=v,
),
value=v,
),
err,
)
execute_cli_command(
'integer',
config,
parser,
certify_int,
value[0] if value else None,
min_value=min_value,
max_value=max_value,
required=config['required'],
) | module function_definition identifier parameters identifier identifier identifier identifier block function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier except_clause identifier block pass_statement try_statement block return_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier identifier expression_statement call identifier argument_list string string_start string_content string_end identifier identifier identifier conditional_expression subscript identifier integer identifier none keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier subscript identifier string string_start string_content string_end | Console script for certify_int |
def set(self, param, value):
self.raw_dict[param] = value
self.manifest.set(self.feature_name, param, value) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier identifier | sets the param to the value provided |
def _generate_output_dir(settings, path):
relpath = os.path.relpath(settings.root,path)
count = relpath.count(os.sep) + 1
return relpath+os.path.sep, count | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list attribute identifier identifier integer return_statement expression_list binary_operator identifier attribute attribute identifier identifier identifier identifier | This is a separate function, so that it can be more easily tested |
def run(*args):
if not args:
args = sys.argv[1:]
if len(args) < 2:
print('Usage: runenv <envfile> <command> <params>')
sys.exit(0)
os.environ.update(create_env(args[0]))
os.environ['_RUNENV_WRAPPED'] = '1'
runnable_path = args[1]
if not runnable_path.startswith(('/', '.')):
runnable_path = spawn.find_executable(runnable_path)
try:
if not(stat.S_IXUSR & os.stat(runnable_path)[stat.ST_MODE]):
print('File `%s is not executable' % runnable_path)
sys.exit(1)
return subprocess.check_call(
args[1:], env=os.environ
)
except subprocess.CalledProcessError as e:
return e.returncode | module function_definition identifier parameters list_splat_pattern identifier block if_statement not_operator identifier block expression_statement assignment identifier subscript attribute identifier identifier slice integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list subscript identifier integer 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 subscript identifier integer if_statement not_operator call attribute identifier identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier try_statement block if_statement not_operator parenthesized_expression binary_operator attribute identifier identifier subscript call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list integer return_statement call attribute identifier identifier argument_list subscript identifier slice integer keyword_argument identifier attribute identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block return_statement attribute identifier identifier | Load given `envfile` and run `command` with `params` |
def to_range(obj, score=None, id=None, strand=None):
from jcvi.utils.range import Range
if score or id:
_score = score if score else obj.score
_id = id if id else obj.id
return Range(seqid=obj.seqid, start=obj.start, end=obj.end, \
score=_score, id=_id)
elif strand:
return (obj.seqid, obj.start, obj.end, obj.strand)
return (obj.seqid, obj.start, obj.end) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block import_from_statement dotted_name identifier identifier identifier dotted_name identifier if_statement boolean_operator identifier identifier block expression_statement assignment identifier conditional_expression identifier identifier attribute identifier identifier expression_statement assignment identifier conditional_expression identifier identifier attribute identifier identifier return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier line_continuation keyword_argument identifier identifier keyword_argument identifier identifier elif_clause identifier block return_statement tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier return_statement tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier | Given a gffutils object, convert it to a range object |
def save_info_df(self):
logger.debug("running save_info_df")
info_df = self.info_df
top_level_dict = {'info_df': info_df, 'metadata': self._prm_packer()}
jason_string = json.dumps(top_level_dict,
default=lambda info_df: json.loads(
info_df.to_json()))
with open(self.info_file, 'w') as outfile:
outfile.write(jason_string)
logger.info("Saved file to {}".format(self.info_file)) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | Saves the DataFrame with info about the runs to a JSON file |
def from_bucket(self, bucket, native=False):
bucket = str(bucket)
if self._step == 'weekly':
year, week = bucket[:4], bucket[4:]
normal = datetime(year=int(year), month=1, day=1) + timedelta(weeks=int(week))
else:
normal = datetime.strptime(bucket, self.FORMATS[self._step])
if native:
return normal
return long(time.mktime( normal.timetuple() )) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier expression_list subscript identifier slice integer subscript identifier slice integer expression_statement assignment identifier binary_operator call identifier argument_list keyword_argument identifier call identifier argument_list identifier keyword_argument identifier integer keyword_argument identifier integer call identifier argument_list keyword_argument identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript attribute identifier identifier attribute identifier identifier if_statement identifier block return_statement identifier return_statement call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Calculate the timestamp given a bucket. |
def build_item(
title, key=None, synonyms=None, description=None, img_url=None, alt_text=None
):
item = {
"info": {"key": key or title, "synonyms": synonyms or []},
"title": title,
"description": description,
"image": {
"imageUri": img_url or "",
"accessibilityText": alt_text or "{} img".format(title),
},
}
return item | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end boolean_operator identifier identifier pair string string_start string_content string_end boolean_operator identifier list pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end boolean_operator identifier string string_start string_end pair string string_start string_content string_end boolean_operator identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Builds an item that may be added to List or Carousel |
def filename(self):
if self.buildver:
buildver = '-' + self.buildver
else:
buildver = ''
pyver = '.'.join(self.pyver)
abi = '.'.join(self.abi)
arch = '.'.join(self.arch)
version = self.version.replace('-', '_')
return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
pyver, abi, arch) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier else_clause block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end return_statement binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier identifier identifier identifier identifier | Build and return a filename from the various components. |
def update_label(signature, post_data):
current_tag_infos = MPost2Label.get_by_uid(signature).objects()
if 'tags' in post_data:
pass
else:
return False
tags_arr = [x.strip() for x in post_data['tags'].split(',')]
for tag_name in tags_arr:
if tag_name == '':
pass
else:
MPost2Label.add_record(signature, tag_name, 1)
for cur_info in current_tag_infos:
if cur_info.tag_name in tags_arr:
pass
else:
MPost2Label.remove_relation(signature, cur_info.tag_id) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block pass_statement else_clause block return_statement false expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator identifier string string_start string_end block pass_statement else_clause block expression_statement call attribute identifier identifier argument_list identifier identifier integer for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block pass_statement else_clause block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier | Update the label when updating. |
def from_db_value(self, value, expression, connection, context):
if value is None:
return value
return self.parse_seconds(value) | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier none block return_statement identifier return_statement call attribute identifier identifier argument_list identifier | Handle data loaded from database. |
def visit_VariableDeclaration(self, node):
var_name = node.assignment.left.identifier.name
var_is_mutable = node.assignment.left.is_mutable
var_symbol = VariableSymbol(var_name, var_is_mutable)
if self.table[var_name] is not None:
raise SementicError(f"Variable `{var_name}` is already declared.")
self.table[var_symbol.name] = var_symbol
self.visit(node.assignment.left)
self.visit(node.assignment.right) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute attribute attribute identifier identifier identifier identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator subscript attribute identifier identifier identifier none block raise_statement call identifier argument_list string string_start string_content interpolation identifier string_content string_end expression_statement assignment subscript attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier | Visitor for `VariableDeclaration` AST node. |
def _GetAFF4AttributeForReportType(report_type
):
if report_type == rdf_stats.ClientGraphSeries.ReportType.GRR_VERSION:
return aff4_stats.ClientFleetStats.SchemaCls.GRRVERSION_HISTOGRAM
elif report_type == rdf_stats.ClientGraphSeries.ReportType.OS_TYPE:
return aff4_stats.ClientFleetStats.SchemaCls.OS_HISTOGRAM
elif report_type == rdf_stats.ClientGraphSeries.ReportType.OS_RELEASE:
return aff4_stats.ClientFleetStats.SchemaCls.RELEASE_HISTOGRAM
elif report_type == rdf_stats.ClientGraphSeries.ReportType.N_DAY_ACTIVE:
return aff4_stats.ClientFleetStats.SchemaCls.LAST_CONTACTED_HISTOGRAM
else:
raise ValueError("Unknown report type %s." % report_type) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement attribute attribute attribute identifier identifier identifier identifier elif_clause comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement attribute attribute attribute identifier identifier identifier identifier elif_clause comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement attribute attribute attribute identifier identifier identifier identifier elif_clause comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement attribute attribute attribute identifier identifier identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Returns the corresponding AFF4 attribute for the given report type. |
def date_from_number(self, value):
if not isinstance(value, numbers.Real):
return None
delta = datetime.timedelta(days=value)
return self._null_date + delta | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement binary_operator attribute identifier identifier identifier | Converts a float value to corresponding datetime instance. |
def name(self):
if self._name:
return self._name
return self.code.replace('_', ' ').capitalize() | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier return_statement call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list | Give back tab name if is set else generate name by code |
def description(self, platform, key):
patterns = self._dict_dscr.get(platform, None)
description = patterns.get(key, None)
return description | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none expression_statement assignment identifier call attribute identifier identifier argument_list identifier none return_statement identifier | Return the patter description. |
def _openResources(self):
with Image.open(self._fileName) as image:
self._array = np.asarray(image)
self._bands = image.getbands()
self._attributes = dict(image.info)
self._attributes['Format'] = image.format
self._attributes['Mode'] = image.mode
self._attributes['Size'] = image.size
self._attributes['Width'] = image.width
self._attributes['Height'] = image.height | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier | Uses open the underlying file |
def _childgroup_by_name(self, children, grid):
children = self._dict_children(children)
result = []
for row in grid:
child_row = []
row_is_void = True
width_sum = 0
for name, width in row:
width_sum += width
if width_sum > self.num_cols:
warnings.warn(u"It seems your grid configuration overlaps \
the bootstrap layout columns number. One of your lines is larger than {0}. \
You can increase this column number by compiling bootstrap css with \
lessc.".format(self.num_cols))
if isinstance(name, StaticWidget):
child = name
child.width = width
row_is_void = False
elif name is not None:
try:
child = children.pop(name)
row_is_void = False
except KeyError:
warnings.warn(u"No node {0} found".format(name))
child = VoidWidget(width)
child.width = width
else:
child = VoidWidget(width)
child_row.append(child)
if not row_is_void:
result.append(child_row)
for value in children.values():
result.append([value])
return result | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier true expression_statement assignment identifier integer for_statement pattern_list identifier identifier identifier block expression_statement augmented_assignment identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier false elif_clause comparison_operator identifier none block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier false except_clause identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list list identifier return_statement identifier | Group the children ordering them by name |
def drange(start: Decimal, stop: Decimal, num: int):
delta = stop - start
step = delta / (num - 1)
yield from (start + step * Decimal(tick) for tick in range(0, num)) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator identifier integer expression_statement yield generator_expression binary_operator identifier binary_operator identifier call identifier argument_list identifier for_in_clause identifier call identifier argument_list integer identifier | A simplified version of numpy.linspace with default options |
def __GetRequestField(self, method_description, body_type):
body_field_name = self.__BodyFieldName(body_type)
if body_field_name in method_description.get('parameters', {}):
body_field_name = self.__names.FieldName(
'%s_resource' % body_field_name)
while body_field_name in method_description.get('parameters', {}):
body_field_name = self.__names.FieldName(
'%s_body' % body_field_name)
return body_field_name | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier while_statement comparison_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier | Determine the request field for this method. |
def search(query, stats):
log.debug("Search query: {0}".format(query))
issues = []
for batch in range(MAX_BATCHES):
response = stats.parent.session.get(
"{0}/rest/api/latest/search?{1}".format(
stats.parent.url, urllib.urlencode({
"jql": query,
"fields": "summary,comment",
"maxResults": MAX_RESULTS,
"startAt": batch * MAX_RESULTS})))
data = response.json()
log.debug("Batch {0} result: {1} fetched".format(
batch, listed(data["issues"], "issue")))
log.data(pretty(data))
issues.extend(data["issues"])
if len(issues) >= data["total"]:
break
return [Issue(issue, prefix=stats.parent.prefix) for issue in issues] | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier subscript identifier string string_start string_content string_end block break_statement return_statement list_comprehension call identifier argument_list identifier keyword_argument identifier attribute attribute identifier identifier identifier for_in_clause identifier identifier | Perform issue search for given stats instance |
def _intro_text(self):
try:
cls_docstring = self._clsdict['__doc__']
except KeyError:
cls_docstring = ''
if cls_docstring is None:
return ''
return textwrap.dedent(cls_docstring).strip() | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator identifier none block return_statement string string_start string_end return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list | Docstring of the enumeration, formatted for documentation page. |
def post_build(self, p, pay):
p += pay
if self.auxdlen != 0:
print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).")
print(" Subsequent Group Records are lost!")
return p | module function_definition identifier parameters identifier identifier identifier block expression_statement augmented_assignment identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end return_statement identifier | Called implicitly before a packet is sent. |
def cross(v1, v2):
return (
v1[1] * v2[2] - v1[2] * v2[1],
v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0],
) | module function_definition identifier parameters identifier identifier block return_statement tuple binary_operator binary_operator subscript identifier integer subscript identifier integer binary_operator subscript identifier integer subscript identifier integer binary_operator binary_operator subscript identifier integer subscript identifier integer binary_operator subscript identifier integer subscript identifier integer binary_operator binary_operator subscript identifier integer subscript identifier integer binary_operator subscript identifier integer subscript identifier integer | Computes the cross product of two vectors. |
def first_spark_call():
tb = traceback.extract_stack()
if len(tb) == 0:
return None
file, line, module, what = tb[len(tb) - 1]
sparkpath = os.path.dirname(file)
first_spark_frame = len(tb) - 1
for i in range(0, len(tb)):
file, line, fun, what = tb[i]
if file.startswith(sparkpath):
first_spark_frame = i
break
if first_spark_frame == 0:
file, line, fun, what = tb[0]
return CallSite(function=fun, file=file, linenum=line)
sfile, sline, sfun, swhat = tb[first_spark_frame]
ufile, uline, ufun, uwhat = tb[first_spark_frame - 1]
return CallSite(function=sfun, file=ufile, linenum=uline) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier integer block return_statement none expression_statement assignment pattern_list identifier identifier identifier identifier subscript identifier binary_operator call identifier argument_list identifier integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier binary_operator call identifier argument_list identifier integer for_statement identifier call identifier argument_list integer call identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier identifier identifier subscript identifier identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier identifier break_statement if_statement comparison_operator identifier integer block expression_statement assignment pattern_list identifier identifier identifier identifier subscript identifier integer return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier subscript identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier subscript identifier binary_operator identifier integer return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Return a CallSite representing the first Spark call in the current call stack. |
def to_python(self, value):
if not value:
return []
return map(super(CommaSepFloatField, self).to_python, value.split(',')) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement list return_statement call identifier argument_list attribute call identifier argument_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end | Normalize data to a list of floats. |
def reacquire(self):
if self.local.token is None:
raise LockError("Cannot reacquire an unlocked lock")
if self.timeout is None:
raise LockError("Cannot reacquire a lock with no timeout")
return self.do_reacquire() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list | Resets a TTL of an already acquired lock back to a timeout value. |
def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ):
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WHERE name_hash128 = ? AND revoked = 0 AND " + unexpired_query + ";"
args = (name_hash128,) + unexpired_args
name_rows = namedb_query_execute( cur, select_query, args )
name_row = name_rows.fetchone()
if name_row is None:
return None
return name_row['name'] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator binary_operator string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier binary_operator tuple identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block return_statement none return_statement subscript identifier string string_start string_content string_end | Given the hexlified 128-bit hash of a name, get the name. |
def file_plus_index(fname):
exts = {".vcf": ".idx", ".bam": ".bai", ".vcf.gz": ".tbi", ".bed.gz": ".tbi",
".fq.gz": ".gbi"}
ext = splitext_plus(fname)[-1]
if ext in exts:
return [fname, fname + exts[ext]]
else:
return [fname] | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript call identifier argument_list identifier unary_operator integer if_statement comparison_operator identifier identifier block return_statement list identifier binary_operator identifier subscript identifier identifier else_clause block return_statement list identifier | Convert a file name into the file plus required indexes. |
def _write_object(self, path, value):
ensure_directory_exists(os.path.dirname(path))
with open(path, 'w') as f:
f.write(value) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier | write out `object` to file at `path` |
def optimise_levenberg_marquardt(x, a, c, damping=0.001, tolerance=0.001):
x_new = x
x_old = x-1
f_old = f(x_new, a, c)
while np.abs(x_new - x_old).sum() > tolerance:
x_old = x_new
x_tmp = levenberg_marquardt_update(x_old, a, c, damping)
f_new = f(x_tmp, a, c)
if f_new < f_old:
damping = np.max(damping/10., 1e-20)
x_new = x_tmp
f_old = f_new
else:
damping *= 10.
return x_new | module function_definition identifier parameters identifier identifier identifier default_parameter identifier float default_parameter identifier float block expression_statement assignment identifier identifier expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call identifier argument_list identifier identifier identifier while_statement comparison_operator call attribute call attribute identifier identifier argument_list binary_operator identifier identifier identifier argument_list identifier block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier float float expression_statement assignment identifier identifier expression_statement assignment identifier identifier else_clause block expression_statement augmented_assignment identifier float return_statement identifier | Optimise value of x using levenberg-marquardt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.