text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _create_update_from_cfg(mode='create', uuid=None, vmcfg=None): ''' Create vm from configuration ''' ret = {} # write json file vmadm_json_file = __salt__['temp.file'](prefix='vmadm-') with salt.utils.files.fopen(vmadm_json_file, 'w') as vmadm_json: salt.utils.json.dump(vmcfg, vm...
[ "def", "_create_update_from_cfg", "(", "mode", "=", "'create'", ",", "uuid", "=", "None", ",", "vmcfg", "=", "None", ")", ":", "ret", "=", "{", "}", "# write json file", "vmadm_json_file", "=", "__salt__", "[", "'temp.file'", "]", "(", "prefix", "=", "'vma...
33.884615
19.153846
def add_handles(self, model, forward_handle, backward_handle): """ Add handles to all non-container layers in the model. Recursively for non-container layers """ handles_list = [] for child in model.children(): if 'nn.modules.container' in str(type(child)): ...
[ "def", "add_handles", "(", "self", ",", "model", ",", "forward_handle", ",", "backward_handle", ")", ":", "handles_list", "=", "[", "]", "for", "child", "in", "model", ".", "children", "(", ")", ":", "if", "'nn.modules.container'", "in", "str", "(", "type"...
46.846154
19.461538
def com_google_fonts_check_os2_metrics_match_hhea(ttFont): """Checking OS/2 Metrics match hhea Metrics. OS/2 and hhea vertical metric values should match. This will produce the same linespacing on Mac, GNU+Linux and Windows. Mac OS X uses the hhea values. Windows uses OS/2 or Win, depending on the OS or fsS...
[ "def", "com_google_fonts_check_os2_metrics_match_hhea", "(", "ttFont", ")", ":", "# OS/2 sTypoAscender and sTypoDescender match hhea ascent and descent", "if", "ttFont", "[", "\"OS/2\"", "]", ".", "sTypoAscender", "!=", "ttFont", "[", "\"hhea\"", "]", ".", "ascent", ":", ...
45.421053
20.631579
def mark_confirmation_as_clear(self, confirmation_id): """ Mark confirmation as clear :param confirmation_id: the confirmation id :return Response """ return self._create_put_request( resource=CONFIRMATIONS, billomat_id=confirmation_id, ...
[ "def", "mark_confirmation_as_clear", "(", "self", ",", "confirmation_id", ")", ":", "return", "self", ".", "_create_put_request", "(", "resource", "=", "CONFIRMATIONS", ",", "billomat_id", "=", "confirmation_id", ",", "command", "=", "CLEAR", ",", ")" ]
27.916667
11.416667
def create_response_adu(self, meta_data, response_pdu): """ Build response ADU from meta data and response PDU and return it. :param meta_data: A dict with meta data. :param request_pdu: A bytearray containing request PDU. :return: A bytearray containing request ADU. """ ...
[ "def", "create_response_adu", "(", "self", ",", "meta_data", ",", "response_pdu", ")", ":", "response_mbap", "=", "pack_mbap", "(", "transaction_id", "=", "meta_data", "[", "'transaction_id'", "]", ",", "protocol_id", "=", "meta_data", "[", "'protocol_id'", "]", ...
38.466667
13.533333
def freq_mag(magnitudes, completeness, max_mag, binsize=0.2, **kwargs): """ Plot a frequency-magnitude histogram and cumulative density plot. Currently this will compute a b-value, for a given completeness. B-value is computed by linear fitting to section of curve between completeness and max_mag. ...
[ "def", "freq_mag", "(", "magnitudes", ",", "completeness", ",", "max_mag", ",", "binsize", "=", "0.2", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "# Ensure magnitudes are sorted", "magnitudes", ".", "sort", "(", ")...
41.353535
18.787879
def restart_service(service_name, minimum_running_time=None): ''' Restart OpenStack service immediately, or only if it's running longer than specified value CLI Example: .. code-block:: bash salt '*' openstack_mng.restart_service neutron salt '*' openstack_mng.restart_service neut...
[ "def", "restart_service", "(", "service_name", ",", "minimum_running_time", "=", "None", ")", ":", "if", "minimum_running_time", ":", "ret_code", "=", "False", "# get system services list for interesting openstack service", "services", "=", "__salt__", "[", "'cmd.run'", "...
37.025
25.575
def syllabify(language, word) : '''Syllabifies the word, given a language configuration loaded with loadLanguage. word is either a string of phonemes from the CMU pronouncing dictionary set (with optional stress numbers after vowels), or a Python list of phonemes, e.g. "B AE1 T" or ["B", "AE1", "T"]''' ...
[ "def", "syllabify", "(", "language", ",", "word", ")", ":", "if", "type", "(", "word", ")", "==", "str", ":", "word", "=", "word", ".", "split", "(", ")", "syllables", "=", "[", "]", "# This is the returned data structure.", "internuclei", "=", "[", "]",...
32.105263
23.105263
def group_remove(groupname, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Removes a group from the Postgres server. CLI Example: .. code-block:: bash s...
[ "def", "group_remove", "(", "groupname", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "return", "_role_remove", "(",...
27.043478
15.652174
def read_metadata_by_name(self, name, metadata_key, caster=None): """Read process metadata using a named identity. :param string name: The ProcessMetadataManager identity/name (e.g. 'pantsd'). :param string metadata_key: The metadata key (e.g. 'pid'). :param func caster: A casting callable to apply to ...
[ "def", "read_metadata_by_name", "(", "self", ",", "name", ",", "metadata_key", ",", "caster", "=", "None", ")", ":", "file_path", "=", "self", ".", "_metadata_file_path", "(", "name", ",", "metadata_key", ")", "try", ":", "metadata", "=", "read_file", "(", ...
42.846154
20.615385
def delta_E( reactants, products, check_balance=True ): """ Calculate the change in energy for reactants --> products. Args: reactants (list(vasppy.Calculation): A list of vasppy.Calculation objects. The initial state. products (list(vasppy.Calculation): A list of vasppy.Calculation ob...
[ "def", "delta_E", "(", "reactants", ",", "products", ",", "check_balance", "=", "True", ")", ":", "if", "check_balance", ":", "if", "delta_stoichiometry", "(", "reactants", ",", "products", ")", "!=", "{", "}", ":", "raise", "ValueError", "(", "\"reaction is...
48.8125
32.5625
def get_nbytes(self): """ Compute and return the object size in bytes (i.e.: octets) A flat dict containing all the objects attributes is first created The size of each attribute is then estimated with np.asarray().nbytes Note : if the attribute is a tofu object, get_nbytes...
[ "def", "get_nbytes", "(", "self", ")", ":", "dd", "=", "self", ".", "to_dict", "(", ")", "dsize", "=", "dd", ".", "fromkeys", "(", "dd", ".", "keys", "(", ")", ",", "0", ")", "total", "=", "0", "for", "k", ",", "v", "in", "dd", ".", "items", ...
33.153846
19.269231
def support_autoupload_param_password(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras") autoupload_param = ET.SubElement(support, "autoupload-param") password = ET...
[ "def", "support_autoupload_param_password", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "support", "=", "ET", ".", "SubElement", "(", "config", ",", "\"support\"", ",", "xmlns", "=", "\"urn:b...
44.454545
17.454545
def list_tickets(self, open_status=True, closed_status=True): """List all tickets. :param boolean open_status: include open tickets :param boolean closed_status: include closed tickets """ mask = """mask[id, title, assignedUser[firstName, lastName], priority, c...
[ "def", "list_tickets", "(", "self", ",", "open_status", "=", "True", ",", "closed_status", "=", "True", ")", ":", "mask", "=", "\"\"\"mask[id, title, assignedUser[firstName, lastName], priority,\n createDate, lastEditDate, accountId, status, updateCount]\"\"\"", "c...
39.947368
16.947368
def get_int(self, key, default=UndefinedKey): """Return int representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: int :return: int value :type r...
[ "def", "get_int", "(", "self", ",", "key", ",", "default", "=", "UndefinedKey", ")", ":", "value", "=", "self", ".", "get", "(", "key", ",", "default", ")", "try", ":", "return", "int", "(", "value", ")", "if", "value", "is", "not", "None", "else",...
38.75
15.8125
def where(cls, **kwargs): """ Returns a generator which yields instances matching the given query arguments. For example, this would yield all :py:class:`.Project`:: Project.where() And this would yield all launch approved :py:class:`.Project`:: Projec...
[ "def", "where", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "_id", "=", "kwargs", ".", "pop", "(", "'id'", ",", "''", ")", "return", "cls", ".", "paginated_results", "(", "*", "cls", ".", "http_get", "(", "_id", ",", "params", "=", "kwargs", "...
28.375
24
def _get_val(other): """ Given a Number, a Numeric Constant or a python number return its value """ assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)) if isinstance(other, SymbolNUMBER): return other.value if isinstance(other, SymbolCONST): return other.expr.value...
[ "def", "_get_val", "(", "other", ")", ":", "assert", "isinstance", "(", "other", ",", "(", "numbers", ".", "Number", ",", "SymbolNUMBER", ",", "SymbolCONST", ")", ")", "if", "isinstance", "(", "other", ",", "SymbolNUMBER", ")", ":", "return", "other", "....
29.818182
16.636364
def add_link(self, link): """ Banana banana """ if link.id_ not in self.__links: self.__links[link.id_] = link
[ "def", "add_link", "(", "self", ",", "link", ")", ":", "if", "link", ".", "id_", "not", "in", "self", ".", "__links", ":", "self", ".", "__links", "[", "link", ".", "id_", "]", "=", "link" ]
24.833333
5.833333
def snapshot_name_to_id(name, snap_name, strict=False, runas=None): ''' Attempt to convert a snapshot name to a snapshot ID. If the name is not found an empty string is returned. If multiple snapshots share the same name, a list will be returned :param str name: Name/ID of VM whose snapsh...
[ "def", "snapshot_name_to_id", "(", "name", ",", "snap_name", ",", "strict", "=", "False", ",", "runas", "=", "None", ")", ":", "# Validate VM and snapshot names", "name", "=", "salt", ".", "utils", ".", "data", ".", "decode", "(", "name", ")", "snap_name", ...
31.089286
22.660714
def retrieveVals(self): """Retrieve values for graphs.""" fs = FSinfo(self._fshost, self._fsport, self._fspass) if self.hasGraph('fs_calls'): count = fs.getCallCount() self.setGraphVal('fs_calls', 'calls', count) if self.hasGraph('fs_channels'): count ...
[ "def", "retrieveVals", "(", "self", ")", ":", "fs", "=", "FSinfo", "(", "self", ".", "_fshost", ",", "self", ".", "_fsport", ",", "self", ".", "_fspass", ")", "if", "self", ".", "hasGraph", "(", "'fs_calls'", ")", ":", "count", "=", "fs", ".", "get...
44.111111
9.111111
def loadfile(args): '''load a log file (path given by arg)''' mestate.console.write("Loading %s...\n" % args) t0 = time.time() mlog = mavutil.mavlink_connection(args, notimestamps=False, zero_time_base=False, progress_callback=p...
[ "def", "loadfile", "(", "args", ")", ":", "mestate", ".", "console", ".", "write", "(", "\"Loading %s...\\n\"", "%", "args", ")", "t0", "=", "time", ".", "time", "(", ")", "mlog", "=", "mavutil", ".", "mavlink_connection", "(", "args", ",", "notimestamps...
34.555556
20.777778
def update_properties(self, new_properties): """ Update config properties values Property name must be equal to 'Section_option' of config property :param new_properties: dict with new properties values """ [self._update_property_from_dict(section, option, new_properties) ...
[ "def", "update_properties", "(", "self", ",", "new_properties", ")", ":", "[", "self", ".", "_update_property_from_dict", "(", "section", ",", "option", ",", "new_properties", ")", "for", "section", "in", "self", ".", "sections", "(", ")", "for", "option", "...
47.875
21.125
def get_argument_parser(): """Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx. """ file_mv = cli.file_mv desc = 'Find all runs (SRR..) ...
[ "def", "get_argument_parser", "(", ")", ":", "file_mv", "=", "cli", ".", "file_mv", "desc", "=", "'Find all runs (SRR..) associated with an SRA experiment (SRX...).'", "parser", "=", "cli", ".", "get_argument_parser", "(", "desc", "=", "desc", ")", "parser", ".", "a...
24.225806
26.967742
def lhd( dist=None, size=None, dims=1, form="randomized", iterations=100, showcorrelations=False, ): """ Create a Latin-Hypercube sample design based on distributions defined in the `scipy.stats` module Parameters ---------- dist: array_like frozen scipy.stat...
[ "def", "lhd", "(", "dist", "=", "None", ",", "size", "=", "None", ",", "dims", "=", "1", ",", "form", "=", "\"randomized\"", ",", "iterations", "=", "100", ",", "showcorrelations", "=", "False", ",", ")", ":", "assert", "dims", ">", "0", ",", "'kwa...
35.375887
18.29078
def running(name, restart=False, update=False, user=None, conf_file=None, bin_env=None, **kwargs): ''' Ensure the named service is running. name Service name as defined in the supervisor configuration file restart ...
[ "def", "running", "(", "name", ",", "restart", "=", "False", ",", "update", "=", "False", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "name", ".", "endswith", "(", ...
31.710407
20.244344
def cheby_op(G, c, signal, **kwargs): r""" Chebyshev polynomial of graph Laplacian applied to vector. Parameters ---------- G : Graph c : ndarray or list of ndarrays Chebyshev coefficients for a Filter or a Filterbank signal : ndarray Signal to filter Returns ------...
[ "def", "cheby_op", "(", "G", ",", "c", ",", "signal", ",", "*", "*", "kwargs", ")", ":", "# Handle if we do not have a list of filters but only a simple filter in cheby_coeff.", "if", "not", "isinstance", "(", "c", ",", "np", ".", "ndarray", ")", ":", "c", "=", ...
24.701754
21.140351
def receive(self,arg_formats=None): """ Recieve commands coming off the serial port. arg_formats is an optimal keyword that specifies the formats to use to parse incoming arguments. If specified here, arg_formats supercedes the formats specified on initialization. ""...
[ "def", "receive", "(", "self", ",", "arg_formats", "=", "None", ")", ":", "# Read serial input until a command separator or empty character is", "# reached ", "msg", "=", "[", "[", "]", "]", "raw_msg", "=", "[", "]", "escaped", "=", "False", "command_sep_found", "...
32.652174
18.878261
def upload(self, local_path, remote_url): """Copy a local file to an S3 location.""" bucket, key = _parse_url(remote_url) with open(local_path, 'rb') as fp: return self.call("PutObject", bucket=bucket, key=key, body=fp)
[ "def", "upload", "(", "self", ",", "local_path", ",", "remote_url", ")", ":", "bucket", ",", "key", "=", "_parse_url", "(", "remote_url", ")", "with", "open", "(", "local_path", ",", "'rb'", ")", "as", "fp", ":", "return", "self", ".", "call", "(", "...
41.833333
13.5
def register_wait(self, task, event_details=None): """ :meth:`.WSimpleTrackerStorage.register_wait` method implementation """ if self.record_wait() is True: record_type = WTrackerEvents.wait record = WSimpleTrackerStorage.Record(record_type, task, event_details=event_details) self.__store_record(record)
[ "def", "register_wait", "(", "self", ",", "task", ",", "event_details", "=", "None", ")", ":", "if", "self", ".", "record_wait", "(", ")", "is", "True", ":", "record_type", "=", "WTrackerEvents", ".", "wait", "record", "=", "WSimpleTrackerStorage", ".", "R...
44.714286
11.428571
def count_selfintersections(self): """ Get the number of self-intersections of this polygonal chain.""" # This can be solved more efficiently with sweep line counter = 0 for i, j in itertools.combinations(range(len(self.lineSegments)), 2): inters = get_segments_intersections(...
[ "def", "count_selfintersections", "(", "self", ")", ":", "# This can be solved more efficiently with sweep line", "counter", "=", "0", "for", "i", ",", "j", "in", "itertools", ".", "combinations", "(", "range", "(", "len", "(", "self", ".", "lineSegments", ")", ...
50.3
18.1
def execute_locally(self): """Runs the equivalent command locally in a blocking way.""" # Make script file # self.make_script() # Do it # with open(self.kwargs['out_file'], 'w') as handle: sh.python(self.script_path, _out=handle, _err=handle)
[ "def", "execute_locally", "(", "self", ")", ":", "# Make script file #", "self", ".", "make_script", "(", ")", "# Do it #", "with", "open", "(", "self", ".", "kwargs", "[", "'out_file'", "]", ",", "'w'", ")", "as", "handle", ":", "sh", ".", "python", "("...
41.142857
15.142857
def cleaned_selector(html): """ Clean parsel.selector. """ import parsel try: tree = _cleaned_html_tree(html) sel = parsel.Selector(root=tree, type='html') except (lxml.etree.XMLSyntaxError, lxml.etree.ParseError, lxml.etree.ParserError, UnicodeEnc...
[ "def", "cleaned_selector", "(", "html", ")", ":", "import", "parsel", "try", ":", "tree", "=", "_cleaned_html_tree", "(", "html", ")", "sel", "=", "parsel", ".", "Selector", "(", "root", "=", "tree", ",", "type", "=", "'html'", ")", "except", "(", "lxm...
28.285714
10.5
def OnUndo(self, event): """Calls the grid undo method""" statustext = undo.stack().undotext() undo.stack().undo() # Update content changed state try: post_command_event(self.grid.main_window, self.grid.ContentChangedMsg) excep...
[ "def", "OnUndo", "(", "self", ",", "event", ")", ":", "statustext", "=", "undo", ".", "stack", "(", ")", ".", "undotext", "(", ")", "undo", ".", "stack", "(", ")", ".", "undo", "(", ")", "# Update content changed state", "try", ":", "post_command_event",...
31.5
18.833333
def menu_item_remove_libraries_or_root_clicked(self, menu_item): """Removes library from hard drive after request second confirmation""" menu_item_text = self.get_menu_item_text(menu_item) logger.info("Delete item '{0}' pressed.".format(menu_item_text)) model, path = self.view.get_sele...
[ "def", "menu_item_remove_libraries_or_root_clicked", "(", "self", ",", "menu_item", ")", ":", "menu_item_text", "=", "self", ".", "get_menu_item_text", "(", "menu_item", ")", "logger", ".", "info", "(", "\"Delete item '{0}' pressed.\"", ".", "format", "(", "menu_item_...
55
29.409836
def _validate(self, sam_template, parameter_values): """ Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user """ if paramete...
[ "def", "_validate", "(", "self", ",", "sam_template", ",", "parameter_values", ")", ":", "if", "parameter_values", "is", "None", ":", "raise", "ValueError", "(", "\"`parameter_values` argument is required\"", ")", "if", "(", "\"Resources\"", "not", "in", "sam_templa...
54.2
28.542857
def create_aggregator(self, subordinates): """Creates an aggregator event source, collecting events from multiple sources. This way a single listener can listen for events coming from multiple sources, using a single blocking :py:func:`get_event` on the returned aggregator. in subordin...
[ "def", "create_aggregator", "(", "self", ",", "subordinates", ")", ":", "if", "not", "isinstance", "(", "subordinates", ",", "list", ")", ":", "raise", "TypeError", "(", "\"subordinates can only be an instance of type list\"", ")", "for", "a", "in", "subordinates", ...
44.727273
18
def add_root_family(self, family_id): """Adds a root family. arg: family_id (osid.id.Id): the ``Id`` of a family raise: AlreadyExists - ``family_id`` is already in hierarchy raise: NotFound - ``family_id`` not found raise: NullArgument - ``family_id`` is ``null`` r...
[ "def", "add_root_family", "(", "self", ",", "family_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchyDesignSession.add_root_bin_template", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session...
46.705882
18.882353
def chi_a(mass1, mass2, spin1z, spin2z): """ Returns the aligned mass-weighted spin difference from mass1, mass2, spin1z, and spin2z. """ return (spin2z * mass2 - spin1z * mass1) / (mass2 + mass1)
[ "def", "chi_a", "(", "mass1", ",", "mass2", ",", "spin1z", ",", "spin2z", ")", ":", "return", "(", "spin2z", "*", "mass2", "-", "spin1z", "*", "mass1", ")", "/", "(", "mass2", "+", "mass1", ")" ]
41.6
7.8
def mesh_other(mesh, other, samples=500, scale=False, icp_first=10, icp_final=50): """ Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest p...
[ "def", "mesh_other", "(", "mesh", ",", "other", ",", "samples", "=", "500", ",", "scale", "=", "False", ",", "icp_first", "=", "10", ",", "icp_final", "=", "50", ")", ":", "def", "key_points", "(", "m", ",", "count", ")", ":", "\"\"\"\n Return a...
33.871622
16.236486
def predict_proba(self, X): """Predict probabilities on test vectors X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input vectors, where n_samples is the number of samples and n_features is the number of features. Returns ...
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_program'", ")", ":", "raise", "NotFittedError", "(", "'SymbolicClassifier not fitted.'", ")", "X", "=", "check_array", "(", "X", ")", "_", ",", "n_feature...
36.741935
19.903226
def add_widget(self, widget): """ Add a Widget as a managed child of this Widget. The child will be automatically positioned and sized to fill the entire space inside this Widget (unless _update_child_widgets is redefined). Parameters ---------- widget :...
[ "def", "add_widget", "(", "self", ",", "widget", ")", ":", "self", ".", "_widgets", ".", "append", "(", "widget", ")", "widget", ".", "parent", "=", "self", "self", ".", "_update_child_widgets", "(", ")", "return", "widget" ]
26.318182
17.681818
def write_to_path(self,path,suffix='',format='png',overwrite=False): """ Output the data the dataframe's 'image' column to a directory structured by project->sample and named by frame Args: path (str): Where to write the directory of images suffix (str): for labeling the...
[ "def", "write_to_path", "(", "self", ",", "path", ",", "suffix", "=", "''", ",", "format", "=", "'png'", ",", "overwrite", "=", "False", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "overwrite", "is", "False", ":", "ra...
52.772727
28.772727
def difference(self, other): """ Compute the difference between this and a given range. >>> intrange(1, 10).difference(intrange(10, 15)) intrange([1,10)) >>> intrange(1, 10).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).differ...
[ "def", "difference", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "\"Unsupported type to test for difference '{.__class__.__name__}'\"", "raise", "TypeError", "(", "msg", ".", "format", "(", ...
42.54
22.42
def iter_statuses(self, number=-1, etag=None): """Iterate over the deployment statuses for this deployment. :param int number: (optional), the number of statuses to return. Default: -1, returns all statuses. :param str etag: (optional), the ETag header value from the last time ...
[ "def", "iter_statuses", "(", "self", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "i", "=", "self", ".", "_iter", "(", "int", "(", "number", ")", ",", "self", ".", "statuses_url", ",", "DeploymentStatus", ",", "etag", "=", "eta...
45.307692
16.307692
def _get_plugin_map(self, compiler, options_src, target): """Returns a map of plugin to args, for the given compiler. Only plugins that must actually be activated will be present as keys in the map. Plugins with no arguments will have an empty list as a value. Active plugins and their args will be gat...
[ "def", "_get_plugin_map", "(", "self", ",", "compiler", ",", "options_src", ",", "target", ")", ":", "# Note that we get() options and getattr() target fields and task methods,", "# so we're robust when those don't exist (or are None).", "plugins_key", "=", "'{}_plugins'", ".", "...
51.375
28.916667
def _parse_response(header_data, ignore_bad_cookies=False, ignore_bad_attributes=True): """Turn one or more lines of 'Set-Cookie:' header data into a list of dicts mapping attribute names to attribute values (as plain strings). """ cookie_dicts = [] for line in Definitions.EOL.sp...
[ "def", "_parse_response", "(", "header_data", ",", "ignore_bad_cookies", "=", "False", ",", "ignore_bad_attributes", "=", "True", ")", ":", "cookie_dicts", "=", "[", "]", "for", "line", "in", "Definitions", ".", "EOL", ".", "split", "(", "header_data", ".", ...
39.7
12.8
def pack_paths(paths, sheet_size=None): """ Pack a list of Path2D objects into a rectangle. Parameters ------------ paths: (n,) Path2D Geometry to be packed Returns ------------ packed : trimesh.path.Path2D Object containing input geometry inserted : (m,) int Inde...
[ "def", "pack_paths", "(", "paths", ",", "sheet_size", "=", "None", ")", ":", "from", ".", "util", "import", "concatenate", "if", "sheet_size", "is", "not", "None", ":", "sheet_size", "=", "np", ".", "sort", "(", "sheet_size", ")", "[", ":", ":", "-", ...
26.622222
18
def build_url_request(self): """ Consults the authenticator and grant for HTTP request parameters and headers to send with the access token request, builds the request using the stored endpoint and returns it. """ params = {} headers = {} self._authenticat...
[ "def", "build_url_request", "(", "self", ")", ":", "params", "=", "{", "}", "headers", "=", "{", "}", "self", ".", "_authenticator", "(", "params", ",", "headers", ")", "self", ".", "_grant", "(", "params", ")", "return", "Request", "(", "self", ".", ...
38.545455
15.818182
def mono(self): """ Return this instance summed to mono. If the instance is already mono, this is a no-op. """ if self.channels == 1: return self x = self.sum(axis=1) * 0.5 y = x * 0.5 return AudioSamples(y, self.samplerate)
[ "def", "mono", "(", "self", ")", ":", "if", "self", ".", "channels", "==", "1", ":", "return", "self", "x", "=", "self", ".", "sum", "(", "axis", "=", "1", ")", "*", "0.5", "y", "=", "x", "*", "0.5", "return", "AudioSamples", "(", "y", ",", "...
29.2
14
def find_page_of_state_m(self, state_m): """Return the identifier and page of a given state model :param state_m: The state model to be searched :return: page containing the state and the state_identifier """ for state_identifier, page_info in list(self.tabs.items()): ...
[ "def", "find_page_of_state_m", "(", "self", ",", "state_m", ")", ":", "for", "state_identifier", ",", "page_info", "in", "list", "(", "self", ".", "tabs", ".", "items", "(", ")", ")", ":", "if", "page_info", "[", "'state_m'", "]", "is", "state_m", ":", ...
43.3
14.8
def set_empty_symbol(self): """Resets the context, retaining the fields that make it a child of its container (``container``, ``queue``, ``depth``, ``whence``), and sets an empty ``pending_symbol``. This is useful when an empty quoted symbol immediately follows a long string. """ ...
[ "def", "set_empty_symbol", "(", "self", ")", ":", "self", ".", "field_name", "=", "None", "self", ".", "annotations", "=", "None", "self", ".", "ion_type", "=", "None", "self", ".", "set_pending_symbol", "(", "CodePointArray", "(", ")", ")", "return", "sel...
42.272727
17.090909
def _get_point_rates(self, source, mmin, mmax=np.inf): """ Adds the rates for a point source :param source: Point source as instance of :class: openquake.hazardlib.source.point.PointSource :param float mmin: Minimum Magnitude :param float mmax...
[ "def", "_get_point_rates", "(", "self", ",", "source", ",", "mmin", ",", "mmax", "=", "np", ".", "inf", ")", ":", "xloc", ",", "yloc", "=", "self", ".", "_get_point_location", "(", "source", ".", "location", ")", "if", "(", "xloc", "is", "None", ")",...
39.464286
15.25
def has_basal_dendrite(neuron, min_number=1, treefun=_read_neurite_type): '''Check if a neuron has basal dendrites Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of basal dendrites required treefun: Optional function to calculate the tree type of neuron'...
[ "def", "has_basal_dendrite", "(", "neuron", ",", "min_number", "=", "1", ",", "treefun", "=", "_read_neurite_type", ")", ":", "types", "=", "[", "treefun", "(", "n", ")", "for", "n", "in", "neuron", ".", "neurites", "]", "return", "CheckResult", "(", "ty...
36.214286
24.785714
def makeAggShkDstn(self): ''' Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount. Parameters ---------- None Returns ------- None ''' ...
[ "def", "makeAggShkDstn", "(", "self", ")", ":", "self", ".", "TranShkAggDstn", "=", "approxMeanOneLognormal", "(", "sigma", "=", "self", ".", "TranShkAggStd", ",", "N", "=", "self", ".", "TranShkAggCount", ")", "self", ".", "PermShkAggDstn", "=", "approxMeanOn...
37
34.875
def call(self, task, decorators=None): """ Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's contained in 'decorators' list :type task: instance of Task class :param decorators: list of TaskDecorator's / Tas...
[ "def", "call", "(", "self", ",", "task", ",", "decorators", "=", "None", ")", ":", "if", "decorators", "is", "None", ":", "decorators", "=", "[", "]", "task", "=", "self", ".", "apply_task_decorators", "(", "task", ",", "decorators", ")", "data", "=", ...
34.807692
17.961538
def select(self, idx): """ Return a new DictArray containing only the indexed values """ data = {} for k in self.data: data[k] = self.data[k][idx] return self._return(data=data)
[ "def", "select", "(", "self", ",", "idx", ")", ":", "data", "=", "{", "}", "for", "k", "in", "self", ".", "data", ":", "data", "[", "k", "]", "=", "self", ".", "data", "[", "k", "]", "[", "idx", "]", "return", "self", ".", "_return", "(", "...
31.857143
8.142857
def plot_envelope(M, C, mesh): """ plot_envelope(M,C,mesh) plots the pointwise mean +/- sd envelope defined by M and C along their base mesh. :Arguments: - `M`: A Gaussian process mean. - `C`: A Gaussian process covariance - `mesh`: The mesh on which to evaluate ...
[ "def", "plot_envelope", "(", "M", ",", "C", ",", "mesh", ")", ":", "try", ":", "from", "pylab", "import", "fill", ",", "plot", ",", "clf", ",", "axis", "x", "=", "concatenate", "(", "(", "mesh", ",", "mesh", "[", ":", ":", "-", "1", "]", ")", ...
25.266667
20.8
def _kraus_to_choi(data, input_dim, output_dim): """Transform Kraus representation to Choi representation.""" choi = 0 kraus_l, kraus_r = data if kraus_r is None: for i in kraus_l: vec = i.ravel(order='F') choi += np.outer(vec, vec.conj()) else: for i, j in zi...
[ "def", "_kraus_to_choi", "(", "data", ",", "input_dim", ",", "output_dim", ")", ":", "choi", "=", "0", "kraus_l", ",", "kraus_r", "=", "data", "if", "kraus_r", "is", "None", ":", "for", "i", "in", "kraus_l", ":", "vec", "=", "i", ".", "ravel", "(", ...
35.083333
15.25
def _threeDdot_simple(M,a): "Return Ma, where M is a 3x3 transformation matrix, for each pixel" result = np.empty(a.shape,dtype=a.dtype) for i in range(a.shape[0]): for j in range(a.shape[1]): A = np.array([a[i,j,0],a[i,j,1],a[i,j,2]]).reshape((3,1)) L = np.dot(M,A) ...
[ "def", "_threeDdot_simple", "(", "M", ",", "a", ")", ":", "result", "=", "np", ".", "empty", "(", "a", ".", "shape", ",", "dtype", "=", "a", ".", "dtype", ")", "for", "i", "in", "range", "(", "a", ".", "shape", "[", "0", "]", ")", ":", "for",...
29.785714
19.357143
def format_title(self): def asciify(_title): _title = unicodedata.normalize('NFD', unicode(_title)) ascii = True out = [] ok = u"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM- '," for ch in _title: if ch in ok: ...
[ "def", "format_title", "(", "self", ")", ":", "def", "asciify", "(", "_title", ")", ":", "_title", "=", "unicodedata", ".", "normalize", "(", "'NFD'", ",", "unicode", "(", "_title", ")", ")", "ascii", "=", "True", "out", "=", "[", "]", "ok", "=", "...
44.967742
17.935484
def _cleanup(lst): ''' Return a list of non-empty dictionaries. ''' clean = [] for ele in lst: if ele and isinstance(ele, dict): clean.append(ele) return clean
[ "def", "_cleanup", "(", "lst", ")", ":", "clean", "=", "[", "]", "for", "ele", "in", "lst", ":", "if", "ele", "and", "isinstance", "(", "ele", ",", "dict", ")", ":", "clean", ".", "append", "(", "ele", ")", "return", "clean" ]
21.666667
19.444444
def round(self, ndigits=0): """ Rounds the amount using the current ``Decimal`` rounding algorithm. """ if ndigits is None: ndigits = 0 return self.__class__( amount=self.amount.quantize(Decimal('1e' + str(-ndigits))), currency=self.currency)
[ "def", "round", "(", "self", ",", "ndigits", "=", "0", ")", ":", "if", "ndigits", "is", "None", ":", "ndigits", "=", "0", "return", "self", ".", "__class__", "(", "amount", "=", "self", ".", "amount", ".", "quantize", "(", "Decimal", "(", "'1e'", "...
34.444444
13.777778
def main(args=None): """Start application.""" parser = _parser() # Python 2 will error 'too few arguments' if no subcommand is supplied. # No such error occurs in Python 3, which makes it feasible to check # whether a subcommand was provided (displaying a help message if not). # argparse intern...
[ "def", "main", "(", "args", "=", "None", ")", ":", "parser", "=", "_parser", "(", ")", "# Python 2 will error 'too few arguments' if no subcommand is supplied.", "# No such error occurs in Python 3, which makes it feasible to check", "# whether a subcommand was provided (displaying a h...
35.368421
23.263158
def __check_equals(self, query): """Check if the query results on the two databases are equals. Returns ------- bool True if the results are the same False otherwise list A list with the differences """ ...
[ "def", "__check_equals", "(", "self", ",", "query", ")", ":", "self", ".", "cur1", ".", "execute", "(", "query", ")", "records1", "=", "self", ".", "cur1", ".", "fetchall", "(", ")", "self", ".", "cur2", ".", "execute", "(", "query", ")", "records2",...
28.575758
14.666667
def get_current_frame_data(self): """ Get all date about the current execution frame :return: current frame data :rtype: dict :raises AttributeError: if the debugger does hold any execution frame. :raises IOError: if source code for the current execution frame is not acc...
[ "def", "get_current_frame_data", "(", "self", ")", ":", "filename", "=", "self", ".", "curframe", ".", "f_code", ".", "co_filename", "lines", ",", "start_line", "=", "inspect", ".", "findsource", "(", "self", ".", "curframe", ")", "if", "sys", ".", "versio...
42.227273
16.863636
def _g_a (self, x, a, b, s): """Asymmetric width term x: frequency coordinate a: peak position b: half width s: asymmetry parameter """ return 2*b/(1.0+np.exp(s*(x-a)))
[ "def", "_g_a", "(", "self", ",", "x", ",", "a", ",", "b", ",", "s", ")", ":", "return", "2", "*", "b", "/", "(", "1.0", "+", "np", ".", "exp", "(", "s", "*", "(", "x", "-", "a", ")", ")", ")" ]
27.125
8.25
def _get_token(url, email, secret_key): ''' retrieve the auth_token from nsot :param url: str :param email: str :param secret_key: str :return: str ''' url = urlparse.urljoin(url, 'authenticate') data_dict = {"email": email, "secret_key": secret_key} query = salt.utils.http.quer...
[ "def", "_get_token", "(", "url", ",", "email", ",", "secret_key", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "url", ",", "'authenticate'", ")", "data_dict", "=", "{", "\"email\"", ":", "email", ",", "\"secret_key\"", ":", "secret_key", "}", "...
35.285714
21.571429
def username(anon, obj, field, val): """ Generates a random username """ return anon.faker.user_name(field=field)
[ "def", "username", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "user_name", "(", "field", "=", "field", ")" ]
25
3.4
def find(self, item): """ Return the smallest i such that i is the index of an element that wholly contains item. Raises ValueError if no such element exists. Does not require the segmentlist to be coalesced. """ for i, seg in enumerate(self): if item in seg: return i raise ValueError(item)
[ "def", "find", "(", "self", ",", "item", ")", ":", "for", "i", ",", "seg", "in", "enumerate", "(", "self", ")", ":", "if", "item", "in", "seg", ":", "return", "i", "raise", "ValueError", "(", "item", ")" ]
27.818182
15.636364
def cleanup_custom_options(id, weakref=None): """ Cleans up unused custom trees if all objects referencing the custom id have been garbage collected or tree is otherwise unreferenced. """ try: if Store._options_context: return weakrefs = Store._weakrefs.get(id, []) ...
[ "def", "cleanup_custom_options", "(", "id", ",", "weakref", "=", "None", ")", ":", "try", ":", "if", "Store", ".", "_options_context", ":", "return", "weakrefs", "=", "Store", ".", "_weakrefs", ".", "get", "(", "id", ",", "[", "]", ")", "if", "weakref"...
35.8
13.666667
def write(self, outfile, encoding): u""" Writes the feed to the specified file in the specified encoding. """ cal = Calendar() cal.add('version', '2.0') cal.add('calscale', 'GREGORIAN') for ifield, efield in FEED_FIELD_MAP: val = self.feed.get...
[ "def", "write", "(", "self", ",", "outfile", ",", "encoding", ")", ":", "cal", "=", "Calendar", "(", ")", "cal", ".", "add", "(", "'version'", ",", "'2.0'", ")", "cal", ".", "add", "(", "'calscale'", ",", "'GREGORIAN'", ")", "for", "ifield", ",", "...
27.55
12.2
def policy_definitions_list(hide_builtin=False, **kwargs): ''' .. versionadded:: 2019.2.0 List all policy definitions for a subscription. :param hide_builtin: Boolean which will filter out BuiltIn policy definitions from the result. CLI Example: .. code-block:: bash salt-call azurea...
[ "def", "policy_definitions_list", "(", "hide_builtin", "=", "False", ",", "*", "*", "kwargs", ")", ":", "result", "=", "{", "}", "polconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'policy'", ",", "*", "*", "kwargs", ")", "try", ":", "p...
30.392857
28.75
def optimizeAngle(angle): """ Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[. """ # First, we put the new ang...
[ "def", "optimizeAngle", "(", "angle", ")", ":", "# First, we put the new angle in the range ]-360, 360[.", "# The modulo operator yields results with the sign of the", "# divisor, so for negative dividends, we preserve the sign", "# of the angle.", "if", "angle", "<", "0", ":", "angle"...
36.875
18.958333
def convert_sbml_model(model): """Convert raw SBML model to extended model. Args: model: :class:`NativeModel` obtained from :class:`SBMLReader`. """ biomass_reactions = set() for reaction in model.reactions: # Extract limits if reaction.id not in model.limits: lo...
[ "def", "convert_sbml_model", "(", "model", ")", ":", "biomass_reactions", "=", "set", "(", ")", "for", "reaction", "in", "model", ".", "reactions", ":", "# Extract limits", "if", "reaction", ".", "id", "not", "in", "model", ".", "limits", ":", "lower", ","...
34.90625
17.1875
def set_alternative(self, experiment_name, alternative): """Explicitly set the alternative the user is enrolled in for the specified experiment. This allows you to change a user between alternatives. The user and goal counts for the new alternative will be increment, but those for the old one w...
[ "def", "set_alternative", "(", "self", ",", "experiment_name", ",", "alternative", ")", ":", "experiment", "=", "experiment_manager", ".", "get_experiment", "(", "experiment_name", ")", "if", "experiment", ":", "self", ".", "_set_enrollment", "(", "experiment", ",...
67
27.111111
def get_char(prompt=None): """ Read a line of text from standard input and return the equivalent char; if text is not a single char, user is prompted to retry. If line can't be read, return None. """ while True: s = get_string(prompt) if s is None: return None ...
[ "def", "get_char", "(", "prompt", "=", "None", ")", ":", "while", "True", ":", "s", "=", "get_string", "(", "prompt", ")", "if", "s", "is", "None", ":", "return", "None", "if", "len", "(", "s", ")", "==", "1", ":", "return", "s", "[", "0", "]",...
29.0625
17.1875
def skipDryRun(logger, dryRun, level=logging.DEBUG): """ Return logging function. When logging function called, will return True if action should be skipped. Log will indicate if skipped because of dry run. """ # This is an undocumented "feature" of logging module: # logging.log() requires a nu...
[ "def", "skipDryRun", "(", "logger", ",", "dryRun", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "# This is an undocumented \"feature\" of logging module:", "# logging.log() requires a numeric level", "# logging.getLevelName() maps names to numbers", "if", "not", "isins...
38.6
15.866667
def parse_form(self, req, name, field): """Pull a form value from the request. .. note:: The request stream will be read and left at EOF. """ form = self._cache.get("form") if form is None: self._cache["form"] = form = parse_form_body(req) return...
[ "def", "parse_form", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "form", "=", "self", ".", "_cache", ".", "get", "(", "\"form\"", ")", "if", "form", "is", "None", ":", "self", ".", "_cache", "[", "\"form\"", "]", "=", "form", "=...
31.272727
15.545455
def reftrack_element_data(rt, role): """Return the data for the element (e.g. the Asset or Shot) :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data fo...
[ "def", "reftrack_element_data", "(", "rt", ",", "role", ")", ":", "element", "=", "rt", ".", "get_element", "(", ")", "if", "element", "is", "None", ":", "return", "if", "role", "==", "QtCore", ".", "Qt", ".", "DisplayRole", "or", "role", "==", "QtCore...
33.75
14.5
def zlexcount(self, name, min, max): """ Return the number of items in the sorted set between the lexicographical range ``min`` and ``max``. :param name: str the name of the redis key :param min: int or '-inf' :param max: int or '+inf' :return: Future() ...
[ "def", "zlexcount", "(", "self", ",", "name", ",", "min", ",", "max", ")", ":", "with", "self", ".", "pipe", "as", "pipe", ":", "return", "pipe", ".", "zlexcount", "(", "self", ".", "redis_key", "(", "name", ")", ",", "min", ",", "max", ")" ]
34.416667
12.916667
def gevent_monkey_patch_report(self): """ Report effective gevent monkey patching on the logs. """ try: import gevent.socket import socket if gevent.socket.socket is socket.socket: self.log("gevent monkey patching is active") ...
[ "def", "gevent_monkey_patch_report", "(", "self", ")", ":", "try", ":", "import", "gevent", ".", "socket", "import", "socket", "if", "gevent", ".", "socket", ".", "socket", "is", "socket", ".", "socket", ":", "self", ".", "log", "(", "\"gevent monkey patchin...
33.625
17.625
def draw_cross(self, position, color=(255, 0, 0), radius=4): """Draw a cross on the canvas. :param position: (row, col) tuple :param color: RGB tuple :param radius: radius of the cross (int) """ y, x = position for xmod in np.arange(-radius, radius+1, 1): ...
[ "def", "draw_cross", "(", "self", ",", "position", ",", "color", "=", "(", "255", ",", "0", ",", "0", ")", ",", "radius", "=", "4", ")", ":", "y", ",", "x", "=", "position", "for", "xmod", "in", "np", ".", "arange", "(", "-", "radius", ",", "...
38.818182
12.045455
def org_describe(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/describe API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Fdescribe """ return DXHTTPRequest('/%s/describe' % object_id, in...
[ "def", "org_describe", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/describe'", "%", "object_id", ",", "input_params", ",", "always_retry", "=...
51.714286
32.571429
def generate_json_schema(cls, schema, context=DEFAULT_DICT): """Generate a JSON Schema from a Marshmallow schema. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_...
[ "def", "generate_json_schema", "(", "cls", ",", "schema", ",", "context", "=", "DEFAULT_DICT", ")", ":", "schema", "=", "cls", ".", "_get_schema", "(", "schema", ")", "# Generate the JSON Schema", "return", "cls", "(", "context", "=", "context", ")", ".", "d...
36.473684
21.789474
def clear(self, asset_manager_id): """ This method deletes all the data for an asset_manager_id. It should be used with extreme caution. In production it is almost always better to Inactivate rather than delete. """ self.logger.info('Clear Market Data - Asset Manager: %s', asset...
[ "def", "clear", "(", "self", ",", "asset_manager_id", ")", ":", "self", ".", "logger", ".", "info", "(", "'Clear Market Data - Asset Manager: %s'", ",", "asset_manager_id", ")", "url", "=", "'%s/clear/%s'", "%", "(", "self", ".", "endpoint", ",", "asset_manager_...
54.9375
18.1875
def build_flat_msg(self, id=None, msg=None): """build_flat_msg :param id: unique id for this message :param msg: message dictionary to flatten """ flat_msg = {} if not id: log.error("Please pass in an id") ...
[ "def", "build_flat_msg", "(", "self", ",", "id", "=", "None", ",", "msg", "=", "None", ")", ":", "flat_msg", "=", "{", "}", "if", "not", "id", ":", "log", ".", "error", "(", "\"Please pass in an id\"", ")", "return", "None", "if", "not", "msg", ":", ...
36.556962
13.721519
def fisher_by_pol(data): """ input: as in dolnp (list of dictionaries with 'dec' and 'inc') description: do fisher mean after splitting data into two polarity domains. output: three dictionaries: 'A'= polarity 'A' 'B = polarity 'B' 'ALL'= switching polarity of 'B' directions, ...
[ "def", "fisher_by_pol", "(", "data", ")", ":", "FisherByPoles", "=", "{", "}", "DIblock", ",", "nameblock", ",", "locblock", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "rec", "in", "data", ":", "if", "'dec'", "in", "list", "(", "rec", "....
41.716216
12.824324
def constrain_opts(self, constraint_dict, options): """ Return result of constraints and options against a template """ constraints = {} for constraint in constraint_dict: if constraint != 'self': if (constraint_dict[constraint] or constraint_d...
[ "def", "constrain_opts", "(", "self", ",", "constraint_dict", ",", "options", ")", ":", "constraints", "=", "{", "}", "for", "constraint", "in", "constraint_dict", ":", "if", "constraint", "!=", "'self'", ":", "if", "(", "constraint_dict", "[", "constraint", ...
52.272727
13.272727
def douglas_peucker(*args, df: pd.DataFrame=None, tolerance: float, x='x', y='y', z=None, z_factor: float = 3.048, lat=None, lon=None) -> np.ndarray: """Ramer-Douglas-Peucker algorithm for 2D/3D trajectories. Simplify a trajectory by keeping the points further away from ...
[ "def", "douglas_peucker", "(", "*", "args", ",", "df", ":", "pd", ".", "DataFrame", "=", "None", ",", "tolerance", ":", "float", ",", "x", "=", "'x'", ",", "y", "=", "'y'", ",", "z", "=", "None", ",", "z_factor", ":", "float", "=", "3.048", ",", ...
41.121212
24.075758
def sql_fingerprint(query, hide_columns=True): """ Simplify a query, taking away exact values and fields selected. Imperfect but better than super explicit, value-dependent queries. """ parsed_query = parse(query)[0] sql_recursively_simplify(parsed_query, hide_columns=hide_columns) return s...
[ "def", "sql_fingerprint", "(", "query", ",", "hide_columns", "=", "True", ")", ":", "parsed_query", "=", "parse", "(", "query", ")", "[", "0", "]", "sql_recursively_simplify", "(", "parsed_query", ",", "hide_columns", "=", "hide_columns", ")", "return", "str",...
36.444444
16.666667
def assertEqual(first, second, message=None): """ Assert that first equals second. :param first: First part to evaluate :param second: Second part to evaluate :param message: Failure message :raises: TestStepFail if not first == second """ if not first == second: raise TestStepF...
[ "def", "assertEqual", "(", "first", ",", "second", ",", "message", "=", "None", ")", ":", "if", "not", "first", "==", "second", ":", "raise", "TestStepFail", "(", "format_message", "(", "message", ")", "if", "message", "is", "not", "None", "else", "\"Ass...
39.230769
15.846154
def get(self, table='', start=0, limit=0, order=None, where=None): """ Get a list of stat items :param table: str database table name :param start: int :param limit: int :param order: list|tuple :param where: list|tuple :return: """ parame...
[ "def", "get", "(", "self", ",", "table", "=", "''", ",", "start", "=", "0", ",", "limit", "=", "0", ",", "order", "=", "None", ",", "where", "=", "None", ")", ":", "parameters", "=", "{", "}", "args", "=", "[", "'start'", ",", "'limit'", ",", ...
28.64
15.28
def _handle_calls(self, service_obj, calls): """ Performs method calls on service object """ for call in calls: method = call.get('method') args = call.get('args', []) kwargs = call.get('kwargs', {}) _check_type('args', args, list) _check_typ...
[ "def", "_handle_calls", "(", "self", ",", "service_obj", ",", "calls", ")", ":", "for", "call", "in", "calls", ":", "method", "=", "call", ".", "get", "(", "'method'", ")", "args", "=", "call", ".", "get", "(", "'args'", ",", "[", "]", ")", "kwargs...
35.578947
16.789474
def visit_assign(self, node): """return an astroid.Assign node as string""" lhs = " = ".join(n.accept(self) for n in node.targets) return "%s = %s" % (lhs, node.value.accept(self))
[ "def", "visit_assign", "(", "self", ",", "node", ")", ":", "lhs", "=", "\" = \"", ".", "join", "(", "n", ".", "accept", "(", "self", ")", "for", "n", "in", "node", ".", "targets", ")", "return", "\"%s = %s\"", "%", "(", "lhs", ",", "node", ".", "...
50.25
12.5
def _resolve_plt(self, addr, irsb, indir_jump): """ Determine if the IRSB at the given address is a PLT stub. If it is, concretely execute the basic block to resolve the jump target. :param int addr: Address of the block. :param irsb: The basic ...
[ "def", "_resolve_plt", "(", "self", ",", "addr", ",", "irsb", ",", "indir_jump", ")", ":", "# is the address identified by CLE as a PLT stub?", "if", "self", ".", "project", ".", "loader", ".", "all_elf_objects", ":", "# restrict this heuristics to ELF files only", "if"...
48.923077
23.897436
def heronian_mean(nums): r"""Return Heronian mean. The Heronian mean is: :math:`\frac{\sum\limits_{i, j}\sqrt{{x_i \cdot x_j}}} {|nums| \cdot \frac{|nums| + 1}{2}}` for :math:`j \ge i` Cf. https://en.wikipedia.org/wiki/Heronian_mean Parameters ---------- nums : list A seri...
[ "def", "heronian_mean", "(", "nums", ")", ":", "mag", "=", "len", "(", "nums", ")", "rolling_sum", "=", "0", "for", "i", "in", "range", "(", "mag", ")", ":", "for", "j", "in", "range", "(", "i", ",", "mag", ")", ":", "if", "nums", "[", "i", "...
22.179487
19.358974
def upload_file(self, container, file_or_path, obj_name=None, content_type=None, etag=None, content_encoding=None, ttl=None, content_length=None, return_none=False, headers=None, metadata=None, extra_info=None): """ Uploads the specified file to the container. If no n...
[ "def", "upload_file", "(", "self", ",", "container", ",", "file_or_path", ",", "obj_name", "=", "None", ",", "content_type", "=", "None", ",", "etag", "=", "None", ",", "content_encoding", "=", "None", ",", "ttl", "=", "None", ",", "content_length", "=", ...
53.75
28.821429
def get_trade_fee(self, **params): """Get trade fee. https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#trade-fee-user_data :param symbol: optional :type symbol: str :param recvWindow: the number of milliseconds the request is valid for ...
[ "def", "get_trade_fee", "(", "self", ",", "*", "*", "params", ")", ":", "res", "=", "self", ".", "_request_withdraw_api", "(", "'get'", ",", "'tradeFee.html'", ",", "True", ",", "data", "=", "params", ")", "if", "not", "res", "[", "'success'", "]", ":"...
29.055556
19.444444
def load_fits(self, filepath): """ Load a FITS file into the viewer. """ image = AstroImage.AstroImage(logger=self.logger) image.load_file(filepath) self.set_image(image)
[ "def", "load_fits", "(", "self", ",", "filepath", ")", ":", "image", "=", "AstroImage", ".", "AstroImage", "(", "logger", "=", "self", ".", "logger", ")", "image", ".", "load_file", "(", "filepath", ")", "self", ".", "set_image", "(", "image", ")" ]
26.5
10.75
def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0): """Patched 'getaddrinfo' with default family IPv4 (enabled by settings IPV4_ONLY=True)""" return orig_getaddrinfo(host, port, family, socktype, proto, flags)
[ "def", "getaddrinfo_wrapper", "(", "host", ",", "port", ",", "family", "=", "socket", ".", "AF_INET", ",", "socktype", "=", "0", ",", "proto", "=", "0", ",", "flags", "=", "0", ")", ":", "return", "orig_getaddrinfo", "(", "host", ",", "port", ",", "f...
84.333333
26.666667