text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def limit_order(self, direction, quantity, price, **kwargs): """ Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) ...
[ "def", "limit_order", "(", "self", ",", "direction", ",", "quantity", ",", "price", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'limit_price'", "]", "=", "price", "kwargs", "[", "'order_type'", "]", "=", "\"LIMIT\"", "self", ".", "parent", ".", ...
38.4
15.066667
def parse_dunder_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == '__all__' self.consume(tk.NAME) # More than one __all__ definition means we ignore all __all__. if self.dunder_all is not None or self.dunder_all_error is not None: ...
[ "def", "parse_dunder_all", "(", "self", ")", ":", "assert", "self", ".", "current", ".", "value", "==", "'__all__'", "self", ".", "consume", "(", "tk", ".", "NAME", ")", "# More than one __all__ definition means we ignore all __all__.", "if", "self", ".", "dunder_...
39.875
18.571429
def init_file(self, filename, lines, expected, line_offset): """Signal a new file.""" self.filename = filename self.lines = lines self.expected = expected or () self.line_offset = line_offset self.file_errors = 0 self.counters['files'] += 1 self.counters['...
[ "def", "init_file", "(", "self", ",", "filename", ",", "lines", ",", "expected", ",", "line_offset", ")", ":", "self", ".", "filename", "=", "filename", "self", ".", "lines", "=", "lines", "self", ".", "expected", "=", "expected", "or", "(", ")", "self...
38
8.444444
def open(self, database, user, password, host): '''This opens a new database connection. Parameters ---------- database : str Name of the database to connect to. user : str User name of the database server user. password : str Passw...
[ "def", "open", "(", "self", ",", "database", ",", "user", ",", "password", ",", "host", ")", ":", "try", ":", "self", ".", "connection", "=", "pg", ".", "connect", "(", "user", "=", "user", ",", "password", "=", "password", ",", "database", "=", "d...
27.738095
23.309524
def update(self): """Sync up changes to reminders. """ params = {} return self.send( url=self._base_url + 'update', method='POST', json=params )
[ "def", "update", "(", "self", ")", ":", "params", "=", "{", "}", "return", "self", ".", "send", "(", "url", "=", "self", ".", "_base_url", "+", "'update'", ",", "method", "=", "'POST'", ",", "json", "=", "params", ")" ]
23.555556
13.666667
def files_upload( self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs ) -> SlackResponse: """Uploads or creates a file. Args: file (str): Supply a file path. when you'd like to upload a specific file. e.g. 'dramacat.gif' content (s...
[ "def", "files_upload", "(", "self", ",", "*", ",", "file", ":", "Union", "[", "str", ",", "IOBase", "]", "=", "None", ",", "content", ":", "str", "=", "None", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "if", "file", "is", "None", "...
43.5
24.115385
def getWmAllowedActions(self, win, str=False): """ Get the list of allowed actions for the given window (property _NET_WM_ALLOWED_ACTIONS). :param win: the window object :param str: True to get a list of string allowed actions instead of int :return: list of (int|str) ...
[ "def", "getWmAllowedActions", "(", "self", ",", "win", ",", "str", "=", "False", ")", ":", "wAllowedActions", "=", "(", "self", ".", "_getProperty", "(", "'_NET_WM_ALLOWED_ACTIONS'", ",", "win", ")", "or", "[", "]", ")", "if", "not", "str", ":", "return"...
37.928571
15.785714
def mkdir(path, mode=0o777, dir_fd=None): """ Create a directory named path with numeric mode mode. Equivalent to "os.mkdir". Args: path (path-like object): Path or URL. mode (int): The mode parameter is passed to os.mkdir(); see the os.mkdir() description for how it is int...
[ "def", "mkdir", "(", "path", ",", "mode", "=", "0o777", ",", "dir_fd", "=", "None", ")", ":", "system", "=", "get_instance", "(", "path", ")", "relative", "=", "system", ".", "relpath", "(", "path", ")", "# Checks if parent directory exists", "parent_dir", ...
34.388889
17
def resources(self): """Returns a list of resources related to the problem (or None)""" with open(os.path.join(EULER_DATA, 'resources.json')) as data_file: data = json.load(data_file) problem_num = str(self.num) if problem_num in data: files = data[problem_num] ...
[ "def", "resources", "(", "self", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "EULER_DATA", ",", "'resources.json'", ")", ")", "as", "data_file", ":", "data", "=", "json", ".", "load", "(", "data_file", ")", "problem_num", "=", ...
32.785714
19.214286
def sign_message(self, key, message, verbose=False): """ Return a signature, encoded in Base64, which can be verified by anyone using the public key. """ secret_exponent = key.secret_exponent() if not secret_exponent: raise ValueError("Private key is required ...
[ "def", "sign_message", "(", "self", ",", "key", ",", "message", ",", "verbose", "=", "False", ")", ":", "secret_exponent", "=", "key", ".", "secret_exponent", "(", ")", "if", "not", "secret_exponent", ":", "raise", "ValueError", "(", "\"Private key is required...
33.681818
19.954545
def _freeze(self) -> OrderedDict: """ Evaluate all of the column values and return the result :return: column/value tuples """ return OrderedDict(**{k: getattr(self, k, None) for k in super().__getattribute__("_columns")})
[ "def", "_freeze", "(", "self", ")", "->", "OrderedDict", ":", "return", "OrderedDict", "(", "*", "*", "{", "k", ":", "getattr", "(", "self", ",", "k", ",", "None", ")", "for", "k", "in", "super", "(", ")", ".", "__getattribute__", "(", "\"_columns\""...
42.833333
16.166667
def normalize(location_name, preserve_commas=False): """Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.""" def replace(match): if preserve_commas and ',' in match.group(0): return ',' return ' ' return NORM...
[ "def", "normalize", "(", "location_name", ",", "preserve_commas", "=", "False", ")", ":", "def", "replace", "(", "match", ")", ":", "if", "preserve_commas", "and", "','", "in", "match", ".", "group", "(", "0", ")", ":", "return", "','", "return", "' '", ...
46.125
14.125
def write_passes(self, outfile, rows, packed=False): """ Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear ...
[ "def", "write_passes", "(", "self", ",", "outfile", ",", "rows", ",", "packed", "=", "False", ")", ":", "# http://www.w3.org/TR/PNG/#5PNG-file-signature", "outfile", ".", "write", "(", "_signature", ")", "# http://www.w3.org/TR/PNG/#11IHDR", "write_chunk", "(", "outfi...
40.335329
17.185629
def add_lexemes(self, **kw): """ :return: list of dicts corresponding to newly created Lexemes """ lexemes = [] # Do we have morpheme segmentation on top of phonemes? with_morphemes = '+' in self['FormTable', 'Segments'].separator for i, form in enumerate(self.d...
[ "def", "add_lexemes", "(", "self", ",", "*", "*", "kw", ")", ":", "lexemes", "=", "[", "]", "# Do we have morpheme segmentation on top of phonemes?", "with_morphemes", "=", "'+'", "in", "self", "[", "'FormTable'", ",", "'Segments'", "]", ".", "separator", "for",...
48.595238
25.166667
def register_onchain_secret( channel_state: NettingChannelState, secret: Secret, secrethash: SecretHash, secret_reveal_block_number: BlockNumber, delete_lock: bool = True, ) -> None: """This will register the onchain secret and set the lock to the unlocked stated. Even t...
[ "def", "register_onchain_secret", "(", "channel_state", ":", "NettingChannelState", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", "secret_reveal_block_number", ":", "BlockNumber", ",", "delete_lock", ":", "bool", "=", "True", ",", ")", "...
28.413793
16.551724
def detach_securitygroup_components(self, group_id, component_ids): """Detaches network components from a security group. :param int group_id: The ID of the security group :param list component_ids: The IDs of the network components to detach """ return self.security_group.detac...
[ "def", "detach_securitygroup_components", "(", "self", ",", "group_id", ",", "component_ids", ")", ":", "return", "self", ".", "security_group", ".", "detachNetworkComponents", "(", "component_ids", ",", "id", "=", "group_id", ")" ]
52.25
23.25
def voxelwise_diff(img_spec1=None, img_spec2=None, abs_value=True, cmap='gray', overlay_image=False, overlay_alpha=0.8, num_rows=2, num_cols=6, rescale_method='global',...
[ "def", "voxelwise_diff", "(", "img_spec1", "=", "None", ",", "img_spec2", "=", "None", ",", "abs_value", "=", "True", ",", "cmap", "=", "'gray'", ",", "overlay_image", "=", "False", ",", "overlay_alpha", "=", "0.8", ",", "num_rows", "=", "2", ",", "num_c...
32.467391
20.163043
def quota(self, quota): """ Sets the quota of this ServicePackageQuota. Available quota for the service package. :param quota: The quota of this ServicePackageQuota. :type: int """ if quota is None: raise ValueError("Invalid value for `quota`, must no...
[ "def", "quota", "(", "self", ",", "quota", ")", ":", "if", "quota", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `quota`, must not be `None`\"", ")", "if", "quota", "is", "not", "None", "and", "quota", "<", "0", ":", "raise", "ValueErr...
35.5
20.642857
def _select_labels(self, segmentation, labels=None): """ Get selection of labels from input segmentation :param segmentation: :param labels: :return: """ logger.debug("select_labels() started with labels={}".format(labels)) if self.slab is not None and labels is...
[ "def", "_select_labels", "(", "self", ",", "segmentation", ",", "labels", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"select_labels() started with labels={}\"", ".", "format", "(", "labels", ")", ")", "if", "self", ".", "slab", "is", "not", "None"...
40.888889
21.777778
def create(self): """Create the file on the file system.""" self.buffer = [] self.buf_count = 0 if not self.directory.exists: self.directory.create() self.open('w') return self
[ "def", "create", "(", "self", ")", ":", "self", ".", "buffer", "=", "[", "]", "self", ".", "buf_count", "=", "0", "if", "not", "self", ".", "directory", ".", "exists", ":", "self", ".", "directory", ".", "create", "(", ")", "self", ".", "open", "...
31.142857
16.142857
def get_dataset(self, dataset_id, project_id=None): """ Method returns dataset_resource if dataset exist and raised 404 error if dataset does not exist :param dataset_id: The BigQuery Dataset ID :type dataset_id: str :param project_id: The GCP Project ID :type pr...
[ "def", "get_dataset", "(", "self", ",", "dataset_id", ",", "project_id", "=", "None", ")", ":", "if", "not", "dataset_id", "or", "not", "isinstance", "(", "dataset_id", ",", "str", ")", ":", "raise", "ValueError", "(", "\"dataset_id argument must be provided and...
40.516129
24
def date_fromnow(self, value): """ Displays humanized date (time since) """ import humanize language = self.get_language() if language != 'en': humanize.i18n.activate(language) return Markup(humanize.naturaltime(value))
[ "def", "date_fromnow", "(", "self", ",", "value", ")", ":", "import", "humanize", "language", "=", "self", ".", "get_language", "(", ")", "if", "language", "!=", "'en'", ":", "humanize", ".", "i18n", ".", "activate", "(", "language", ")", "return", "Mark...
37.857143
7.857143
def iter(self, bucket): """https://github.com/frictionlessdata/tableschema-sql-py#storage """ # Get table and fallbacks table = self.__get_table(bucket) schema = tableschema.Schema(self.describe(bucket)) # Open and close transaction with self.__connection.begin(...
[ "def", "iter", "(", "self", ",", "bucket", ")", ":", "# Get table and fallbacks", "table", "=", "self", ".", "__get_table", "(", "bucket", ")", "schema", "=", "tableschema", ".", "Schema", "(", "self", ".", "describe", "(", "bucket", ")", ")", "# Open and ...
40.058824
15.941176
def addAffectedLocus( self, allele_id, gene_id, rel_id=None): """ We make the assumption here that if the relationship is not provided, it is a GENO:is_allele_of. Here, the allele should be a variant_locus, not a sequence alteration. :param allele_id: ...
[ "def", "addAffectedLocus", "(", "self", ",", "allele_id", ",", "gene_id", ",", "rel_id", "=", "None", ")", ":", "if", "rel_id", "is", "None", ":", "rel_id", "=", "self", ".", "globaltt", "[", "'has_affected_feature'", "]", "self", ".", "graph", ".", "add...
29.444444
20.666667
def prepare(self): """ Called when builder run collect files in builder group :rtype: list[static_bundle.files.StaticFileResult] """ result_files = self.collect_files() chain = self.prepare_handlers_chain if chain is None: # default handlers ...
[ "def", "prepare", "(", "self", ")", ":", "result_files", "=", "self", ".", "collect_files", "(", ")", "chain", "=", "self", ".", "prepare_handlers_chain", "if", "chain", "is", "None", ":", "# default handlers", "chain", "=", "[", "LessCompilerPrepareHandler", ...
32.0625
14.3125
def setup_driver(scenario): """Scenario initialization :param scenario: running scenario """ if not hasattr(world, 'config_files'): world.config_files = ConfigFiles() # By default config directory is located in terrain path if not world.config_files.config_directory: world.conf...
[ "def", "setup_driver", "(", "scenario", ")", ":", "if", "not", "hasattr", "(", "world", ",", "'config_files'", ")", ":", "world", ".", "config_files", "=", "ConfigFiles", "(", ")", "# By default config directory is located in terrain path", "if", "not", "world", "...
34.571429
17.071429
def main(argv=None): """ben-nett entry point""" arguments = cli_common(__doc__, argv=argv) benet = BeNet(arguments['CAMPAIGN_FILE']) benet.run() if argv is not None: return benet
[ "def", "main", "(", "argv", "=", "None", ")", ":", "arguments", "=", "cli_common", "(", "__doc__", ",", "argv", "=", "argv", ")", "benet", "=", "BeNet", "(", "arguments", "[", "'CAMPAIGN_FILE'", "]", ")", "benet", ".", "run", "(", ")", "if", "argv", ...
28.571429
13.142857
def piece_to_id(input, model_file=None, model_proto=None, name=None): """Converts piece into vocabulary id. Args: input: An arbitrary tensor of string. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_pr...
[ "def", "piece_to_id", "(", "input", ",", "model_file", "=", "None", ",", "model_proto", "=", "None", ",", "name", "=", "None", ")", ":", "return", "_gen_sentencepiece_processor_op", ".", "sentencepiece_piece_to_id", "(", "input", ",", "model_file", "=", "model_f...
39.733333
21.2
def FindAnomalies(self): """Identify any anomalous group attributes or memberships.""" for grp_name, group in iteritems(self.entry): shadow = self.shadow.get(grp_name) gshadows = self.gshadow_members.get(grp_name, []) if shadow is not None: diff = self.MemberDiff(group.members, "group"...
[ "def", "FindAnomalies", "(", "self", ")", ":", "for", "grp_name", ",", "group", "in", "iteritems", "(", "self", ".", "entry", ")", ":", "shadow", "=", "self", ".", "shadow", ".", "get", "(", "grp_name", ")", "gshadows", "=", "self", ".", "gshadow_membe...
44.571429
19.928571
def build_listing(self): """ Builds a listing of all functions sorted A-Z, with their names and descriptions """ def func_entry(name, func): args, varargs, defaults = self._get_arg_spec(func) # add regular arguments params = [{'name': str(a), 'optiona...
[ "def", "build_listing", "(", "self", ")", ":", "def", "func_entry", "(", "name", ",", "func", ")", ":", "args", ",", "varargs", ",", "defaults", "=", "self", ".", "_get_arg_spec", "(", "func", ")", "# add regular arguments", "params", "=", "[", "{", "'na...
40.45
23.95
def _pretty_const_type_val(typecode, val): """ given a typecode and a value, returns the appropriate pretty version of that value (not the dereferenced data) """ if typecode == CONST_Utf8: typestr = "Utf8" # formerly Asciz, which was considered Java bug if not isinstance(val, str):...
[ "def", "_pretty_const_type_val", "(", "typecode", ",", "val", ")", ":", "if", "typecode", "==", "CONST_Utf8", ":", "typestr", "=", "\"Utf8\"", "# formerly Asciz, which was considered Java bug", "if", "not", "isinstance", "(", "val", ",", "str", ")", ":", "# Py2, v...
32.157895
13.315789
def lovasz_hinge(logits, labels, per_image=True, ignore=None): """ Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ...
[ "def", "lovasz_hinge", "(", "logits", ",", "labels", ",", "per_image", "=", "True", ",", "ignore", "=", "None", ")", ":", "if", "per_image", ":", "loss", "=", "mean", "(", "lovasz_hinge_flat", "(", "*", "flatten_binary_scores", "(", "log", ".", "unsqueeze"...
45.214286
24.785714
def _max_weight_operator(ops: Iterable[PauliTerm]) -> Union[None, PauliTerm]: """Construct a PauliTerm operator by taking the non-identity single-qubit operator at each qubit position. This function will return ``None`` if the input operators do not share a natural tensor product basis. For exampl...
[ "def", "_max_weight_operator", "(", "ops", ":", "Iterable", "[", "PauliTerm", "]", ")", "->", "Union", "[", "None", ",", "PauliTerm", "]", ":", "mapping", "=", "dict", "(", ")", "# type: Dict[int, str]", "for", "op", "in", "ops", ":", "for", "idx", ",", ...
40.25
21.9
def log_in(self, username, password): """ Logs in to the CouchDB instance with the credentials `username` and `password` """ self.resource.credentials = (username, password) return self.resource.get_json("_session")[2]
[ "def", "log_in", "(", "self", ",", "username", ",", "password", ")", ":", "self", ".", "resource", ".", "credentials", "=", "(", "username", ",", "password", ")", "return", "self", ".", "resource", ".", "get_json", "(", "\"_session\"", ")", "[", "2", "...
37.142857
12.571429
def search_base_learner(id): """Creates a set of base learners from base learner origin using grid search and queues them up """ path = functions.get_path_from_query_string(request) req_body = request.get_json() if req_body['method'] == 'grid': param_grid = functions.import_object_from_s...
[ "def", "search_base_learner", "(", "id", ")", ":", "path", "=", "functions", ".", "get_path_from_query_string", "(", "request", ")", "req_body", "=", "request", ".", "get_json", "(", ")", "if", "req_body", "[", "'method'", "]", "==", "'grid'", ":", "param_gr...
40.575342
22.479452
def do_tree(self, line): """Shows entities of a given kind.""" opts = self.TREE_OPTS line = line.split() _pattern = "" if not self.current: self._help_noontology() return if len(line) == 0: # default contextual behaviour [2016-03-01] ...
[ "def", "do_tree", "(", "self", ",", "line", ")", ":", "opts", "=", "self", ".", "TREE_OPTS", "line", "=", "line", ".", "split", "(", ")", "_pattern", "=", "\"\"", "if", "not", "self", ".", "current", ":", "self", ".", "_help_noontology", "(", ")", ...
30.47619
18.214286
def _save_plot(self, *args, extension='pdf', **kwargs): """Save the plot. Returns ------- str The basename with which the plot has been saved. """ import matplotlib.pyplot as plt tmp_path = make_temp_dir() filename = '{}.{}'.format(str(uuid.u...
[ "def", "_save_plot", "(", "self", ",", "*", "args", ",", "extension", "=", "'pdf'", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "tmp_path", "=", "make_temp_dir", "(", ")", "filename", "=", "'{}.{}'", ".", "for...
28.8125
19.4375
def chunks(self): """ Generates chunks from stream, each chunk is an instace of bytes. """ if self.is_null(): return total = 0 while True: chunk_len = self._rdr.get_uint() if chunk_len == 0: if not self.is_unknown_len() and tota...
[ "def", "chunks", "(", "self", ")", ":", "if", "self", ".", "is_null", "(", ")", ":", "return", "total", "=", "0", "while", "True", ":", "chunk_len", "=", "self", ".", "_rdr", ".", "get_uint", "(", ")", "if", "chunk_len", "==", "0", ":", "if", "no...
32.809524
18.47619
def render(self, node): """Renders a node. This function is used internally, as it returns a list of lines. Use :func:`~asciitree.LeftAligned.__call__` instead. """ lines = [] children = self.traverse.get_children(node) lines.append(self.draw.node_label(self.traverse.get...
[ "def", "render", "(", "self", ",", "node", ")", ":", "lines", "=", "[", "]", "children", "=", "self", ".", "traverse", ".", "get_children", "(", "node", ")", "lines", ".", "append", "(", "self", ".", "draw", ".", "node_label", "(", "self", ".", "tr...
38.869565
19.869565
def wrap(self, req, result): """ Wrap method return results. The return value of the action method and of the action extensions is passed through this method before being returned to the caller. Instances of `webob.Response` are thrown, to abort the rest of action and e...
[ "def", "wrap", "(", "self", ",", "req", ",", "result", ")", ":", "if", "isinstance", "(", "result", ",", "webob", ".", "exc", ".", "HTTPException", ")", ":", "# It's a webob HTTP exception; use raise to bail out", "# immediately and pass it upstream", "raise", "resu...
45.12
17.04
def create_tag(self, version, params): """Create VCS tag :param version: :param params: :return: """ cmd = self._command.tag(version, params) (code, stdout, stderr) = self._exec(cmd) if code: raise errors.VCSError('Can\'t create VCS tag %s. ...
[ "def", "create_tag", "(", "self", ",", "version", ",", "params", ")", ":", "cmd", "=", "self", ".", "_command", ".", "tag", "(", "version", ",", "params", ")", "(", "code", ",", "stdout", ",", "stderr", ")", "=", "self", ".", "_exec", "(", "cmd", ...
28.928571
21.357143
def apply_payoff(self): """Apply the payoff that has been accumulated from immediate reward and/or payments from successor match sets. Attempting to call this method before an action has been selected or after it has already been called for the same match set will result in a Val...
[ "def", "apply_payoff", "(", "self", ")", ":", "if", "self", ".", "_selected_action", "is", "None", ":", "raise", "ValueError", "(", "\"The action has not been selected yet.\"", ")", "if", "self", ".", "_closed", ":", "raise", "ValueError", "(", "\"The payoff for t...
36.916667
16.958333
def listidentifiers(**kwargs): """Create OAI-PMH response for verb ListIdentifiers.""" e_tree, e_listidentifiers = verb(**kwargs) result = get_records(**kwargs) for record in result.items: pid = oaiid_fetcher(record['id'], record['json']['_source']) header( e_listidentifiers...
[ "def", "listidentifiers", "(", "*", "*", "kwargs", ")", ":", "e_tree", ",", "e_listidentifiers", "=", "verb", "(", "*", "*", "kwargs", ")", "result", "=", "get_records", "(", "*", "*", "kwargs", ")", "for", "record", "in", "result", ".", "items", ":", ...
34.25
17.6875
def dist_minkowski(src, tar, qval=2, pval=1, alphabet=None): """Return normalized Minkowski distance of two strings. This is a wrapper for :py:meth:`Minkowski.dist`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string...
[ "def", "dist_minkowski", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "pval", "=", "1", ",", "alphabet", "=", "None", ")", ":", "return", "Minkowski", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "qval", ",", "pval", ",", "alphabet"...
26.75
21.472222
def lowercase_attr_names(tag): """Lower-case all attribute names of the provided BeautifulSoup tag. Note: this mutates the tag's attribute names and does not return a new tag. :param Tag: BeautifulSoup tag """ # Use list comprehension instead of dict comprehension for 2.6 support tag.attrs...
[ "def", "lowercase_attr_names", "(", "tag", ")", ":", "# Use list comprehension instead of dict comprehension for 2.6 support", "tag", ".", "attrs", "=", "dict", "(", "[", "(", "key", ".", "lower", "(", ")", ",", "value", ")", "for", "key", ",", "value", "in", ...
30.769231
20.538462
def is_retryable(err): """ Determines if the given exception is something that is network/socket-related and should thus cause the TCP connection to close and the operation retried on another node. :rtype: boolean """ if isinstance(err, ConnectionClosed): # NB: only retryable if we'...
[ "def", "is_retryable", "(", "err", ")", ":", "if", "isinstance", "(", "err", ",", "ConnectionClosed", ")", ":", "# NB: only retryable if we're not mid-streaming", "if", "err", ".", "mid_stream", ":", "return", "False", "else", ":", "return", "True", "elif", "isi...
29.052632
15.578947
def toposort_rules(rules): """ Sort given rules using toposort with dependency parameter. :param rules: :type rules: :return: :rtype: """ graph = {} class_dict = {} for rule in rules: if rule.__class__ in class_dict: raise ValueError("Duplicate class rules are...
[ "def", "toposort_rules", "(", "rules", ")", ":", "graph", "=", "{", "}", "class_dict", "=", "{", "}", "for", "rule", "in", "rules", ":", "if", "rule", ".", "__class__", "in", "class_dict", ":", "raise", "ValueError", "(", "\"Duplicate class rules are not all...
33.142857
15.571429
def pixy_value_update(blocks): """ Prints the Pixy blocks data.""" if len(blocks) > 0: pan_error = X_CENTER - blocks[0]["x"] tilt_error = blocks[0]["y"] - Y_CENTER pan_loop.update(pan_error) tilt_loop.update(tilt_error) loop = asyncio.get_event_loop() if loop.is_...
[ "def", "pixy_value_update", "(", "blocks", ")", ":", "if", "len", "(", "blocks", ")", ">", "0", ":", "pan_error", "=", "X_CENTER", "-", "blocks", "[", "0", "]", "[", "\"x\"", "]", "tilt_error", "=", "blocks", "[", "0", "]", "[", "\"y\"", "]", "-", ...
56.833333
29.777778
def get_data(self, latitude, longitude, start, end, vert_level=None, query_variables=None, close_netcdf_data=True): """ Submits a query to the UNIDATA servers using Siphon NCSS and converts the netcdf data to a pandas DataFrame. Parameters -----...
[ "def", "get_data", "(", "self", ",", "latitude", ",", "longitude", ",", "start", ",", "end", ",", "vert_level", "=", "None", ",", "query_variables", "=", "None", ",", "close_netcdf_data", "=", "True", ")", ":", "if", "not", "self", ".", "connected", ":",...
32.676471
18.176471
def p_expr_new(p): 'expr : NEW class_name_reference ctor_arguments' p[0] = ast.New(p[2], p[3], lineno=p.lineno(1))
[ "def", "p_expr_new", "(", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "New", "(", "p", "[", "2", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")" ]
40
14.666667
def AverageGatewayDegree_metric(bpmn_graph): """ Returns the value of the Average Gateway Degree metric ("Average of the number of both incoming and outgoing arcs of the gateway nodes in the process model") for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph repres...
[ "def", "AverageGatewayDegree_metric", "(", "bpmn_graph", ")", ":", "gateways_ids", "=", "[", "gateway", "[", "0", "]", "for", "gateway", "in", "get_all_gateways", "(", "bpmn_graph", ")", "]", "all_nodes_degrees", "=", "bpmn_graph", ".", "diagram_graph", ".", "de...
46
28.142857
def _LoadDataIntoCache( self, file_object, minimum_offset, read_all_data=False): """Reads and decompresses the data in the member. This function already loads as much data as possible in the cache, up to UNCOMPRESSED_DATA_CACHE_SIZE bytes. Args: file_object (FileIO): file-like object. ...
[ "def", "_LoadDataIntoCache", "(", "self", ",", "file_object", ",", "minimum_offset", ",", "read_all_data", "=", "False", ")", ":", "# Decompression can only be performed from beginning to end of the stream.", "# So, if data before the current position of the decompressor in the stream"...
42.66129
21.790323
def check_response(self, response): """ Checks that a JSON response from the WebDriver does not have an error. :Args: - response - The JSON response from the WebDriver server as a dictionary object. :Raises: If the response contains an error message. """ ...
[ "def", "check_response", "(", "self", ",", "response", ")", ":", "status", "=", "response", ".", "get", "(", "'status'", ",", "None", ")", "if", "status", "is", "None", "or", "status", "==", "ErrorCode", ".", "SUCCESS", ":", "return", "value", "=", "No...
46.007407
14.940741
def get_id(self, details=False): # pylint: disable=unused-argument """Get daemon identification information :return: A dict with the following structure :: { "alignak": selfAlignak instance name "type": daemon type "name": daemon name...
[ "def", "get_id", "(", "self", ",", "details", "=", "False", ")", ":", "# pylint: disable=unused-argument", "# Modules information", "res", "=", "{", "\"alignak\"", ":", "getattr", "(", "self", ",", "'alignak_name'", ",", "'unknown'", ")", ",", "\"type\"", ":", ...
30.409091
18
def sudo(orig): # pragma: no cover """ a nicer version of sudo that uses getpass to ask for a password, or allows the first argument to be a string password """ prompt = "[sudo] password for %s: " % getpass.getuser() def stdin(): pw = getpass.getpass(prompt=prompt) + "\n" yield pw ...
[ "def", "sudo", "(", "orig", ")", ":", "# pragma: no cover", "prompt", "=", "\"[sudo] password for %s: \"", "%", "getpass", ".", "getuser", "(", ")", "def", "stdin", "(", ")", ":", "pw", "=", "getpass", ".", "getpass", "(", "prompt", "=", "prompt", ")", "...
26.583333
20.583333
def tofile(self, fileobj): """ write a cache object to the fileobj as a lal cache file """ for entry in self: print >>fileobj, str(entry) fileobj.close()
[ "def", "tofile", "(", "self", ",", "fileobj", ")", ":", "for", "entry", "in", "self", ":", "print", ">>", "fileobj", ",", "str", "(", "entry", ")", "fileobj", ".", "close", "(", ")" ]
22.857143
12
def user_default_serializer(self, obj): """Convert a User to a cached instance representation.""" if not obj: return None self.user_default_add_related_pks(obj) return dict(( ('id', obj.id), ('username', obj.username), self.field_to_json('D...
[ "def", "user_default_serializer", "(", "self", ",", "obj", ")", ":", "if", "not", "obj", ":", "return", "None", "self", ".", "user_default_add_related_pks", "(", "obj", ")", "return", "dict", "(", "(", "(", "'id'", ",", "obj", ".", "id", ")", ",", "(",...
38.666667
15.083333
def get_permission(context, method, *args, **kwargs): """ This will return a boolean indicating if the considered permission is granted for the passed user. Usage:: {% get_permission 'can_access_moderation_panel' request.user as var %} """ request = context.get('request', None) pe...
[ "def", "get_permission", "(", "context", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", "=", "context", ".", "get", "(", "'request'", ",", "None", ")", "perm_handler", "=", "request", ".", "forum_permission_handler", "if", ...
38.863636
24.636364
def login(self, username, password, namespace=None): """ Performs the login against zimbra (sends AuthRequest, receives AuthResponse). :param namespace: if specified, the namespace used for authetication (if the client namespace is not suitable for ...
[ "def", "login", "(", "self", ",", "username", ",", "password", ",", "namespace", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "self", ".", "client", ".", "NAMESPACE", "data", "=", "self", ".", "client", ".", "request",...
33.583333
17.333333
def access_token_response(self, token, message_id=None): """Access token response structure. Success if token is set, otherwise (None, empty string) give error response. If message_id is set then an extra messageId attribute is set in the response to handle postMessage() responses. ...
[ "def", "access_token_response", "(", "self", ",", "token", ",", "message_id", "=", "None", ")", ":", "if", "(", "token", ")", ":", "data", "=", "{", "\"accessToken\"", ":", "token", ",", "\"expiresIn\"", ":", "self", ".", "access_token_lifetime", "}", "if"...
41.8125
18.5625
def copy_from(self, src, dest): """ copy a file or a directory from container or image to host system. If you are copying directories, the target directory must not exist (this function is using `shutil.copytree` to copy directories and that's a requirement of the function). In case the ...
[ "def", "copy_from", "(", "self", ",", "src", ",", "dest", ")", ":", "p", "=", "self", ".", "p", "(", "src", ")", "if", "os", ".", "path", ".", "isfile", "(", "p", ")", ":", "logger", ".", "info", "(", "\"copying file %s to %s\"", ",", "p", ",", ...
46.555556
24.666667
def add_route(route, endpoint=None, **kw): """Add a new JSON API route """ # ensure correct amout of slashes def apiurl(route): return '/'.join(s.strip('/') for s in ["", BASE_URL, route]) return add_senaite_route(apiurl(route), endpoint, **kw)
[ "def", "add_route", "(", "route", ",", "endpoint", "=", "None", ",", "*", "*", "kw", ")", ":", "# ensure correct amout of slashes", "def", "apiurl", "(", "route", ")", ":", "return", "'/'", ".", "join", "(", "s", ".", "strip", "(", "'/'", ")", "for", ...
29.555556
16.666667
def get_parameters(parser, token): """ {% get_parameters except_field %} """ args = token.split_contents() if len(args) < 2: raise template.TemplateSyntaxError( "get_parameters tag takes at least 1 argument" ) return GetParametersNode(args[1].strip())
[ "def", "get_parameters", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "<", "2", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"get_parameters tag takes at least 1 ar...
29.4
9.2
def from_file(cls, source): """Instantiate Relations from a relations file.""" if hasattr(source, 'read'): relations = cls.from_string(source.read()) else: with open(source) as f: relations = cls.from_string(f.read()) return relations
[ "def", "from_file", "(", "cls", ",", "source", ")", ":", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "relations", "=", "cls", ".", "from_string", "(", "source", ".", "read", "(", ")", ")", "else", ":", "with", "open", "(", "source", ")...
37.375
11.625
def _enter_newline(self): """ Remove the trailing spaces in the current line, and then mark that the leading spaces of the next line need to be removed. .. seealso:: `CSS Text Module Level 3 - The White Space Processing Rules <http://www.w3.org/TR/css3-text/#white...
[ "def", "_enter_newline", "(", "self", ")", ":", "last_text_idx", "=", "self", ".", "_last_text_idx", "if", "last_text_idx", ">=", "0", ":", "buf", "=", "self", ".", "_buffer", "buf", "[", "last_text_idx", "]", "=", "buf", "[", "last_text_idx", "]", ".", ...
33.9375
19.5625
def submit_files(self, halt_on_error=True): """Submit Files for Documents and Reports to ThreatConnect API. Critical Errors * There is insufficient document storage allocated to this account. Args: halt_on_error (bool, default:True): If True any exception will raise an err...
[ "def", "submit_files", "(", "self", ",", "halt_on_error", "=", "True", ")", ":", "# check global setting for override", "if", "self", ".", "halt_on_file_error", "is", "not", "None", ":", "halt_on_error", "=", "self", ".", "halt_on_file_error", "upload_status", "=", ...
44.793103
23.37931
def serialize_ndarray_b64(o): """ Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are human-readable, but the array data itself is binary64 encoded. Args: o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized. Returns: A dictionary that can be passed ...
[ "def", "serialize_ndarray_b64", "(", "o", ")", ":", "if", "o", ".", "flags", "[", "'C_CONTIGUOUS'", "]", ":", "o_data", "=", "o", ".", "data", "else", ":", "o_data", "=", "np", ".", "ascontiguousarray", "(", "o", ")", ".", "data", "data_b64", "=", "b...
29.095238
19.190476
def parseStr(self, st) : """Parses a string""" self.data = st.replace('\r', '\n') self.data = self.data.replace('\n\n', '\n') self.data = self.data.split('\n')
[ "def", "parseStr", "(", "self", ",", "st", ")", ":", "self", ".", "data", "=", "st", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "self", ".", "data", "=", "self", ".", "data", ".", "replace", "(", "'\\n\\n'", ",", "'\\n'", ")", "self", ".", ...
32.6
6
def _create_objective(self, m, n): """ Parameters ---------- m, n : int Dimensions that of solution matrix Returns the objective function and a variable representing the solution to the convex optimization problem. """ # S is the completed matr...
[ "def", "_create_objective", "(", "self", ",", "m", ",", "n", ")", ":", "# S is the completed matrix", "shape", "=", "(", "m", ",", "n", ")", "S", "=", "cvxpy", ".", "Variable", "(", "shape", ",", "name", "=", "\"S\"", ")", "norm", "=", "cvxpy", ".", ...
32
10.933333
def _augment_text_w_syntactic_info( self, text, text_layer ): ''' Augments given Text object with the syntactic information from the *text_layer*. More specifically, adds information about SYNTAX_LABEL, SYNTAX_HEAD and DEPREL to each token in the Text object; ...
[ "def", "_augment_text_w_syntactic_info", "(", "self", ",", "text", ",", "text_layer", ")", ":", "j", "=", "0", "for", "sentence", "in", "text", ".", "divide", "(", "layer", "=", "WORDS", ",", "by", "=", "SENTENCES", ")", ":", "for", "i", "in", "range",...
53.870968
21.677419
def cancel_charge(charge_id: str) -> None: """ Cancels an existing charge. If the charge was already cancelled then an Exception is raised. If it is not in an invoice then the charge is deleted, otherwise a Credit object is created to reverse the Charge. :param charge_id: The id of the charge...
[ "def", "cancel_charge", "(", "charge_id", ":", "str", ")", "->", "None", ":", "logger", ".", "info", "(", "'cancelling-charge'", ",", "charge_id", "=", "charge_id", ")", "with", "transaction", ".", "atomic", "(", ")", ":", "charge", "=", "Charge", ".", "...
32.83871
20.064516
def fetch_file(dataset_name, url, dataset_dir, dataset_prefix=None, default_paths=None, filetype=None, resume=True, overwrite=False, md5sum=None, username=None, password=None, retry=0, verbose=1, temp_downloads=None): """Load requested file, downloading it if needed or r...
[ "def", "fetch_file", "(", "dataset_name", ",", "url", ",", "dataset_dir", ",", "dataset_prefix", "=", "None", ",", "default_paths", "=", "None", ",", "filetype", "=", "None", ",", "resume", "=", "True", ",", "overwrite", "=", "False", ",", "md5sum", "=", ...
39.388889
20.876543
def get_uvi(self, params_dict): """ Invokes the UV Index endpoint :param params_dict: dict of parameters :returns: a string containing raw JSON data :raises: *ValueError*, *APICallError* """ lat = str(params_dict['lat']) lon = str(params_dict['lon']) ...
[ "def", "get_uvi", "(", "self", ",", "params_dict", ")", ":", "lat", "=", "str", "(", "params_dict", "[", "'lat'", "]", ")", "lon", "=", "str", "(", "params_dict", "[", "'lon'", "]", ")", "params", "=", "dict", "(", "lat", "=", "lat", ",", "lon", ...
32.235294
15.411765
def mount_point(self): """ ostree checkout -- real filesystem """ if self._mount_point is None: self._mount_point = os.path.join(self.tmpdir, "checkout") os.makedirs(self._mount_point) self._checkout() return self._mount_point
[ "def", "mount_point", "(", "self", ")", ":", "if", "self", ".", "_mount_point", "is", "None", ":", "self", ".", "_mount_point", "=", "os", ".", "path", ".", "join", "(", "self", ".", "tmpdir", ",", "\"checkout\"", ")", "os", ".", "makedirs", "(", "se...
40
10.285714
def write(self, data): """ write the data to the serial port return: None """ if sys.version_info[0] < 3: self.arduino.write(data) else: self.arduino.write(bytes([ord(data)]))
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "self", ".", "arduino", ".", "write", "(", "data", ")", "else", ":", "self", ".", "arduino", ".", "write", "(", "bytes", "(", "[...
27.444444
9.444444
def save_example_fit(fit): """ Save fit result to a json file and a plot to an svg file. """ json_directory = os.path.join('examples', 'json') plot_directory = os.path.join('examples', 'plots') if not os.path.isdir(json_directory): os.makedirs(json_directory) if not os.path.isdir(plot_direct...
[ "def", "save_example_fit", "(", "fit", ")", ":", "json_directory", "=", "os", ".", "path", ".", "join", "(", "'examples'", ",", "'json'", ")", "plot_directory", "=", "os", ".", "path", ".", "join", "(", "'examples'", ",", "'plots'", ")", "if", "not", "...
37.714286
22.142857
def backoff_generator(self): """Generate a series of integers used for the length of the sleep between retries. It produces after exhausting the list, it repeats the last value from the list forever. This generator will never raise the StopIteration exception.""" for x in self....
[ "def", "backoff_generator", "(", "self", ")", ":", "for", "x", "in", "self", ".", "config", ".", "backoff_delays", ":", "yield", "x", "while", "True", ":", "yield", "self", ".", "config", ".", "backoff_delays", "[", "-", "1", "]" ]
47
15.444444
def saveToFile(self,imageObjectList): """ Saves the static mask to a file it uses the signatures associated with each mask to contruct the filename for the output mask image. """ virtual = imageObjectList[0].inmemory for key in self.masklist.keys(): #...
[ "def", "saveToFile", "(", "self", ",", "imageObjectList", ")", ":", "virtual", "=", "imageObjectList", "[", "0", "]", ".", "inmemory", "for", "key", "in", "self", ".", "masklist", ".", "keys", "(", ")", ":", "#check to see if the file already exists on disk", ...
38.857143
17
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: PublishedTrackContext for this PublishedTrackInstance :rtype: twilio.rest.video.v1.room.room_part...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "PublishedTrackContext", "(", "self", ".", "_version", ",", "room_sid", "=", "self", ".", "_solution", "[", "'room_sid'", "]", ",", ...
43.8125
22.3125
def from_text(text): """Strip `text` (unicode/str) from all non-digit chars and return a new Phone object with the number from text. >>> phone = Phone.from_text('(888) 777-666') >>> phone.number 888777666 """ number = int(filter(unicode....
[ "def", "from_text", "(", "text", ")", ":", "number", "=", "int", "(", "filter", "(", "unicode", ".", "isdigit", ",", "unicode", "(", "text", ")", ")", ")", "return", "Phone", "(", "number", "=", "number", ")" ]
33.727273
15
def access(self, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None): """ Fetches the **protected resource** of an authenticated **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). ...
[ "def", "access", "(", "self", ",", "url", ",", "params", "=", "None", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "max_redirects", "=", "5", ",", "content_parser", "=", "None", ")", ":", "if", "not", "self...
29.35
21.35
def start(self): ''' Serving loop ''' print('Waiting for a client to connect to url http://%s:%d/' % (self.host, self.port)) self.state = RpcServer._STATE_RUN while self.state == RpcServer._STATE_RUN: self.server.handle_request() self.server.server_clo...
[ "def", "start", "(", "self", ")", ":", "print", "(", "'Waiting for a client to connect to url http://%s:%d/'", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "self", ".", "state", "=", "RpcServer", ".", "_STATE_RUN", "while", "self", ".",...
35.8
17.4
def libvlc_audio_output_device_get(mp): '''Get the current audio output device identifier. This complements L{libvlc_audio_output_device_set}(). @warning: The initial value for the current audio output device identifier may not be set or may be some unknown value. A LibVLC application should compare...
[ "def", "libvlc_audio_output_device_get", "(", "mp", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_audio_output_device_get'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_audio_output_device_get'", ",", "(", "(", "1", ",", ")", ",", ")", "...
63.3
30.7
def detailed_tokens(tokenizer, text): """Format Mecab output into a nice data structure, based on Janome.""" node = tokenizer.parseToNode(text) node = node.next # first node is beginning of sentence and empty, skip it words = [] while node.posid != 0: surface = node.surface base = s...
[ "def", "detailed_tokens", "(", "tokenizer", ",", "text", ")", ":", "node", "=", "tokenizer", ".", "parseToNode", "(", "text", ")", "node", "=", "node", ".", "next", "# first node is beginning of sentence and empty, skip it", "words", "=", "[", "]", "while", "nod...
40.411765
15.470588
def ReadAttachment(self, attachment_link, options=None): """Reads an attachment. :param str attachment_link: The link to the attachment. :param dict options: The request options for the request. :return: The read Attachment. :rtype: ...
[ "def", "ReadAttachment", "(", "self", ",", "attachment_link", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "path", "=", "base", ".", "GetPathFromLink", "(", "attachment_link", ")", "attachment_id", "=...
28.25
16.25
def _get_path(self, filename): """Creates the cache directory if it doesn't already exist. Returns the full path to the specified file inside the cache directory.""" tempdir = settings._temp_directory if not os.path.exists(tempdir): os.makedirs(tempdir) return os.path...
[ "def", "_get_path", "(", "self", ",", "filename", ")", ":", "tempdir", "=", "settings", ".", "_temp_directory", "if", "not", "os", ".", "path", ".", "exists", "(", "tempdir", ")", ":", "os", ".", "makedirs", "(", "tempdir", ")", "return", "os", ".", ...
48.285714
3.857143
def get( self: 'Option[Mapping[K,V]]', key: K, default=None ) -> 'Option[V]': """ Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The ...
[ "def", "get", "(", "self", ":", "'Option[Mapping[K,V]]'", ",", "key", ":", "K", ",", "default", "=", "None", ")", "->", "'Option[V]'", ":", "if", "self", ".", "_is_some", ":", "return", "self", ".", "_type", ".", "maybe", "(", "self", ".", "_val", "....
29.28125
16.53125
def polylinear_gradient(colors, n): """ Interpolates the color gradients between a list of hex colors. """ n_out = int(float(n) / (len(colors)-1)) gradient = linear_gradient(colors[0], colors[1], n_out) if len(colors) == len(gradient): return gradient for col in range(1, len(colors...
[ "def", "polylinear_gradient", "(", "colors", ",", "n", ")", ":", "n_out", "=", "int", "(", "float", "(", "n", ")", "/", "(", "len", "(", "colors", ")", "-", "1", ")", ")", "gradient", "=", "linear_gradient", "(", "colors", "[", "0", "]", ",", "co...
34.714286
17.571429
def remove_seat(self, seat_id): """ Remove a seat from your team :param seat_id: Id of user """ url = self.TEAM_SEATS_ID_URL % seat_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
[ "def", "remove_seat", "(", "self", ",", "seat_id", ")", ":", "url", "=", "self", ".", "TEAM_SEATS_ID_URL", "%", "seat_id", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", ...
25.166667
13.166667
def CMOVP(cpu, dest, src): """ Conditional move - Parity/parity even. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. ...
[ "def", "CMOVP", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "PF", ",", "src", ".", "read", "(", ")", ",", "dest", ".", "read", "(", ")", ")", ...
36.461538
18.769231
def socket_parse(self, astr_destination): ''' Examines <astr_destination> and if of form <str1>:<str2> assumes that <str1> is a host to send datagram comms to over port <str2>. Returns True or False. ''' t_socketInfo = astr_destination.partition(':') if ...
[ "def", "socket_parse", "(", "self", ",", "astr_destination", ")", ":", "t_socketInfo", "=", "astr_destination", ".", "partition", "(", "':'", ")", "if", "len", "(", "t_socketInfo", "[", "1", "]", ")", ":", "self", ".", "_b_isSocket", "=", "True", "self", ...
34.4375
17.8125
def get_missing(self, verify_file): """ Use a verification configuration which has a list of required options and their respective types. This information is used to identify missing and incompatible options in the loaded configuration. :param str verify_file: The file to load for verification data. :retur...
[ "def", "get_missing", "(", "self", ",", "verify_file", ")", ":", "vconf", "=", "Configuration", "(", "verify_file", ")", "missing", "=", "{", "}", "for", "setting", ",", "setting_type", "in", "vconf", ".", "get", "(", "'settings'", ")", ".", "items", "("...
40.9
17.6
def _op(self, line, op=None, offset=0): """ Returns the gate name for placing a gate on a line. :param int line: Line number. :param int op: Operation number or, by default, uses the current op count. :return: Gate name. :rtype: string """ if op is None: ...
[ "def", "_op", "(", "self", ",", "line", ",", "op", "=", "None", ",", "offset", "=", "0", ")", ":", "if", "op", "is", "None", ":", "op", "=", "self", ".", "op_count", "[", "line", "]", "return", "\"line{}_gate{}\"", ".", "format", "(", "line", ","...
33.5
14.5
def _chunk_filter(self, extensions): """ Create a filter from the extensions and ignore files """ if isinstance(extensions, six.string_types): extensions = extensions.split() def _filter(chunk): """ Exclusion filter """ name = chunk['name'] if ext...
[ "def", "_chunk_filter", "(", "self", ",", "extensions", ")", ":", "if", "isinstance", "(", "extensions", ",", "six", ".", "string_types", ")", ":", "extensions", "=", "extensions", ".", "split", "(", ")", "def", "_filter", "(", "chunk", ")", ":", "\"\"\"...
38.105263
10.210526
def _update(self): """ Update vertex buffers & texture """ if self._vertices_buffer is not None: self._vertices_buffer.delete() self._vertices_buffer = VertexBuffer(self._vertices_list.data) if self.itype is not None: if self._indices_buffer is not None: ...
[ "def", "_update", "(", "self", ")", ":", "if", "self", ".", "_vertices_buffer", "is", "not", "None", ":", "self", ".", "_vertices_buffer", ".", "delete", "(", ")", "self", ".", "_vertices_buffer", "=", "VertexBuffer", "(", "self", ".", "_vertices_list", "....
41.969697
18.909091
def add(name, beacon_data, **kwargs): ''' Add a beacon on the minion Args: name (str): Name of the beacon to configure beacon_data (dict): Dictionary or list containing configuration for beacon. Returns: dict: Boolean and status message on success or f...
[ "def", "add", "(", "name", ",", "beacon_data", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'comment'", ":", "'Failed to add beacon {0}.'", ".", "format", "(", "name", ")", ",", "'result'", ":", "False", "}", "if", "name", "in", "list_", "(", ...
38.683168
23.831683
def setval(key, val, dict_=None, delim=defaults.DEFAULT_DELIM): ''' Set a value under the dictionary hierarchy identified under the key. The target 'foo/bar/baz' returns the dictionary hierarchy {'foo': {'bar': {'baz': {}}}}. .. note:: Currently this doesn't work with integers, i.e. ...
[ "def", "setval", "(", "key", ",", "val", ",", "dict_", "=", "None", ",", "delim", "=", "defaults", ".", "DEFAULT_DELIM", ")", ":", "if", "not", "dict_", ":", "dict_", "=", "{", "}", "prev_hier", "=", "dict_", "dict_hier", "=", "key", ".", "split", ...
29.807692
17.115385
def __create(self, opcode): """This method returns the appropriate class object corresponding to the passed opcode.""" tftpassert(opcode in self.classes, "Unsupported opcode: %d" % opcode) packet = self.classes[opcode]() return packet
[ "def", "__create", "(", "self", ",", "opcode", ")", ":", "tftpassert", "(", "opcode", "in", "self", ".", "classes", ",", "\"Unsupported opcode: %d\"", "%", "opcode", ")", "packet", "=", "self", ".", "classes", "[", "opcode", "]", "(", ")", "return", "pac...
31.888889
14.222222
def validate(self, body_to_validate): """ Validates if the body (dictionary) follows specification that the validator was instantiated with. Raises ValidationSpecificationException or ValidationFieldException in case of problems with specification or the body not conforming to th...
[ "def", "validate", "(", "self", ",", "body_to_validate", ")", ":", "try", ":", "for", "validation_spec", "in", "self", ".", "_validation_specs", ":", "self", ".", "_validate_field", "(", "validation_spec", "=", "validation_spec", ",", "dictionary_to_validate", "="...
56.128205
23.051282
def _sample_mvn(mean, cov, cov_structure=None, num_samples=None): """ Returns a sample from a D-dimensional Multivariate Normal distribution :param mean: [..., N, D] :param cov: [..., N, D] or [..., N, D, D] :param cov_structure: "diag" or "full" - "diag": cov holds the diagonal elements of the ...
[ "def", "_sample_mvn", "(", "mean", ",", "cov", ",", "cov_structure", "=", "None", ",", "num_samples", "=", "None", ")", ":", "mean_shape", "=", "tf", ".", "shape", "(", "mean", ")", "S", "=", "num_samples", "if", "num_samples", "is", "not", "None", "el...
49.2
22.75