code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def _generate_delete_sql(self, delete_keys): for key in delete_keys: app_label, sql_name = key old_node = self.from_sql_graph.nodes[key] operation = DeleteSQL(sql_name, old_node.reverse_sql, reverse_sql=old_node.sql) sql_deps = [n.key for n in self.from_sql_graph....
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier subscript attribute attribute identifier identifier identifier identifier expres...
Generate forward delete operations for SQL items.
def endpoint_search(filter_fulltext, filter_owner_id, filter_scope): if filter_scope == "all" and not filter_fulltext: raise click.UsageError( "When searching all endpoints (--filter-scope=all, the default), " "a full-text search filter is required. Other scopes (e.g. " "...
module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator identifier string string_start string_content string_end not_operator identifier block raise_statement call attribute identifier identifier argument_list concatenated_string string s...
Executor for `globus endpoint search`
def _json_to_unicode(data): ret = {} for key, value in data.items(): if not isinstance(value, six.text_type): if isinstance(value, dict): ret[key] = _json_to_unicode(value) else: ret[key] = six.text_type(value).lower() else: ret...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement not_operator call identifier argument_list identifier attribute identifier identi...
Encode json values in unicode to match that of the API
def _is_replacement_allowed(self, s): if any(tag in s.parent_tags for tag in self.skipped_tags): return False if any(tag not in self.textflow_tags for tag in s.involved_tags): return False return True
module function_definition identifier parameters identifier identifier block if_statement call identifier generator_expression comparison_operator identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier block return_statement false if_statement call identifier generator_expre...
Tests whether replacement is allowed on given piece of HTML text.
def unique_list(lst): uniq = [] for item in lst: if item not in uniq: uniq.append(item) return uniq
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement ide...
Make a list unique, retaining order of initial appearance.
def search_weekday(weekday, jd, direction, offset): return weekday_before(weekday, jd + (direction * offset))
module function_definition identifier parameters identifier identifier identifier identifier block return_statement call identifier argument_list identifier binary_operator identifier parenthesized_expression binary_operator identifier identifier
Determine the Julian date for the next or previous weekday
def create_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False): tenant_name = fw_dict.get('tenant_name') ret = self._create_service_nwk(tenant_id, tenant_name, 'in') if ret: res = fw_const.DCNM_IN_NETWORK_CREATE_SUCCESS LOG.info("In Service network created for tenant ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute...
Create the DCNM In Network and store the result in DB.
def trigger(self, *args, **kargs): event = args[0] if isinstance(event, str) and ' ' in event: event = event.split(' ') if isinstance(event, list): for each in event: self.events[each].trigger(*args[1:], **kargs) else: self.events[event...
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier integer if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator string string_...
Execute all event handlers with optional arguments for the observable.
def sam_parse_reply(line): parts = line.split(' ') opts = {k: v for (k, v) in split_kv(parts[2:])} return SAMReply(parts[0], opts)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause tuple...
parse a reply line into a dict
def hash_name(name, script_pubkey, register_addr=None): bin_name = b40_to_bin(name) name_and_pubkey = bin_name + unhexlify(script_pubkey) if register_addr is not None: name_and_pubkey += str(register_addr) return hex_hash160(name_and_pubkey)
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier if_statement c...
Generate the hash over a name and hex-string script pubkey
def _process_output(self, node, **kwargs): for n in node.nodes: self._process_node(n, **kwargs)
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier
Processes an output node, which will contain things like `Name` and `TemplateData` nodes.
def _check_content(self, content_str): if self.do_content_check: space_ratio = float(content_str.count(' '))/len(content_str) if space_ratio > self.max_space_ratio: return "space-ratio: %f > %f" % (space_ratio, self.max_spa...
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier binary_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end call i...
Check if the content is likely to be successfully read.
def _add_mxnet_ctc_loss(pred, seq_len, label): pred_ctc = mx.sym.Reshape(data=pred, shape=(-4, seq_len, -1, 0)) loss = mx.sym.contrib.ctc_loss(data=pred_ctc, label=label) ctc_loss = mx.sym.MakeLoss(loss) softmax_class = mx.symbol.SoftmaxActivation(data=pred) softmax_loss = mx.sym.MakeLoss(softmax_cl...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier tuple unary_operator integer identifier unary_oper...
Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol
def getavailable(self): from importlib import import_module available = [] for script in self.SCRIPTS: if have(script): available.append(script) for module in self.MODULES: try: import_module(module) available.append...
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier block expression_stat...
Return a list of subtitle downloaders available.
def censor(self, input_text): bad_words = self.get_profane_words() res = input_text for word in bad_words: regex_string = r'{0}' if self._no_word_boundaries else r'\b{0}\b' regex_string = regex_string.format(word) regex = re.compile(regex_string, re.IGNORECA...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier identifier for_statement identifier identifier block expression_statement assignment identifier conditiona...
Returns input_text with any profane words censored.
def _current_user_manager(self, session=None): if session is None: session = db.session() try: user = g.user except Exception: return session.query(User).get(0) if sa.orm.object_session(user) is not session: return session.query(User).get(u...
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier attribut...
Return the current user, or SYSTEM user.
def _split_one_end(path): s = path.rsplit('/', 1) if len(s) == 1: return s[0], '' else: return tuple(s)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator call identifier argument_list identifier integer block return_statement e...
Utility function for splitting off the very end part of a path.
def body(self): for fp, need_close in self.files: try: name = os.path.basename(fp.name) except AttributeError: name = '' for chunk in self.gen_chunks(self.envelope.file_open(name)): yield chunk for chunk in self.file...
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier ...
Yields the body of the buffered file.
def write(self, fptr): fptr.write(struct.pack('>I4s', 12, b'jP ')) fptr.write(struct.pack('>BBBB', *self.signature))
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end integer string string_start string_content string_end expression_statement...
Write a JPEG 2000 Signature box to file.
def _compile_itemsort(): def is_extra(key_): return key_ is Extra def is_remove(key_): return isinstance(key_, Remove) def is_marker(key_): return isinstance(key_, Marker) def is_type(key_): return inspect.isclass(key_) def is_callable(key_): return callable(k...
module function_definition identifier parameters block function_definition identifier parameters identifier block return_statement comparison_operator identifier identifier function_definition identifier parameters identifier block return_statement call identifier argument_list identifier identifier function_definition...
return sort function of mappings
def _create(archive, compression, cmd, format, verbosity, filenames): if len(filenames) > 1: raise util.PatoolError('multi-file compression not supported in Python lzma') try: with lzma.LZMAFile(archive, mode='wb', **_get_lzma_options(format, preset=9)) as lzmafile: filename = filena...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call attribute identifier identifier argument_list string string_start string_content string_en...
Create an LZMA or XZ archive with the lzma Python module.
def mkUTC(year, month, day, hour, min, sec): "similar to python's mktime but for utc" spec = [year, month, day, hour, min, sec] + [0, 0, 0] utc = time.mktime(spec) - time.timezone return utc
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier binary_operator list identifier identifier identifier identifier identifier identifier li...
similar to python's mktime but for utc
def remove(self, transport): recipients = copy.copy(self.recipients) for address, recManager in recipients.items(): recManager.remove(transport) if not len(recManager.transports): del self.recipients[address]
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_...
removes a transport from all channels to which it belongs.
def project_inspect_template_path(cls, project, inspect_template): return google.api_core.path_template.expand( "projects/{project}/inspectTemplates/{inspect_template}", project=project, inspect_template=inspect_template, )
module function_definition identifier parameters 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 identifie...
Return a fully-qualified project_inspect_template string.
def get(self, key, subcommand="config:get"): cmd = ["heroku", subcommand, key, "--app", self.name] return self._result(cmd)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list string string_start string_content string_end identifier identifier string string_start string_content string_end attrib...
Get a app config value by name
def RemoveEventHandler(self, wb): from UcsBase import WriteUcsWarning if wb in self._wbs: self._remove_watch_block(wb) else: WriteUcsWarning("Event handler not found")
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier dotted_name identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_claus...
Removes an event handler.
def three_d_effect(img, **kwargs): w = kwargs.get('weight', 1) LOG.debug("Applying 3D effect with weight %.2f", w) kernel = np.array([[-w, 0, w], [-w, 1, w], [-w, 0, w]]) mode = kwargs.get('convolve_mode', 'same') def func(band_data, kernel=kernel, mode=...
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_lis...
Create 3D effect using convolution
def append_warning(self, msg): assert self.model is not None, "You must already have run make_model!" addendum = ('\t<span style="color:red;">(CAUTION: %s occurred when ' 'creating this page.)</span>' % msg) self.model = self.model.replace(self.title, self.title + addendum) ...
module function_definition identifier parameters identifier identifier block assert_statement comparison_operator attribute identifier identifier none string string_start string_content string_end expression_statement assignment identifier parenthesized_expression binary_operator concatenated_string string string_start...
Append a warning message to the model to expose issues.
def _start(self): self.start = time.time() self.result['start'] = str(datetime.datetime.now()) if not self.pause_type == 'prompt': print "(^C-c = continue early, ^C-a = abort)"
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier arg...
mark the time of execution for duration calculations later
def make_response(message, status_code, details=None): response_body = dict(message=message) if details: response_body['details'] = details response = jsonify(response_body) response.status_code = status_code return response
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier if_statement identifier block expression_statement assignment subscript identifier string string_...
Make a jsonified response with specified message and status code.
def valid_modes(self): default_mode = (self.mode,) if self.mode is not None else None return getattr(self, '_valid_mode', default_mode)
module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression tuple attribute identifier identifier comparison_operator attribute identifier identifier none none return_statement call identifier argument_list identifier string string_start string_con...
Valid modes of an open file
def streamify(self, state, frame): enc_tab = self._tables[1][:] untrail_len, untrail_code = enc_tab.pop(0) result = [] blocks = frame.split('\0') skip = False for i in range(len(blocks)): if skip: skip = False continue ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier integer slice expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list integ...
Prepare frame for output as a COBS-encoded stream.
def file_ns_handler(importer, path_item, packageName, module): subpath = os.path.join(path_item, packageName.split('.')[-1]) normalized = _normalize_cached(subpath) for item in module.__path__: if _normalize_cached(item) == normalized: break else: return subpath
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier subscript call attribute identifier identifier argument_list string string_start string_content...
Compute an ns-package subpath for a filesystem or zipfile importer
def ellipse(center,covariance_matrix,level=1, n=1000): U, s, rotation_matrix = N.linalg.svd(covariance_matrix) saxes = N.sqrt(s)*level u = N.linspace(0, 2*N.pi, n) data = N.column_stack((saxes[0]*N.cos(u), saxes[1]*N.sin(u))) return N.dot(data, rotation_matrix)+ center
module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier integer block expression_statement assignment pattern_list identifier identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expressi...
Returns error ellipse in slope-azimuth space
def _set_opt(config_dict, path, value): if value is None: return if '.' not in path: config_dict[path] = value return key, rest = path.split(".", 1) if key not in config_dict: config_dict[key] = {} _set_opt(config_dict[key], rest, value)
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block return_statement if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier identifier ...
Set the value in the dictionary at the given path if the value is not None.
def _get_pq_array_construct(self): bus_no = integer.setResultsName("bus_no") s_rating = real.setResultsName("s_rating") v_rating = real.setResultsName("v_rating") p = real.setResultsName("p") q = real.setResultsName("q") v_max = Optional(real).setResultsName("v_max") ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start ...
Returns a construct for an array of PQ load data.
def from_genes(cls, genes: List[ExpGene]): data = [g.to_dict() for g in genes] index = [d.pop('ensembl_id') for d in data] table = cls(data, index=index) return table
module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier expression_stateme...
Initialize instance using a list of `ExpGene` objects.
def _PartitionChunks(chunks): partitions = [[]] partition_size = 0 for chunk in chunks: cursize = len(chunk["blob_chunk"]) if (cursize + partition_size > BLOB_CHUNK_SIZE or len(partitions[-1]) >= CHUNKS_PER_INSERT): partitions.append([]) partition_size = 0 partitions[-1].append(chu...
module function_definition identifier parameters identifier block expression_statement assignment identifier list list expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier string string_...
Groups chunks into partitions of size safe for a single INSERT.
def _check_directory_arguments(self): if not os.path.isdir(self.datapath): raise (NotADirectoryError('Directory does not exist: %s' % self.datapath)) if self.time_delay: if self.time_delay < 1: raise ValueError('Time step argument must be greater than 0, but gave:...
module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block raise_statement parenthesized_expression call identifier argument_list binary_operator string string_start string_cont...
Validates arguments for loading from directories, including static image and time series directories.
def printSegmentForCell(tm, cell): print "Segments for cell", cell, ":" for seg in tm.basalConnections._cells[cell]._segments: print " ", synapses = seg._synapses for s in synapses: print "%d:%g" %(s.presynapticCell,s.permanence), print
module function_definition identifier parameters identifier identifier block print_statement string string_start string_content string_end identifier string string_start string_content string_end for_statement identifier attribute subscript attribute attribute identifier identifier identifier identifier identifier bloc...
Print segment information for this cell
def load(self, file=None): "Read and decompress a compact script from the Pickler's file object." if file is None: file = self._file script_class = self.get_script_class() script = self._load(file, self._protocol, self._version) return script_class(script)
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement as...
Read and decompress a compact script from the Pickler's file object.
def overlap(self, other: 'Span'): return not ( other.column_end <= self.column_start or self.column_end <= other.column_start or other.row_end <= self.row_start or self.row_end <= other.row_start )
module function_definition identifier parameters identifier typed_parameter identifier type string string_start string_content string_end block return_statement not_operator parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator attribute identifier identifier attribute identifi...
Detect if two spans overlap.
def connect(self): self.client = smtplib.SMTP(self.options['server'], self.options['port'], local_hostname='local.domain', timeout=15)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string st...
Connect to the SMTP server.
def find_free_port(): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.bind(('', 0)) return sock.getsockname()[1]
module function_definition identifier parameters block with_statement with_clause with_item as_pattern call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier as_pattern_target identifier block expression_statement call attribute i...
Finds a free port.
def netmask(mask): if not isinstance(mask, string_types): return False octets = mask.split('.') if not len(octets) == 4: return False return ipv4_addr(mask) and octets == sorted(octets, reverse=True)
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement false expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_stat...
Returns True if the value passed is a valid netmask, otherwise return False
def as_dict(self): d = {"ion": self.ion.as_dict(), "energy": self.energy, "name": self.name} return d
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end attribute identifier ident...
Creates a dict of composition, energy, and ion name
def write(*args, **kwargs): debug = kwargs.pop("debug", None) warning = kwargs.pop("warning", None) if _logger: kwargs.pop("end", None) kwargs.pop("file", None) if debug: _logger.debug(*args, **kwargs) elif warning: _logger.warning(*args, **kwargs) ...
module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier call attrib...
Redirectable wrapper for print statements.
def traverse_levelorder(self, leaves=True, internal=True): for node in self.root.traverse_levelorder(leaves=leaves, internal=internal): yield node
module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier true block for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier block expre...
Perform a levelorder traversal of the ``Node`` objects in this ``Tree``
def expand(self, msgpos): MT = self._tree[msgpos] MT.expand(MT.root)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier
expand message at given position
def file_contents(file_name): curr_dir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(curr_dir, file_name)) as the_file: contents = the_file.read() return contents
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call ide...
Given a file name to a valid file returns the file object.
def copy_w_id_suffix(elem, suffix="_copy"): mycopy = deepcopy(elem) for id_elem in mycopy.xpath('//*[@id]'): id_elem.set('id', id_elem.get('id') + suffix) return mycopy
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 for_statement identifier call attribute identifier identifier argument_list string string_start...
Make a deep copy of the provided tree, altering ids.
def click_table_printer(headers, _filter, data): _filter = [h.lower() for h in _filter] + [h.upper() for h in _filter] headers = [h for h in headers if not _filter or h in _filter] header_widths = [len(h) for h in headers] for row in data: for idx in range(len(headers)): if header_wi...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier list_comprehension call attribute identifier identifier argument_li...
Generate space separated output for click commands.
def render_pulp_tag(self): if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'pulp_tag'): return pulp_registry = self.spec.pulp_registry.value if pulp_registry: self.dj.dock_json_set_arg('postbuild_plugins', 'pu...
module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block return_statement expression_statement assignment identifie...
Configure the pulp_tag plugin.
def collect(self): if boto is None: self.log.error("Unable to import boto python module") return {} for s3instance in self.config['s3']: self.log.info("S3: byte_unit: %s" % self.config['byte_unit']) aws_access = self.config['s3'][s3instance]['aws_access_ke...
module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement dictionary for_statement identifier subscri...
Collect s3 bucket stats
def update(callback=None, path=None, method=Method.PUT, resource=None, tags=None, summary="Update specified resource.", middleware=None): def inner(c): op = ResourceOperation(c, path or PathParam('{key_field}'), method, resource, tags, summary, middleware) op.responses.add(Response(HTTPSt...
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier attribute identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end...
Decorator to configure an operation that updates a resource.
def convert_doc_to_text(filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: antiword = tools['antiword'] if antiword: if filename: return get_cmd_output(antiword, '-w', str(config.width), filename) ...
module function_definition identifier parameters typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier identifier type identifier block expression_statement assignment identifier subscript identifier string stri...
Converts Microsoft Word DOC files to text.
def _addNoise(self, pattern, noiseLevel): if pattern is None: return None newBits = [] for bit in pattern: if random.random() < noiseLevel: newBits.append(random.randint(0, max(pattern))) else: newBits.append(bit) return set(newBits)
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block return_statement none expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator call attribute identifier identi...
Adds noise the given list of patterns and returns a list of noisy copies.
def pulp_repo_path(connection, repoid): dl_base = connection.base_url.replace('/pulp/api/v2', '/pulp/repos') _m = re.match('(.*)-(.*)', repoid) repo = _m.group(1) env = _m.group(2) return "%s/%s/%s" % (dl_base, env, repo)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment iden...
Given a connection and a repoid, return the url of the repository
def reorder(self, dst_order, arr, src_order=None): if dst_order is None: dst_order = self.viewer.rgb_order if src_order is None: src_order = self.rgb_order if src_order != dst_order: arr = trcalc.reorder_image(dst_order, arr, src_order) return arr
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier non...
Reorder the output array to match that needed by the viewer.
def log_accept(self, block_id, vtxindex, opcode, op_data): log.debug("ACCEPT op {} at ({}, {}) ({})".format(opcode, block_id, vtxindex, json.dumps(op_data, sort_keys=True)))
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier call attribute iden...
Log an accepted operation
def remove_files_in_dir(dpath, fname_pattern_list='*', recursive=False, verbose=VERBOSE, dryrun=False, ignore_errors=False): if isinstance(fname_pattern_list, six.string_types): fname_pattern_list = [fname_pattern_list] if verbose > 2: print('[util_path] Removing files:')...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier identifier default_parameter identifier false default_parameter identifier false block if_statement call identifier argum...
Removes files matching a pattern from a directory
def build_index(self, idx_name, _type='default'): "Build the index related to the `name`." indexes = {} has_non_string_values = False for key, item in self.data.items(): if idx_name in item: value = item[idx_name] if not isinstance(value, six.s...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier dictionary expression_statement assignment identifier fals...
Build the index related to the `name`.
def short_token(): hash = hashlib.sha1(shortuuid.uuid()) hash.update(settings.SECRET_KEY) return hash.hexdigest()[::2]
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement...
Generate a hash that can be used as an application identifier
def _grouped_backends(cls, options, backend): "Group options by backend and filter out output group appropriately" if options is None: return [(backend or Store.current_backend, options)] dfltdict = defaultdict(dict) for spec, groups in options.items(): if 'output...
module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier none block return_statement list tuple boolean_operator identifier attribute identifier identifier identifier expression_...
Group options by backend and filter out output group appropriately
def __get_cycle(graph, ordering, parent_lookup): root_node = ordering[0] for i in range(2, len(ordering)): current_node = ordering[i] if graph.adjacent(current_node, root_node): path = [] while current_node != root_node: path.append(current_node) ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript identifier integer for_statement identifier call identifier argument_list integer call identifier argument_list identifier block expression_statement assignment identifier subscri...
Gets the main cycle of the dfs tree.
def _create_buffers(self): self.buffers = {} for step in self.graph.nodes(): num_buffers = 1 if isinstance(step, Reduction): num_buffers = len(step.parents) self.buffers[step] = Buffer(step.min_frames, step.left_context, step.right_context, num_buffers...
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier integer if_statement call identif...
Create a buffer for every step in the pipeline.
def __clean_tmp(sfn): if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): all_roots = itertools.chain.from_iterable( six.itervalues(__opts__['file_roots'])) in_roots = any(sfn.startswith(root) for root in all_ro...
module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list attribute attribute attribute identifier identifier identifier iden...
Clean out a template temp file
def _get_value(self): if self._aux_variable: return self._aux_variable['law'](self._aux_variable['variable'].value) if self._transformation is None: return self._internal_value else: return self._transformation.backward(self._internal_value)
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement call subscript attribute identifier identifier string string_start string_content string_end argument_list attribute subscript attribute identifier identifier string string_start string_...
Return current parameter value
def id_request(self): import inspect curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) _LOGGER.debug('caller name: %s', calframe[1][3]) msg = StandardSend(self.address, COMMAND_ID_REQUEST_0X10_0X00) self._plm.send_msg(msg)
module function_definition identifier parameters identifier block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer express...
Request a device ID from a device.
def tmp_context(fn, mode="r"): with open(tmp_context_name(fn), mode) as f: return f.read()
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 identifier argument_list call identifier argument_list identifier identifier as_pattern_target identifier block return_stateme...
Return content fo the `fn` from the temporary directory.
def clean_ns(tag): if '}' in tag: split = tag.split('}') return split[0].strip('{'), split[-1] return '', tag
module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement e...
Return a tag and its namespace separately.
def process_request(self, request_object): resources = (request_object.entity_cls.query .filter(**request_object.filters) .offset((request_object.page - 1) * request_object.per_page) .limit(request_object.per_page) .order_by(req...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier parenthesized_expression call attribute call attribute call attribute call attribute call attribute attribute attribute identifier identifier identifier identifier argument_list dictionary_splat attri...
Return a list of resources
def _next_id(self): assert get_thread_ident() == self.ioloop_thread_id self._last_msg_id += 1 return str(self._last_msg_id)
module function_definition identifier parameters identifier block assert_statement comparison_operator call identifier argument_list attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer return_statement call identifier argument_list attribute identifier ident...
Return the next available message id.
def parse_cfg(self): self.cfgparser = ConfigParser() if not self.cfgparser.read(self.options.config): raise SystemExit('config file %s not found.'%self.options.config) projectDir = os.path.dirname(self.options.config) projectDir = os.path.abspath(projectDir) os.chdir...
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier block rai...
parses the given config file for experiments.
def send_response(self, response): response_bytes = response.encode(config.CODEC) log.debug("About to send reponse: %r", response_bytes) self.socket.send(response_bytes)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end...
Send a unicode object as reply to the most recently-issued command
def make_gui(self): self.option_window = Toplevel() self.option_window.protocol("WM_DELETE_WINDOW", self.on_exit) self.canvas_frame = tk.Frame(self, height=500) self.option_frame = tk.Frame(self.option_window, height=300) self.canvas_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=...
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier ...
Setups the general structure of the gui, the first function called
def _build_resource(self): resource = {"name": self.name} if self.dns_name is not None: resource["dnsName"] = self.dns_name if self.description is not None: resource["description"] = self.description if self.name_server_set is not None: resource["nameS...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript...
Generate a resource for ``create`` or ``update``.
def _write_config(self, memory): memory.seek(0) memory.write(struct.pack("<II", self._simulator.length, self.output.routing_key)) memory.write(bitarray( self.stimulus.ljust(self._simulator.length, "0"), end...
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content strin...
Write the configuration for this stimulus to memory.
def packet_write(self): bytes_written = 0 if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN, bytes_written while len(self.out_packet) > 0: pkt = self.out_packet[0] write_length, status = nyamuk_net.write(self.sock, pkt.payload) if write_leng...
module function_definition identifier parameters identifier block expression_statement assignment identifier integer if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement expression_list attribute identifier identifier identifier while_statement comparis...
Write packet to network.
def touch_file(self, filename): path_to_file = self.__file_class__(os.path.join(self, filename)) path_to_file.touch() return path_to_file
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifi...
Touch a file in the directory
def lock_exists_in_either_channel_side( channel_state: NettingChannelState, secrethash: SecretHash, ) -> bool: lock = get_lock(channel_state.our_state, secrethash) if not lock: lock = get_lock(channel_state.partner_state, secrethash) return lock is not None
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier if_statement not_operator identifier block expr...
Check if the lock with `secrethash` exists in either our state or the partner's state
async def server_stop(app, loop): em = Embed(color=0xe67e22) em.set_footer('Host: {}'.format(socket.gethostname())) em.description = '[INFO] Server Stopped' await app.webhook.send(embed=em) await app.session.close()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end i...
Sends a message to the webhook channel when server stops.
def connect(uri, factory=pymongo.MongoClient): warnings.warn( "do not use. Just call MongoClient directly.", DeprecationWarning) return factory(uri)
module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call identifier argument_list identifier
Use the factory to establish a connection to uri.
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2): dx = xt - xt1 dy = yt - yt1 if self.numPoints < self.maxPoints: self.dxValues[self.numPoints,0] = dx self.dxValues[self.numPoints,1] = dy self.thetaValues[self.numPoints,0] = theta1 self.thetaValues[self.numPoin...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_s...
Accumulate the various inputs.
def _build_all_dependencies(self): ret = {} for model, schema in six.iteritems(self._models()): dep_list = self._build_dependent_model_list(schema) ret[model] = dep_list return ret
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier ...
Helper function to build a map of model to their list of model reference dependencies
def search_related(self, request): logger.debug("Cache Search Request") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None result = [] items = list(self.cache.cache.items()) for key, item in items: element = self.cache.ge...
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list true block expressio...
extracting everything from the cache
def do_application_actions_plus(parser, token): nodelist = parser.parse(('end_application_actions',)) parser.delete_first_token() return ApplicationActionsPlus(nodelist)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple string string_start string_content string_end expression_statement call attribute identifier identifier argument_list return_statement call ide...
Render actions available with extra text.
def func(self, p): self._set_stochastics(p) try: return -1. * self.logp except ZeroProbability: return Inf
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier try_statement block return_statement binary_operator unary_operator float attribute identifier identifier except_clause identifier block return_statement identi...
The function that gets passed to the optimizers.
def from_ad_date(cls, date): functions.check_valid_ad_range(date) days = values.START_EN_DATE - date start_date = NepDate(values.START_NP_YEAR, 1, 1) return start_date + (date - values.START_EN_DATE)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier call identifier...
Gets a NepDate object from gregorian calendar date
def parse_array(raw_array): array_strip_brackets = raw_array.replace('{', '').replace('}', '') array_strip_spaces = array_strip_brackets.replace('"', '').replace(' ', '') return array_strip_spaces.split(',')
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_e...
Parse a WMIC array.
def list_fpgas(self): click.echo('\nSupported FPGAs:\n') FPGALIST_TPL = ('{fpga:30} {type:<5} {size:<5} {pack:<10}') terminal_width, _ = click.get_terminal_size() click.echo('-' * terminal_width) click.echo(FPGALIST_TPL.format( fpga=click.style('FPGA', fg='cyan'), typ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier parenthesized_expression string string_start string_content s...
Return a list with all the supported FPGAs
def execInspectorDialog(self): dialog = OpenInspectorDialog(self.argosApplication.inspectorRegistry, parent=self) dialog.setCurrentInspectorRegItem(self.inspectorRegItem) dialog.exec_() if dialog.result(): inspectorRegItem = dialog.getCurrentInspectorRegItem() if ...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list attribute identif...
Opens the inspector dialog box to let the user change the current inspector.
def select_template_name(template_name_list, using=None): if not isinstance(template_name_list, tuple): template_name_list = tuple(template_name_list) try: return _cached_name_lookups[template_name_list] except KeyError: for template_name in template_name_list: try: ...
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block return_statement subscript ident...
Given a list of template names, find the first one that exists.
def resolve_service_id(self, service_name=None, service_type=None): services = [s._info for s in self.api.services.list()] service_name = service_name.lower() for s in services: name = s['name'].lower() if service_type and service_name: if (service_name ==...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier call attribute attribute attribute identifier identifier identifier...
Find the service_id of a given service
def n_failed(self): return self._counters[JobStatus.failed] + self._counters[JobStatus.partial_failed]
module function_definition identifier parameters identifier block return_statement binary_operator subscript attribute identifier identifier attribute identifier identifier subscript attribute identifier identifier attribute identifier identifier
Return the number of failed jobs
def run(self, cmd): cmd = ['git', '--git-dir=%s' % self.path] + cmd print("cmd list", cmd) print("cmd", ' '.join(cmd)) res = None try: res = subprocess.check_output(cmd) except BaseException: pass if res: try: re...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator list string string_start string_content string_end binary_operator string string_start string_content string_end attribute identifier identifier identifier expression_statement call id...
Execute git command in bash
def aggregated_relevant_items(raw_df): df = ( raw_df[['idSegmento', 'idPlanilhaItens', 'VlUnitarioAprovado']] .groupby(by=['idSegmento', 'idPlanilhaItens']) .agg([np.mean, lambda x: np.std(x, ddof=0)]) ) df.columns = df.columns.droplevel(0) return ( df .rename(col...
module function_definition identifier parameters identifier block expression_statement assignment identifier parenthesized_expression call attribute call attribute subscript identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content str...
Aggragation for calculate mean and std.
def intersect_two(f1, f2, work_dir, data): bedtools = config_utils.get_program("bedtools", data, default="bedtools") f1_exists = f1 and utils.file_exists(f1) f2_exists = f2 and utils.file_exists(f2) if not f1_exists and not f2_exists: return None elif f1_exists and not f2_exists: ret...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier string string_start string_content string_...
Intersect two regions, handling cases where either file is not present.
def similar_items(self, itemid, N=10): if itemid >= self.similarity.shape[0]: return [] return sorted(list(nonzeros(self.similarity, itemid)), key=lambda x: -x[1])[:N]
module function_definition identifier parameters identifier identifier default_parameter identifier integer block if_statement comparison_operator identifier subscript attribute attribute identifier identifier identifier integer block return_statement list return_statement subscript call identifier argument_list call i...
Returns a list of the most similar other items
def _is_streaming_request(self): arg2 = self.argstreams[1] arg3 = self.argstreams[2] return not (isinstance(arg2, InMemStream) and isinstance(arg3, InMemStream) and ((arg2.auto_close and arg3.auto_close) or ( arg2.state == StreamSta...
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier subscript attribute identifier identifier integer return_statement not_operator parenthesized_expression boolean_opera...
check request is stream request or not