code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def area2lonlat(dataarray):
area = dataarray.attrs['area']
lons, lats = area.get_lonlats_dask()
lons = xr.DataArray(lons, dims=['y', 'x'],
attrs={'name': "longitude",
'standard_name': "longitude",
'units': 'degrees_east'},
name='longitude')
lats = xr.DataArray(lats, dims=['y', 'x'],
attrs={'name': "latitude",
'standard_name': "latitude",
'units': 'degrees_north'},
name='latitude')
dataarray.attrs['coordinates'] = 'longitude latitude'
return [dataarray, lons, lats] | 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 pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end return_statement list identifier identifier identifier | Convert an area to longitudes and latitudes. |
def explorev2(self, datasource_type, datasource_id):
return redirect(url_for(
'Superset.explore',
datasource_type=datasource_type,
datasource_id=datasource_id,
**request.args)) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat attribute identifier identifier | Deprecated endpoint, here for backward compatibility of urls |
def force_single_imports(self):
for import_stmt in self.imports[:]:
import_info = import_stmt.import_info
if import_info.is_empty() or import_stmt.readonly:
continue
if len(import_info.names_and_aliases) > 1:
for name_and_alias in import_info.names_and_aliases:
if hasattr(import_info, "module_name"):
new_import = importinfo.FromImport(
import_info.module_name, import_info.level,
[name_and_alias])
else:
new_import = importinfo.NormalImport([name_and_alias])
self.add_import(new_import)
import_stmt.empty_import() | module function_definition identifier parameters identifier block for_statement identifier subscript attribute identifier identifier slice block expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator call attribute identifier identifier argument_list attribute identifier identifier block continue_statement if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | force a single import per statement |
def update_ticket(self, ticket_id, **kwargs):
url = 'tickets/%d' % ticket_id
ticket = self._api._put(url, data=json.dumps(kwargs))
return Ticket(**ticket) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list dictionary_splat identifier | Updates a ticket from a given ticket ID |
def subset(data, sel0, sel1):
data = np.asarray(data)
if data.ndim < 2:
raise ValueError('data must have 2 or more dimensions')
sel0 = asarray_ndim(sel0, 1, allow_none=True)
sel1 = asarray_ndim(sel1, 1, allow_none=True)
if sel0 is not None and sel0.dtype.kind == 'b':
sel0, = np.nonzero(sel0)
if sel1 is not None and sel1.dtype.kind == 'b':
sel1, = np.nonzero(sel1)
if sel0 is not None and sel1 is not None:
sel0 = sel0[:, np.newaxis]
if sel0 is None:
sel0 = _total_slice
if sel1 is None:
sel1 = _total_slice
return data[sel0, sel1] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier integer keyword_argument identifier true expression_statement assignment identifier call identifier argument_list identifier integer keyword_argument identifier true if_statement boolean_operator comparison_operator identifier none comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block expression_statement assignment identifier subscript identifier slice attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier identifier return_statement subscript identifier identifier identifier | Apply selections on first and second axes. |
def _dismiss_worker(self, worker):
self._workers.remove(worker)
if len(self._workers) < self._min_workers:
self._workers.add(worker)
return False
return True | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement false return_statement true | Dismiss ``worker`` unless it is still required |
def get(self, thread_uuid, uuid):
members = (v for v in self.list(thread_uuid) if v.get('userUuid') == uuid)
for i in members:
self.log.debug(i)
return i
return None | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier generator_expression identifier for_in_clause identifier call attribute identifier identifier argument_list identifier if_clause comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier return_statement none | Get one thread member. |
def crashlog_clean(name, timestamp, size, **kwargs):
ctx = Context(**kwargs)
ctx.execute_action('crashlog:clean', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'size': size,
'timestamp': timestamp,
}) | module function_definition identifier parameters identifier identifier 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 pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | For application NAME leave SIZE crashlogs or remove all crashlogs with timestamp > TIMESTAMP. |
def wait_for_ssh(ip):
for _ in range(12):
with safe_socket() as s:
try:
s.connect((ip, 22))
return True
except socket.timeout:
pass
time.sleep(10)
return False | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list integer block with_statement with_clause with_item as_pattern call identifier argument_list as_pattern_target identifier block try_statement block expression_statement call attribute identifier identifier argument_list tuple identifier integer return_statement true except_clause attribute identifier identifier block pass_statement expression_statement call attribute identifier identifier argument_list integer return_statement false | Wait for SSH to be available at given IP address. |
def _extract_germline(in_file, data):
out_file = "%s-germline.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
reader = cyvcf2.VCF(str(in_file))
reader.add_filter_to_header({'ID': 'Somatic', 'Description': 'Variant called as Somatic'})
with open(tx_out_file, "w") as out_handle:
out_handle.write(reader.raw_header)
for rec in reader:
rec = _update_germline_filters(rec)
out_handle.write(str(rec))
return out_file | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end subscript call attribute identifier identifier argument_list identifier integer if_statement boolean_operator not_operator call attribute identifier identifier argument_list identifier identifier not_operator call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier | Extract germline calls non-somatic, non-filtered calls. |
def _attach_config(mfg_event, record):
if 'config' not in record.metadata:
return
attachment = mfg_event.attachment.add()
attachment.name = 'config'
attachment.value_binary = _convert_object_to_json(record.metadata['config'])
attachment.type = test_runs_pb2.TEXT_UTF8 | module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier attribute identifier identifier | Attaches the OpenHTF config file as JSON. |
def OnTextSize(self, event):
try:
size = int(event.GetString())
except Exception:
size = get_default_font().GetPointSize()
post_command_event(self, self.FontSizeMsg, size=size) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list except_clause identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list expression_statement call identifier argument_list identifier attribute identifier identifier keyword_argument identifier identifier | Text size combo text event handler |
def find_silent_exception(node):
return (
isinstance(node, ast.ExceptHandler)
and node.type is None
and len(node.body) == 1
and isinstance(node.body[0], ast.Pass)
) | module function_definition identifier parameters identifier block return_statement parenthesized_expression boolean_operator boolean_operator boolean_operator call identifier argument_list identifier attribute identifier identifier comparison_operator attribute identifier identifier none comparison_operator call identifier argument_list attribute identifier identifier integer call identifier argument_list subscript attribute identifier identifier integer attribute identifier identifier | Finds silent generic exceptions |
def timeit(output):
b = time.time()
yield
print output, 'time used: %.3fs' % (time.time()-b) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement yield print_statement identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator call attribute identifier identifier argument_list identifier | If output is string, then print the string and also time used |
def percent(self, value: float) -> 'Size':
raise_not_number(value)
self.maximum = '{}%'.format(value)
return self | module function_definition identifier parameters identifier typed_parameter identifier type identifier type string string_start string_content string_end block expression_statement call identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Set the percentage of free space to use. |
def register_class(cls):
if cls.appname in LinkFactory._class_dict:
return
LinkFactory.register(cls.appname, cls) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Regsiter this class in the `LinkFactory` |
def sendTemplate(mailer, sender, recipient, template, context, hook=_nop):
headers, parts = template.evaluate(context)
headers["From"] = sender
headers["To"] = recipient
hook(headers, parts)
content = mime.buildMessage(headers, parts)
return mailer.send(sender, recipient, content) | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier | Simple case for sending some e-mail using a template. |
def index(self, alias):
clone = self._clone()
clone._index = alias
return clone | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier return_statement identifier | Selects which database this QuerySet should execute its query against. |
def page_response(self, title='', body=''):
f = StringIO()
f.write('<!DOCTYPE html>\n')
f.write('<html>\n')
f.write('<head><title>{}</title><head>\n'.format(title))
f.write('<body>\n<h2>{}</h2>\n'.format(title))
f.write('<div class="content">{}</div>\n'.format(body))
f.write('</body>\n</html>\n')
length = f.tell()
f.seek(0)
self.send_response(200)
encoding = sys.getfilesystemencoding()
self.send_header("Content-type", "text/html; charset=%s" % encoding)
self.send_header("Content-Length", str(length))
self.end_headers()
self.copyfile(f, self.wfile)
f.close() | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list integer 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 binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Helper to render an html page with dynamic content |
def _copy_source_to_target(self):
if self.source and self.target:
for k, v in self.source.items('config'):
self.target.set_input(k, v) | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier attribute identifier identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | copy source user configuration to target |
def fasta_cmd_get_seqs(acc_list,
blast_db=None,
is_protein=None,
out_filename=None,
params={},
WorkingDir=tempfile.gettempdir(),
SuppressStderr=None,
SuppressStdout=None):
if is_protein is None:
params["-p"] = 'G'
elif is_protein:
params["-p"] = 'T'
else:
params["-p"] = 'F'
if blast_db:
params["-d"] = blast_db
if out_filename:
params["-o"] = out_filename
params["-a"] = "F"
fasta_cmd = FastaCmd(params=params,
InputHandler='_input_as_string',
WorkingDir=WorkingDir,
SuppressStderr=SuppressStderr,
SuppressStdout=SuppressStdout)
return fasta_cmd("\"%s\"" % ','.join(acc_list)) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier dictionary default_parameter identifier call attribute identifier identifier argument_list default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end elif_clause identifier block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence string_end call attribute string string_start string_content string_end identifier argument_list identifier | Retrieve sequences for list of accessions |
def check_bbox(bbox):
for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]):
if not 0 <= value <= 1:
raise ValueError(
'Expected {name} for bbox {bbox} '
'to be in the range [0.0, 1.0], got {value}.'.format(
bbox=bbox,
name=name,
value=value,
)
)
x_min, y_min, x_max, y_max = bbox[:4]
if x_max <= x_min:
raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format(
bbox=bbox,
))
if y_max <= y_min:
raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format(
bbox=bbox,
)) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end subscript identifier slice integer block if_statement not_operator comparison_operator integer identifier integer block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier subscript identifier slice integer if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier | Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums |
def compliance(self, value):
if (self.api_version < '2.0'):
self.profile = value
else:
try:
self.profile[0] = value
except AttributeError:
self.profile = [value] | module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier identifier else_clause block try_statement block expression_statement assignment subscript attribute identifier identifier integer identifier except_clause identifier block expression_statement assignment attribute identifier identifier list identifier | Set the compliance profile URI. |
def _needs_elements(self, f):
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.elements == None:
self.getelements()
return f(self, *args, **kwargs)
return wrapper | module function_definition identifier parameters identifier 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 comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | Decorator used to make sure that there are elements prior to running the task. |
def _delete_chars(self, value):
value = int(value)
if value <= 0:
value = 1
for i in range(value):
self._cursor.deleteChar()
self._text_edit.setTextCursor(self._cursor)
self._last_cursor_pos = self._cursor.position() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier integer for_statement identifier call identifier argument_list identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list | Deletes the specified number of charachters. |
def _transform_coefficients(self, NN, HHw, CCw, ffparm, polycf,
any_pwl, npol, nw):
nnw = any_pwl + npol + nw
M = csr_matrix((ffparm[:, 3], (range(nnw), range(nnw))))
MR = M * ffparm[:, 2]
HMR = HHw * MR
MN = M * NN
HH = MN.T * HHw * MN
CC = MN.T * (CCw - HMR)
C0 = 1./2. * MR.T * HMR + sum(polycf[:, 2])
return HH, CC, C0[0] | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator identifier identifier identifier expression_statement assignment identifier call identifier argument_list tuple subscript identifier slice integer tuple call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier subscript identifier slice integer expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator identifier identifier expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator float float attribute identifier identifier identifier call identifier argument_list subscript identifier slice integer return_statement expression_list identifier identifier subscript identifier integer | Transforms quadratic coefficients for w into coefficients for x. |
def generate_route(self, route):
self.emit('')
self.emit('route %s (%s, %s, %s)' % (
route.name,
self.format_data_type(route.arg_data_type),
self.format_data_type(route.result_data_type),
self.format_data_type(route.error_data_type)
))
with self.indent():
if route.doc is not None:
self.emit(self.format_string(route.doc)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier with_statement with_clause with_item call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier | Output a route definition. |
def _refresh_path(self):
if os.path.exists(self.path):
try:
i = open(self.path, 'r')
i.close()
juicer.utils.Log.log_debug("Successfully read item at: %s" % self.path)
except:
raise IOError("Error while attempting to access item at path: %s" % self.path)
else:
raise IOError("Could not locate item at path: %s" % self.path) | module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier except_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Does it exist? Can we read it? Is it an RPM? |
def __create_xml_request(self, text):
soap_root = ET.Element('soap:Envelope', {
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:soap': 'http://schemas.xmlsoap.org/soap/envelope/', })
body = ET.SubElement(soap_root, 'soap:Body')
process_text = ET.SubElement(body, 'ProcessText', {
'xmlns': 'http://typograf.artlebedev.ru/webservices/', })
ET.SubElement(process_text, 'text').text = text
ET.SubElement(process_text, 'entityType').text = str(self._entityType)
ET.SubElement(process_text, 'useBr').text = str(self._useBr)
ET.SubElement(process_text, 'useP').text = str(self._useP)
ET.SubElement(process_text, 'maxNobr').text = str(self._maxNobr)
string = Container()
soap = ET.ElementTree(soap_root)
soap.write(string, encoding=self._encoding, xml_declaration=True)
if PY3:
return string.getvalue().decode(self._encoding)
return string.getvalue() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list 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 dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier identifier expression_statement assignment attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true if_statement identifier block return_statement call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list | make xml content from given text |
def register_single(key, value, param=None):
get_current_scope().container.register(key, lambda: value, param) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute attribute call identifier argument_list identifier identifier argument_list identifier lambda identifier identifier | Generates resolver to return singleton value and adds it to global container |
def apply_filters(df, filters):
idx = pd.Series([True]*df.shape[0])
for k, v in list(filters.items()):
if k not in df.columns:
continue
idx &= (df[k] == v)
return df.loc[idx] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator list true subscript attribute identifier identifier integer for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement augmented_assignment identifier parenthesized_expression comparison_operator subscript identifier identifier identifier return_statement subscript attribute identifier identifier identifier | Basic filtering for a dataframe. |
def setdefault(obj, field, default):
setattr(obj, field, getattr(obj, field, default)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier identifier call identifier argument_list identifier identifier identifier | Set an object's field to default if it doesn't have a value |
def _check_descendant(self, item):
children = self.get_children(item)
for iid in children:
self.change_state(iid, "checked")
self._check_descendant(iid) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Check the boxes of item's descendants. |
def _dataChanged(self, item):
index = self.items.index(item)
qindex = self.createIndex(index, 0)
self.dataChanged.emit(qindex, qindex) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Explicitly emit dataChanged upon item changing |
def copy_abiext(self, inext, outext):
infile = self.has_abiext(inext)
if not infile:
raise RuntimeError('no file with extension %s in %s' % (inext, self))
for i in range(len(infile) - 1, -1, -1):
if infile[i] == '_':
break
else:
raise RuntimeError('Extension %s could not be detected in file %s' % (inext, infile))
outfile = infile[:i] + '_' + outext
shutil.copy(infile, outfile)
return 0 | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier for_statement identifier call identifier argument_list binary_operator call identifier argument_list identifier integer unary_operator integer unary_operator integer block if_statement comparison_operator subscript identifier identifier string string_start string_content string_end block break_statement else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier binary_operator binary_operator subscript identifier slice identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier identifier return_statement integer | Copy the Abinit file with extension inext to a new file withw extension outext |
def add_empty_fields(untl_dict):
for element in UNTL_XML_ORDER:
if element not in untl_dict:
try:
py_object = PYUNTL_DISPATCH[element](
content='',
qualifier='',
)
except:
try:
py_object = PYUNTL_DISPATCH[element](content='')
except:
try:
py_object = PYUNTL_DISPATCH[element]()
except:
raise PyuntlException(
'Could not add empty element field.'
)
else:
untl_dict[element] = [{'content': {}}]
else:
if not py_object.contained_children:
untl_dict[element] = [{'content': ''}]
else:
untl_dict[element] = [{'content': {}}]
else:
if not py_object.contained_children:
untl_dict[element] = [{'content': '', 'qualifier': ''}]
else:
untl_dict[element] = [{'content': {}, 'qualifier': ''}]
for child in py_object.contained_children:
untl_dict[element][0].setdefault('content', {})
untl_dict[element][0]['content'][child] = ''
return untl_dict | module function_definition identifier parameters identifier block for_statement identifier identifier block if_statement comparison_operator identifier identifier block try_statement block expression_statement assignment identifier call subscript identifier identifier argument_list keyword_argument identifier string string_start string_end keyword_argument identifier string string_start string_end except_clause block try_statement block expression_statement assignment identifier call subscript identifier identifier argument_list keyword_argument identifier string string_start string_end except_clause block try_statement block expression_statement assignment identifier call subscript identifier identifier argument_list except_clause block raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment subscript identifier identifier list dictionary pair string string_start string_content string_end dictionary else_clause block if_statement not_operator attribute identifier identifier block expression_statement assignment subscript identifier identifier list dictionary pair string string_start string_content string_end string string_start string_end else_clause block expression_statement assignment subscript identifier identifier list dictionary pair string string_start string_content string_end dictionary else_clause block if_statement not_operator attribute identifier identifier block expression_statement assignment subscript identifier identifier list dictionary pair string string_start string_content string_end string string_start string_end pair string string_start string_content string_end string string_start string_end else_clause block expression_statement assignment subscript identifier identifier list dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_end for_statement identifier attribute identifier identifier block expression_statement call attribute subscript subscript identifier identifier integer identifier argument_list string string_start string_content string_end dictionary expression_statement assignment subscript subscript subscript subscript identifier identifier integer string string_start string_content string_end identifier string string_start string_end return_statement identifier | Add empty values if UNTL fields don't have values. |
def product_path(cls, project, location, product):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/products/{product}",
project=project,
location=location,
product=product,
) | module function_definition identifier parameters 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 | Return a fully-qualified product string. |
def save_image(self, image_file):
self.ensure_pyplot()
command = 'plt.gcf().savefig("%s")'%image_file
self.process_input_line('bookmark ipy_thisdir', store_history=False)
self.process_input_line('cd -b ipy_savedir', store_history=False)
self.process_input_line(command, store_history=False)
self.process_input_line('cd -b ipy_thisdir', store_history=False)
self.process_input_line('bookmark -d ipy_thisdir', store_history=False)
self.clear_cout() | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier false expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier false expression_statement call attribute identifier identifier argument_list | Saves the image file to disk. |
def status(self, verbose=False):
try:
response=api(url=self.__url, method="GET", verbose=verbose)
except Exception as e:
print('Could not get status from CyREST:\n\n' + str(e))
else:
print('CyREST online!') | module function_definition identifier parameters identifier default_parameter identifier false block try_statement block 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 identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence string_end call identifier argument_list identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end | Checks the status of your CyREST server. |
def binary_report(self, sha256sum, apikey):
url = self.base_url + "file/report"
params = {"apikey": apikey, "resource": sha256sum}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, data=params)
if response.status_code == self.HTTP_OK:
json_response = response.json()
response_code = json_response['response_code']
return json_response
elif response.status_code == self.HTTP_RATE_EXCEEDED:
time.sleep(20)
else:
self.logger.warning("retrieve report: %s, HTTP code: %d", os.path.basename(filename), response.status_code) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary 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 if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement identifier elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list integer else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier | retrieve report from file scan |
def _format_list_objects(result):
all_keys = set()
for item in result:
all_keys = all_keys.union(item.keys())
all_keys = sorted(all_keys)
table = Table(all_keys)
for item in result:
values = []
for key in all_keys:
value = iter_to_table(item.get(key))
values.append(value)
table.add_row(values)
return table | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Format list of objects into a table. |
def delete(self, *args, **kwargs):
source_cache = self.get_source_cache()
self.delete_thumbnails(source_cache)
super(ThumbnailerFieldFile, self).delete(*args, **kwargs)
if source_cache and source_cache.pk is not None:
source_cache.delete() | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier if_statement boolean_operator identifier comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list | Delete the image, along with any generated thumbnails. |
def config_value_changed(option):
hook_data = unitdata.HookData()
with hook_data():
db = unitdata.kv()
current = config(option)
saved = db.get(option)
db.set(option, current)
if saved is None:
return False
return current != saved | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list with_statement with_clause with_item call identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block return_statement false return_statement comparison_operator identifier identifier | Determine if config value changed since last call to this function. |
def range_r(self):
return self.radius - self.dr, self.radius + self.dr | module function_definition identifier parameters identifier block return_statement expression_list binary_operator attribute identifier identifier attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier | Current interpolation range of radius |
def compute_message_authenticator(radius_packet, packed_req_authenticator,
shared_secret):
data = prepare_packed_data(radius_packet, packed_req_authenticator)
radius_hmac = hmac.new(shared_secret, data, hashlib.md5)
return radius_hmac.digest() | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list | Computes the "Message-Authenticator" of a given RADIUS packet. |
def printSequence(x, formatString="%d"):
numElements = len(x)
s = ""
for j in range(numElements):
s += formatString % x[j]
print s | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier string string_start string_end for_statement identifier call identifier argument_list identifier block expression_statement augmented_assignment identifier binary_operator identifier subscript identifier identifier print_statement identifier | Compact print a list or numpy array. |
def deep_encode(s, encoding='utf-8', errors='strict'):
s = deep_encode(s)
if sys.version_info.major < 3 and isinstance(s, unicode):
return s.encode(encoding, errors)
if isinstance(s, (list, tuple)):
return [deep_encode(i, encoding=encoding, errors=errors) for i in s]
if isinstance(s, dict):
return dict([
(
deep_encode(key, encoding=encoding, errors=errors),
deep_encode(s[key], encoding=encoding, errors=errors)
) for key in s
])
return s | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator attribute attribute identifier identifier identifier integer call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier if_statement call identifier argument_list identifier tuple identifier identifier block return_statement list_comprehension call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier for_in_clause identifier identifier if_statement call identifier argument_list identifier identifier block return_statement call identifier argument_list list_comprehension tuple call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier call identifier argument_list subscript identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier for_in_clause identifier identifier return_statement identifier | Encode "DEEP" S using the codec registered for encoding. |
def create_order(self, order_deets):
request = self._post('transactions/orders', order_deets)
return self.responder(request) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list identifier | Creates a new order transaction. |
def on_get(self, req, resp):
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
try:
containers = docker.from_env()
except Exception as e:
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
container_list = []
try:
for c in containers.containers.list(all=True):
if c.attrs['Config']['Image'] == \
'cyberreboot/vent-ncapture:master':
if 'core' not in c.attrs['Config']['Labels']['vent.groups']:
lst = {}
lst['id'] = c.attrs['Id'][:12]
lst['status'] = c.attrs['State']['Status']
lst['args'] = c.attrs['Args']
container_list.append(lst)
except Exception as e:
resp.body = "(False, 'Failure because: " + str(e) + "')"
return
resp.body = json.dumps(container_list)
return | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end return_statement expression_statement assignment identifier list try_statement block for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true block if_statement comparison_operator subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator string string_start string_content string_end subscript subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end subscript subscript attribute identifier identifier string string_start string_content string_end slice integer expression_statement assignment subscript identifier string string_start string_content string_end subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end return_statement expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement | Send a GET request to get the list of all of the filter containers |
def _process_open(self):
click.launch(self._format_issue_url())
if not click.confirm('Did it work?', default=True):
click.echo()
self._process_print()
click.secho(
'\nOpen the line manually and copy the text above\n',
fg='yellow'
)
click.secho(
' ' + self.REPO_URL + self.ISSUE_SUFFIX + '\n', bold=True
) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator string string_start string_content string_end attribute identifier identifier attribute identifier identifier string string_start string_content escape_sequence string_end keyword_argument identifier true | Open link in a browser. |
def _prepare_if_args(stmt):
args = stmt['args']
if args and args[0].startswith('(') and args[-1].endswith(')'):
args[0] = args[0][1:].lstrip()
args[-1] = args[-1][:-1].rstrip()
start = int(not args[0])
end = len(args) - int(not args[-1])
args[:] = args[start:end] | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement boolean_operator boolean_operator identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end call attribute subscript identifier unary_operator integer identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier integer call attribute subscript subscript identifier integer slice integer identifier argument_list expression_statement assignment subscript identifier unary_operator integer call attribute subscript subscript identifier unary_operator integer slice unary_operator integer identifier argument_list expression_statement assignment identifier call identifier argument_list not_operator subscript identifier integer expression_statement assignment identifier binary_operator call identifier argument_list identifier call identifier argument_list not_operator subscript identifier unary_operator integer expression_statement assignment subscript identifier slice subscript identifier slice identifier identifier | Removes parentheses from an "if" directive's arguments |
def commit(self):
if self.session is not None:
logger.info("committing transaction in %s" % self)
tmp = self.stable
self.stable, self.session = self.session, None
self.istable = 1 - self.istable
self.write_istable()
tmp.close()
self.lock_update.release()
else:
logger.warning("commit called but there's no open session in %s" % self) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier expression_list attribute identifier identifier none expression_statement assignment attribute identifier identifier binary_operator integer attribute identifier identifier 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 else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier | Commit changes made by the latest session. |
def eigenvalues_(self):
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end return_statement call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list | The eigenvalues associated with each principal component. |
def tokhex(length=10, urlsafe=False):
if urlsafe is True:
return secrets.token_urlsafe(length)
return secrets.token_hex(length) | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier false block if_statement comparison_operator identifier true block return_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Return a random string in hexadecimal |
def breaks(self, frame, no_remove=False):
for breakpoint in set(self.breakpoints):
if breakpoint.breaks(frame):
if breakpoint.temporary and not no_remove:
self.breakpoints.remove(breakpoint)
return True
return False | module function_definition identifier parameters identifier identifier default_parameter identifier false block for_statement identifier call identifier argument_list attribute identifier identifier block if_statement call attribute identifier identifier argument_list identifier block if_statement boolean_operator attribute identifier identifier not_operator identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement true return_statement false | Return True if there's a breakpoint at frame |
def compute(cls, observation, prediction):
assert isinstance(observation, dict)
try:
p_value = prediction['mean']
except (TypeError, KeyError, IndexError):
try:
p_value = prediction['value']
except (TypeError, IndexError):
p_value = prediction
o_mean = observation['mean']
o_std = observation['std']
value = (p_value - o_mean)/o_std
value = utils.assert_dimensionless(value)
if np.isnan(value):
score = InsufficientDataScore('One of the input values was NaN')
else:
score = ZScore(value)
return score | module function_definition identifier parameters identifier identifier identifier block assert_statement call identifier argument_list identifier identifier try_statement block expression_statement assignment identifier subscript identifier string string_start string_content string_end except_clause tuple identifier identifier identifier block try_statement block expression_statement assignment identifier subscript identifier string string_start string_content string_end except_clause tuple identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Compute a z-score from an observation and a prediction. |
def run_forecast(self):
self.prepare_hmet()
self.prepare_gag()
self.rapid_to_gssha()
self.hotstart()
return self.run() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list | Updates card & runs for RAPID to GSSHA & LSM to GSSHA |
def load_jupyter_server_extension(nbapp):
here = PACKAGE_DIR
nbapp.log.info('nteract extension loaded from %s' % here)
app_dir = here
web_app = nbapp.web_app
config = NteractConfig(parent=nbapp)
config.assets_dir = app_dir
config.page_url = '/nteract'
config.dev_mode = False
core_mode = ''
if hasattr(nbapp, 'core_mode'):
core_mode = nbapp.core_mode
if app_dir == here or app_dir == os.path.join(here, 'build'):
core_mode = True
config.settings_dir = ''
web_app.settings.setdefault('page_config_data', dict())
web_app.settings['page_config_data']['token'] = nbapp.token
web_app.settings['page_config_data']['ga_code'] = config.ga_code
web_app.settings['page_config_data']['asset_url'] = config.asset_url
web_app.settings['nteract_config'] = config
add_handlers(web_app, config) | module function_definition identifier parameters identifier block expression_statement assignment identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier false expression_statement assignment identifier string string_start string_end if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier true expression_statement assignment attribute identifier identifier string string_start string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier identifier | Load the server extension. |
def browse(self):
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open('file://' + path) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier | Save response in temporary file and open it in GUI browser. |
def visit_Name(self, node):
return self.add(node, self.result[node.id]) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list identifier subscript attribute identifier identifier attribute identifier identifier | Get range for parameters for examples or false branching. |
def text(self):
txBody = self.txBody
if txBody is None:
return ''
return '\n'.join([p.text for p in txBody.p_lst]) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block return_statement string string_start string_end return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier | str text contained in cell |
def read_variant(variant):
result = 0
cnt = 0
for data in variant:
result |= (data & 0x7f) << (7 * cnt)
cnt += 1
if not data & 0x80:
return result, variant[cnt:]
raise Exception('invalid variant') | module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement assignment identifier integer for_statement identifier identifier block expression_statement augmented_assignment identifier binary_operator parenthesized_expression binary_operator identifier integer parenthesized_expression binary_operator integer identifier expression_statement augmented_assignment identifier integer if_statement not_operator binary_operator identifier integer block return_statement expression_list identifier subscript identifier slice identifier raise_statement call identifier argument_list string string_start string_content string_end | Read and parse a binary protobuf variant value. |
def patch_tree(actions, tree):
patcher = patch.Patcher()
return patcher.patch(actions, tree) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier | Takes an lxml root element or element tree, and a list of actions |
def cache(cls, id):
sampler = {'unit': 'days', 'value': 1, 'function': 'sum'}
query = 'webacc.requests.cache.all'
metrics = Metric.query(id, 60 * 60 * 24, query, 'paas', sampler)
cache = {'hit': 0, 'miss': 0, 'not': 0, 'pass': 0}
for metric in metrics:
what = metric['cache'].pop()
for point in metric['points']:
value = point.get('value', 0)
cache[what] += value
return cache | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end integer pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator binary_operator integer integer integer identifier string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end integer pair string string_start string_content string_end integer pair string string_start string_content string_end integer for_statement identifier identifier block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement augmented_assignment subscript identifier identifier identifier return_statement identifier | return the number of query cache for the last 24H |
async def _async_get_sshable_ips(self, ip_addresses):
async def _async_ping(ip_address):
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(ip_address, 22), timeout=5)
except (OSError, TimeoutError):
return None
try:
line = await reader.readline()
finally:
writer.close()
if line.startswith(b'SSH-'):
return ip_address
ssh_ips = await asyncio.gather(*[
_async_ping(ip_address)
for ip_address in ip_addresses
])
return [
ip_address
for ip_address in ssh_ips
if ip_address is not None
] | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block try_statement block expression_statement assignment pattern_list identifier identifier await call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier integer keyword_argument identifier integer except_clause tuple identifier identifier block return_statement none try_statement block expression_statement assignment identifier await call attribute identifier identifier argument_list finally_clause block expression_statement call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement identifier expression_statement assignment identifier await call attribute identifier identifier argument_list list_splat list_comprehension call identifier argument_list identifier for_in_clause identifier identifier return_statement list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier none | Return list of all IP address that could be pinged. |
def gray2int(graystr):
num = bin2int(graystr)
num ^= (num >> 8)
num ^= (num >> 4)
num ^= (num >> 2)
num ^= (num >> 1)
return num | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement augmented_assignment identifier parenthesized_expression binary_operator identifier integer expression_statement augmented_assignment identifier parenthesized_expression binary_operator identifier integer expression_statement augmented_assignment identifier parenthesized_expression binary_operator identifier integer expression_statement augmented_assignment identifier parenthesized_expression binary_operator identifier integer return_statement identifier | Convert greycode to binary |
def reset_experiment(experiment):
redis = _get_redis_connection()
experiment = Experiment.find(redis, experiment)
if experiment:
experiment.reset()
return redirect(url_for('.index')) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list call identifier argument_list string string_start string_content string_end | Delete all data for an experiment. |
def to_filter(self, query, arg):
return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list attribute identifier identifier identifier identifier keyword_argument identifier identifier | Json-server filter using the _or_ operator. |
def purge_old_event_logs(delete_before_days=7):
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = EventLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | module function_definition identifier parameters default_parameter identifier integer block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list return_statement identifier | Purges old event logs from the database table |
def start_stop_video(self):
if self.parent.info.dataset is None:
self.parent.statusBar().showMessage('No Dataset Loaded')
return
if 'Start' in self.idx_button.text().replace('&', ''):
try:
self.update_video()
except IndexError as er:
lg.debug(er)
self.idx_button.setText('Not Available / Start')
return
except OSError as er:
lg.debug(er)
self.idx_button.setText('NO VIDEO for this dataset')
return
self.idx_button.setText('Stop')
elif 'Stop' in self.idx_button.text():
self.idx_button.setText('Start')
self.medialistplayer.stop()
self.t.stop() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute attribute identifier identifier identifier identifier none block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end return_statement if_statement comparison_operator string string_start string_content string_end call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_end block try_statement block expression_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end elif_clause comparison_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Start and stop the video, and change the button. |
def clear_cache(self):
super(HyperparameterTuningJobAnalytics, self).clear_cache()
self._tuning_job_describe_result = None
self._training_job_summaries = None | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none | Clear the object of all local caches of API methods. |
def getPhotos(self):
method = 'flickr.photosets.getPhotos'
data = _doget(method, photoset_id=self.id)
photos = data.rsp.photoset.photo
p = []
for photo in photos:
p.append(Photo(photo.id, title=photo.title, secret=photo.secret, \
server=photo.server))
return p | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier line_continuation keyword_argument identifier attribute identifier identifier return_statement identifier | Returns list of Photos. |
def _find_entity_in_records_by_class_name(self, entity_name):
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
if len(records) > 1:
raise ConfigurationError(
f'Entity with name {entity_name} has been registered twice. '
f'Please use fully qualified Entity name to specify the exact Entity.')
elif len(records) == 1:
return next(iter(records.values()))
else:
raise AssertionError(f'No Entity registered with name {entity_name}') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause comparison_operator attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list concatenated_string string string_start string_content interpolation identifier string_content string_end string string_start string_content string_end elif_clause comparison_operator call identifier argument_list identifier integer block return_statement call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list else_clause block raise_statement call identifier argument_list string string_start string_content interpolation identifier string_end | Fetch by Entity Name in values |
def _readuntil(f, end=_TYPE_END):
buf = bytearray()
byte = f.read(1)
while byte != end:
if byte == b'':
raise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))
buf += byte
byte = f.read(1)
return buf | module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list integer while_statement comparison_operator identifier identifier block if_statement comparison_operator identifier string string_start string_end block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement augmented_assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list integer return_statement identifier | Helper function to read bytes until a certain end byte is hit |
def rejectEdit(self):
if self._lineEdit:
self._lineEdit.hide()
self.editingCancelled.emit() | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Cancels the edit for this label. |
def from_mapping(cls, mapping):
group = cls()
for name, value in mapping.items():
if name.startswith('_'):
continue
group[name] = Parameter(
name=name,
value=value,
constraint=Parameter.constraint_from_type(value),
)
return group | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block continue_statement expression_statement assignment subscript identifier identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier return_statement identifier | Produces a set of parameters from a mapping |
def keys(self) -> Iterator[str]:
if self.param:
yield self.param_name
yield from self.paths.keys() | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block if_statement attribute identifier identifier block expression_statement yield attribute identifier identifier expression_statement yield call attribute attribute identifier identifier identifier argument_list | return all possible paths one can take from this ApiNode |
def save(self, expires=None):
if expires is None:
expires = self.expires
s = self.serialize()
key = self._key(self._all_keys())
_cache.set(key, s, expires) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Save a copy of the object into the cache. |
def loadedfields(self):
if self._loadedfields is None:
for field in self._meta.scalarfields:
yield field
else:
fields = self._meta.dfields
processed = set()
for name in self._loadedfields:
if name in processed:
continue
if name in fields:
processed.add(name)
yield fields[name]
else:
name = name.split(JSPLITTER)[0]
if name in fields and name not in processed:
field = fields[name]
if field.type == 'json object':
processed.add(name)
yield field | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block for_statement identifier attribute attribute identifier identifier identifier block expression_statement yield identifier else_clause block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block continue_statement if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement yield subscript identifier identifier else_clause block expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement yield identifier | Generator of fields loaded from database |
def archive_namespace(self):
try:
for ns_prefix, url in self.feed.namespaces.items():
if url == 'http://purl.org/syndication/history/1.0':
return ns_prefix
except AttributeError:
pass
return None | module function_definition identifier parameters identifier block try_statement block for_statement pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block if_statement comparison_operator identifier string string_start string_content string_end block return_statement identifier except_clause identifier block pass_statement return_statement none | Returns the known namespace of the RFC5005 extension, if any |
def load_schema(path):
with open(path) as json_data:
schema = json.load(json_data)
return schema | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Loads a JSON schema file. |
def _get_perf(text, msg_id):
msg = KQMLPerformative('REQUEST')
msg.set('receiver', 'READER')
content = KQMLList('run-text')
content.sets('text', text)
msg.set('content', content)
msg.set('reply-with', msg_id)
return msg | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Return a request message for a given text. |
def add_complex(self, **kwargs):
self.check_developer()
self.post('developers/%s/complexes/' % self.developer, data=kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier | Add a new complex to the rumetr db |
def _make_info(self, name, stat_result, namespaces):
info = {
'basic': {
'name': name,
'is_dir': stat.S_ISDIR(stat_result.st_mode)
}
}
if 'details' in namespaces:
info['details'] = self._make_details_from_stat(stat_result)
if 'stat' in namespaces:
info['stat'] = {
k: getattr(stat_result, k)
for k in dir(stat_result) if k.startswith('st_')
}
if 'access' in namespaces:
info['access'] = self._make_access_from_stat(stat_result)
return Info(info) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end dictionary_comprehension pair identifier call identifier argument_list identifier identifier for_in_clause identifier call identifier argument_list identifier if_clause call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Create an `Info` object from a stat result. |
def _row_resized(self, row, old_height, new_height):
self.dataTable.setRowHeight(row, new_height)
self._update_layout() | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list | Update the row height. |
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None):
fileobj = filething.fileobj
iff_file = IFFFile(fileobj)
if u'ID3' not in iff_file:
iff_file.insert_chunk(u'ID3')
chunk = iff_file[u'ID3']
try:
data = self._prepare_data(
fileobj, chunk.data_offset, chunk.data_size, v2_version,
v23_sep, padding)
except ID3Error as e:
reraise(error, e, sys.exc_info()[2])
new_size = len(data)
new_size += new_size % 2
assert new_size % 2 == 0
chunk.resize(new_size)
data += (new_size - len(data)) * b'\x00'
assert new_size == len(data)
chunk.write(data) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier integer default_parameter identifier string string_start string_content string_end default_parameter identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list identifier identifier subscript call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list identifier expression_statement augmented_assignment identifier binary_operator identifier integer assert_statement comparison_operator binary_operator identifier integer integer expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier binary_operator parenthesized_expression binary_operator identifier call identifier argument_list identifier string string_start string_content escape_sequence string_end assert_statement comparison_operator identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Save ID3v2 data to the AIFF file |
def indented(text, level, indent=2):
return "\n".join("%s%s" % (level * indent * " ", s) for s in text.splitlines()) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block return_statement call attribute string string_start string_content escape_sequence string_end identifier generator_expression binary_operator string string_start string_content string_end tuple binary_operator binary_operator identifier identifier string string_start string_content string_end identifier for_in_clause identifier call attribute identifier identifier argument_list | Take a multiline text and indent it as a block |
def read_args_tool(toolkey, example_parameters, tool_add_args=None):
import scanpy as sc
p = default_tool_argparser(help(toolkey), example_parameters)
if tool_add_args is None:
p = add_args(p)
else:
p = tool_add_args(p)
args = vars(p.parse_args())
args = settings.process_args(args)
return args | module function_definition identifier parameters identifier identifier default_parameter identifier none block import_statement aliased_import dotted_name identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list 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 expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Read args for single tool. |
def validate(self):
for name, field in self:
try:
field.validate_for_object(self)
except ValidationError as error:
raise ValidationError(
"Error for field '{name}'.".format(name=name),
error,
) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list 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 keyword_argument identifier identifier identifier | Explicitly validate all the fields. |
def on_load(self, event):
dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*', wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.settings.load(dlg.GetPath())
for label in self.setting_map.keys():
setting = self.setting_map[label]
ctrl = self.controls[label]
value = ctrl.GetValue()
if isinstance(value, str) or isinstance(value, unicode):
ctrl.SetValue(str(setting.value))
else:
ctrl.SetValue(setting.value) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list none call attribute attribute identifier identifier identifier argument_list string string_start string_end string string_start string_end string string_start string_content string_end attribute identifier identifier if_statement comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list attribute identifier identifier | called on load button |
def _correct_dims(data):
if not hasattr(data, 'dims'):
raise TypeError("Data must have a 'dims' attribute.")
data = data.copy()
if 'y' not in data.dims or 'x' not in data.dims:
if data.ndim != 2:
raise ValueError("Data must have a 'y' and 'x' dimension")
if 'y' not in data.dims:
old_dim = [d for d in data.dims if d != 'x'][0]
data = data.rename({old_dim: 'y'})
if 'x' not in data.dims:
old_dim = [d for d in data.dims if d != 'y'][0]
data = data.rename({old_dim: 'x'})
if "bands" not in data.dims:
if data.ndim <= 2:
data = data.expand_dims('bands')
data['bands'] = ['L']
else:
raise ValueError("No 'bands' dimension provided.")
return data | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier block if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator identifier string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator identifier string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end list string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content string_end return_statement identifier | Standardize dimensions to bands, y, and x. |
def __send_command(self, command, args=[]):
self.ws.send(json.dumps({"op": command, "args": args})) | module function_definition identifier parameters identifier identifier default_parameter identifier list block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Send a raw command. |
def period(self):
return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu)) | module function_definition identifier parameters identifier block return_statement call identifier argument_list keyword_argument identifier binary_operator binary_operator integer attribute identifier identifier call attribute identifier identifier argument_list binary_operator binary_operator attribute attribute identifier identifier identifier integer attribute identifier identifier | Period of the orbit as a timedelta |
def min_freq(self):
i = np.unravel_index(np.argmin(self.bands), self.bands.shape)
return self.qpoints[i[1]], self.bands[i] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier return_statement expression_list subscript attribute identifier identifier subscript identifier integer subscript attribute identifier identifier identifier | Returns the point where the minimum frequency is reached and its value |
def sqlvm_group_list(
client,
resource_group_name=None):
if resource_group_name:
return client.list_by_resource_group(resource_group_name=resource_group_name)
return client.list() | module function_definition identifier parameters identifier default_parameter identifier none block if_statement identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list | Lists all SQL virtual machine groups in a resource group or subscription. |
def export_datasources(print_stdout, datasource_file,
back_references, include_defaults):
data = dict_import_export.export_to_dict(
session=db.session,
recursive=True,
back_references=back_references,
include_defaults=include_defaults)
if print_stdout or not datasource_file:
yaml.safe_dump(data, stdout, default_flow_style=False)
if datasource_file:
logging.info('Exporting datasources to %s', datasource_file)
with open(datasource_file, 'w') as data_stream:
yaml.safe_dump(data, data_stream, default_flow_style=False) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier true keyword_argument identifier identifier keyword_argument identifier identifier if_statement boolean_operator identifier not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier false if_statement identifier block 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 call attribute identifier identifier argument_list identifier identifier keyword_argument identifier false | Export datasources to YAML |
def exclude_data_files(self, package, src_dir, files):
files = list(files)
patterns = self._get_platform_patterns(
self.exclude_package_data,
package,
src_dir,
)
match_groups = (
fnmatch.filter(files, pattern)
for pattern in patterns
)
matches = itertools.chain.from_iterable(match_groups)
bad = set(matches)
keepers = (
fn
for fn in files
if fn not in bad
)
return list(_unique_everseen(keepers)) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier identifier expression_statement assignment identifier generator_expression call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier generator_expression identifier for_in_clause identifier identifier if_clause comparison_operator identifier identifier return_statement call identifier argument_list call identifier argument_list identifier | Filter filenames for package's data files in 'src_dir |
def write_config(configfile, content):
with open(configfile, 'w+') as ymlfile:
yaml.dump(
content,
ymlfile,
default_flow_style=False,
) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier false | Write dict to a file in yaml format |
def write(self, data):
self.backingStream.write(data)
for listener in self.writeListeners:
listener(len(data)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list call identifier argument_list identifier | Write the given data to the file. |
def read_string_from_file(path, encoding="utf8"):
with codecs.open(path, "rb", encoding=encoding) as f:
value = f.read()
return value | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | Read entire contents of file into a string. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.