text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def find_template(self, name, context, peeking=False): """ Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name...
[ "def", "find_template", "(", "self", ",", "name", ",", "context", ",", "peeking", "=", "False", ")", ":", "# These imports want settings, which aren't available when this", "# module is imported to ``add_to_builtins``, so do them here.", "from", "django", ".", "conf", "import...
46.589744
0.001078
def get_data(self, datatype, mode, disp): """ .. todo:: docstring for get_data """ # Imports import os from ..const import EnumDispDirection as _E_DD from ..const import EnumAnharmRepoData from ..error import RepoError as RErr # Must be valid mode ...
[ "def", "get_data", "(", "self", ",", "datatype", ",", "mode", ",", "disp", ")", ":", "# Imports", "import", "os", "from", ".", ".", "const", "import", "EnumDispDirection", "as", "_E_DD", "from", ".", ".", "const", "import", "EnumAnharmRepoData", "from", "....
32.311475
0.009355
def cp(src_hdfs_path, dest_hdfs_path, **kwargs): """\ Copy the contents of ``src_hdfs_path`` to ``dest_hdfs_path``. If ``src_hdfs_path`` is a directory, its contents will be copied recursively. Source file(s) are opened for reading and copies are opened for writing. Additional keyword arguments, if...
[ "def", "cp", "(", "src_hdfs_path", ",", "dest_hdfs_path", ",", "*", "*", "kwargs", ")", ":", "src", ",", "dest", "=", "{", "}", ",", "{", "}", "try", ":", "for", "d", ",", "p", "in", "(", "(", "src", ",", "src_hdfs_path", ")", ",", "(", "dest",...
42.537037
0.000426
def get_base_url(config, args): """ Get the API base url. Try Terraform state first, then :py:class:`~.AWSInfo`. :param config: configuration :type config: :py:class:`~.Config` :param args: command line arguments :type args: :py:class:`argparse.Namespace` :return: API base URL :rtyp...
[ "def", "get_base_url", "(", "config", ",", "args", ")", ":", "try", ":", "logger", ".", "debug", "(", "'Trying to get Terraform base_url output'", ")", "runner", "=", "TerraformRunner", "(", "config", ",", "args", ".", "tf_path", ")", "outputs", "=", "runner",...
34.555556
0.001043
def _mdens_deriv(self,m): """Derivative of the density as a function of m""" return -self.a4*(self.a+4.*m)/m**2/(self.a+m)**4
[ "def", "_mdens_deriv", "(", "self", ",", "m", ")", ":", "return", "-", "self", ".", "a4", "*", "(", "self", ".", "a", "+", "4.", "*", "m", ")", "/", "m", "**", "2", "/", "(", "self", ".", "a", "+", "m", ")", "**", "4" ]
46.333333
0.021277
def patSiemensStar(s0, n=72, vhigh=255, vlow=0, antiasing=False): '''make line pattern''' arr = np.full((s0,s0),vlow, dtype=np.uint8) c = int(round(s0/2.)) s = 2*np.pi/(2*n) step = 0 for i in range(2*n): p0 = round(c+np.sin(step)*2*s0) p1 = round(c+np.cos(step)*2*s0) ...
[ "def", "patSiemensStar", "(", "s0", ",", "n", "=", "72", ",", "vhigh", "=", "255", ",", "vlow", "=", "0", ",", "antiasing", "=", "False", ")", ":", "arr", "=", "np", ".", "full", "(", "(", "s0", ",", "s0", ")", ",", "vlow", ",", "dtype", "=",...
29.72
0.022164
def _get_formatted_feature_dependencies(data): """ Takes the format of the feature_order.json in featuremodel pool. Creates a list of conditions in the following format: ] dict( name='django_productline.features.admin', subject='django_productline', ctype='aft...
[ "def", "_get_formatted_feature_dependencies", "(", "data", ")", ":", "conditions", "=", "list", "(", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "for", "feature", "in", "v", ".", "get", "(", "'after'", ",", "list", "(", ")",...
27
0.001021
def rough_time_estimate(m1, m2, flow, fudge_length=1.1, fudge_min=0.02): """ A very rough estimate of the duration of the waveform. An estimate of the waveform duration starting from flow. This is intended to be fast but not necessarily accurate. It should be an overestimate of the length. It is derive...
[ "def", "rough_time_estimate", "(", "m1", ",", "m2", ",", "flow", ",", "fudge_length", "=", "1.1", ",", "fudge_min", "=", "0.02", ")", ":", "m", "=", "m1", "+", "m2", "msun", "=", "m", "*", "lal", ".", "MTSUN_SI", "t", "=", "5.0", "/", "256.0", "*...
36.742857
0.002273
def port_create(request, network_id, **kwargs): """Create a port on a specified network. :param request: request context :param network_id: network id a subnet is created on :param device_id: (optional) device id attached to the port :param tenant_id: (optional) tenant id of the port created :p...
[ "def", "port_create", "(", "request", ",", "network_id", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "\"port_create(): netid=%(network_id)s, kwargs=%(kwargs)s\"", ",", "{", "'network_id'", ":", "network_id", ",", "'kwargs'", ":", "kwargs", "}", ...
43
0.001198
def new_action(self, method='GET', **kwargs): """ Create a new Action linked to this endpoint with the given args. """ if method not in self.methods: raise TypeError('{} not in valid method(s): {}.'.format(method, self.methods)) return Action(self, method, **kwargs)
[ "def", "new_action", "(", "self", ",", "method", "=", "'GET'", ",", "*", "*", "kwargs", ")", ":", "if", "method", "not", "in", "self", ".", "methods", ":", "raise", "TypeError", "(", "'{} not in valid method(s): {}.'", ".", "format", "(", "method", ",", ...
44.571429
0.009434
def AgregarCTG(self, nro_ctg=None, nro_carta_porte=None, porcentaje_secado_humedad=None, importe_secado=None, peso_neto_merma_secado=None, tarifa_secado=None, importe_zarandeo=None, peso_neto_merma_zarandeo=None, tarifa_...
[ "def", "AgregarCTG", "(", "self", ",", "nro_ctg", "=", "None", ",", "nro_carta_porte", "=", "None", ",", "porcentaje_secado_humedad", "=", "None", ",", "importe_secado", "=", "None", ",", "peso_neto_merma_secado", "=", "None", ",", "tarifa_secado", "=", "None", ...
49.695652
0.008584
def add_text_structure(self, label): """ Adds a citable text structure to the work. """ ts = self.session.get_resource("%s/text_structure" % self.subject , self.session.get_class(surf.ns.HUCIT['TextStructure'])) ts.rdfs_label.append(Literal(...
[ "def", "add_text_structure", "(", "self", ",", "label", ")", ":", "ts", "=", "self", ".", "session", ".", "get_resource", "(", "\"%s/text_structure\"", "%", "self", ".", "subject", ",", "self", ".", "session", ".", "get_class", "(", "surf", ".", "ns", "....
36.5
0.011136
def combine_first_two_dimensions(x): """Reshape x so that the first two dimension become one. Args: x: a Tensor with shape [a, b, ...] Returns: a Tensor with shape [ab, ...] """ ret = tf.reshape(x, tf.concat([[-1], common_layers.shape_list(x)[2:]], 0)) old_shape = x.get_shape().dims a, b = old_s...
[ "def", "combine_first_two_dimensions", "(", "x", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "x", ",", "tf", ".", "concat", "(", "[", "[", "-", "1", "]", ",", "common_layers", ".", "shape_list", "(", "x", ")", "[", "2", ":", "]", "]", ",", ...
27.533333
0.018735
def restoreXml(self, xml): """ Restores properties for this tree widget from the inputed XML. :param xml | <xml.etree.ElementTree.Element> :return <bool> success """ if xml is None: return False self.setUp...
[ "def", "restoreXml", "(", "self", ",", "xml", ")", ":", "if", "xml", "is", "None", ":", "return", "False", "self", ".", "setUpdatesEnabled", "(", "False", ")", "self", ".", "blockSignals", "(", "True", ")", "# restore column data\r", "header", "=", "self",...
35.127273
0.009063
def profile(name): ''' This state module allows you to modify system tuned parameters Example tuned.sls file to set profile to virtual-guest tuned: tuned: - profile - name: virtual-guest name tuned profile name to set the system to To see a valid list of states ...
[ "def", "profile", "(", "name", ")", ":", "# create data-structure to return with default value", "ret", "=", "{", "'name'", ":", "''", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "ret", "[", "name", "]"...
27.913043
0.000502
def predict_subsequences( self, sequence_dict, peptide_lengths=None): """ Given a dictionary mapping sequence names to amino acid strings, and an optional list of peptide lengths, returns a BindingPredictionCollection. """ if isinstance...
[ "def", "predict_subsequences", "(", "self", ",", "sequence_dict", ",", "peptide_lengths", "=", "None", ")", ":", "if", "isinstance", "(", "sequence_dict", ",", "string_types", ")", ":", "sequence_dict", "=", "{", "\"seq\"", ":", "sequence_dict", "}", "elif", "...
40.911111
0.001061
def tube_hires(script, height=1.0, radius=None, radius1=None, radius2=None, diameter=None, diameter1=None, diameter2=None, cir_segments=32, rad_segments=1, height_segments=1, center=False, simple_bottom=False, color=None): """Create a cylinder with user defined number of...
[ "def", "tube_hires", "(", "script", ",", "height", "=", "1.0", ",", "radius", "=", "None", ",", "radius1", "=", "None", ",", "radius2", "=", "None", ",", "diameter", "=", "None", ",", "diameter1", "=", "None", ",", "diameter2", "=", "None", ",", "cir...
34.112676
0.000803
def release(): """ Check release before upload to PyPI. """ sh("paver bdist_egg") # Check that source distribution can be built and is complete print print "~" * 78 print "TESTING SOURCE BUILD" sh( "{ cd dist/ && unzip -q %s-%s.zip && cd %s-%s/" " && /usr/bin/python set...
[ "def", "release", "(", ")", ":", "sh", "(", "\"paver bdist_egg\"", ")", "# Check that source distribution can be built and is complete", "print", "print", "\"~\"", "*", "78", "print", "\"TESTING SOURCE BUILD\"", "sh", "(", "\"{ cd dist/ && unzip -q %s-%s.zip && cd %s-%s/\"", ...
36.84
0.001058
async def send(self): """Send new GUI""" await client.send_typing(self.channel) self.sent_embed = await client.send_message(self.channel, embed=self.built_embed)
[ "async", "def", "send", "(", "self", ")", ":", "await", "client", ".", "send_typing", "(", "self", ".", "channel", ")", "self", ".", "sent_embed", "=", "await", "client", ".", "send_message", "(", "self", ".", "channel", ",", "embed", "=", "self", ".",...
36.4
0.016129
def convert(values): """ convert the numpy values to a list """ dtype = values.dtype if is_categorical_dtype(values): return values elif is_object_dtype(dtype): return values.ravel().tolist() if needs_i8_conversion(dtype): values = values.view('i8') v = values.ravel()...
[ "def", "convert", "(", "values", ")", ":", "dtype", "=", "values", ".", "dtype", "if", "is_categorical_dtype", "(", "values", ")", ":", "return", "values", "elif", "is_object_dtype", "(", "dtype", ")", ":", "return", "values", ".", "ravel", "(", ")", "."...
23.410256
0.001052
def get_term_config(platform, filter_name, term_name, filter_options=None, pillar_key='acl', pillarenv=None, saltenv=None, merge_pillar=True, revision_id=None, ...
[ "def", "get_term_config", "(", "platform", ",", "filter_name", ",", "term_name", ",", "filter_options", "=", "None", ",", "pillar_key", "=", "'acl'", ",", "pillarenv", "=", "None", ",", "saltenv", "=", "None", ",", "merge_pillar", "=", "True", ",", "revision...
29.452899
0.002261
def _compute_distance_term(self, C, rrup, mag): """ Returns the distance scaling term """ exponent_term = (1.0 + C["c3"] * np.exp(mag - 5.)) ** 2. return C["c2"] * np.log(np.sqrt(rrup ** 2. + exponent_term))
[ "def", "_compute_distance_term", "(", "self", ",", "C", ",", "rrup", ",", "mag", ")", ":", "exponent_term", "=", "(", "1.0", "+", "C", "[", "\"c3\"", "]", "*", "np", ".", "exp", "(", "mag", "-", "5.", ")", ")", "**", "2.", "return", "C", "[", "...
40.333333
0.008097
def _wrap_content(content, width): """ Wrap given content into lines of given width. """ data = [] if isinstance(content, list): data += content else: data.append(content) lines = [] for d in data: l = textwrap.wrap(d, ...
[ "def", "_wrap_content", "(", "content", ",", "width", ")", ":", "data", "=", "[", "]", "if", "isinstance", "(", "content", ",", "list", ")", ":", "data", "+=", "content", "else", ":", "data", ".", "append", "(", "content", ")", "lines", "=", "[", "...
23.733333
0.008108
def iter_get_triggers(self): """ generator that yields triggers Returns ------- trigger_info : dict trigger information with the following keys: * comment : trigger comment * time : trigger time * pre_time : trigger pre time ...
[ "def", "iter_get_triggers", "(", "self", ")", ":", "for", "i", ",", "gp", "in", "enumerate", "(", "self", ".", "groups", ")", ":", "trigger", "=", "gp", ".", "trigger", "if", "trigger", ":", "for", "j", "in", "range", "(", "trigger", "[", "\"trigger_...
35.62069
0.001885
def run_on_executor(*args: Any, **kwargs: Any) -> Callable: """Decorator to run a synchronous method asynchronously on an executor. The decorated method may be called with a ``callback`` keyword argument and returns a future. The executor to be used is determined by the ``executor`` attributes of ...
[ "def", "run_on_executor", "(", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Callable", ":", "# Fully type-checking decorators is tricky, and this one is", "# discouraged anyway so it doesn't have all the generic magic.", "def", "run_on_executor_de...
37.709677
0.000834
def _get_xml(self, close_tag=True): """ generate the xml string representation. :param close_tag: should the '</provenance_step>' tag be added or not. :type close_tag: bool :return: the xml :rtype: str """ provenance_step_element = Element('provenance_s...
[ "def", "_get_xml", "(", "self", ",", "close_tag", "=", "True", ")", ":", "provenance_step_element", "=", "Element", "(", "'provenance_step'", ",", "{", "'timestamp'", ":", "self", ".", "time", ".", "isoformat", "(", ")", "}", ")", "title", "=", "SubElement...
30.692308
0.00243
def suddendeathmessage(message): ''' suddendeathmessage returns "突然の死" like ascii art decorated message string. :param str message: random unicode mixed text :rtype: str ''' msg_len = message_length(message) header_len = msg_len // 2 + 2 footer_len = (msg_len // 2) * 2 + 1 footer_pa...
[ "def", "suddendeathmessage", "(", "message", ")", ":", "msg_len", "=", "message_length", "(", "message", ")", "header_len", "=", "msg_len", "//", "2", "+", "2", "footer_len", "=", "(", "msg_len", "//", "2", ")", "*", "2", "+", "1", "footer_pattern", "=",...
27.9
0.001733
def classify_nodes(graph, hub): """Classify each node based on its type and relationship to the hub.""" node_stats = defaultdict(lambda: defaultdict(list)) for u, v, data in graph.edges(data=True): # This means the node is downstream of the hub if hub == u: h, o = u, v ...
[ "def", "classify_nodes", "(", "graph", ",", "hub", ")", ":", "node_stats", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "list", ")", ")", "for", "u", ",", "v", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ...
42.147059
0.000682
def minimum(lhs, rhs): """Returns element-wise minimum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a com...
[ "def", "minimum", "(", "lhs", ",", "rhs", ")", ":", "# pylint: disable= no-member, protected-access", "return", "_ufunc_helper", "(", "lhs", ",", "rhs", ",", "op", ".", "broadcast_minimum", ",", "lambda", "x", ",", "y", ":", "x", "if", "x", "<", "y", "else...
28.777778
0.001867
def open(target): """Opens the target file or URL in the default application. **Attribution**: Written by user4815162342 and originally posted on `Stack Overflow <http://stackoverflow.com/a/17317468>`_. **Examples**: :: auxly.open("myfile.txt") auxly.open("https://www.github.co...
[ "def", "open", "(", "target", ")", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "os", ".", "startfile", "(", "target", ")", "else", ":", "opener", "=", "\"open\"", "if", "sys", ".", "platform", "==", "\"darwin\"", "else", "\"xdg-open\"", ...
29.235294
0.001949
def positions(self): """ Generator producing all 2D positions of all squares. """ for y in range(self.height): for x in range(self.length): yield x, y
[ "def", "positions", "(", "self", ")", ":", "for", "y", "in", "range", "(", "self", ".", "height", ")", ":", "for", "x", "in", "range", "(", "self", ".", "length", ")", ":", "yield", "x", ",", "y" ]
38
0.010309
def iter_settings(mixed: Settings) -> Iterator[Tuple[str, Any]]: """Iterate over settings values from settings module or dict-like instance. :param mixed: Settings instance to iterate. """ if isinstance(mixed, types.ModuleType): for attr in dir(mixed): if not is_setting_key(attr): ...
[ "def", "iter_settings", "(", "mixed", ":", "Settings", ")", "->", "Iterator", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ":", "if", "isinstance", "(", "mixed", ",", "types", ".", "ModuleType", ")", ":", "for", "attr", "in", "dir", "(", "mixed", ...
39
0.002088
def tryload_cache_list(dpath, fname, cfgstr_list, verbose=False): """ loads a list of similar cached datas. Returns flags that needs to be computed """ data_list = [tryload_cache(dpath, fname, cfgstr, verbose) for cfgstr in cfgstr_list] ismiss_list = [data is None for data in data_list] return d...
[ "def", "tryload_cache_list", "(", "dpath", ",", "fname", ",", "cfgstr_list", ",", "verbose", "=", "False", ")", ":", "data_list", "=", "[", "tryload_cache", "(", "dpath", ",", "fname", ",", "cfgstr", ",", "verbose", ")", "for", "cfgstr", "in", "cfgstr_list...
47.857143
0.008798
def set_n(self, value): ''' setter ''' if isinstance(value, int): self.__n = value else: raise TypeError("The type of n must be int.")
[ "def", "set_n", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "self", ".", "__n", "=", "value", "else", ":", "raise", "TypeError", "(", "\"The type of n must be int.\"", ")" ]
29.5
0.010989
def do_create(self, line): """create <identifier> <file> Create a new Science Object on a Member Node. The System Metadata that becomes associated with the new Science Object is generated from the session variables. """ pid, sciobj_path = self._split_args(line, 2, 0) se...
[ "def", "do_create", "(", "self", ",", "line", ")", ":", "pid", ",", "sciobj_path", "=", "self", ".", "_split_args", "(", "line", ",", "2", ",", "0", ")", "self", ".", "_command_processor", ".", "science_object_create", "(", "pid", ",", "sciobj_path", ")"...
41.75
0.009766
def _find_conflicts(problem, assignment, variable=None, value=None): ''' Find violated constraints on a given assignment, with the possibility of specifying a new variable and value to add to the assignment before checking. ''' if variable is not None and value is not None: assignment = ...
[ "def", "_find_conflicts", "(", "problem", ",", "assignment", ",", "variable", "=", "None", ",", "value", "=", "None", ")", ":", "if", "variable", "is", "not", "None", "and", "value", "is", "not", "None", ":", "assignment", "=", "deepcopy", "(", "assignme...
39.888889
0.001361
def transform(string, transliterations=None): """ Transform the string to "upside-down" writing. Example: >>> import upsidedown >>> print(upsidedown.transform('Hello World!')) ¡pꞁɹoM oꞁꞁǝH For languages with diacritics you might want to supply a transliteration to work aro...
[ "def", "transform", "(", "string", ",", "transliterations", "=", "None", ")", ":", "transliterations", "=", "transliterations", "or", "TRANSLITERATIONS", "for", "character", "in", "transliterations", ":", "string", "=", "string", ".", "replace", "(", "character", ...
32.073171
0.001476
def rfc1123_date(timestamp=None): """Create a RFC1123 style Date header for *timestamp*.""" if timestamp is None: timestamp = time.time() timestamp = int(timestamp) global _cached_timestamp, _cached_datestring if timestamp != _cached_timestamp: # The time stamp must be GMT, and canno...
[ "def", "rfc1123_date", "(", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "time", ".", "time", "(", ")", "timestamp", "=", "int", "(", "timestamp", ")", "global", "_cached_timestamp", ",", "_cached_datestring", ...
42.642857
0.001639
def excluded_length(self): """Surveyed length which does not count toward the included total""" return sum([shot.length for shot in self.shots if Exclude.LENGTH in shot.flags or Exclude.TOTAL in shot.flags])
[ "def", "excluded_length", "(", "self", ")", ":", "return", "sum", "(", "[", "shot", ".", "length", "for", "shot", "in", "self", ".", "shots", "if", "Exclude", ".", "LENGTH", "in", "shot", ".", "flags", "or", "Exclude", ".", "TOTAL", "in", "shot", "."...
73.666667
0.013453
def read(self): """Read version from version file :rtype : Version :return: """ with self._path.open(mode='r') as fh: version = fh.read().strip() return Version(version)
[ "def", "read", "(", "self", ")", ":", "with", "self", ".", "_path", ".", "open", "(", "mode", "=", "'r'", ")", "as", "fh", ":", "version", "=", "fh", ".", "read", "(", ")", ".", "strip", "(", ")", "return", "Version", "(", "version", ")" ]
24.666667
0.008696
def deep_nodes(self, allnodes=None): """ A recursive method to return a ``list`` of *all* **node objects** connected from this **toplogical node**. """ allnodes = (allnodes or []) for (node, node_) in ((node, node_) for (node, node_) in\ self.iterite...
[ "def", "deep_nodes", "(", "self", ",", "allnodes", "=", "None", ")", ":", "allnodes", "=", "(", "allnodes", "or", "[", "]", ")", "for", "(", "node", ",", "node_", ")", "in", "(", "(", "node", ",", "node_", ")", "for", "(", "node", ",", "node_", ...
36.333333
0.017897
def COOKIES(self): """ Cookies parsed into a dictionary. Signed cookies are NOT decoded automatically. See :meth:`get_cookie` for details. """ raw_dict = SimpleCookie(self.headers.get('Cookie','')) cookies = {} for cookie in six.itervalues(raw_dict): cooki...
[ "def", "COOKIES", "(", "self", ")", ":", "raw_dict", "=", "SimpleCookie", "(", "self", ".", "headers", ".", "get", "(", "'Cookie'", ",", "''", ")", ")", "cookies", "=", "{", "}", "for", "cookie", "in", "six", ".", "itervalues", "(", "raw_dict", ")", ...
40.444444
0.008065
def SegmentSum(a, ids, *args): """ Segmented sum op. """ func = lambda idxs: reduce(np.add, a[idxs]) return seg_map(func, a, ids),
[ "def", "SegmentSum", "(", "a", ",", "ids", ",", "*", "args", ")", ":", "func", "=", "lambda", "idxs", ":", "reduce", "(", "np", ".", "add", ",", "a", "[", "idxs", "]", ")", "return", "seg_map", "(", "func", ",", "a", ",", "ids", ")", "," ]
24.166667
0.013333
def line_counts_as_uncovered(line: str, is_from_cover_annotation_file: bool) -> bool: """ Args: line: The line of code (including coverage annotation). is_from_cover_annotation_file: Whether this line has been annotated. Returns: Does the line count as un...
[ "def", "line_counts_as_uncovered", "(", "line", ":", "str", ",", "is_from_cover_annotation_file", ":", "bool", ")", "->", "bool", ":", "# Ignore this line?", "if", "is_from_cover_annotation_file", ":", "# Already covered, or the tool deemed it not relevant for coverage.", "if",...
29.794118
0.000956
def itertrajs(meta, stride=1): """Load one mdtraj trajectory at a time and yield it. MDTraj does striding badly. It reads in the whole trajectory and then performs a stride. We join(iterload) to conserve memory. """ tops = preload_tops(meta) for i, row in meta.iterrows(): yield i, md.j...
[ "def", "itertrajs", "(", "meta", ",", "stride", "=", "1", ")", ":", "tops", "=", "preload_tops", "(", "meta", ")", "for", "i", ",", "row", "in", "meta", ".", "iterrows", "(", ")", ":", "yield", "i", ",", "md", ".", "join", "(", "md", ".", "iter...
39.928571
0.001748
def index(): """ Display productpage with normal user and test user buttons""" global productpage table = json2html.convert(json = json.dumps(productpage), table_attributes="class=\"table table-condensed table-bordered table-hover\"") return render_template('index.html', ...
[ "def", "index", "(", ")", ":", "global", "productpage", "table", "=", "json2html", ".", "convert", "(", "json", "=", "json", ".", "dumps", "(", "productpage", ")", ",", "table_attributes", "=", "\"class=\\\"table table-condensed table-bordered table-hover\\\"\"", ")...
41.5
0.011799
def getFcpDevices(rh): """ Lists the FCP device channels that are active, free, or offline. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'FCPDEVICES' Output: Request Handle updated with the results. Return code - 0:...
[ "def", "getFcpDevices", "(", "rh", ")", ":", "rh", ".", "printSysLog", "(", "\"Enter getHost.getFcpDevices\"", ")", "parms", "=", "[", "\"-T\"", ",", "\"dummy\"", "]", "results", "=", "invokeSMCLI", "(", "rh", ",", "\"System_WWPN_Query\"", ",", "parms", ")", ...
29.285714
0.002361
def filter(cls, datetimes, number, now=None, **options): """Return a set of datetimes, after filtering ``datetimes``. The result will be the ``datetimes`` which are ``number`` of units before ``now``, until ``now``, with approximately one unit between each of them. The first datetime f...
[ "def", "filter", "(", "cls", ",", "datetimes", ",", "number", ",", "now", "=", "None", ",", "*", "*", "options", ")", ":", "if", "not", "isinstance", "(", "number", ",", "int", ")", "or", "number", "<", "0", ":", "raise", "ValueError", "(", "'Inval...
35.355556
0.001835
def _create_consumer(self): """Tries to establing the Kafka consumer connection""" if not self.closed: try: self.logger.debug("Creating new kafka consumer using brokers: " + str(self.settings['KAFKA_HOSTS']) + ' and topic ' + ...
[ "def", "_create_consumer", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "try", ":", "self", ".", "logger", ".", "debug", "(", "\"Creating new kafka consumer using brokers: \"", "+", "str", "(", "self", ".", "settings", "[", "'KAFKA_HOSTS'", ...
58.12
0.010833
def __parse_domain_to_employer_stream(self, stream): """Parse domain to employer stream. Each line of the stream has to contain a domain and a organization, or employer, separated by tabs. Comment lines start with the hash character (#) Example: # Domains from domains....
[ "def", "__parse_domain_to_employer_stream", "(", "self", ",", "stream", ")", ":", "if", "not", "stream", ":", "return", "f", "=", "self", ".", "__parse_domain_to_employer_line", "for", "o", "in", "self", ".", "__parse_stream", "(", "stream", ",", "f", ")", "...
27.827586
0.002395
def get_account(self, account_id, **params): """https://developers.coinbase.com/api/v2#show-an-account""" response = self._get('v2', 'accounts', account_id, params=params) return self._make_api_object(response, Account)
[ "def", "get_account", "(", "self", ",", "account_id", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'accounts'", ",", "account_id", ",", "params", "=", "params", ")", "return", "self", ".", "_make_api_object"...
60
0.00823
def assign(name, value): ''' Assign a single sysctl parameter for this minion CLI Example: .. code-block:: bash salt '*' sysctl.assign net.inet.icmp.icmplim 50 ''' ret = {} cmd = 'sysctl {0}="{1}"'.format(name, value) data = __salt__['cmd.run_all'](cmd, python_shell=False) ...
[ "def", "assign", "(", "name", ",", "value", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'sysctl {0}=\"{1}\"'", ".", "format", "(", "name", ",", "value", ")", "data", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_shell", "=", "...
26.95
0.001792
def get_customjs(self, references, plot_id=None): """ Creates a CustomJS callback that will send the requested attributes back to python. """ # Generate callback JS code to get all the requested data if plot_id is None: plot_id = self.plot.id or 'PLACEHOLDER_P...
[ "def", "get_customjs", "(", "self", ",", "references", ",", "plot_id", "=", "None", ")", ":", "# Generate callback JS code to get all the requested data", "if", "plot_id", "is", "None", ":", "plot_id", "=", "self", ".", "plot", ".", "id", "or", "'PLACEHOLDER_PLOT_...
46.952381
0.001988
def annual_reading_counts(kind='all'): """ Returns a list of dicts, one per year of reading. In year order. Each dict is like this (if kind is 'all'): {'year': datetime.date(2003, 1, 1), 'book': 12, # only included if kind is 'all' or 'book' 'periodical': 18, ...
[ "def", "annual_reading_counts", "(", "kind", "=", "'all'", ")", ":", "if", "kind", "==", "'all'", ":", "kinds", "=", "[", "'book'", ",", "'periodical'", "]", "else", ":", "kinds", "=", "[", "kind", "]", "# This will have keys of years (strings) and dicts of data...
31.092308
0.000959
def makeairloop(idf, loopname, sloop, dloop, testing=None): """make an airloop""" # -------- testing --------- testn = 0 # -------- testing --------- newairloop = idf.newidfobject("AirLoopHVAC".upper(), Name=loopname) # -------- testing --------- testn = doingtesting(testing, testn, newairlo...
[ "def", "makeairloop", "(", "idf", ",", "loopname", ",", "sloop", ",", "dloop", ",", "testing", "=", "None", ")", ":", "# -------- testing ---------", "testn", "=", "0", "# -------- testing ---------", "newairloop", "=", "idf", ".", "newidfobject", "(", "\"AirLoo...
38.828996
0.002334
def refresh(self): # type: () -> None """Refresh the object in place.""" src = self._client.reload(self) self.__dict__.update(src.__dict__)
[ "def", "refresh", "(", "self", ")", ":", "# type: () -> None", "src", "=", "self", ".", "_client", ".", "reload", "(", "self", ")", "self", ".", "__dict__", ".", "update", "(", "src", ".", "__dict__", ")" ]
33.4
0.017544
def required(field): """Decorator that checks if return value is set, if not, raises exception. """ def wrap(f): def wrappedf(*args): result = f(*args) if result is None or result == "": raise Exception( "Config option '%s' is required." %...
[ "def", "required", "(", "field", ")", ":", "def", "wrap", "(", "f", ")", ":", "def", "wrappedf", "(", "*", "args", ")", ":", "result", "=", "f", "(", "*", "args", ")", "if", "result", "is", "None", "or", "result", "==", "\"\"", ":", "raise", "E...
28.714286
0.00241
def surf(z, x=None, y=None, elev=None, azim=None, xlbl=None, ylbl=None, zlbl=None, title=None, lblpad=8.0, cntr=None, cmap=None, fgsz=None, fgnm=None, fig=None, ax=None): """ Plot a 2D surface in 3D. If a figure object is specified then the surface is drawn in that figure, and ``fig.show()...
[ "def", "surf", "(", "z", ",", "x", "=", "None", ",", "y", "=", "None", ",", "elev", "=", "None", ",", "azim", "=", "None", ",", "xlbl", "=", "None", ",", "ylbl", "=", "None", ",", "zlbl", "=", "None", ",", "title", "=", "None", ",", "lblpad",...
33.738318
0.000269
def ldr(scatterer, h_pol=True): """ Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR. """ Z = scatterer.get_Z() if h_pol: r...
[ "def", "ldr", "(", "scatterer", ",", "h_pol", "=", "True", ")", ":", "Z", "=", "scatterer", ".", "get_Z", "(", ")", "if", "h_pol", ":", "return", "(", "Z", "[", "0", ",", "0", "]", "-", "Z", "[", "0", ",", "1", "]", "+", "Z", "[", "1", ",...
27.052632
0.031955
def run_nested_groups(): """Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase """ test = htf.Test( htf.PhaseGroup( main=[ ...
[ "def", "run_nested_groups", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "main", "=", "[", "main_phase", ",", "htf", ".", "PhaseGroup", ".", "with_teardown", "(", "inner_teardown_phase", ")", "(", "inner_main_phase", ...
23.666667
0.009671
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( 'Calculates a message digest hash for every file in a directory or ' 'storage media image.')) argument_parser.add_argument( 'source',...
[ "def", "Main", "(", ")", ":", "argument_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "'Calculates a message digest hash for every file in a directory or '", "'storage media image.'", ")", ")", "argument_parser", ".", "add_argument", "(", ...
25.490909
0.010989
def from_dict(data, ctx): """ Instantiate a new OrderBook from a dict (generally from loading a JSON response). The data used to instantiate the OrderBook is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ data =...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'price'", ")", "is", "not", "None", ":", "data", "[", "'price'", "]", "=", "ctx", ".", "convert_decimal_number", "(",...
31.592593
0.002275
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is ...
[ "def", "_read_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "wrapped_socket", "=", "None", "try", ":", "wrapped_socket", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "wrapped_socket", "is", "Non...
35.169811
0.000522
def get_file_path(dotted_path, extension='json'): """ Reads a dotted file path and returns the file path. """ # If the operating system's file path seperator character is in the string if os.sep in dotted_path or '/' in dotted_path: # Assume the path is a valid file path return dotte...
[ "def", "get_file_path", "(", "dotted_path", ",", "extension", "=", "'json'", ")", ":", "# If the operating system's file path seperator character is in the string", "if", "os", ".", "sep", "in", "dotted_path", "or", "'/'", "in", "dotted_path", ":", "# Assume the path is a...
30.25
0.001603
def _skip_frame(self): """Skip the next time frame""" for line in self._f: if line == 'ITEM: ATOMS\n': break for i in range(self.num_atoms): next(self._f)
[ "def", "_skip_frame", "(", "self", ")", ":", "for", "line", "in", "self", ".", "_f", ":", "if", "line", "==", "'ITEM: ATOMS\\n'", ":", "break", "for", "i", "in", "range", "(", "self", ".", "num_atoms", ")", ":", "next", "(", "self", ".", "_f", ")" ...
30.285714
0.009174
def exports(self): """ :rtype: twilio.rest.preview.bulk_exports.export.ExportList """ if self._exports is None: self._exports = ExportList(self) return self._exports
[ "def", "exports", "(", "self", ")", ":", "if", "self", ".", "_exports", "is", "None", ":", "self", ".", "_exports", "=", "ExportList", "(", "self", ")", "return", "self", ".", "_exports" ]
30.142857
0.009217
def get_requirements(requirements_filepath): ''' Return list of this package requirements via local filepath. ''' requirements = [] with open(os.path.join(ROOT_DIR, requirements_filepath), 'rt') as f: for line in f: if line.startswith('#'): continue li...
[ "def", "get_requirements", "(", "requirements_filepath", ")", ":", "requirements", "=", "[", "]", "with", "open", "(", "os", ".", "path", ".", "join", "(", "ROOT_DIR", ",", "requirements_filepath", ")", ",", "'rt'", ")", "as", "f", ":", "for", "line", "i...
31.214286
0.002222
def gather_metadata(fn_glob, parser): """Given a glob and a parser object, create a metadata dataframe. Parameters ---------- fn_glob : str Glob string to find trajectory files. parser : descendant of _Parser Object that handles conversion of filenames to metadata rows. """ ...
[ "def", "gather_metadata", "(", "fn_glob", ",", "parser", ")", ":", "meta", "=", "pd", ".", "DataFrame", "(", "parser", ".", "parse_fn", "(", "fn", ")", "for", "fn", "in", "glob", ".", "iglob", "(", "fn_glob", ")", ")", "return", "meta", ".", "set_ind...
36
0.002257
def _time_dependent_to_qutip( op, full_space=None, time_symbol=symbols("t", real=True), convert_as='pyfunc'): """Convert a possiblty time-dependent operator into the nested-list structure required by QuTiP""" if full_space is None: full_space = op.space if time_symbol in op.free_...
[ "def", "_time_dependent_to_qutip", "(", "op", ",", "full_space", "=", "None", ",", "time_symbol", "=", "symbols", "(", "\"t\"", ",", "real", "=", "True", ")", ",", "convert_as", "=", "'pyfunc'", ")", ":", "if", "full_space", "is", "None", ":", "full_space"...
47.596154
0.000396
def allow_access_for_roles(roles): """Access control helper to check user's roles against a list of valid roles.""" if isinstance(roles, Role): roles = (roles,) valid_roles = frozenset(roles) if Anonymous in valid_roles: return allow_anonymous def check_role(user, roles, **kwar...
[ "def", "allow_access_for_roles", "(", "roles", ")", ":", "if", "isinstance", "(", "roles", ",", "Role", ")", ":", "roles", "=", "(", "roles", ",", ")", "valid_roles", "=", "frozenset", "(", "roles", ")", "if", "Anonymous", "in", "valid_roles", ":", "retu...
28
0.002033
def Somayajulu(T, Tc, A, B, C): r'''Calculates air-water surface tension using the [1]_ emperical (parameter-regressed) method. Well regressed, no recent data. .. math:: \sigma=aX^{5/4}+bX^{9/4}+cX^{13/4} X=(T_c-T)/T_c Parameters ---------- T : float Temperature of flu...
[ "def", "Somayajulu", "(", "T", ",", "Tc", ",", "A", ",", "B", ",", "C", ")", ":", "X", "=", "(", "Tc", "-", "T", ")", "/", "Tc", "sigma", "=", "(", "A", "*", "X", "**", "1.25", "+", "B", "*", "X", "**", "2.25", "+", "C", "*", "X", "**...
27.693878
0.000712
def evaluate_variable(self, name): """Evaluates the variable given by name.""" if isinstance(self.variables[name], six.string_types): # TODO: this does not allow more than one level deep variable, like a depends on b, b on c, c is a const value = eval(self.variables[name], expres...
[ "def", "evaluate_variable", "(", "self", ",", "name", ")", ":", "if", "isinstance", "(", "self", ".", "variables", "[", "name", "]", ",", "six", ".", "string_types", ")", ":", "# TODO: this does not allow more than one level deep variable, like a depends on b, b on c, c...
52.875
0.009302
def parse_control_options(controls, variable_defaults=None): """ Parse a set of control options. Args: controls: The dictionary of control options. variable_defaults: If the controls are for a Query with variables, then this is the default variable values defined in the Query module. The options in...
[ "def", "parse_control_options", "(", "controls", ",", "variable_defaults", "=", "None", ")", ":", "controls_html", "=", "''", "control_defaults", "=", "{", "}", "control_ids", "=", "[", "]", "div_id", "=", "_html", ".", "Html", ".", "next_id", "(", ")", "i...
43.628319
0.012297
def load_paired_notebook(notebook, fmt, nb_file, log): """Update the notebook with the inputs and outputs of the most recent paired files""" formats = notebook.metadata.get('jupytext', {}).get('formats') if not formats: raise ValueError("'{}' is not a paired notebook".format(nb_file)) max_mtim...
[ "def", "load_paired_notebook", "(", "notebook", ",", "fmt", ",", "nb_file", ",", "log", ")", ":", "formats", "=", "notebook", ".", "metadata", ".", "get", "(", "'jupytext'", ",", "{", "}", ")", ".", "get", "(", "'formats'", ")", "if", "not", "formats",...
46
0.002301
def extract_residue_accessibility(in_rsa, path=True, get_total=False): """Parses rsa file for solvent accessibility for each residue. Parameters ---------- in_rsa : str Path to naccess rsa file path : bool Indicates if in_rsa is a path or a string get_total : bool Indica...
[ "def", "extract_residue_accessibility", "(", "in_rsa", ",", "path", "=", "True", ",", "get_total", "=", "False", ")", ":", "if", "path", ":", "with", "open", "(", "in_rsa", ",", "'r'", ")", "as", "inf", ":", "rsa", "=", "inf", ".", "read", "(", ")", ...
30.358974
0.000818
def p_randomvar_expr(self, p): '''randomvar_expr : BERNOULLI LPAREN expr RPAREN | DIRAC_DELTA LPAREN expr RPAREN | KRON_DELTA LPAREN expr RPAREN | UNIFORM LPAREN expr COMMA expr RPAREN | NORMAL LPAREN expr CO...
[ "def", "p_randomvar_expr", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "7", ":", "if", "isinstance", "(", "p", "[", "5", "]", ",", "list", ")", ":", "p", "[", "0", "]", "=", "(", "'randomvar'", ",", "(", "p", "[", "1"...
52.947368
0.001953
def ss_reg(self): """Sum of squares of the regression.""" return np.sum(np.square(self.predicted - self.ybar), axis=0)
[ "def", "ss_reg", "(", "self", ")", ":", "return", "np", ".", "sum", "(", "np", ".", "square", "(", "self", ".", "predicted", "-", "self", ".", "ybar", ")", ",", "axis", "=", "0", ")" ]
44.666667
0.014706
def get_map(self, create_html=True): """Strike data should be a pd.DF from the WWLN data files read by read_WWLN()""" strike_data = self.df num_rows = len(self.df) if num_rows > 1000: print("Warning, you have requested lots of data be mapped." / " Li...
[ "def", "get_map", "(", "self", ",", "create_html", "=", "True", ")", ":", "strike_data", "=", "self", ".", "df", "num_rows", "=", "len", "(", "self", ".", "df", ")", "if", "num_rows", ">", "1000", ":", "print", "(", "\"Warning, you have requested lots of d...
46.869565
0.001818
def unlock(self): """Unlock the device.""" success = self.set_status(CONST.STATUS_LOCKOPEN_INT) if success: self._json_state['status'] = CONST.STATUS_LOCKOPEN return success
[ "def", "unlock", "(", "self", ")", ":", "success", "=", "self", ".", "set_status", "(", "CONST", ".", "STATUS_LOCKOPEN_INT", ")", "if", "success", ":", "self", ".", "_json_state", "[", "'status'", "]", "=", "CONST", ".", "STATUS_LOCKOPEN", "return", "succe...
26.5
0.009132
def TruncatedNormal(shape, dtype, seed): """ Standard (mu=0, sigma=1) gaussian op with truncation above 2 sigma. """ if seed: np.random.seed(seed) n = reduce(mul, shape) r = np.empty(n, dtype=dtype_map[dtype]) idxs = np.ones(n, dtype=np.bool) while n: r[idxs] = np.random....
[ "def", "TruncatedNormal", "(", "shape", ",", "dtype", ",", "seed", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "n", "=", "reduce", "(", "mul", ",", "shape", ")", "r", "=", "np", ".", "empty", "(", "n", ",", ...
28.857143
0.002398
def get_ruptures(self, srcfilter=calc.filters.nofilter): """ :returns: a list of EBRuptures filtered by bounding box """ ebrs = [] with datastore.read(self.filename) as dstore: rupgeoms = dstore['rupgeoms'] for rec in self.rup_array: if src...
[ "def", "get_ruptures", "(", "self", ",", "srcfilter", "=", "calc", ".", "filters", ".", "nofilter", ")", ":", "ebrs", "=", "[", "]", "with", "datastore", ".", "read", "(", "self", ".", "filename", ")", "as", "dstore", ":", "rupgeoms", "=", "dstore", ...
48.826923
0.000772
def get_card(self): ''' Get card this checklist is on. ''' card_id = self.get_checklist_information().get('idCard', None) if card_id: return self.client.get_card(card_id)
[ "def", "get_card", "(", "self", ")", ":", "card_id", "=", "self", ".", "get_checklist_information", "(", ")", ".", "get", "(", "'idCard'", ",", "None", ")", "if", "card_id", ":", "return", "self", ".", "client", ".", "get_card", "(", "card_id", ")" ]
30.857143
0.009009
def celery_task_wrapper(f): """ Provides a task wrapper for celery that sets up cache and ensures that the local store is cleared after completion """ from celery.utils import fun_takes_kwargs @wraps(f, assigned=available_attrs(f)) def newf(*args, **kwargs): backend = get_backend() ...
[ "def", "celery_task_wrapper", "(", "f", ")", ":", "from", "celery", ".", "utils", "import", "fun_takes_kwargs", "@", "wraps", "(", "f", ",", "assigned", "=", "available_attrs", "(", "f", ")", ")", "def", "newf", "(", "*", "args", ",", "*", "*", "kwargs...
33.037037
0.002179
def _setup_authentication(self, username, password): '''Create the authentication object with the given credentials.''' ## BUG WORKAROUND if self.version < 1.1: # Version 1.0 had a bug when using the key parameter. # Later versions have the opposite bug (a key in the use...
[ "def", "_setup_authentication", "(", "self", ",", "username", ",", "password", ")", ":", "## BUG WORKAROUND", "if", "self", ".", "version", "<", "1.1", ":", "# Version 1.0 had a bug when using the key parameter.", "# Later versions have the opposite bug (a key in the username d...
36.741935
0.013687
def apply(self, token, previous=(None, None), next=(None, None)): """ Returns a (token, tag)-tuple for the given token, in context of the given previous and next (token, tag)-tuples. """ return [token[0], self._classifier.classify(self._v(token[0], previous, next))]
[ "def", "apply", "(", "self", ",", "token", ",", "previous", "=", "(", "None", ",", "None", ")", ",", "next", "=", "(", "None", ",", "None", ")", ")", ":", "return", "[", "token", "[", "0", "]", ",", "self", ".", "_classifier", ".", "classify", ...
59.6
0.009934
def astype(self, dtype): """Return a point of the specified dtype.""" if dtype == "int": return Point2D( int( round(self.x, 0) ), int( round(self.y, 0) ) ) elif dtype == "float": return Point2D( float(self.x), float(self.y)) else: raise(RuntimeError("I...
[ "def", "astype", "(", "self", ",", "dtype", ")", ":", "if", "dtype", "==", "\"int\"", ":", "return", "Point2D", "(", "int", "(", "round", "(", "self", ".", "x", ",", "0", ")", ")", ",", "int", "(", "round", "(", "self", ".", "y", ",", "0", ")...
43.25
0.025496
def TP0(dv, u): '''Demo problem 0 for horsetail matching, takes two input vectors of any size and returns a single output''' return np.linalg.norm(np.array(dv)) + np.linalg.norm(np.array(u))
[ "def", "TP0", "(", "dv", ",", "u", ")", ":", "return", "np", ".", "linalg", ".", "norm", "(", "np", ".", "array", "(", "dv", ")", ")", "+", "np", ".", "linalg", ".", "norm", "(", "np", ".", "array", "(", "u", ")", ")" ]
49.75
0.009901
def _parse_svc_config(self, json_dic, view = None): """ Parse a json-decoded ApiServiceConfig dictionary into a 2-tuple. @param json_dic: The json dictionary with the config data. @param view: View to materialize. @return: 2-tuple (service config dictionary, role type configurations) """ sv...
[ "def", "_parse_svc_config", "(", "self", ",", "json_dic", ",", "view", "=", "None", ")", ":", "svc_config", "=", "json_to_config", "(", "json_dic", ",", "view", "==", "'full'", ")", "rt_configs", "=", "{", "}", "if", "json_dic", ".", "has_key", "(", "ROL...
38.125
0.0096
def read_raw_samples(self, fields, thin_start=None, thin_interval=None, thin_end=None, iteration=None, walkers=None, flatten=True): """Base function for reading samples. Parameters ----------- fields : list The list of field ...
[ "def", "read_raw_samples", "(", "self", ",", "fields", ",", "thin_start", "=", "None", ",", "thin_interval", "=", "None", ",", "thin_end", "=", "None", ",", "iteration", "=", "None", ",", "walkers", "=", "None", ",", "flatten", "=", "True", ")", ":", "...
39.223881
0.001485
def patch_file(actions, tree): """Takes two filenames or streams, one with XML the other a diff""" tree = etree.parse(tree) if isinstance(actions, six.string_types): # It's a string, so it's a filename with open(actions) as f: actions = f.read() else: # We assume it'...
[ "def", "patch_file", "(", "actions", ",", "tree", ")", ":", "tree", "=", "etree", ".", "parse", "(", "tree", ")", "if", "isinstance", "(", "actions", ",", "six", ".", "string_types", ")", ":", "# It's a string, so it's a filename", "with", "open", "(", "ac...
31.2
0.002075
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string abbreviation of the team, such as 'PURDUE'. """ fields_to_include = { 'abbreviation': self.abbreviation, ...
[ "def", "dataframe", "(", "self", ")", ":", "fields_to_include", "=", "{", "'abbreviation'", ":", "self", ".", "abbreviation", ",", "'assist_percentage'", ":", "self", ".", "assist_percentage", ",", "'assists'", ":", "self", ".", "assists", ",", "'away_losses'", ...
52.433962
0.000353
def minimal_random_graph(num_vertices, seed=None, **kwargs): """Creates a connected graph with random vertex locations. Parameters ---------- num_vertices : int The number of vertices in the graph. seed : int (optional) An integer used to initialize numpy's psuedorandom number ...
[ "def", "minimal_random_graph", "(", "num_vertices", ",", "seed", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "seed", ",", "numbers", ".", "Integral", ")", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "points", ...
29.509091
0.000596
def toggle(s): """ Toggle back and forth between a name and a tuple representation. :param str s: a string which is either a text name, or a tuple-string: a string with three numbers separated by commas :returns: if the string was a text name, return a tuple. If it's a ...
[ "def", "toggle", "(", "s", ")", ":", "is_numeric", "=", "','", "in", "s", "or", "s", ".", "startswith", "(", "'0x'", ")", "or", "s", ".", "startswith", "(", "'#'", ")", "c", "=", "name_to_color", "(", "s", ")", "return", "color_to_name", "(", "c", ...
41.857143
0.001669
def Convert(self, metadata, value, token=None): """Converts a single ArtifactFilesDownloaderResult.""" for r in self.BatchConvert([(metadata, value)], token=token): yield r
[ "def", "Convert", "(", "self", ",", "metadata", ",", "value", ",", "token", "=", "None", ")", ":", "for", "r", "in", "self", ".", "BatchConvert", "(", "[", "(", "metadata", ",", "value", ")", "]", ",", "token", "=", "token", ")", ":", "yield", "r...
36.6
0.010695
def sync_update_info(self, *_): """Update home info.""" loop = asyncio.get_event_loop() task = loop.create_task(self.update_info()) loop.run_until_complete(task)
[ "def", "sync_update_info", "(", "self", ",", "*", "_", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "task", "=", "loop", ".", "create_task", "(", "self", ".", "update_info", "(", ")", ")", "loop", ".", "run_until_complete", "(", "...
37.8
0.010363
def plot_movie2d_with_matplotlib( worlds, plane='xy', marker_size=3, figsize=6, grid=True, wireframe=False, species_list=None, max_count=None, angle=None, noaxis=False, interval=0.16, repeat_delay=3000, stride=1, rotate=None, legend=True, scale=1, output=None, crf=10, bitrate='1M', **kwa...
[ "def", "plot_movie2d_with_matplotlib", "(", "worlds", ",", "plane", "=", "'xy'", ",", "marker_size", "=", "3", ",", "figsize", "=", "6", ",", "grid", "=", "True", ",", "wireframe", "=", "False", ",", "species_list", "=", "None", ",", "max_count", "=", "N...
36.882353
0.001165
def _resolve_dotted_name(dotted_name): """Returns objects from strings Deals e.g. with 'torch.nn.Softmax(dim=-1)'. Modified from palladium: https://github.com/ottogroup/palladium/blob/8a066a9a7690557d9b1b6ed54b7d1a1502ba59e3/palladium/util.py with added support for instantiated objects. """...
[ "def", "_resolve_dotted_name", "(", "dotted_name", ")", ":", "if", "not", "isinstance", "(", "dotted_name", ",", "str", ")", ":", "return", "dotted_name", "if", "'.'", "not", "in", "dotted_name", ":", "return", "dotted_name", "args", "=", "None", "params", "...
24.147059
0.001171
def _merge_prefix(self, size): """Replace the first entries in a deque of strings with a single string of up to size bytes. >>> d = collections.deque(['abc', 'de', 'fghi', 'j']) >>> _merge_prefix(d, 5); print(d) deque(['abcde', 'fghi', 'j']) Strings will be split as nec...
[ "def", "_merge_prefix", "(", "self", ",", "size", ")", ":", "if", "len", "(", "self", ".", "_buf", ")", "==", "1", "and", "len", "(", "self", ".", "_buf", "[", "0", "]", ")", "<=", "size", ":", "return", "prefix", "=", "[", "]", "remaining", "=...
34
0.001733
def ready(self): """ Add user info to ExtensibleNodeSerializer """ from nodeshot.core.nodes.base import ExtensibleNodeSerializer from .models import Vote from .serializers import (CommentRelationSerializer, ParticipationSerializer) ExtensibleNod...
[ "def", "ready", "(", "self", ")", ":", "from", "nodeshot", ".", "core", ".", "nodes", ".", "base", "import", "ExtensibleNodeSerializer", "from", ".", "models", "import", "Vote", "from", ".", "serializers", "import", "(", "CommentRelationSerializer", ",", "Part...
32.28169
0.00127
def build_tree(self, directory): '''build scene tree from images''' confile = os.path.join(directory, 'config.yml') conf = {} if os.path.exists(confile): conf = yaml.load(open(confile).read()) class node(defaultdict): name = '' parent...
[ "def", "build_tree", "(", "self", ",", "directory", ")", ":", "confile", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "'config.yml'", ")", "conf", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "confile", ")", ":", "conf...
32.391304
0.001954