text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def handle_page_location_changed(self, timeout=None): ''' If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location. ''' # In general, this is often called after other mecha...
[ "def", "handle_page_location_changed", "(", "self", ",", "timeout", "=", "None", ")", ":", "# In general, this is often called after other mechanisms have confirmed", "# that the tab has already navigated. As such, we want to not wait a while", "# to discover something went wrong, so use a t...
44.769231
33.74359
def get(self, sid): """ Constructs a FactorContext :param sid: A string that uniquely identifies this Factor. :returns: twilio.rest.authy.v1.service.entity.factor.FactorContext :rtype: twilio.rest.authy.v1.service.entity.factor.FactorContext """ return FactorCon...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "FactorContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "identity", "=", "self", ".", "_solution", "[", "'identity'", "]"...
31.533333
19.8
def lineReceived(self, line): """ A line was received. """ if line.startswith(b"#"): # ignore it return if line.startswith(b"OK"): # if no command issued, then just 'ready' if self._ready: self._dq.pop(0).callback(self._currentR...
[ "def", "lineReceived", "(", "self", ",", "line", ")", ":", "if", "line", ".", "startswith", "(", "b\"#\"", ")", ":", "# ignore it", "return", "if", "line", ".", "startswith", "(", "b\"OK\"", ")", ":", "# if no command issued, then just 'ready'", "if", "self", ...
38.333333
13.111111
def verification_list(self, limit=10): """ Get list of verifications. Uses GET to /verifications interface. :Returns: (list) Verification list as specified `here <https://cloud.knuverse.com/docs/api/#api-Verifications-Get_verification_list>`_. """ # TODO add arguments for pagi...
[ "def", "verification_list", "(", "self", ",", "limit", "=", "10", ")", ":", "# TODO add arguments for paging and stuff", "params", "=", "{", "}", "params", "[", "\"limit\"", "]", "=", "limit", "response", "=", "self", ".", "_get", "(", "url", ".", "verificat...
39.071429
24.928571
def set_data(self, data, addr=0): ''' Sets data for outgoing stream ''' if self._mem_bytes < len(data): raise ValueError('Size of data (%d bytes) is too big for memory (%d bytes)' % (len(data), self._mem_bytes)) self._intf.write(self._conf['base_addr'] + self._spi_mem...
[ "def", "set_data", "(", "self", ",", "data", ",", "addr", "=", "0", ")", ":", "if", "self", ".", "_mem_bytes", "<", "len", "(", "data", ")", ":", "raise", "ValueError", "(", "'Size of data (%d bytes) is too big for memory (%d bytes)'", "%", "(", "len", "(", ...
47.857143
27.571429
def group_update(auth=None, **kwargs): ''' Update a group CLI Example: .. code-block:: bash salt '*' keystoneng.group_update name=group1 description='new description' salt '*' keystoneng.group_create name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e new_name=newgroupname ...
[ "def", "group_update", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "if", "'new_name'", "in", "kwargs", ":", "kwargs", "...
35
26.882353
def _slice_weights(self, arr, li, lh): """slice fused rnn weights""" args = {} gate_names = self._gate_names directions = self._directions b = len(directions) p = 0 for layer in range(self._num_layers): for direction in directions: for...
[ "def", "_slice_weights", "(", "self", ",", "arr", ",", "li", ",", "lh", ")", ":", "args", "=", "{", "}", "gate_names", "=", "self", ".", "_gate_names", "directions", "=", "self", ".", "_directions", "b", "=", "len", "(", "directions", ")", "p", "=", ...
40.342105
16.210526
def run(name, chip_bam, input_bam, genome_build, out_dir, method, resources, data): """ Run macs2 for chip and input samples avoiding errors due to samples. """ # output file name need to have the caller name config = dd.get_config(data) out_file = os.path.join(out_dir, name + "_peaks_macs2....
[ "def", "run", "(", "name", ",", "chip_bam", ",", "input_bam", ",", "genome_build", ",", "out_dir", ",", "method", ",", "resources", ",", "data", ")", ":", "# output file name need to have the caller name", "config", "=", "dd", ".", "get_config", "(", "data", "...
52.096774
20.032258
def get_num_features(estimator): """ Return size of a feature vector estimator expects as an input. """ if hasattr(estimator, 'coef_'): # linear models if len(estimator.coef_.shape) == 0: return 1 return estimator.coef_.shape[-1] elif hasattr(estimator, 'feature_importances_'): ...
[ "def", "get_num_features", "(", "estimator", ")", ":", "if", "hasattr", "(", "estimator", ",", "'coef_'", ")", ":", "# linear models", "if", "len", "(", "estimator", ".", "coef_", ".", "shape", ")", "==", "0", ":", "return", "1", "return", "estimator", "...
46.111111
14.555556
def run(self, request, tempdir, opts): """ Constructs a command to run a cwl/json from requests and opts, runs it, and deposits the outputs in outdir. Runner: opts.getopt("runner", default="cwl-runner") CWL (url): request["workflow_url"] == a url to a cwl file ...
[ "def", "run", "(", "self", ",", "request", ",", "tempdir", ",", "opts", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "workdir", ",", "\"request.json\"", ")", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dum...
41.278689
24.360656
def edit(directory=None, revision='current'): """Edit current revision.""" if alembic_version >= (0, 8, 0): config = current_app.extensions['migrate'].migrate.get_config( directory) command.edit(config, revision) else: raise RuntimeError('Alembic 0.8.0 or greater is requi...
[ "def", "edit", "(", "directory", "=", "None", ",", "revision", "=", "'current'", ")", ":", "if", "alembic_version", ">=", "(", "0", ",", "8", ",", "0", ")", ":", "config", "=", "current_app", ".", "extensions", "[", "'migrate'", "]", ".", "migrate", ...
39.75
14.5
def _render_extended_error_message_list(self, extended_error): """Parse the ExtendedError object and retruns the message. Build a list of decoded messages from the extended_error using the message registries. An ExtendedError JSON object is a response from the with its own schema. This...
[ "def", "_render_extended_error_message_list", "(", "self", ",", "extended_error", ")", ":", "messages", "=", "[", "]", "if", "isinstance", "(", "extended_error", ",", "dict", ")", ":", "if", "(", "'Type'", "in", "extended_error", "and", "extended_error", "[", ...
47.227273
21.613636
def unpack_sver_response_version(packet): """For internal use. Unpack the version-related parts of an sver (aka CMD_VERSION) response. Parameters ---------- packet : :py:class:`~rig.machine_control.packets.SCPPacket` The packet recieved in response to the version command. Returns -...
[ "def", "unpack_sver_response_version", "(", "packet", ")", ":", "software_name", "=", "packet", ".", "data", ".", "decode", "(", "\"utf-8\"", ")", "legacy_version_field", "=", "packet", ".", "arg2", ">>", "16", "if", "legacy_version_field", "!=", "0xFFFF", ":", ...
35.27907
21.139535
def _update_capacity(self, data): """ Update the consumed capacity metrics """ if 'ConsumedCapacity' in data: # This is all for backwards compatibility consumed = data['ConsumedCapacity'] if not isinstance(consumed, list): consumed = [consumed] ...
[ "def", "_update_capacity", "(", "self", ",", "data", ")", ":", "if", "'ConsumedCapacity'", "in", "data", ":", "# This is all for backwards compatibility", "consumed", "=", "data", "[", "'ConsumedCapacity'", "]", "if", "not", "isinstance", "(", "consumed", ",", "li...
52.947368
14.421053
def mkrngs(self): """ Transform boolean arrays into list of limit pairs. Gets Time limits of signal/background boolean arrays and stores them as sigrng and bkgrng arrays. These arrays can be saved by 'save_ranges' in the analyse object. """ bbool = bool_2_indices...
[ "def", "mkrngs", "(", "self", ")", ":", "bbool", "=", "bool_2_indices", "(", "self", ".", "bkg", ")", "if", "bbool", "is", "not", "None", ":", "self", ".", "bkgrng", "=", "self", ".", "Time", "[", "bbool", "]", "else", ":", "self", ".", "bkgrng", ...
31.911765
15.029412
def to_struct(self, value): """Cast `date` object to string.""" if self.str_format: return value.strftime(self.str_format) return value.strftime(self.default_format)
[ "def", "to_struct", "(", "self", ",", "value", ")", ":", "if", "self", ".", "str_format", ":", "return", "value", ".", "strftime", "(", "self", ".", "str_format", ")", "return", "value", ".", "strftime", "(", "self", ".", "default_format", ")" ]
39.4
9.2
def rotate_quat(attitude, roll, pitch, yaw): ''' Returns rotated quaternion :param attitude: quaternion [w, x, y , z] :param roll: rotation in rad :param pitch: rotation in rad :param yaw: rotation in rad :returns: quaternion [w, x, y , z] ''' quat = Quaternion(attitude) rotation = Quaternion([roll,...
[ "def", "rotate_quat", "(", "attitude", ",", "roll", ",", "pitch", ",", "yaw", ")", ":", "quat", "=", "Quaternion", "(", "attitude", ")", "rotation", "=", "Quaternion", "(", "[", "roll", ",", "pitch", ",", "yaw", "]", ")", "res", "=", "rotation", "*",...
25.714286
15.714286
def _axis(self, axis): """ Return the corresponding labels taking into account the axis. The axis could be horizontal (0) or vertical (1). """ return self.df.columns if axis == 0 else self.df.index
[ "def", "_axis", "(", "self", ",", "axis", ")", ":", "return", "self", ".", "df", ".", "columns", "if", "axis", "==", "0", "else", "self", ".", "df", ".", "index" ]
34
18
def is_identity(self): """If `self` is I, returns True, otherwise False.""" if not self.terms: return True return len(self.terms) == 1 and not self.terms[0].ops and self.terms[0].coeff == 1.0
[ "def", "is_identity", "(", "self", ")", ":", "if", "not", "self", ".", "terms", ":", "return", "True", "return", "len", "(", "self", ".", "terms", ")", "==", "1", "and", "not", "self", ".", "terms", "[", "0", "]", ".", "ops", "and", "self", ".", ...
44.6
20.2
def json_qs_parser(body): """ Parses response body from JSON, XML or query string. :param body: string :returns: :class:`dict`, :class:`list` if input is JSON or query string, :class:`xml.etree.ElementTree.Element` if XML. """ try: # Try JSON first. ret...
[ "def", "json_qs_parser", "(", "body", ")", ":", "try", ":", "# Try JSON first.", "return", "json", ".", "loads", "(", "body", ")", "except", "(", "OverflowError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "try", ":", "# Then XML.", "return", "...
22.846154
21.692308
def is_connected(H, source_node, target_node): """Checks if a target node is connected to a source node. That is, this method determines if a target node can be visited from the source node in the sense of the 'Visit' algorithm. Refer to 'visit's documentation for more details. :param H: the hyper...
[ "def", "is_connected", "(", "H", ",", "source_node", ",", "target_node", ")", ":", "visited_nodes", ",", "Pv", ",", "Pe", "=", "visit", "(", "H", ",", "source_node", ")", "return", "target_node", "in", "visited_nodes" ]
42.133333
18.466667
def _read_from_folder(self, dirname): """ Internal folder reader. :type dirname: str :param dirname: Folder to read from. """ templates = _par_read(dirname=dirname, compressed=False) t_files = glob.glob(dirname + os.sep + '*.ms') tribe_cat_file = glob.glo...
[ "def", "_read_from_folder", "(", "self", ",", "dirname", ")", ":", "templates", "=", "_par_read", "(", "dirname", "=", "dirname", ",", "compressed", "=", "False", ")", "t_files", "=", "glob", ".", "glob", "(", "dirname", "+", "os", ".", "sep", "+", "'*...
41.5
14.264706
def get_system_data() -> typing.Union[None, dict]: """ Returns information about the system in which Cauldron is running. If the information cannot be found, None is returned instead. :return: Dictionary containing information about the Cauldron system, whic includes: * name ...
[ "def", "get_system_data", "(", ")", "->", "typing", ".", "Union", "[", "None", ",", "dict", "]", ":", "site_packages", "=", "get_site_packages", "(", ")", "path_prefixes", "=", "[", "(", "'[SP]'", ",", "p", ")", "for", "p", "in", "site_packages", "]", ...
29.242424
21.787879
def copy(self, h5file=None): """Create a copy of the current instance This is done by recursively copying the underlying hdf5 data. Parameters ---------- h5file: str, h5py.File, h5py.Group, or None see `QPImage.__init__` """ h5 = copyh5(self.h5, h5fi...
[ "def", "copy", "(", "self", ",", "h5file", "=", "None", ")", ":", "h5", "=", "copyh5", "(", "self", ".", "h5", ",", "h5file", ")", "return", "QPImage", "(", "h5file", "=", "h5", ",", "h5dtype", "=", "self", ".", "h5dtype", ")" ]
30.666667
16.75
def CA_code_header(fname_out, Nca): """ Write 1023 bit CA (Gold) Code Header Files Mark Wickert February 2015 """ dir_path = os.path.dirname(os.path.realpath(__file__)) ca = loadtxt(dir_path + '/ca1thru37.txt', dtype=int16, usecols=(Nca - 1,), unpack=True) M = 1023 # code period ...
[ "def", "CA_code_header", "(", "fname_out", ",", "Nca", ")", ":", "dir_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "ca", "=", "loadtxt", "(", "dir_path", "+", "'/ca1thru37.txt'", ","...
34.414634
16.365854
def css(self, path): """ Link/embed CSS file. """ if self.settings.embed_content: content = codecs.open(path, 'r', encoding='utf8').read() tag = Style(content, type="text/css") else: tag = Link(href=path, rel="stylesheet", type_="text/css") ...
[ "def", "css", "(", "self", ",", "path", ")", ":", "if", "self", ".", "settings", ".", "embed_content", ":", "content", "=", "codecs", ".", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "'utf8'", ")", ".", "read", "(", ")", "tag", "=", "S...
33.7
13.7
def accepts_valid_urls(func): """Return a wrapper that runs given method only for valid URLs. :param func: a method to be wrapped :returns: a wrapper that adds argument validation """ @functools.wraps(func) def wrapper(obj, urls, *args, **kwargs): """Run the function and return a value ...
[ "def", "accepts_valid_urls", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "obj", ",", "urls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Run the function and return a value for valid URLs.\n\n...
39.363636
13.227273
def _generateEncoderStringsV2(includedFields, options): """ Generate and return the following encoder related substitution variables: encoderSpecsStr: For the base description file, this string defines the default encoding dicts for each encoder. For example: __gym_encoder = { 'fieldname': 'gym...
[ "def", "_generateEncoderStringsV2", "(", "includedFields", ",", "options", ")", ":", "width", "=", "21", "encoderDictsList", "=", "[", "]", "# If this is a NontemporalClassification experiment, then the", "# the \"predicted\" field (the classification value) should be marked to ONLY...
34.252294
23.206422
def run_steps(args: argparse.Namespace): """Run all steps required to complete task. Called directly from main.""" logging.basicConfig(level=logging.INFO, format="sockeye.autopilot: %(message)s") # (1) Establish task logging.info("=== Start Autopilot ===") # Listed task if args.task: ...
[ "def", "run_steps", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "\"sockeye.autopilot: %(message)s\"", ")", "# (1) Establish task", "logging", ".", "info",...
49.871508
22.625698
def advance(self, blocksize): """ Add blocksize seconds more to the buffer, push blocksize seconds from the beginning. Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel Returns ------- status: bool...
[ "def", "advance", "(", "self", ",", "blocksize", ")", ":", "try", ":", "if", "self", ".", "increment_update_cache", ":", "self", ".", "update_cache_by_increment", "(", "blocksize", ")", "ts", "=", "DataBuffer", ".", "advance", "(", "self", ",", "blocksize", ...
31.173913
16.782609
def clinvar_submission_lines(submission_objs, submission_header): """Create the lines to include in a Clinvar submission csv file from a list of submission objects and a custom document header Args: submission_objs(list): a list of objects (variants or casedata) to include in a csv file ...
[ "def", "clinvar_submission_lines", "(", "submission_objs", ",", "submission_header", ")", ":", "submission_lines", "=", "[", "]", "for", "submission_obj", "in", "submission_objs", ":", "# Loop over the submission objects. Each of these is a line", "csv_line", "=", "[", "]",...
54.5
35.636364
def update_assessment_offered(self, assessment_offered_form): """Updates an existing assessment offered. arg: assessment_offered_form (osid.assessment.AssessmentOfferedForm): the form containing the elements to be updated raise: IllegalState - ``assessment_of...
[ "def", "update_assessment_offered", "(", "self", ",", "assessment_offered_form", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.update_resource_template", "collection", "=", "JSONClientValidated", "(", "'assessment'", ",", "collection", "=", "'...
55.166667
26.190476
def intersection(self,other): """ Return a new Interval with the intersection of the two intervals, i.e. all elements that are in both self and other. :param Interval other: Interval to intersect with :rtype: Interval """ if self.bounds[0] < other.bounds[0]: ...
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "if", "self", ".", "bounds", "[", "0", "]", "<", "other", ".", "bounds", "[", "0", "]", ":", "i1", ",", "i2", "=", "self", ",", "other", "else", ":", "i2", ",", "i1", "=", "self", ",...
29.233333
15.033333
def standard_kinetics(target, quantity, prefactor, exponent): r""" """ X = target[quantity] A = target[prefactor] b = target[exponent] r = A*(X**b) S1 = A*b*(X**(b - 1)) S2 = A*(1 - b)*(X**b) values = {'S1': S1, 'S2': S2, 'rate': r} return values
[ "def", "standard_kinetics", "(", "target", ",", "quantity", ",", "prefactor", ",", "exponent", ")", ":", "X", "=", "target", "[", "quantity", "]", "A", "=", "target", "[", "prefactor", "]", "b", "=", "target", "[", "exponent", "]", "r", "=", "A", "*"...
21.230769
17.615385
def add_event_detect(channel, trigger, callback=None, bouncetime=None): """ This function is designed to be used in a loop with other things, but unlike polling it is not going to miss the change in state of an input while the CPU is busy working on other things. This could be useful when using some...
[ "def", "add_event_detect", "(", "channel", ",", "trigger", ",", "callback", "=", "None", ",", "bouncetime", "=", "None", ")", ":", "_check_configured", "(", "channel", ",", "direction", "=", "IN", ")", "if", "bouncetime", "is", "not", "None", ":", "if", ...
45.166667
25.966667
def reject_sender(self, link_handle, pn_condition=None): """Rejects the SenderLink, and destroys the handle.""" link = self._sender_links.get(link_handle) if not link: raise Exception("Invalid link_handle: %s" % link_handle) link.reject(pn_condition) # note: normally,...
[ "def", "reject_sender", "(", "self", ",", "link_handle", ",", "pn_condition", "=", "None", ")", ":", "link", "=", "self", ".", "_sender_links", ".", "get", "(", "link_handle", ")", "if", "not", "link", ":", "raise", "Exception", "(", "\"Invalid link_handle: ...
51.1
17.9
def tracelines(self, xstart, ystart, zstart, hstepmax, vstepfrac=0.2, tmax=1e12, nstepmax=100, silent='.', color=None, orientation='hor', win=[-1e30, 1e30, -1e30, 1e30], newfig=False, figsize=None): """Draw trace lines """ if color is None: c = p...
[ "def", "tracelines", "(", "self", ",", "xstart", ",", "ystart", ",", "zstart", ",", "hstepmax", ",", "vstepfrac", "=", "0.2", ",", "tmax", "=", "1e12", ",", "nstepmax", "=", "100", ",", "silent", "=", "'.'", ",", "color", "=", "None", ",", "orientati...
49.148936
20.93617
def os_release(package, base='essex', reset_cache=False): ''' Returns OpenStack release codename from a cached global. If reset_cache then unset the cached os_release version and return the freshly determined version. If the codename can not be determined from either an installed package or th...
[ "def", "os_release", "(", "package", ",", "base", "=", "'essex'", ",", "reset_cache", "=", "False", ")", ":", "global", "_os_rel", "if", "reset_cache", ":", "reset_os_release", "(", ")", "if", "_os_rel", ":", "return", "_os_rel", "_os_rel", "=", "(", "get_...
32.333333
25.952381
def expand_dataset(X, y_proba, factor=10, random_state=None, extra_arrays=None): """ Convert a dataset with float multiclass probabilities to a dataset with indicator probabilities by duplicating X rows and sampling true labels. """ rng = check_random_state(random_state) extra_arrays = extra...
[ "def", "expand_dataset", "(", "X", ",", "y_proba", ",", "factor", "=", "10", ",", "random_state", "=", "None", ",", "extra_arrays", "=", "None", ")", ":", "rng", "=", "check_random_state", "(", "random_state", ")", "extra_arrays", "=", "extra_arrays", "or", ...
39.533333
13.666667
def receive(self, x, mesh_axis, source_pcoord): """Collective receive in groups. Each group contains the processors that differ only in mesh_axis. ```python group_size = self.shape[mesh_axis].size ``` Args: x: a LaidOutTensor mesh_axis: an integer source_pcoord: a list of op...
[ "def", "receive", "(", "self", ",", "x", ",", "mesh_axis", ",", "source_pcoord", ")", ":", "x", "=", "x", ".", "to_laid_out_tensor", "(", ")", "shape", "=", "x", ".", "tensor_list", "[", "0", "]", ".", "shape", "dtype", "=", "x", ".", "tensor_list", ...
34.583333
20.666667
def evaluate(self, s): r"""Evaluate :math:`B(s)` along the curve. This method acts as a (partial) inverse to :meth:`locate`. See :meth:`evaluate_multi` for more details. .. image:: ../../images/curve_evaluate.png :align: center .. doctest:: curve-eval :o...
[ "def", "evaluate", "(", "self", ",", "s", ")", ":", "return", "_curve_helpers", ".", "evaluate_multi", "(", "self", ".", "_nodes", ",", "np", ".", "asfortranarray", "(", "[", "s", "]", ")", ")" ]
27.891892
18.405405
def difference(self, other, joinBy=None, exact=False): """ *Wrapper of* ``DIFFERENCE`` DIFFERENCE is a binary, non-symmetric operator that produces one sample in the result for each sample of the first operand, by keeping the same metadata of the first operand sample and only th...
[ "def", "difference", "(", "self", ",", "other", ",", "joinBy", "=", "None", ",", "exact", "=", "False", ")", ":", "if", "isinstance", "(", "other", ",", "GMQLDataset", ")", ":", "other_idx", "=", "other", ".", "__index", "else", ":", "raise", "TypeErro...
47.350877
28.473684
def getCharAtIndex(self, index): ''' Used for searching, this function masks the complexity behind retrieving a specific character at a specific index in our compressed BWT. @param index - the index to retrieve the character from @param return - return the character in our BWT th...
[ "def", "getCharAtIndex", "(", "self", ",", "index", ")", ":", "#get the bin we should start from", "binID", "=", "index", ">>", "self", ".", "bitPower", "bwtIndex", "=", "self", ".", "refFM", "[", "binID", "]", "#these are the values that indicate how far in we really...
43.820513
22.487179
def line_alignment(self): """Alignment, one of `inner`, `outer`, `center`.""" key = self._data.get(b'strokeStyleLineAlignment').enum return self.STROKE_STYLE_LINE_ALIGNMENTS.get(key, str(key))
[ "def", "line_alignment", "(", "self", ")", ":", "key", "=", "self", ".", "_data", ".", "get", "(", "b'strokeStyleLineAlignment'", ")", ".", "enum", "return", "self", ".", "STROKE_STYLE_LINE_ALIGNMENTS", ".", "get", "(", "key", ",", "str", "(", "key", ")", ...
53.25
16
def new_instance(type, frum, schema=None): """ Factory! """ if not type2container: _delayed_imports() if isinstance(frum, Container): return frum elif isinstance(frum, _Cube): return frum elif isinstance(frum, _Query): ...
[ "def", "new_instance", "(", "type", ",", "frum", ",", "schema", "=", "None", ")", ":", "if", "not", "type2container", ":", "_delayed_imports", "(", ")", "if", "isinstance", "(", "frum", ",", "Container", ")", ":", "return", "frum", "elif", "isinstance", ...
38.219512
18.073171
def _get_raw(source, bitarray): ''' Get raw data as integer, based on offset and size ''' offset = int(source['offset']) size = int(source['size']) return int(''.join(['1' if digit else '0' for digit in bitarray[offset:offset + size]]), 2)
[ "def", "_get_raw", "(", "source", ",", "bitarray", ")", ":", "offset", "=", "int", "(", "source", "[", "'offset'", "]", ")", "size", "=", "int", "(", "source", "[", "'size'", "]", ")", "return", "int", "(", "''", ".", "join", "(", "[", "'1'", "if...
53.4
20.2
def parse_paragraph(self, markup): """ Creates a list from lines of text in a paragraph. Each line of text is a new item in the list, except lists and preformatted chunks (<li> and <pre>), these are kept together as a single chunk. Lists are formatted u...
[ "def", "parse_paragraph", "(", "self", ",", "markup", ")", ":", "s", "=", "self", ".", "plain", "(", "markup", ")", "# Add an extra linebreak between the last list item", "# and the normal line following after it, so they don't stick together, e.g.", "# **[[Alin Magic]], magic us...
38.5625
17.645833
def extractInputForTP(self, tm): """ Extract inputs for TP from the state of temporal memory three information are extracted 1. correctly predicted cells 2. all active cells 3. bursting cells (unpredicted input) """ # bursting cells in layer 4 burstingColumns = tm.activeState["t"].s...
[ "def", "extractInputForTP", "(", "self", ",", "tm", ")", ":", "# bursting cells in layer 4", "burstingColumns", "=", "tm", ".", "activeState", "[", "\"t\"", "]", ".", "sum", "(", "axis", "=", "1", ")", "burstingColumns", "[", "burstingColumns", "<", "tm", "....
41.296296
19.222222
def to_output(self, value): """Convert value to process output format.""" return {self.name: [self.inner.to_output(v)[self.name] for v in value]}
[ "def", "to_output", "(", "self", ",", "value", ")", ":", "return", "{", "self", ".", "name", ":", "[", "self", ".", "inner", ".", "to_output", "(", "v", ")", "[", "self", ".", "name", "]", "for", "v", "in", "value", "]", "}" ]
53
17.333333
def nma_attribute(self, stmt, p_elem, pset=None): """Map `stmt` to a NETMOD-specific attribute. The name of the attribute is the same as the 'keyword' of `stmt`. """ att = "nma:" + stmt.keyword if att not in p_elem.attr: p_elem.attr[att] = stmt.arg
[ "def", "nma_attribute", "(", "self", ",", "stmt", ",", "p_elem", ",", "pset", "=", "None", ")", ":", "att", "=", "\"nma:\"", "+", "stmt", ".", "keyword", "if", "att", "not", "in", "p_elem", ".", "attr", ":", "p_elem", ".", "attr", "[", "att", "]", ...
33.444444
12.333333
def classifyParameters(self): """Return (arguments, options, outputs) tuple. Together, the three lists contain all parameters (recursively fetched from all parameter groups), classified into optional parameters, required ones (with an index), and simple output parameters (that w...
[ "def", "classifyParameters", "(", "self", ")", ":", "arguments", "=", "[", "]", "options", "=", "[", "]", "outputs", "=", "[", "]", "for", "parameter", "in", "self", ".", "parameters", "(", ")", ":", "if", "parameter", ".", "channel", "==", "'output'",...
51.615385
20.423077
def fix(self, param): """ Disable parameter optimization. Parameters ---------- param : str Possible values are ``"delta"``, ``"beta"``, and ``"scale"``. """ if param == "delta": super()._fix("logistic") else: self._fix...
[ "def", "fix", "(", "self", ",", "param", ")", ":", "if", "param", "==", "\"delta\"", ":", "super", "(", ")", ".", "_fix", "(", "\"logistic\"", ")", "else", ":", "self", ".", "_fix", "[", "param", "]", "=", "True" ]
24.769231
15.846154
def delete_scan(self, scan_id): """ Delete a scan if fully finished. """ if self.get_status(scan_id) == ScanStatus.RUNNING: return False self.scans_table.pop(scan_id) if len(self.scans_table) == 0: del self.data_manager self.data_manager = None ...
[ "def", "delete_scan", "(", "self", ",", "scan_id", ")", ":", "if", "self", ".", "get_status", "(", "scan_id", ")", "==", "ScanStatus", ".", "RUNNING", ":", "return", "False", "self", ".", "scans_table", ".", "pop", "(", "scan_id", ")", "if", "len", "("...
32.4
12
def _pooling_output_shape(input_shape, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: compute the output shape for the pooling layer.""" dims = (1,) + pool_size + (1,) # NHWC spatial_strides = strides or (1,) * len(pool_size) strides = (1,) + spatial_strides + (1,) pad...
[ "def", "_pooling_output_shape", "(", "input_shape", ",", "pool_size", "=", "(", "2", ",", "2", ")", ",", "strides", "=", "None", ",", "padding", "=", "'VALID'", ")", ":", "dims", "=", "(", "1", ",", ")", "+", "pool_size", "+", "(", "1", ",", ")", ...
51.9
14.2
def is_command(self, text: str) -> bool: """ checks for presence of shebang in the first character of the text """ if text[0] in self.shebangs: return True return False
[ "def", "is_command", "(", "self", ",", "text", ":", "str", ")", "->", "bool", ":", "if", "text", "[", "0", "]", "in", "self", ".", "shebangs", ":", "return", "True", "return", "False" ]
26.75
14.25
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 7) self.set_attributes(priority, address, rtr) self.channel = self...
[ "def", "populate", "(", "self", ",", "priority", ",", "address", ",", "rtr", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", "self", ".", "needs_low_priority", "(", "priority", ")", "self", ".", "needs_no_rtr", "(", "rtr", ...
37.117647
7.588235
def search_users(self, username_keyword, limit=10): """ Searches for users whose username matches ``username_keyword``, and returns a list of matched users. :param str username_keyword: keyword to search with :param int limit: maximum number of returned users :return: a ...
[ "def", "search_users", "(", "self", ",", "username_keyword", ",", "limit", "=", "10", ")", ":", "params", "=", "{", "\"q\"", ":", "username_keyword", ",", "\"limit\"", ":", "limit", "}", "response", "=", "self", ".", "get", "(", "\"/users/search\"", ",", ...
48
19.6
def poll(self): """Return pairs of run ids and results of finish event loops. """ ret = self.communicationChannel.receive_finished() self.nruns -= len(ret) return ret
[ "def", "poll", "(", "self", ")", ":", "ret", "=", "self", ".", "communicationChannel", ".", "receive_finished", "(", ")", "self", ".", "nruns", "-=", "len", "(", "ret", ")", "return", "ret" ]
33.5
12.5
def _group_report(self,group,name): """Report summary for a given job group. Return True if the group had any elements.""" if group: print '%s jobs:' % name for job in group: print '%s : %s' % (job.num,job) print return True
[ "def", "_group_report", "(", "self", ",", "group", ",", "name", ")", ":", "if", "group", ":", "print", "'%s jobs:'", "%", "name", "for", "job", "in", "group", ":", "print", "'%s : %s'", "%", "(", "job", ".", "num", ",", "job", ")", "print", "return",...
27.636364
15.545455
def set_detail_level(self, detail_levels): """ Sets the detail levels from the input dictionary in detail_levels. """ if detail_levels is None: return self.detail_levels = detail_levels if 'api' in detail_levels: self.api_detail_level = detail_lev...
[ "def", "set_detail_level", "(", "self", ",", "detail_levels", ")", ":", "if", "detail_levels", "is", "None", ":", "return", "self", ".", "detail_levels", "=", "detail_levels", "if", "'api'", "in", "detail_levels", ":", "self", ".", "api_detail_level", "=", "de...
38.6875
12.3125
def is_match(self, match): """Return whether this model is the same as `match`. Matches if the model is the same as or has the same name as `match`. """ result = False if self == match: result = True elif isinstance(match, str) and fnmatchcase(self.name, matc...
[ "def", "is_match", "(", "self", ",", "match", ")", ":", "result", "=", "False", "if", "self", "==", "match", ":", "result", "=", "True", "elif", "isinstance", "(", "match", ",", "str", ")", "and", "fnmatchcase", "(", "self", ".", "name", ",", "match"...
35.454545
18.272727
def _check_type(name, obj, expected_type): """ Raise a TypeError if object is not of expected type """ if not isinstance(obj, expected_type): raise TypeError( '"%s" must be an a %s' % (name, expected_type.__name__) )
[ "def", "_check_type", "(", "name", ",", "obj", ",", "expected_type", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "expected_type", ")", ":", "raise", "TypeError", "(", "'\"%s\" must be an a %s'", "%", "(", "name", ",", "expected_type", ".", "__name_...
41.166667
13
def fetchJobStoreFiles(jobStore, options): """ Takes a list of file names as glob patterns, searches for these within a given directory, and attempts to take all of the files found and copy them into options.localFilePath. :param jobStore: A fileJobStore object. :param options.fetch: List of fi...
[ "def", "fetchJobStoreFiles", "(", "jobStore", ",", "options", ")", ":", "for", "jobStoreFile", "in", "options", ".", "fetch", ":", "jobStoreHits", "=", "recursiveGlob", "(", "directoryname", "=", "options", ".", "jobStore", ",", "glob_pattern", "=", "jobStoreFil...
49.478261
16.869565
def pmdec(self,*args,**kwargs): """ NAME: pmdec PURPOSE: return proper motion in declination (in mas/yr) INPUT: t - (optional) time at which to get pmdec obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer ...
[ "def", "pmdec", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_check_roSet", "(", "self", ",", "kwargs", ",", "'pmdec'", ")", "_check_voSet", "(", "self", ",", "kwargs", ",", "'pmdec'", ")", "pmrapmdec", "=", "self", ".", "_pmrap...
41.25
18.666667
def _check_min_max_range(self, var, test_ctx): """ Checks that either both valid_min and valid_max exist, or valid_range exists. """ if 'valid_range' in var.ncattrs(): test_ctx.assert_true(var.valid_range.dtype == var.dtype and len(var...
[ "def", "_check_min_max_range", "(", "self", ",", "var", ",", "test_ctx", ")", ":", "if", "'valid_range'", "in", "var", ".", "ncattrs", "(", ")", ":", "test_ctx", ".", "assert_true", "(", "var", ".", "valid_range", ".", "dtype", "==", "var", ".", "dtype",...
56.291667
26.541667
def discard_config(self): """Discard changes (rollback 0).""" self.device.cu.rollback(rb_id=0) if not self.config_lock: self._unlock()
[ "def", "discard_config", "(", "self", ")", ":", "self", ".", "device", ".", "cu", ".", "rollback", "(", "rb_id", "=", "0", ")", "if", "not", "self", ".", "config_lock", ":", "self", ".", "_unlock", "(", ")" ]
33.2
7.4
def update(self): """Update repository from its remote. Calling this method, the repository will be synchronized with the remote repository using 'fetch' command for 'heads' refs. Any commit stored in the local copy will be removed; refs will be overwritten. :raises Rep...
[ "def", "update", "(", "self", ")", ":", "cmd_update", "=", "[", "'git'", ",", "'fetch'", ",", "'origin'", ",", "'+refs/heads/*:refs/heads/*'", ",", "'--prune'", "]", "self", ".", "_exec", "(", "cmd_update", ",", "cwd", "=", "self", ".", "dirpath", ",", "...
40.375
23.5
def update_mapping_meta(self, doc_type, values, indices=None): """ Update mapping meta :param doc_type: a doc type or a list of doctypes :param values: the dict of meta :param indices: a list of indices :return: """ indices = self._validate_indices(indices...
[ "def", "update_mapping_meta", "(", "self", ",", "doc_type", ",", "values", ",", "indices", "=", "None", ")", ":", "indices", "=", "self", ".", "_validate_indices", "(", "indices", ")", "for", "index", "in", "indices", ":", "mapping", "=", "self", ".", "m...
39.235294
12.764706
def check_against_chunks(self, chunks): # type: (Iterator[bytes]) -> None """Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. """ gots = {} for hash_name in iterkeys(self._allowed): try: ...
[ "def", "check_against_chunks", "(", "self", ",", "chunks", ")", ":", "# type: (Iterator[bytes]) -> None", "gots", "=", "{", "}", "for", "hash_name", "in", "iterkeys", "(", "self", ".", "_allowed", ")", ":", "try", ":", "gots", "[", "hash_name", "]", "=", "...
31.782609
16.434783
def get_upload_path(finfo, sample_info, config): """"Dry" update the file: only return the upload path """ try: storage_dir = _get_storage_dir(finfo, config) except ValueError: return None if finfo.get("type") == "directory": return _get_dir_upload_path(finfo, storage_di...
[ "def", "get_upload_path", "(", "finfo", ",", "sample_info", ",", "config", ")", ":", "try", ":", "storage_dir", "=", "_get_storage_dir", "(", "finfo", ",", "config", ")", "except", "ValueError", ":", "return", "None", "if", "finfo", ".", "get", "(", "\"typ...
31.5
15.833333
async def handle_request(self, request: Request) -> Response: """ coroutine: This method is called by Transport implementation to handle the actual request. It returns a webtype.Response object. """ # Get handler try: try: self._set_ctx...
[ "async", "def", "handle_request", "(", "self", ",", "request", ":", "Request", ")", "->", "Response", ":", "# Get handler", "try", ":", "try", ":", "self", ".", "_set_ctx", "(", "request", ")", "handler", "=", "self", ".", "router", ".", "get_handler_for_r...
39.606061
18.954545
def get(self): """API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided". """ p...
[ "def", "get", "(", "self", ")", ":", "parser", "=", "reqparse", ".", "RequestParser", "(", ")", "parser", ".", "add_argument", "(", "'transaction_id'", ",", "type", "=", "str", ",", "required", "=", "True", ")", "args", "=", "parser", ".", "parse_args", ...
33
21.05
def unadvertise_endpoint(self, endpointid): """ Unadvertise a previously-advertised endpointid (string). :param endpointid. The string returned from ed.get_id() or the value of property endpoint.id. Should not be None :return True if removed, False if not removed (hasn't been...
[ "def", "unadvertise_endpoint", "(", "self", ",", "endpointid", ")", ":", "with", "self", ".", "_published_endpoints_lock", ":", "with", "self", ".", "_published_endpoints_lock", ":", "advertised", "=", "self", ".", "get_advertised_endpoint", "(", "endpointid", ")", ...
37.333333
19.52381
def indexdelta(self, stop_id, start_id): """returns the distance (int) between to idices. Two consecutive tokens must have a delta of 1. """ return self.tokenid2index(stop_id) - self.tokenid2index(start_id)
[ "def", "indexdelta", "(", "self", ",", "stop_id", ",", "start_id", ")", ":", "return", "self", ".", "tokenid2index", "(", "stop_id", ")", "-", "self", ".", "tokenid2index", "(", "start_id", ")" ]
39
14.5
def _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line): """Reflow the lines so that it looks nice.""" if unicode(parsed_tokens[0]) == 'def': # A function definition gets indented a bit more. continued_indent = indentation + ' ' * 2 * DEFAULT_INDEN...
[ "def", "_reflow_lines", "(", "parsed_tokens", ",", "indentation", ",", "max_line_length", ",", "start_on_prefix_line", ")", ":", "if", "unicode", "(", "parsed_tokens", "[", "0", "]", ")", "==", "'def'", ":", "# A function definition gets indented a bit more.", "contin...
36.45
21.275
def syncScrollbars(self): """ Synchronizes the various scrollbars within this chart. """ chart_hbar = self.uiChartVIEW.horizontalScrollBar() chart_vbar = self.uiChartVIEW.verticalScrollBar() x_hbar = self.uiXAxisVIEW.horizontalScrollBar() x_vbar =...
[ "def", "syncScrollbars", "(", "self", ")", ":", "chart_hbar", "=", "self", ".", "uiChartVIEW", ".", "horizontalScrollBar", "(", ")", "chart_vbar", "=", "self", ".", "uiChartVIEW", ".", "verticalScrollBar", "(", ")", "x_hbar", "=", "self", ".", "uiXAxisVIEW", ...
36.619048
17.952381
def deploy_files(local_dir, remote_dir, pattern = '',rsync_exclude=['*.pyc','.*'], use_sudo=False): """ Generic deploy function for cases where one or more files are being deployed to a host. Wraps around ``rsync_project`` and stages files locally and/or remotely for network efficiency. ``local...
[ "def", "deploy_files", "(", "local_dir", ",", "remote_dir", ",", "pattern", "=", "''", ",", "rsync_exclude", "=", "[", "'*.pyc'", ",", "'.*'", "]", ",", "use_sudo", "=", "False", ")", ":", "#normalise paths", "if", "local_dir", "[", "-", "1", "]", "==", ...
43.327586
26.568966
def get_company_user(self, email): """Get company user based on email. :param email: address of contact :type email: ``str``, ``unicode`` :rtype: ``dict`` with contact information """ users = self.get_company_users() for user in users: if user['email...
[ "def", "get_company_user", "(", "self", ",", "email", ")", ":", "users", "=", "self", ".", "get_company_users", "(", ")", "for", "user", "in", "users", ":", "if", "user", "[", "'email'", "]", "==", "email", ":", "return", "user", "msg", "=", "'No user ...
31.6
14
def PixelsHDU(model): ''' Construct the HDU containing the pixel-level light curve. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=2) # Add EVEREST info cards = [] cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVERES...
[ "def", "PixelsHDU", "(", "model", ")", ":", "# Get mission cards", "cards", "=", "model", ".", "_mission", ".", "HDUCards", "(", "model", ".", "meta", ",", "hdu", "=", "2", ")", "# Add EVEREST info", "cards", "=", "[", "]", "cards", ".", "append", "(", ...
34.432432
25.351351
def send_message(self): """Send message over UDP. If tracking is disables, the bytes_sent will always be set to -1 Returns: (bytes_sent, time_taken) """ start = time.time() message = None if not self.initialized: message = self.construct_...
[ "def", "send_message", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "message", "=", "None", "if", "not", "self", ".", "initialized", ":", "message", "=", "self", ".", "construct_start_message", "(", ")", "self", ".", "initialized",...
25.55
18.05
def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, ke...
[ "def", "_create_resource", "(", "resource", ",", "name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ...
39.75
21.75
def fields(self): """ return all the fields and their raw values for this Orm instance. This property returns a dict with the field names and their current values if you want to control the values for outputting to an api, use .jsonable() """ return {k:getattr(self, k, N...
[ "def", "fields", "(", "self", ")", ":", "return", "{", "k", ":", "getattr", "(", "self", ",", "k", ",", "None", ")", "for", "k", "in", "self", ".", "schema", ".", "fields", "}" ]
43.25
26.25
def do_build(self, argv): """\ build [TARGETS] Build the specified TARGETS and their dependencies. 'b' is a synonym. """ import SCons.Node import SCons.SConsign import SCons.Script.Main options = copy.deepcopy(self.options...
[ "def", "do_build", "(", "self", ",", "argv", ")", ":", "import", "SCons", ".", "Node", "import", "SCons", ".", "SConsign", "import", "SCons", ".", "Script", ".", "Main", "options", "=", "copy", ".", "deepcopy", "(", "self", ".", "options", ")", "option...
39.927928
22.333333
def commitData(self, widget): """ Commits the data from the widget to the model. :param widget | <QWidget> """ self._editColumn = self.currentColumn() self.itemChanged.connect(self._commitToSelected) super(XOrbTreeWidget, self).commitData(wid...
[ "def", "commitData", "(", "self", ",", "widget", ")", ":", "self", ".", "_editColumn", "=", "self", ".", "currentColumn", "(", ")", "self", ".", "itemChanged", ".", "connect", "(", "self", ".", "_commitToSelected", ")", "super", "(", "XOrbTreeWidget", ",",...
37.090909
11.454545
def db_manager(self): """ " Do series of DB operations. """ rc_create = self.create_db() # for first create try: self.load_db() # load existing/factory except Exception as e: _logger.debug("*** %s" % str(e)) try: sel...
[ "def", "db_manager", "(", "self", ")", ":", "rc_create", "=", "self", ".", "create_db", "(", ")", "# for first create", "try", ":", "self", ".", "load_db", "(", ")", "# load existing/factory", "except", "Exception", "as", "e", ":", "_logger", ".", "debug", ...
29.612903
13.419355
def change_columns(self, model, **fields): """Change fields.""" for name, field in fields.items(): old_field = model._meta.fields.get(name, field) old_column_name = old_field and old_field.column_name model._meta.add_field(name, field) if isinstance(old_...
[ "def", "change_columns", "(", "self", ",", "model", ",", "*", "*", "fields", ")", ":", "for", "name", ",", "field", "in", "fields", ".", "items", "(", ")", ":", "old_field", "=", "model", ".", "_meta", ".", "fields", ".", "get", "(", "name", ",", ...
43.547619
23.595238
def finalize(self): """ finalize simulation for consumer """ # todo sort self.result by path_num if self.result: self.result = sorted(self.result, key=lambda x: x[0]) p, r = map(list, zip(*self.result)) self.result = r
[ "def", "finalize", "(", "self", ")", ":", "# todo sort self.result by path_num", "if", "self", ".", "result", ":", "self", ".", "result", "=", "sorted", "(", "self", ".", "result", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "p", ",...
31.777778
9.555556
def register(self, model, **attr): """Register a model or a table with this mapper :param model: a table or a :class:`.BaseModel` class :return: a Model class or a table """ metadata = self.metadata if not isinstance(model, Table): model_name = self._create_m...
[ "def", "register", "(", "self", ",", "model", ",", "*", "*", "attr", ")", ":", "metadata", "=", "self", ".", "metadata", "if", "not", "isinstance", "(", "model", ",", "Table", ")", ":", "model_name", "=", "self", ".", "_create_model", "(", "model", "...
30.621622
13.756757
def noninteractive_changeset_update(self, fqn, template, old_parameters, parameters, stack_policy, tags, **kwargs): """Update a Cloudformation stack using a change set. This is required for stacks with a defined Transform (...
[ "def", "noninteractive_changeset_update", "(", "self", ",", "fqn", ",", "template", ",", "old_parameters", ",", "parameters", ",", "stack_policy", ",", "tags", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"Using noninterative changeset provide...
49.121212
24.727273
def flavor_access_list(name, projects, **kwargs): ''' Grants access of the flavor to a project. Flavor must be private. :param name: non-public flavor name :param projects: list of projects which should have the access to the flavor .. code-block:: yaml nova-flavor-share: nova...
[ "def", "flavor_access_list", "(", "name", ",", "projects", ",", "*", "*", "kwargs", ")", ":", "dry_run", "=", "__opts__", "[", "'test'", "]", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'c...
40.278689
24.409836
def decode_cmd_out(self, completed_cmd): """ return a standard message """ try: stdout = completed_cmd.stdout.encode('utf-8').decode() except AttributeError: try: stdout = str(bytes(completed_cmd.stdout), 'big5').strip() except ...
[ "def", "decode_cmd_out", "(", "self", ",", "completed_cmd", ")", ":", "try", ":", "stdout", "=", "completed_cmd", ".", "stdout", ".", "encode", "(", "'utf-8'", ")", ".", "decode", "(", ")", "except", "AttributeError", ":", "try", ":", "stdout", "=", "str...
36.291667
17.958333
def _all(self, *args, **kwargs): ''' Return all the summary of the particular system. ''' data = dict() data['software'] = self._software(**kwargs) data['system'] = self._system(**kwargs) data['services'] = self._services(**kwargs) try: data['c...
[ "def", "_all", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "dict", "(", ")", "data", "[", "'software'", "]", "=", "self", ".", "_software", "(", "*", "*", "kwargs", ")", "data", "[", "'system'", "]", "=", "sel...
34.0625
17.6875
def get_active_position(self, category, name, nofallback=False): """ Get active position for given position name. params: category - Category model to look for name - name of the position nofallback - if True than do not fall back to parent ...
[ "def", "get_active_position", "(", "self", ",", "category", ",", "name", ",", "nofallback", "=", "False", ")", ":", "now", "=", "timezone", ".", "now", "(", ")", "lookup", "=", "(", "Q", "(", "active_from__isnull", "=", "True", ")", "|", "Q", "(", "a...
39.37931
20.551724
def create_observation_streams(self, num_streams, h_size, num_layers): """ Creates encoding stream for observations. :param num_streams: Number of streams to create. :param h_size: Size of hidden linear layers in stream. :param num_layers: Number of hidden linear layers in stream...
[ "def", "create_observation_streams", "(", "self", ",", "num_streams", ",", "h_size", ",", "num_layers", ")", ":", "brain", "=", "self", ".", "brain", "activation_fn", "=", "self", ".", "swish", "self", ".", "visual_in", "=", "[", "]", "for", "i", "in", "...
57.734694
26.142857
def download_and_transfer_sample(job, sample, inputs): """ Downloads a sample from CGHub via GeneTorrent, then uses S3AM to transfer it to S3 input_args: dict Dictionary of input arguments analysis_id: str An analysis ID for a sample in CGHub """ analysis_id = sample[0] work_...
[ "def", "download_and_transfer_sample", "(", "job", ",", "sample", ",", "inputs", ")", ":", "analysis_id", "=", "sample", "[", "0", "]", "work_dir", "=", "job", ".", "fileStore", ".", "getLocalTempDir", "(", ")", "folder_path", "=", "os", ".", "path", ".", ...
44.568182
19.204545
def compactness_frompts(geoseries): """ Inverse of 4 * pi * Area / perimeter^2 """ measure = ( 4 * 3.1415 * ( (geoseries.unary_union).convex_hull.area) ) / ( (geoseries.unary_union).convex_hull.length ) return measure
[ "def", "compactness_frompts", "(", "geoseries", ")", ":", "measure", "=", "(", "4", "*", "3.1415", "*", "(", "(", "geoseries", ".", "unary_union", ")", ".", "convex_hull", ".", "area", ")", ")", "/", "(", "(", "geoseries", ".", "unary_union", ")", ".",...
25
14.272727
def remove_tar_files(file_list): """Public function that removes temporary tar archive files in a local directory""" for f in file_list: if file_exists(f) and f.endswith('.tar'): os.remove(f)
[ "def", "remove_tar_files", "(", "file_list", ")", ":", "for", "f", "in", "file_list", ":", "if", "file_exists", "(", "f", ")", "and", "f", ".", "endswith", "(", "'.tar'", ")", ":", "os", ".", "remove", "(", "f", ")" ]
43
10
def _populate_tournament_payoff_array0(payoff_array, k, indices, indptr): """ Populate `payoff_array` with the payoff values for player 0 in the tournament game given a random tournament graph in CSR format. Parameters ---------- payoff_array : ndarray(float, ndim=2) ndarray of shape (n...
[ "def", "_populate_tournament_payoff_array0", "(", "payoff_array", ",", "k", ",", "indices", ",", "indptr", ")", ":", "n", "=", "payoff_array", ".", "shape", "[", "0", "]", "X", "=", "np", ".", "empty", "(", "k", ",", "dtype", "=", "np", ".", "int_", ...
34.121212
16.363636
def groupby_tags(item_list, tags_list): r""" case where an item can belong to multiple groups Args: item_list (list): tags_list (list): Returns: dict: groupid_to_items CommandLine: python -m utool.util_dict --test-groupby_tags Example: >>> # ENABLE_DOC...
[ "def", "groupby_tags", "(", "item_list", ",", "tags_list", ")", ":", "groupid_to_items", "=", "defaultdict", "(", "list", ")", "for", "tags", ",", "item", "in", "zip", "(", "tags_list", ",", "item_list", ")", ":", "for", "tag", "in", "tags", ":", "groupi...
32.608696
16.76087
def recursive_division(self, cells, min_size, width, height, x=0, y=0, depth=0): """ Recursive division: 1. Split room randomly 1a. Dodge towards larger half if in doorway 2. Place doorway randomly 3. Repeat for each half """ assert isi...
[ "def", "recursive_division", "(", "self", ",", "cells", ",", "min_size", ",", "width", ",", "height", ",", "x", "=", "0", ",", "y", "=", "0", ",", "depth", "=", "0", ")", ":", "assert", "isinstance", "(", "cells", ",", "list", ")", "assert", "isins...
33.327869
17.196721