code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def can_add_post(self, topic, user):
can_add_post = self._perform_basic_permission_check(
topic.forum, user, 'can_reply_to_topics',
)
can_add_post &= (
not topic.is_locked or
self._perform_basic_permission_check(topic.forum, user, 'can_reply_to_locked_topics')
)
return can_add_post | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier string string_start string_content string_end expression_statement augmented_assignment identifier parenthesized_expression boolean_operator not_operator attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier identifier string string_start string_content string_end return_statement identifier | Given a topic, checks whether the user can append posts to it. |
def copy(self):
other = self.__class__(self.p)
other.coef = self.coef.copy()
other.residuals = self.residuals.copy()
other.rescov = self.rescov.copy()
return other | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list return_statement identifier | Create a copy of the VAR model. |
def _process_string(self, char):
if char in self.QUOTES:
if (char == self._last_quote and
not self._escaped or self._double_escaped):
self._new_token()
self._state = self.ST_TOKEN
return
elif char == self.ESCAPE:
if not self._double_escaped:
self._double_escaped = self._escaped
else:
self._double_escaped = False
self._token_chars.append(char) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator comparison_operator identifier attribute identifier identifier not_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement elif_clause comparison_operator identifier attribute identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier else_clause block expression_statement assignment attribute identifier identifier false expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Process a character as part of a string token. |
def _timeout_future(self, tag, matcher, future):
if (tag, matcher) not in self.tag_map:
return
if not future.done():
future.set_exception(TimeoutException())
self.tag_map[(tag, matcher)].remove(future)
if not self.tag_map[(tag, matcher)]:
del self.tag_map[(tag, matcher)] | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator tuple identifier identifier attribute identifier identifier block return_statement if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call identifier argument_list expression_statement call attribute subscript attribute identifier identifier tuple identifier identifier identifier argument_list identifier if_statement not_operator subscript attribute identifier identifier tuple identifier identifier block delete_statement subscript attribute identifier identifier tuple identifier identifier | Timeout a specific future |
def write(self):
with open(self.filepath, 'wb') as outfile:
outfile.write(
self.fernet.encrypt(
yaml.dump(self.data, encoding='utf-8'))) | module function_definition identifier parameters identifier block 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 call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end | Encrypts and writes the current state back onto the filesystem |
def update_version(self, service_id, version_number, **kwargs):
body = self._formdata(kwargs, FastlyVersion.FIELDS)
content = self._fetch("/service/%s/version/%d/" % (service_id, version_number), method="PUT", body=body)
return FastlyVersion(self, content) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Update a particular version for a particular service. |
def action_handler(verb, **kwargs):
kwargs.pop('signal', None)
actor = kwargs.pop('sender')
if hasattr(verb, '_proxy____args'):
verb = verb._proxy____args[0]
newaction = apps.get_model('actstream', 'action')(
actor_content_type=ContentType.objects.get_for_model(actor),
actor_object_id=actor.pk,
verb=text_type(verb),
public=bool(kwargs.pop('public', True)),
description=kwargs.pop('description', None),
timestamp=kwargs.pop('timestamp', now())
)
for opt in ('target', 'action_object'):
obj = kwargs.pop(opt, None)
if obj is not None:
check(obj)
setattr(newaction, '%s_object_id' % opt, obj.pk)
setattr(newaction, '%s_content_type' % opt,
ContentType.objects.get_for_model(obj))
if settings.USE_JSONFIELD and len(kwargs):
newaction.data = kwargs
newaction.save(force_insert=True)
return newaction | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end argument_list keyword_argument identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end true keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list for_statement identifier 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 none if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier binary_operator string string_start string_content string_end identifier attribute identifier identifier expression_statement call identifier argument_list identifier binary_operator string string_start string_content string_end identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement boolean_operator attribute identifier identifier call identifier argument_list identifier block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier true return_statement identifier | Handler function to create Action instance upon action signal call. |
def dump(self, zone, output_dir, lenient, split, source, *sources):
self.log.info('dump: zone=%s, sources=%s', zone, sources)
sources = [source] + list(sources)
try:
sources = [self.providers[s] for s in sources]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
clz = YamlProvider
if split:
clz = SplitYamlProvider
target = clz('dump', output_dir)
zone = Zone(zone, self.configured_sub_zones(zone))
for source in sources:
source.populate(zone, lenient=lenient)
plan = target.plan(zone)
if plan is None:
plan = Plan(zone, zone, [], False)
target.apply(plan) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier list_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement assignment identifier binary_operator list identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier list_comprehension subscript attribute identifier identifier identifier for_in_clause identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript attribute identifier identifier integer expression_statement assignment identifier identifier if_statement identifier block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier list false expression_statement call attribute identifier identifier argument_list identifier | Dump zone data from the specified source |
def strip_footer(ref_lines, section_title):
pattern = ur'\(?\[?\d{0,4}\]?\)?\.?\s*%s\s*$' % re.escape(section_title)
re_footer = re.compile(pattern, re.UNICODE)
return [l for l in ref_lines if not re_footer.match(l)] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier return_statement list_comprehension identifier for_in_clause identifier identifier if_clause not_operator call attribute identifier identifier argument_list identifier | Remove footer title from references lines |
def create_equipamento_acesso(self):
return EquipamentoAcesso(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Get an instance of equipamento_acesso services facade. |
def from_row(row):
subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5]
return Advice.objects.create(
id=row[0],
administration=cleanup(row[1]),
type=row[2],
session=datetime.strptime(row[4], '%d/%m/%Y'),
subject=cleanup(subject),
topics=[t.title() for t in cleanup(row[6]).split(', ')],
tags=[tag.strip() for tag in row[7].split(',') if tag.strip()],
meanings=cleanup(row[8]).replace(' / ', '/').split(', '),
part=_part(row[9]),
content=cleanup(row[10]),
) | module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression parenthesized_expression binary_operator call attribute subscript subscript identifier integer integer identifier argument_list subscript subscript identifier integer slice integer subscript identifier integer subscript identifier integer return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier subscript identifier integer keyword_argument identifier call identifier argument_list subscript identifier integer keyword_argument identifier subscript identifier integer keyword_argument identifier call attribute identifier identifier argument_list subscript identifier integer string string_start string_content string_end keyword_argument identifier call identifier argument_list identifier keyword_argument identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute call identifier argument_list subscript identifier integer identifier argument_list string string_start string_content string_end keyword_argument identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end if_clause call attribute identifier identifier argument_list keyword_argument identifier call attribute call attribute call identifier argument_list subscript identifier integer identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end keyword_argument identifier call identifier argument_list subscript identifier integer keyword_argument identifier call identifier argument_list subscript identifier integer | Create an advice from a CSV row |
def write_file(fname_parts, content):
fname_parts = [str(part) for part in fname_parts]
if len(fname_parts) > 1:
try:
os.makedirs(os.path.join(*fname_parts[:-1]))
except OSError:
pass
fhandle = open(os.path.join(*fname_parts), "w")
fhandle.write(content)
fhandle.close() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block try_statement block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list list_splat subscript identifier slice unary_operator integer except_clause identifier block pass_statement expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list list_splat identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | write a file and create all needed directories |
def data(self):
def read(path):
with open(path, 'r', encoding='UTF-8') as f:
return f.read()
return [
read(f) for f in self.files
] | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block return_statement call attribute identifier identifier argument_list return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier | Read all of the documents from disk into an in-memory list. |
def _get_next_nn_id(self):
self._nn_id = self._nn_id + 1 if self._nn_id < 126 else 1
return self._nn_id * 2 | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier conditional_expression binary_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer integer return_statement binary_operator attribute identifier identifier integer | Get the next nearest neighbour ID. |
def destroy(self):
if self.id is not None and self._mumps_c is not None:
self.id.job = -2
self._mumps_c(self.id)
self.id = None
self._refs = None | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier none block expression_statement assignment attribute attribute identifier identifier identifier unary_operator integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none | Delete the MUMPS context and release all array references. |
def collect_dashboard_js(collector):
dashmat = collector.configuration["dashmat"]
modules = collector.configuration["__active_modules__"]
compiled_static_prep = dashmat.compiled_static_prep
compiled_static_folder = dashmat.compiled_static_folder
npm_deps = list_npm_modules(collector, no_print=True)
react_server = ReactServer()
react_server.prepare(npm_deps, compiled_static_folder)
for dashboard in collector.configuration["dashboards"].values():
log.info("Generating compiled javascript for dashboard:{0}".format(dashboard.path))
filename = dashboard.path.replace("_", "__").replace("/", "_")
location = os.path.join(compiled_static_folder, "dashboards", "{0}.js".format(filename))
if os.path.exists(location):
os.remove(location)
generate_dashboard_js(dashboard, react_server, compiled_static_folder, compiled_static_prep, modules) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier for_statement identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier 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 string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier identifier identifier | Generate dashboard javascript for each dashboard |
def migrator(state):
cleverbot_kwargs, convos_kwargs = state
cb = Cleverbot(**cleverbot_kwargs)
for convo_kwargs in convos_kwargs:
cb.conversation(**convo_kwargs)
return cb | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list dictionary_splat identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary_splat identifier return_statement identifier | Nameless conversations will be lost. |
def transport_meta_data(self):
for item in self.input_stream:
trans_data = item['packet']['data']
trans_type = self._get_transport_type(trans_data)
if trans_type and trans_data:
item['transport'] = data_utils.make_dict(trans_data)
item['transport']['type'] = trans_type
item['transport']['flags'] = self._readable_flags(item['transport'])
item['transport']['data'] = trans_data['data']
yield item | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement yield identifier | Pull out the transport metadata for each packet in the input_stream |
def save_key_file(self):
if self.client_key is None:
return
if self.key_file_path:
key_file_path = self.key_file_path
else:
key_file_path = self._get_key_file_path()
logger.debug('save keyfile to %s', key_file_path);
with open(key_file_path, 'w+') as f:
raw_data = f.read()
key_dict = {}
if raw_data:
key_dict = json.loads(raw_data)
key_dict[self.ip] = self.client_key
f.write(json.dumps(key_dict)) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement if_statement attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end 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 assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier | Save the current client key. |
def add_sim_options(p):
p.add_option("--distance", default=500, type="int",
help="Outer distance between the two ends [default: %default]")
p.add_option("--readlen", default=150, type="int",
help="Length of the read")
p.set_depth(depth=10)
p.set_outfile(outfile=None) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list keyword_argument identifier none | Add options shared by eagle or wgsim. |
def add_filter(self, name, filter_values):
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [filter_values, ]
self.filter_values[name] = filter_values
f = self.facets[name].add_filter(filter_values)
if f is None:
return
self._filters[name] = f | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list identifier tuple identifier identifier block if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier list identifier expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute subscript attribute identifier identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment subscript attribute identifier identifier identifier identifier | Add a filter for a facet. |
def namedb_get_value_hash_txids(cur, value_hash):
query = 'SELECT txid FROM history WHERE value_hash = ? ORDER BY block_id,vtxindex;'
args = (value_hash,)
rows = namedb_query_execute(cur, query, args)
txids = []
for r in rows:
txid = str(r['txid'])
txids.append(txid)
return txids | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier tuple identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Get the list of txs that sent this value hash, ordered by block and vtxindex |
def plot_sections(self, fout_dir=".", **kws_usr):
kws_plt, _ = self._get_kws_plt(None, **kws_usr)
PltGroupedGos(self).plot_sections(fout_dir, **kws_plt) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list none dictionary_splat identifier expression_statement call attribute call identifier argument_list identifier identifier argument_list identifier dictionary_splat identifier | Plot groups of GOs which have been placed in sections. |
def _get_labels_right(self, validate=None):
labels = []
for compare_func in self.features:
labels = labels + listify(compare_func.labels_right)
if not is_label_dataframe(labels, validate):
error_msg = "label is not found in the dataframe"
raise KeyError(error_msg)
return unique(labels) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier binary_operator identifier call identifier argument_list attribute identifier identifier if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list identifier return_statement call identifier argument_list identifier | Get all labels of the right dataframe. |
def unicode_left(s, width):
i = 0
j = 0
for ch in s:
j += __unicode_width_mapping[east_asian_width(ch)]
if width < j:
break
i += 1
return s[:i] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier integer for_statement identifier identifier block expression_statement augmented_assignment identifier subscript identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block break_statement expression_statement augmented_assignment identifier integer return_statement subscript identifier slice identifier | Cut unicode string from left to fit a given width. |
def display_image(self, reset=1):
try:
fb = self.server.controller.get_frame(self.frame)
except KeyError:
fb = self.server.controller.init_frame(self.frame)
if not fb.height:
width = fb.width
height = int(len(fb.buffer) / width)
fb.height = height
if (len(fb.buffer) > 0) and (height > 0):
self.server.controller.display(self.frame, width, height,
True)
else:
self.server.controller.display(self.frame, fb.width, fb.height,
False) | module function_definition identifier parameters identifier default_parameter identifier integer block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier if_statement not_operator attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier if_statement boolean_operator parenthesized_expression comparison_operator call identifier argument_list attribute identifier identifier integer parenthesized_expression comparison_operator identifier integer block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier identifier identifier true else_clause block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier false | Utility routine used to display an updated frame from a framebuffer. |
def _include_query_example(self, f, method, path, api_version, server_type):
m = method["method"].lower()
query_path = "{}_{}_{}.txt".format(server_type, m, self._file_path(path))
if os.path.isfile(os.path.join(self._directory, "api", "examples", query_path)):
f.write("Sample session\n***************\n")
f.write("\n\n.. literalinclude:: ../../../examples/{}\n\n".format(query_path)) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier if_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end identifier argument_list identifier | If a sample session is available we include it in documentation |
def _build_calmar_data(self):
assert self.initial_weight_name is not None
data = pd.DataFrame()
data[self.initial_weight_name] = self.initial_weight * self.filter_by
for variable in self.margins_by_variable:
if variable == 'total_population':
continue
assert variable in self.survey_scenario.tax_benefit_system.variables
period = self.period
data[variable] = self.survey_scenario.calculate_variable(variable = variable, period = period)
return data | module function_definition identifier parameters identifier block assert_statement comparison_operator attribute identifier identifier none expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block continue_statement assert_statement comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment subscript identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Builds the data dictionnary used as calmar input argument |
def user(self, email: str) -> models.User:
return self.User.query.filter_by(email=email).first() | module function_definition identifier parameters identifier typed_parameter identifier type identifier type attribute identifier identifier block return_statement call attribute call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list | Fetch a user from the database. |
def list_templates():
templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))]
return templates | module function_definition identifier parameters block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end return_statement identifier | Returns a list of all templates. |
def _createValueObjects(self, valueList, varList, mapTable, indexMap, contaminant, replaceParamFile):
def assign_values_to_table(value_list, layer_id):
for i, value in enumerate(value_list):
value = vrp(value, replaceParamFile)
mtValue = MTValue(variable=varList[i], value=float(value))
mtValue.index = mtIndex
mtValue.mapTable = mapTable
mtValue.layer_id = layer_id
if contaminant:
mtValue.contaminant = contaminant
for row in valueList:
mtIndex = MTIndex(index=row['index'], description1=row['description1'], description2=row['description2'])
mtIndex.indexMap = indexMap
if len(np.shape(row['values'])) == 2:
for layer_id, values in enumerate(row['values']):
assign_values_to_table(values, layer_id)
else:
assign_values_to_table(row['values'], 0) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier identifier keyword_argument identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier if_statement identifier block expression_statement assignment attribute identifier identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end integer block for_statement pattern_list identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier else_clause block expression_statement call identifier argument_list subscript identifier string string_start string_content string_end integer | Populate GSSHAPY MTValue and MTIndex Objects Method |
def render_filter(self, next_filter):
next(next_filter)
while True:
data = (yield)
res = [self.cell_format(access(data)) for access in self.accessors]
next_filter.send(res) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier while_statement true block expression_statement assignment identifier parenthesized_expression yield expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Produce formatted output from the raw data stream. |
def load_roller_shutter(self, item):
rollershutter = RollerShutter.from_config(self.pyvlx, item)
self.add(rollershutter) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Load roller shutter from JSON. |
def update_billing_info(self, billing_info):
url = urljoin(self._url, '/billing_info')
response = billing_info.http_request(url, 'PUT', billing_info,
{'Content-Type': 'application/xml; charset=utf-8'})
if response.status == 200:
pass
elif response.status == 201:
billing_info._url = response.getheader('Location')
else:
billing_info.raise_http_error(response)
response_xml = response.read()
logging.getLogger('recurly.http.response').debug(response_xml)
billing_info.update_from_element(ElementTree.fromstring(response_xml)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier dictionary pair string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier integer block pass_statement elif_clause comparison_operator attribute identifier identifier integer block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier | Change this account's billing information to the given `BillingInfo`. |
def cli(self, method):
routes = getattr(method, '_hug_cli_routes', [])
routes.append(self.route)
method._hug_cli_routes = routes
return method | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end list expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Registers a method on an Object as a CLI route |
def copy_all(self, source_databox):
self.copy_headers(source_databox)
self.copy_columns(source_databox)
return self | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Copies the header and columns from source_databox to this databox. |
def column_spec_path(cls, project, location, dataset, table_spec, column_spec):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/datasets/{dataset}/tableSpecs/{table_spec}/columnSpecs/{column_spec}",
project=project,
location=location,
dataset=dataset,
table_spec=table_spec,
column_spec=column_spec,
) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Return a fully-qualified column_spec string. |
def _ed1(token):
insertion = {letter.join([token[:i], token[i:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)}
deletion = {''.join([token[:i], token[i+1:]]) for i in range(1, len(token) + 1)}
substitution = {letter.join([token[:i], token[i+1:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)}
transposition = {''.join([token[:i], token[i+1:i+2], token[i:i+1], token[i+2:]]) for i in range(1, len(token)-1)}
return set.union(insertion, deletion, substitution, transposition) | module function_definition identifier parameters identifier block expression_statement assignment identifier set_comprehension call attribute identifier identifier argument_list list subscript identifier slice identifier subscript identifier slice identifier for_in_clause identifier attribute identifier identifier for_in_clause identifier call identifier argument_list integer binary_operator call identifier argument_list identifier integer expression_statement assignment identifier set_comprehension call attribute string string_start string_end identifier argument_list list subscript identifier slice identifier subscript identifier slice binary_operator identifier integer for_in_clause identifier call identifier argument_list integer binary_operator call identifier argument_list identifier integer expression_statement assignment identifier set_comprehension call attribute identifier identifier argument_list list subscript identifier slice identifier subscript identifier slice binary_operator identifier integer for_in_clause identifier attribute identifier identifier for_in_clause identifier call identifier argument_list integer binary_operator call identifier argument_list identifier integer expression_statement assignment identifier set_comprehension call attribute string string_start string_end identifier argument_list list subscript identifier slice identifier subscript identifier slice binary_operator identifier integer binary_operator identifier integer subscript identifier slice identifier binary_operator identifier integer subscript identifier slice binary_operator identifier integer for_in_clause identifier call identifier argument_list integer binary_operator call identifier argument_list identifier integer return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | Return tokens the edit distance of which is one from the given token |
def start(self):
if self.cov_config and os.path.exists(self.cov_config):
self.config.option.rsyncdir.append(self.cov_config)
self.cov = coverage.coverage(source=self.cov_source,
data_file=self.cov_data_file,
config_file=self.cov_config)
self.cov.erase()
self.cov.start()
self.cov.config.paths['source'] = [self.topdir] | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier 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 assignment subscript attribute attribute attribute identifier identifier identifier identifier string string_start string_content string_end list attribute identifier identifier | Ensure coverage rc file rsynced if appropriate. |
def total_length(nrn_pop, neurite_type=NeuriteType.all):
nrns = _neuronfunc.neuron_population(nrn_pop)
return list(sum(section_lengths(n, neurite_type=neurite_type)) for n in nrns) | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier generator_expression call identifier argument_list call identifier argument_list identifier keyword_argument identifier identifier for_in_clause identifier identifier | Get the total length of all sections in the group of neurons or neurites |
def run_in_executor(f):
@wraps(f)
def new_f(self, *args, **kwargs):
if self.is_shutdown:
return
try:
future = self.executor.submit(f, self, *args, **kwargs)
future.add_done_callback(_future_completed)
except Exception:
log.exception("Failed to submit task to executor")
return new_f | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement attribute identifier identifier block return_statement try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | A decorator to run the given method in the ThreadPoolExecutor. |
def log_reject( self, block_id, vtxindex, op, op_data ):
debug_op = self.sanitize_op( op_data )
if 'history' in debug_op:
del debug_op['history']
log.debug("REJECT %s at (%s, %s) data: %s", op_get_opcode_name( op ), block_id, vtxindex,
", ".join( ["%s='%s'" % (k, debug_op[k]) for k in sorted(debug_op.keys())] ))
return | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block delete_statement subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end tuple identifier subscript identifier identifier for_in_clause identifier call identifier argument_list call attribute identifier identifier argument_list return_statement | Log a rejected operation |
def _set_reg(cls, reg):
cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS] | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier attribute identifier identifier | The writing complement of _get_reg |
def delete(self, uri, query=None, **kwargs):
return self.fetch('delete', uri, query, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier dictionary_splat identifier | make a DELETE request |
def update_all_tags_cache(self):
self._all_tags_cache = None
self._all_tags_cache_list = {}
self._all_tags_cache_list_admin = {}
self._organisational_tags_to_task = {}
self.get_all_tags()
self.get_all_tags_names_as_list()
self.get_organisational_tags_to_task() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier dictionary expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Force the cache refreshing |
def connection_made(self, transport):
self.transport = transport
sock = self.transport.get_extra_info("socket")
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.loop.call_soon(self.discover) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Method run when the UDP broadcast server is started |
def determine_actions(self, request, view):
from rest_framework.generics import GenericAPIView
actions = {}
excluded_methods = {'HEAD', 'OPTIONS', 'PATCH', 'DELETE'}
for method in set(view.allowed_methods) - excluded_methods:
view.request = clone_request(request, method)
try:
if isinstance(view, GenericAPIView):
has_object = view.lookup_url_kwarg or view.lookup_field in view.kwargs
elif method in {'PUT', 'POST'}:
has_object = method in {'PUT'}
else:
continue
if hasattr(view, 'check_permissions'):
view.check_permissions(view.request)
if has_object and hasattr(view, 'get_object'):
view.get_object()
except (exceptions.APIException, PermissionDenied, Http404):
pass
else:
serializer = view.get_serializer()
actions[method] = self.get_serializer_info(serializer)
finally:
view.request = request
return actions | module function_definition identifier parameters identifier identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier dictionary expression_statement assignment identifier set string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end for_statement identifier binary_operator call identifier argument_list attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list identifier identifier try_statement block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier elif_clause comparison_operator identifier set string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier comparison_operator identifier set string string_start string_content string_end else_clause block continue_statement if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator identifier call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list except_clause tuple attribute identifier identifier identifier identifier block pass_statement else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier finally_clause block expression_statement assignment attribute identifier identifier identifier return_statement identifier | Allow all allowed methods |
def logging_remove_filter(filter_id, **kwargs):
ctx = Context(**kwargs)
ctx.execute_action('logging:remove_filter', **{
'logging_service': ctx.repo.create_secure_service('logging'),
'filter_id': filter_id,
}) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary_splat dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end identifier | Remove filter by filter id. |
def getHosts(filename=None, hostlist=None):
if filename:
return getHostsFromFile(filename)
elif hostlist:
return getHostsFromList(hostlist)
elif getEnv() == "SLURM":
return getHostsFromSLURM()
elif getEnv() == "PBS":
return getHostsFromPBS()
elif getEnv() == "SGE":
return getHostsFromSGE()
else:
return getDefaultHosts() | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement identifier block return_statement call identifier argument_list identifier elif_clause identifier block return_statement call identifier argument_list identifier elif_clause comparison_operator call identifier argument_list string string_start string_content string_end block return_statement call identifier argument_list elif_clause comparison_operator call identifier argument_list string string_start string_content string_end block return_statement call identifier argument_list elif_clause comparison_operator call identifier argument_list string string_start string_content string_end block return_statement call identifier argument_list else_clause block return_statement call identifier argument_list | Return a list of hosts depending on the environment |
def read(fname):
content = None
with open(os.path.join(here, fname)) as f:
content = f.read()
return content | module function_definition identifier parameters identifier block expression_statement assignment identifier none with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | Quick way to read a file content. |
def _secret_generator(baseline):
for filename, secrets in baseline['results'].items():
for secret in secrets:
yield filename, secret | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list block for_statement identifier identifier block expression_statement yield expression_list identifier identifier | Generates secrets to audit, from the baseline |
def build_wheel(self, wheel, directory, compile_c=True):
arguments = ['--no-deps', '--wheel-dir', directory, wheel]
env_vars = self._osutils.environ()
shim = ''
if not compile_c:
env_vars.update(pip_no_compile_c_env_vars)
shim = pip_no_compile_c_shim
self._execute('wheel', arguments,
env_vars=env_vars, shim=shim) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier string string_start string_end if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier identifier keyword_argument identifier identifier | Build an sdist into a wheel file. |
def add(self, list_id, email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False):
validate_consent_to_track(consent_to_track)
body = {
"EmailAddress": email_address,
"Name": name,
"CustomFields": custom_fields,
"Resubscribe": resubscribe,
"ConsentToTrack": consent_to_track,
"RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders}
response = self._post("/subscribers/%s.json" %
list_id, json.dumps(body))
return json_to_py(response) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier default_parameter identifier false block expression_statement call identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier 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 identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Adds a subscriber to a subscriber list. |
def compileMatchList(self):
self.matchList = []
numChar = len(self.toReplace)
if numChar == 0:
return
stop = 0
text = self.qteWidget.text()
while True:
start = text.find(self.toReplace, stop)
if start == -1:
break
else:
stop = start + numChar
self.matchList.append((start, stop)) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier list expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator identifier integer block return_statement expression_statement assignment identifier integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier if_statement comparison_operator identifier unary_operator integer block break_statement else_clause block expression_statement assignment identifier binary_operator identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier | Compile the list of spans of every match. |
def load(self, value):
self.reset(
value,
validator=self.__dict__.get('validator'),
env=self.__dict__.get('env'),
) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | enforce env > value when loading from file |
def on_breakpoints_changed(self, removed=False):
if not self.ready_to_run:
return
self.mtime += 1
if not removed:
self.set_tracing_for_untraced_contexts() | module function_definition identifier parameters identifier default_parameter identifier false block if_statement not_operator attribute identifier identifier block return_statement expression_statement augmented_assignment attribute identifier identifier integer if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list | When breakpoints change, we have to re-evaluate all the assumptions we've made so far. |
def _render(self, text):
parser = commonmark.Parser()
ast = parser.parse(text)
renderer = HtmlRenderer(self)
html = renderer.render(ast)
return html | module function_definition identifier parameters identifier identifier 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 identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Render CommonMark with ettings taken in account |
def __exists_row_not_too_old(self, row):
if row is None:
return False
record_time = dateutil.parser.parse(row[2])
now = datetime.datetime.now(dateutil.tz.gettz())
age = (record_time - now).total_seconds()
if age > self.max_age:
return False
return True | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement false expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute parenthesized_expression binary_operator identifier identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block return_statement false return_statement true | Check if the given row exists and is not too old |
def render_roughpage(request, t):
import django
if django.VERSION >= (1, 8):
c = {}
response = HttpResponse(t.render(c, request))
else:
c = RequestContext(request)
response = HttpResponse(t.render(c))
return response | module function_definition identifier parameters identifier identifier block import_statement dotted_name identifier if_statement comparison_operator attribute identifier identifier tuple integer integer block expression_statement assignment identifier dictionary expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier | Internal interface to the rough page view. |
def address(self):
self._address, value = self.get_attr_string(self._address, 'address')
return value | module function_definition identifier parameters identifier block expression_statement assignment pattern_list attribute identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end return_statement identifier | Returns the name of the port that this motor is connected to. |
def _pending_of(self, workload):
pending = sum(list(scope.values()).count(False) for scope in workload.values())
return pending | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier generator_expression call attribute call identifier argument_list call attribute identifier identifier argument_list identifier argument_list false for_in_clause identifier call attribute identifier identifier argument_list return_statement identifier | Return the number of pending tests in a workload. |
def visit_DictComp(self, node: AST, dfltChaining: bool = True) -> str:
return f"{{{self.visit(node.key)}: {self.visit(node.value)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}}}" | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier true type identifier block return_statement concatenated_string string string_start string_content escape_interpolation interpolation call attribute identifier identifier argument_list attribute identifier identifier string_content interpolation call attribute identifier identifier argument_list attribute identifier identifier string_content string_end string string_start interpolation call attribute string string_start string_content string_end identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier string_content escape_interpolation string_end | Return `node`s representation as dict comprehension. |
def save_to(self, obj):
if isinstance(obj, dict):
obj = dict(obj)
for key in self.changed_fields:
if key in self.cleaned_data:
val = self.cleaned_data.get(key)
set_obj_value(obj, key, val)
return obj | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier return_statement identifier | Save the cleaned data to an object. |
def latlon_round(latlon, spacing=1000):
g = latlon_to_grid(latlon)
g.easting = (g.easting // spacing) * spacing
g.northing = (g.northing // spacing) * spacing
return g.latlon() | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier identifier identifier expression_statement assignment attribute identifier identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list | round to nearest grid corner |
def apply_change(self, change):
text = change['text']
change_range = change.get('range')
if not change_range:
self._source = text
return
start_line = change_range['start']['line']
start_col = change_range['start']['character']
end_line = change_range['end']['line']
end_col = change_range['end']['character']
if start_line == len(self.lines):
self._source = self.source + text
return
new = io.StringIO()
for i, line in enumerate(self.lines):
if i < start_line:
new.write(line)
continue
if i > end_line:
new.write(line)
continue
if i == start_line:
new.write(line[:start_col])
new.write(text)
if i == end_line:
new.write(line[end_col:])
self._source = new.getvalue() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment attribute identifier identifier identifier return_statement expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end 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 assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier call identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier identifier return_statement expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier continue_statement if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier continue_statement if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier slice identifier expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier slice identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list | Apply a change to the document. |
def can_fetch_pool(self, request: Request):
url_info = request.url_info
user_agent = request.fields.get('User-agent', '')
if self._robots_txt_pool.has_parser(url_info):
return self._robots_txt_pool.can_fetch(url_info, user_agent)
else:
raise NotInPoolError() | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment identifier 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_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier else_clause block raise_statement call identifier argument_list | Return whether the request can be fetched based on the pool. |
def query_item(self, key, abis):
try:
key = int(key)
field = 'number'
except ValueError:
try:
key = int(key, 16)
field = 'number'
except ValueError:
field = 'name'
arg = and_(getattr(Item, field) == key,
or_(Item.abi == abi for abi in abis))
return self.session.query(Item).filter(arg).all() | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier string string_start string_content string_end except_clause identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier integer expression_statement assignment identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list comparison_operator call identifier argument_list identifier identifier identifier call identifier generator_expression comparison_operator attribute identifier identifier identifier for_in_clause identifier identifier return_statement call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list identifier identifier argument_list | Query items based on system call number or name. |
def read_bytes(self, count):
if self.pos + count > self.remaining_length:
return NC.ERR_PROTOCOL, None
ba = bytearray(count)
for x in xrange(0, count):
ba[x] = self.payload[self.pos]
self.pos += 1
return NC.ERR_SUCCESS, ba | module function_definition identifier parameters identifier identifier block if_statement comparison_operator binary_operator attribute identifier identifier identifier attribute identifier identifier block return_statement expression_list attribute identifier identifier none expression_statement assignment identifier call identifier argument_list identifier for_statement identifier call identifier argument_list integer identifier block expression_statement assignment subscript identifier identifier subscript attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer return_statement expression_list attribute identifier identifier identifier | Read count number of bytes. |
def _str_subgroups(self):
if not self.subgroups:
return ""
return ['subGroups %s'
% ' '.join(['%s=%s' % (k, v) for (k, v) in
self.subgroups.items()])] | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement string string_start string_end return_statement list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end tuple identifier identifier for_in_clause tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list | helper function to render subgroups as a string |
def extract_name(self, data):
name = re.search('<h1[^>]*>(.+?)</h1>', data).group(1)
name = re.sub(r'<([^>]+)>', r'', name)
name = re.sub(r'>', r'>', name)
name = re.sub(r'<', r'<', name)
return name | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier return_statement identifier | Extract man page name from web page. |
def set(self, value):
if self.is_value_set:
_LOG.warning(
'Overriding previous measurement %s value of %s with %s, the old '
'value will be lost. Use a dimensioned measurement if you need to '
'save multiple values.', self.name, self.stored_value, value)
if value is None:
_LOG.warning('Measurement %s is set to None', self.name)
self.stored_value = value
self._cached_value = data.convert_to_base_types(value)
self.is_value_set = True | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end attribute identifier identifier attribute identifier identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier true | Set the value for this measurement, with some sanity checks. |
def run(self):
while self.status != 'EXIT':
print(self.process_input(self.get_input()))
print('Bye') | module function_definition identifier parameters identifier block while_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end | loops until exit command given |
def export_osm_file(self):
osm = create_elem('osm', {'generator': self.generator,
'version': self.version})
osm.extend(obj.toosm() for obj in self)
return etree.ElementTree(osm) | module function_definition identifier parameters identifier block expression_statement assignment identifier 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 attribute identifier identifier expression_statement call attribute identifier identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier identifier return_statement call attribute identifier identifier argument_list identifier | Generate OpenStreetMap element tree from ``Osm``. |
def flatten(lis):
new_lis = []
for item in lis:
if isinstance(item, collections.Sequence) and not isinstance(item, basestring):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier not_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Given a list, possibly nested to any level, return it flattened. |
def _init_from_file(self, filename):
if not filename.endswith("detx"):
raise NotImplementedError('Only the detx format is supported.')
self._open_file(filename)
self._extract_comments()
self._parse_header()
self._parse_doms()
self._det_file.close() | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Create detector from detx file. |
def walk_nodes(self, node, original):
try:
nodelist = self.parser.get_nodelist(node, original=original)
except TypeError:
nodelist = self.parser.get_nodelist(node, original=original, context=None)
for node in nodelist:
if isinstance(node, SassSrcNode):
if node.is_sass:
yield node
else:
for node in self.walk_nodes(node, original=original):
yield node | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier except_clause identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier none for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement attribute identifier identifier block expression_statement yield identifier else_clause block for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier block expression_statement yield identifier | Iterate over the nodes recursively yielding the templatetag 'sass_src' |
async def _reconnect(self):
for msg_class in self._transactions:
_1, _2, _3, coroutine_abrt, _4 = self._msgs_registered[msg_class]
if coroutine_abrt is not None:
for key in self._transactions[msg_class]:
for args, kwargs in self._transactions[msg_class][key]:
self._loop.create_task(coroutine_abrt(key, *args, **kwargs))
self._transactions[msg_class] = {}
await self._on_disconnect()
for task in self._restartable_tasks:
task.cancel()
self._restartable_tasks = []
self._socket.disconnect(self._router_addr)
await self.client_start() | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier identifier subscript attribute identifier identifier identifier if_statement comparison_operator identifier none block for_statement identifier subscript attribute identifier identifier identifier block for_statement pattern_list identifier identifier subscript subscript attribute identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment subscript attribute identifier identifier identifier dictionary expression_statement await call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement await call attribute identifier identifier argument_list | Called when the remote server is innacessible and the connection has to be restarted |
def infer_compartment_entries(model):
compartment_ids = set()
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
for compound, _ in equation.compounds:
compartment = compound.compartment
if compartment is None:
compartment = model.default_compartment
if compartment is not None:
compartment_ids.add(compartment)
for compartment in compartment_ids:
if compartment in model.compartments:
continue
entry = DictCompartmentEntry(dict(id=compartment))
model.compartments.add_entry(entry) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block continue_statement for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement assignment identifier call identifier argument_list call identifier argument_list keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Infer compartment entries for model based on reaction compounds. |
def _read_component_definitions(self, graph):
for e in self._get_elements(graph, SBOL.ComponentDefinition):
identity = e[0]
c = self._get_rdf_identified(graph, identity)
c['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role)
c['types'] = self._get_triplet_value_list(graph, identity, SBOL.type)
obj = ComponentDefinition(**c)
self._components[identity.toPython()] = obj
self._collection_store[identity.toPython()] = obj | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier identifier attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list identifier | Read graph and add component defintions to document |
def show_customer(self, customer_id):
request = self._get('customers/' + str(customer_id))
return self.responder(request) | 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 call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Shows an existing customer. |
def sum(self, weights=None):
if weights is None:
weights = self.data.weights
return utils.bincount(self.labels, weights, self.N) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier | return the sum of weights of each object |
def assign(self, dst, req, src):
if req == 'null':
return
elif req in ('write', 'inplace'):
dst[:] = src
elif req == 'add':
dst[:] += src | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block return_statement elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript identifier slice identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment subscript identifier slice identifier | Helper function for assigning into dst depending on requirements. |
def pre_dissect(self, s):
length = len(s)
if length < _NTP_PACKET_MIN_SIZE:
err = " ({}".format(length) + " is < _NTP_PACKET_MIN_SIZE "
err += "({})).".format(_NTP_PACKET_MIN_SIZE)
raise _NTPInvalidDataException(err)
return s | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end expression_statement augmented_assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier raise_statement call identifier argument_list identifier return_statement identifier | Check that the payload is long enough to build a NTP packet. |
def _to_hours_mins_secs(time_taken):
mins, secs = divmod(time_taken, 60)
hours, mins = divmod(mins, 60)
return hours, mins, secs | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier integer expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier integer return_statement expression_list identifier identifier identifier | Convert seconds to hours, mins, and seconds. |
def avail_images(conn=None, call=None):
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for appliance in conn.list_appliances():
ret[appliance['name']] = appliance
return ret | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier string string_start string_content string_end 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 identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier subscript identifier string string_start string_content string_end identifier return_statement identifier | Return a list of the server appliances that are on the provider |
def strip_possessives(self, word):
if word.endswith("'s'"):
return word[:-3]
elif word.endswith("'s"):
return word[:-2]
elif word.endswith("'"):
return word[:-1]
else:
return word | module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement subscript identifier slice unary_operator integer elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block return_statement subscript identifier slice unary_operator integer elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block return_statement subscript identifier slice unary_operator integer else_clause block return_statement identifier | Get rid of apostrophes indicating possession. |
def post(self, endpoint: str, **kwargs) -> dict:
return self._request('POST', endpoint, **kwargs) | module function_definition identifier parameters identifier typed_parameter identifier type identifier dictionary_splat_pattern identifier type identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier dictionary_splat identifier | HTTP POST operation to API endpoint. |
def create(gandi, name, vm, size, snapshotprofile, datacenter, source,
background):
try:
gandi.datacenter.is_opened(datacenter, 'iaas')
except DatacenterLimited as exc:
gandi.echo('/!\ Datacenter %s will be closed on %s, '
'please consider using another datacenter.' %
(datacenter, exc.date))
if vm:
vm_dc = gandi.iaas.info(vm)
vm_dc_id = vm_dc['datacenter_id']
dc_id = int(gandi.datacenter.usable_id(datacenter))
if vm_dc_id != dc_id:
gandi.echo('/!\ VM %s datacenter will be used instead of %s.'
% (vm, datacenter))
datacenter = vm_dc_id
output_keys = ['id', 'type', 'step']
name = name or randomstring('vdi')
disk_type = 'data'
oper = gandi.disk.create(name, vm, size, snapshotprofile, datacenter,
source, disk_type, background)
if background:
output_generic(gandi, oper, output_keys)
return oper | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end tuple identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier boolean_operator identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier identifier identifier identifier identifier if_statement identifier block expression_statement call identifier argument_list identifier identifier identifier return_statement identifier | Create a new disk. |
def debug(self, text):
self.logger.debug("{}{}".format(self.message_prefix, text)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier | Ajout d'un message de log de type DEBUG |
def start(name, config_file=None):
if not exists(name):
raise ContainerNotExists("The container (%s) does not exist!" % name)
if name in running():
raise ContainerAlreadyRunning('The container %s is already started!' % name)
cmd = ['lxc-start', '-n', name, '-d']
if config_file:
cmd += ['-f', config_file]
subprocess.check_call(cmd) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier if_statement comparison_operator identifier call identifier argument_list block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end if_statement identifier block expression_statement augmented_assignment identifier list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier | starts a container in daemon mode |
def _set_cpu_throttling(self):
if not self.is_running():
return
try:
if sys.platform.startswith("win") and hasattr(sys, "frozen"):
cpulimit_exec = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "cpulimit", "cpulimit.exe")
else:
cpulimit_exec = "cpulimit"
subprocess.Popen([cpulimit_exec, "--lazy", "--pid={}".format(self._process.pid), "--limit={}".format(self._cpu_throttling)], cwd=self.working_dir)
log.info("CPU throttled to {}%".format(self._cpu_throttling))
except FileNotFoundError:
raise QemuError("cpulimit could not be found, please install it or deactivate CPU throttling")
except (OSError, subprocess.SubprocessError) as e:
raise QemuError("Could not throttle CPU: {}".format(e)) | module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list block return_statement try_statement block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end except_clause as_pattern tuple identifier attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Limits the CPU usage for current QEMU process. |
def delete_object(self, cont, obj):
try:
self.conn.delete_object(cont, obj)
return True
except Exception as exc:
log.error('There was an error::')
if hasattr(exc, 'code') and hasattr(exc, 'msg'):
log.error(' Code: %s: %s', exc.code, exc.msg)
log.error(' Content: \n%s', getattr(exc, 'read', lambda: six.text_type(exc))())
return False | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement true except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end call call identifier argument_list identifier string string_start string_content string_end lambda call attribute identifier identifier argument_list identifier argument_list return_statement false | Delete a file from Swift |
def validate(self, sig=None):
if sig is not None:
sig_mtime, sig_size, sig_md5 = sig
else:
try:
with open(self.sig_file()) as sig:
sig_mtime, sig_size, sig_md5 = sig.read().strip().split()
except:
return False
if not self.exists():
if (self + '.zapped').is_file():
with open(self + '.zapped') as sig:
line = sig.readline()
return sig_md5 == line.strip().rsplit('\t', 3)[-1]
else:
return False
if sig_mtime == os.path.getmtime(self) and sig_size == os.path.getsize(
self):
return True
return fileMD5(self) == sig_md5 | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier identifier identifier else_clause block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier argument_list except_clause block return_statement false if_statement not_operator call attribute identifier identifier argument_list block if_statement call attribute parenthesized_expression binary_operator identifier string string_start string_content string_end identifier argument_list block with_statement with_clause with_item as_pattern call identifier argument_list binary_operator identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement comparison_operator identifier subscript call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end integer unary_operator integer else_clause block return_statement false if_statement boolean_operator comparison_operator identifier call attribute attribute identifier identifier identifier argument_list identifier comparison_operator identifier call attribute attribute identifier identifier identifier argument_list identifier block return_statement true return_statement comparison_operator call identifier argument_list identifier identifier | Check if file matches its signature |
def values_for_column(self,
column_name,
limit=10000):
logging.info(
'Getting values for columns [{}] limited to [{}]'
.format(column_name, limit))
if self.fetch_values_from:
from_dttm = utils.parse_human_datetime(self.fetch_values_from)
else:
from_dttm = datetime(1970, 1, 1)
qry = dict(
datasource=self.datasource_name,
granularity='all',
intervals=from_dttm.isoformat() + '/' + datetime.now().isoformat(),
aggregations=dict(count=count('count')),
dimension=column_name,
metric='count',
threshold=limit,
)
client = self.cluster.get_pydruid_client()
client.topn(**qry)
df = client.export_pandas()
return [row[column_name] for row in df.to_records(index=False)] | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list integer integer integer expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier binary_operator binary_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier call identifier argument_list keyword_argument identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement list_comprehension subscript identifier identifier for_in_clause identifier call attribute identifier identifier argument_list keyword_argument identifier false | Retrieve some values for the given column |
def _check_config_exists(config_file=None):
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True | module function_definition identifier parameters default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block return_statement false return_statement true | Verify the config file is present |
def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right) | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type string string_start string_content string_end block return_statement call identifier generator_expression tuple tuple identifier identifier identifier for_in_clause pattern_list tuple_pattern identifier identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier | Returns the induced subgraph where only the nodes from the given sets are included. |
def stop(self):
try:
self.aitask.stop()
self.aotask.stop()
pass
except:
print u"No task running"
self.aitask = None
self.aotask = None | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list pass_statement except_clause block print_statement string string_start string_content string_end expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none | Halts the acquisition, this must be called before resetting acquisition |
async def get_image(
self,
input_source: str,
output_format: str = IMAGE_JPEG,
extra_cmd: Optional[str] = None,
timeout: int = 15,
) -> Optional[bytes]:
command = ["-an", "-frames:v", "1", "-c:v", output_format]
is_open = await self.open(
cmd=command,
input_source=input_source,
output="-f image2pipe -",
extra_cmd=extra_cmd,
)
if not is_open:
_LOGGER.warning("Error starting FFmpeg.")
return None
try:
proc_func = functools.partial(self._proc.communicate, timeout=timeout)
image, _ = await self._loop.run_in_executor(None, proc_func)
return image
except (subprocess.TimeoutExpired, ValueError):
_LOGGER.warning("Timeout reading image.")
self.kill()
return None | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier none typed_default_parameter identifier type identifier integer type generic_type identifier type_parameter type identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier await call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement none try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier await call attribute attribute identifier identifier identifier argument_list none identifier return_statement identifier except_clause tuple attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list return_statement none | Open FFmpeg process as capture 1 frame. |
def cast_item(cls, item):
if not isinstance(item, cls.subtype):
incompatible = isinstance(item, Base) and not any(
issubclass(cls.subtype, tag_type) and isinstance(item, tag_type)
for tag_type in cls.all_tags.values()
)
if incompatible:
raise IncompatibleItemType(item, cls.subtype)
try:
return cls.subtype(item)
except EndInstantiation:
raise ValueError('List tags without an explicit subtype must '
'either be empty or instantiated with '
'elements from which a subtype can be '
'inferred') from None
except (IncompatibleItemType, CastError):
raise
except Exception as exc:
raise CastError(item, cls.subtype) from exc
return item | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier boolean_operator call identifier argument_list identifier identifier not_operator call identifier generator_expression boolean_operator call identifier argument_list attribute identifier identifier identifier call identifier argument_list identifier identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block raise_statement call identifier argument_list identifier attribute identifier identifier try_statement block return_statement call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end none except_clause tuple identifier identifier block raise_statement except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier attribute identifier identifier identifier return_statement identifier | Cast list item to the appropriate tag type. |
def actions_for_project(self, project):
project.cflags = ["-O3", "-fno-omit-frame-pointer"]
project.runtime_extension = time.RunWithTime(
run.RuntimeExtension(project, self))
return self.default_runtime_actions(project) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier list string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list identifier | Compile & Run the experiment with -O3 enabled. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.