text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def callback(status, message, job, result, exception, stacktrace): """Example callback function. :param status: Job status. Possible values are "invalid" (job could not be deserialized or was malformed), "failure" (job raised an exception), "timeout" (job timed out), or "success" (job finished ...
[ "def", "callback", "(", "status", ",", "message", ",", "job", ",", "result", ",", "exception", ",", "stacktrace", ")", ":", "assert", "status", "in", "[", "'invalid'", ",", "'success'", ",", "'timeout'", ",", "'failure'", "]", "assert", "isinstance", "(", ...
35.113636
0.00063
def orient_import2(self, event): """ initialize window to import an AzDip format file into the working directory """ pmag_menu_dialogs.ImportAzDipFile(self.parent, self.parent.WD)
[ "def", "orient_import2", "(", "self", ",", "event", ")", ":", "pmag_menu_dialogs", ".", "ImportAzDipFile", "(", "self", ".", "parent", ",", "self", ".", "parent", ".", "WD", ")" ]
41.4
0.014218
def create(self,image_path, size=1024, sudo=False): '''create will create a a new image Parameters ========== image_path: full path to image size: image sizein MiB, default is 1024MiB filesystem: supported file systems ext3/ext4 (ext[2/3]: default ext3 ''' f...
[ "def", "create", "(", "self", ",", "image_path", ",", "size", "=", "1024", ",", "sudo", "=", "False", ")", ":", "from", "spython", ".", "utils", "import", "check_install", "check_install", "(", ")", "cmd", "=", "self", ".", "init_command", "(", "'image.c...
26.833333
0.010495
def validate_polygon(obj): """ Make sure an input can be returned as a valid polygon. Parameters ------------- obj : shapely.geometry.Polygon, str (wkb), or (n, 2) float Object which might be a polygon Returns ------------ polygon : shapely.geometry.Polygon Valid polygon ob...
[ "def", "validate_polygon", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "Polygon", ")", ":", "polygon", "=", "obj", "elif", "util", ".", "is_shape", "(", "obj", ",", "(", "-", "1", ",", "2", ")", ")", ":", "polygon", "=", "Polygon", ...
24.90625
0.001208
def count(keys, axis=semantics.axis_default): """count the number of times each key occurs in the input set Arguments --------- keys : indexable object Returns ------- unique : ndarray, [groups, ...] unique keys count : ndarray, [groups], int the number of times each ke...
[ "def", "count", "(", "keys", ",", "axis", "=", "semantics", ".", "axis_default", ")", ":", "index", "=", "as_index", "(", "keys", ",", "axis", ",", "base", "=", "True", ")", "return", "index", ".", "unique", ",", "index", ".", "count" ]
26.142857
0.001757
def _futureExceptions(self, request): """ Returns all future extra info, cancellations and postponements created for this recurring event """ retval = [] # We know all future exception dates are in the parent time zone myToday = timezone.localdate(timezone=self.tz...
[ "def", "_futureExceptions", "(", "self", ",", "request", ")", ":", "retval", "=", "[", "]", "# We know all future exception dates are in the parent time zone", "myToday", "=", "timezone", ".", "localdate", "(", "timezone", "=", "self", ".", "tz", ")", "for", "extr...
44.636364
0.001994
def PintPars(datablock, araiblock, zijdblock, start, end, accept, **kwargs): """ calculate the paleointensity magic parameters make some definitions """ if 'version' in list(kwargs.keys()) and kwargs['version'] == 3: meth_key = 'method_codes' beta_key = 'int_b_beta' temp_key, m...
[ "def", "PintPars", "(", "datablock", ",", "araiblock", ",", "zijdblock", ",", "start", ",", "end", ",", "accept", ",", "*", "*", "kwargs", ")", ":", "if", "'version'", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "and", "kwargs", "[", "...
39.671533
0.001122
def create_calc_dh_dv(estimator): """ Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the index. Parameters ---------- estimator : an instance of the estimation.LogitTypeEstimator class. ...
[ "def", "create_calc_dh_dv", "(", "estimator", ")", ":", "dh_dv", "=", "diags", "(", "np", ".", "ones", "(", "estimator", ".", "design", ".", "shape", "[", "0", "]", ")", ",", "0", ",", "format", "=", "'csr'", ")", "# Create a function that will take in the...
44.964286
0.000778
def holiday_day(self, value=None): """Corresponds to IDD Field `holiday_day` Args: value (str): value for IDD Field `holiday_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
[ "def", "holiday_day", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str ...
35.086957
0.002413
def from_dict(data, ctx): """ Instantiate a new OrderClientExtensionsModifyRejectTransaction from a dict (generally from loading a JSON response). The data used to instantiate the OrderClientExtensionsModifyRejectTransaction is a shallow copy of the dict passed in, with any compl...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'clientExtensionsModify'", ")", "is", "not", "None", ":", "data", "[", "'clientExtensionsModify'", "]", "=", "ctx", ".", ...
39.708333
0.002049
def set_primary_contact(self, email): """assigns the primary contact for this client""" params = {"email": email} response = self._put(self.uri_for('primarycontact'), params=params) return json_to_py(response)
[ "def", "set_primary_contact", "(", "self", ",", "email", ")", ":", "params", "=", "{", "\"email\"", ":", "email", "}", "response", "=", "self", ".", "_put", "(", "self", ".", "uri_for", "(", "'primarycontact'", ")", ",", "params", "=", "params", ")", "...
47.4
0.008299
def currency_to_satoshi(amount, currency): """Converts a given amount of currency to the equivalent number of satoshi. The amount can be either an int, float, or string as long as it is a valid input to :py:class:`decimal.Decimal`. :param amount: The quantity of currency. :param currency: One of th...
[ "def", "currency_to_satoshi", "(", "amount", ",", "currency", ")", ":", "satoshis", "=", "EXCHANGE_RATES", "[", "currency", "]", "(", ")", "return", "int", "(", "satoshis", "*", "Decimal", "(", "amount", ")", ")" ]
40
0.002037
def gender(self): ''' Tries to scrape the correct gender for a given word from wordreference.com ''' elements = self.tree.xpath('//table[@class="WRD"]') if len(elements): elements = self.tree.xpath('//table[@class="WRD"]')[0] if len(elements): if '/iten/' in self.page.url: elements = elements.xpat...
[ "def", "gender", "(", "self", ")", ":", "elements", "=", "self", ".", "tree", ".", "xpath", "(", "'//table[@class=\"WRD\"]'", ")", "if", "len", "(", "elements", ")", ":", "elements", "=", "self", ".", "tree", ".", "xpath", "(", "'//table[@class=\"WRD\"]'",...
38.052632
0.026991
def input_object(prompt_text, cast = None, default = None, prompt_ext = ': ', castarg = [], castkwarg = {}): """Gets input from the command line and validates it. prompt_text A string. Used to prompt the user. Do not include a trailing space. prompt_ext ...
[ "def", "input_object", "(", "prompt_text", ",", "cast", "=", "None", ",", "default", "=", "None", ",", "prompt_ext", "=", "': '", ",", "castarg", "=", "[", "]", ",", "castkwarg", "=", "{", "}", ")", ":", "while", "True", ":", "stdout", ".", "write", ...
41.155556
0.013186
def compile(self, program: Program, to_native_gates: bool = True, optimize: bool = True) -> Union[BinaryExecutableResponse, PyQuilExecutableResponse]: """ A high-level interface to program compilation. Compilation currently consists of two stages. Please see the ...
[ "def", "compile", "(", "self", ",", "program", ":", "Program", ",", "to_native_gates", ":", "bool", "=", "True", ",", "optimize", ":", "bool", "=", "True", ")", "->", "Union", "[", "BinaryExecutableResponse", ",", "PyQuilExecutableResponse", "]", ":", "flags...
47.37037
0.009195
def wrap(self, filename, boxes=None): """Create a new JP2/JPX file wrapped in a new set of JP2 boxes. This method is primarily aimed at wrapping a raw codestream in a set of of JP2 boxes (turning it into a JP2 file instead of just a raw codestream), or rewrapping a codestream in a JP2 f...
[ "def", "wrap", "(", "self", ",", "filename", ",", "boxes", "=", "None", ")", ":", "if", "boxes", "is", "None", ":", "boxes", "=", "self", ".", "_get_default_jp2_boxes", "(", ")", "self", ".", "_validate_jp2_box_sequence", "(", "boxes", ")", "with", "open...
33.957447
0.001218
def create(self, name, category, applications=None, servers=None): """ This API endpoint will create a new label with the provided name and category :type name: str :param name: The name of the label :type category: str :param category: The Category :ty...
[ "def", "create", "(", "self", ",", "name", ",", "category", ",", "applications", "=", "None", ",", "servers", "=", "None", ")", ":", "data", "=", "{", "\"label\"", ":", "{", "\"category\"", ":", "category", ",", "\"name\"", ":", "name", ",", "\"links\"...
25.339286
0.001357
def ascii85decode(data): """ In ASCII85 encoding, every four bytes are encoded with five ASCII letters, using 85 different types of characters (as 256**4 < 85**5). When the length of the original bytes is not a multiple of 4, a special rule is used for round up. The Adobe's ASCII85 implementati...
[ "def", "ascii85decode", "(", "data", ")", ":", "n", "=", "b", "=", "0", "out", "=", "b''", "for", "c", "in", "data", ":", "if", "b'!'", "<=", "c", "and", "c", "<=", "b'u'", ":", "n", "+=", "1", "b", "=", "b", "*", "85", "+", "(", "ord", "...
29.864865
0.000876
def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canon...
[ "def", "delete_cname", "(", "name", "=", "None", ",", "canonical", "=", "None", ",", "*", "*", "api_opts", ")", ":", "cname", "=", "get_cname", "(", "name", "=", "name", ",", "canonical", "=", "canonical", ",", "*", "*", "api_opts", ")", "if", "cname...
29
0.001965
def get_handler_class(ext): """Get the IOHandler that can handle the extension *ext*.""" if ext in _extensions_map: format = _extensions_map[ext] else: raise ValueError("Unknown format for %s extension." % ext) if format in _handler_map: hc = _handler_map[format] return...
[ "def", "get_handler_class", "(", "ext", ")", ":", "if", "ext", "in", "_extensions_map", ":", "format", "=", "_extensions_map", "[", "ext", "]", "else", ":", "raise", "ValueError", "(", "\"Unknown format for %s extension.\"", "%", "ext", ")", "if", "format", "i...
34.6
0.001876
async def fetch_block(self, request): """Fetches a specific block from the validator, specified by id. Request: path: - block_id: The 128-character id of the block to be fetched Response: data: A JSON object with the data from the fully expanded Block ...
[ "async", "def", "fetch_block", "(", "self", ",", "request", ")", ":", "error_traps", "=", "[", "error_handlers", ".", "BlockNotFoundTrap", "]", "block_id", "=", "request", ".", "match_info", ".", "get", "(", "'block_id'", ",", "''", ")", "self", ".", "_val...
37.24
0.002094
def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') ...
[ "def", "apply_network_settings", "(", "*", "*", "settings", ")", ":", "if", "__grains__", "[", "'lsb_distrib_id'", "]", "==", "'nilrt'", ":", "raise", "salt", ".", "exceptions", ".", "CommandExecutionError", "(", "'Not supported in this version.'", ")", "if", "'re...
30.190476
0.002292
def clean(self): ''' Only allow submission if there are not already slots in the submitted window, and only allow rooms associated with the chosen location. ''' super(SlotCreationForm,self).clean() startDate = self.cleaned_data.get('startDate') endDate ...
[ "def", "clean", "(", "self", ")", ":", "super", "(", "SlotCreationForm", ",", "self", ")", ".", "clean", "(", ")", "startDate", "=", "self", ".", "cleaned_data", ".", "get", "(", "'startDate'", ")", "endDate", "=", "self", ".", "cleaned_data", ".", "ge...
42.72
0.008242
def float_field_data(field, **kwargs): """ Return random value for FloatField >>> result = any_form_field(forms.FloatField(max_value=200, min_value=100)) >>> type(result) <type 'str'> >>> float(result) >=100, float(result) <=200 (True, True) """ min_value = 0 max_value = 100 ...
[ "def", "float_field_data", "(", "field", ",", "*", "*", "kwargs", ")", ":", "min_value", "=", "0", "max_value", "=", "100", "from", "django", ".", "core", ".", "validators", "import", "MinValueValidator", ",", "MaxValueValidator", "for", "elem", "in", "field...
34.291667
0.002364
def form_node(cls): """A class decorator to finalize fully derived FormNode subclasses.""" assert issubclass(cls, FormNode) res = attrs(init=False, slots=True)(cls) res._args = [] res._required_args = 0 res._rest_arg = None state = _FormArgMode.REQUIRED for field in fields(res): ...
[ "def", "form_node", "(", "cls", ")", ":", "assert", "issubclass", "(", "cls", ",", "FormNode", ")", "res", "=", "attrs", "(", "init", "=", "False", ",", "slots", "=", "True", ")", "(", "cls", ")", "res", ".", "_args", "=", "[", "]", "res", ".", ...
41.076923
0.000915
def entry_links(self): """ Given a parsed feed, return the links to its entries, including ones which disappeared (as a quick-and-dirty way to support deletions) """ return {entry['link'] for entry in self.feed.entries if entry and entry.get('link')}
[ "def", "entry_links", "(", "self", ")", ":", "return", "{", "entry", "[", "'link'", "]", "for", "entry", "in", "self", ".", "feed", ".", "entries", "if", "entry", "and", "entry", ".", "get", "(", "'link'", ")", "}" ]
55.6
0.014184
def squared_distance(self, other): """ Squared distance of two Vectors. >>> dense1 = DenseVector(array.array('d', [1., 2.])) >>> dense1.squared_distance(dense1) 0.0 >>> dense2 = np.array([2., 1.]) >>> dense1.squared_distance(dense2) 2.0 >>> dense3...
[ "def", "squared_distance", "(", "self", ",", "other", ")", ":", "assert", "len", "(", "self", ")", "==", "_vector_size", "(", "other", ")", ",", "\"dimension mismatch\"", "if", "isinstance", "(", "other", ",", "SparseVector", ")", ":", "return", "other", "...
35.378378
0.001487
def get_cases(self, target): """switch.get_cases(target) -> [case]""" if target in self.targets: return self._reverse_map[target] raise KeyError("Target 0x{:08X} does not exist.".format(target))
[ "def", "get_cases", "(", "self", ",", "target", ")", ":", "if", "target", "in", "self", ".", "targets", ":", "return", "self", ".", "_reverse_map", "[", "target", "]", "raise", "KeyError", "(", "\"Target 0x{:08X} does not exist.\"", ".", "format", "(", "targ...
37.666667
0.008658
def remove_image_info_cb(self, viewer, channel, image_info): """Almost the same as remove_image_cb(). """ return self.remove_image_cb(viewer, channel.name, image_info.name, image_info.path)
[ "def", "remove_image_info_cb", "(", "self", ",", "viewer", ",", "channel", ",", "image_info", ")", ":", "return", "self", ".", "remove_image_cb", "(", "viewer", ",", "channel", ".", "name", ",", "image_info", ".", "name", ",", "image_info", ".", "path", ")...
49
0.008032
def _mixup( self, ps ): """Private method to mix up a list of values in-place using a Fisher-Yates shuffle (see https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). :param ps: the array :returns: the array, shuffled in-place""" for i in range(len(ps) - 1, 0, -1): j =...
[ "def", "_mixup", "(", "self", ",", "ps", ")", ":", "for", "i", "in", "range", "(", "len", "(", "ps", ")", "-", "1", ",", "0", ",", "-", "1", ")", ":", "j", "=", "int", "(", "numpy", ".", "random", ".", "random", "(", ")", "*", "i", ")", ...
36.166667
0.011236
def select_k_best(self, k): """Selects k best features in dataset :param k: features to select :return: k best features """ x_new = SelectKBest(chi2, k=k).fit_transform(self.x_train, self.y_train) return x_new
[ "def", "select_k_best", "(", "self", ",", "k", ")", ":", "x_new", "=", "SelectKBest", "(", "chi2", ",", "k", "=", "k", ")", ".", "fit_transform", "(", "self", ".", "x_train", ",", "self", ".", "y_train", ")", "return", "x_new" ]
31.375
0.011628
def initialize(self, endog, freq_weights): ''' Initialize the response variable. Parameters ---------- endog : array Endogenous response variable Returns -------- If `endog` is binary, returns `endog` If `endog` is a 2d array, then t...
[ "def", "initialize", "(", "self", ",", "endog", ",", "freq_weights", ")", ":", "# if not np.all(np.asarray(freq_weights) == 1):", "# self.variance = V.Binomial(n=freq_weights)", "if", "(", "endog", ".", "ndim", ">", "1", "and", "endog", ".", "shape", "[", "1", "...
32.185185
0.002235
def add(self, delta): """Increment weights: lw <-lw + delta. Parameters ---------- delta: (N,) array incremental log-weights """ if self.lw is None: return Weights(lw=delta) else: return Weights(lw=self.lw + delta)
[ "def", "add", "(", "self", ",", "delta", ")", ":", "if", "self", ".", "lw", "is", "None", ":", "return", "Weights", "(", "lw", "=", "delta", ")", "else", ":", "return", "Weights", "(", "lw", "=", "self", ".", "lw", "+", "delta", ")" ]
22.846154
0.009709
async def get_stream(self, *command_args, conn_type="I", offset=0): """ :py:func:`asyncio.coroutine` Create :py:class:`aioftp.DataConnectionThrottleStreamIO` for straight read/write io. :param command_args: arguments for :py:meth:`aioftp.Client.command` :param conn_typ...
[ "async", "def", "get_stream", "(", "self", ",", "*", "command_args", ",", "conn_type", "=", "\"I\"", ",", "offset", "=", "0", ")", ":", "reader", ",", "writer", "=", "await", "self", ".", "get_passive_connection", "(", "conn_type", ")", "if", "offset", "...
33.344828
0.00201
def fgp_dual(p, data, alpha, niter, grad, proj_C, proj_P, tol=None, **kwargs): """Computes a solution to the ROF problem with the fast gradient projection algorithm. Parameters ---------- p : np.array dual initial variable data : np.array noisy data / proximal point alpha : ...
[ "def", "fgp_dual", "(", "p", ",", "data", ",", "alpha", ",", "niter", ",", "grad", ",", "proj_C", ",", "proj_P", ",", "tol", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Callback object", "callback", "=", "kwargs", ".", "pop", "(", "'callback'"...
25.306818
0.000432
def topic_inject(self, topic_name, _msg_content=None, **kwargs): """ Injecting message into topic. if _msg_content, we inject it directly. if not, we use all extra kwargs :param topic_name: name of the topic :param _msg_content: optional message content :param kwargs: each extra ...
[ "def", "topic_inject", "(", "self", ",", "topic_name", ",", "_msg_content", "=", "None", ",", "*", "*", "kwargs", ")", ":", "#changing unicode to string ( testing stability of multiprocess debugging )", "if", "isinstance", "(", "topic_name", ",", "unicode", ")", ":", ...
52.2
0.008467
def parallel_concat_lcdir(lcbasedir, objectidlist, aperture='TF1', postfix='.gz', sortby='rjd', normalize=True, outdir=None, recursive=Tru...
[ "def", "parallel_concat_lcdir", "(", "lcbasedir", ",", "objectidlist", ",", "aperture", "=", "'TF1'", ",", "postfix", "=", "'.gz'", ",", "sortby", "=", "'rjd'", ",", "normalize", "=", "True", ",", "outdir", "=", "None", ",", "recursive", "=", "True", ",", ...
31
0.008043
def map_query(self, variables=None, evidence=None): """ MAP Query method using belief propagation. Note: When multiple variables are passed, it returns the map_query for each of them individually. Parameters ---------- variables: list list of variabl...
[ "def", "map_query", "(", "self", ",", "variables", "=", "None", ",", "evidence", "=", "None", ")", ":", "# TODO:Check the note in docstring. Change that behavior to return the joint MAP", "if", "not", "variables", ":", "variables", "=", "set", "(", "self", ".", "var...
41.507692
0.002172
def plot_line_ids(wave, flux, line_wave, line_label1, label1_size=None, extend=True, annotate_kwargs=None, plot_kwargs=None, **kwargs): """Label features with automatic layout of labels. Parameters ---------- wave: list or array of floats Wave lengths of data...
[ "def", "plot_line_ids", "(", "wave", ",", "flux", ",", "line_wave", ",", "line_label1", ",", "label1_size", "=", "None", ",", "extend", "=", "True", ",", "annotate_kwargs", "=", "None", ",", "plot_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", ...
43.037975
0.000096
def make_request( ins, method, url, stripe_account=None, params=None, headers=None, **kwargs ): """ Return a deferred or handle error. For overriding in various classes. """ if txstripe.api_key is None: raise error.AuthenticationError( 'No API key provided. (HINT: set your A...
[ "def", "make_request", "(", "ins", ",", "method", ",", "url", ",", "stripe_account", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "txstripe", ".", "api_key", "is", "None", ":", "raise"...
29.559322
0.000555
def _rectangles_to_polygons(df): """ Convert rect data to polygons Paramters --------- df : dataframe Dataframe with *xmin*, *xmax*, *ymin* and *ymax* columns, plus others for aesthetics ... Returns ------- data : dataframe Dataframe with *x* and *y* columns, pl...
[ "def", "_rectangles_to_polygons", "(", "df", ")", ":", "n", "=", "len", "(", "df", ")", "# Helper indexing arrays", "xmin_idx", "=", "np", ".", "tile", "(", "[", "True", ",", "True", ",", "False", ",", "False", "]", ",", "n", ")", "xmax_idx", "=", "~...
26.477273
0.000828
def verified_funds(pronac, dt): """ Responsable for detecting anomalies in projects total verified funds. """ dataframe = data.planilha_comprovacao project = dataframe.loc[dataframe['PRONAC'] == pronac] segment_id = project.iloc[0]["idSegmento"] pronac_funds = project[ ["idPlanilhaAp...
[ "def", "verified_funds", "(", "pronac", ",", "dt", ")", ":", "dataframe", "=", "data", ".", "planilha_comprovacao", "project", "=", "dataframe", ".", "loc", "[", "dataframe", "[", "'PRONAC'", "]", "==", "pronac", "]", "segment_id", "=", "project", ".", "il...
39.153846
0.000959
def _list_cmaps(provider=None, records=False): """ List available colormaps by combining matplotlib, bokeh, and colorcet colormaps or palettes if available. May also be narrowed down to a particular provider or list of providers. """ if provider is None: provider = providers elif isi...
[ "def", "_list_cmaps", "(", "provider", "=", "None", ",", "records", "=", "False", ")", ":", "if", "provider", "is", "None", ":", "provider", "=", "providers", "elif", "isinstance", "(", "provider", ",", "basestring", ")", ":", "if", "provider", "not", "i...
39.319149
0.008976
def setShadowed(self, state): """ Sets whether or not this toolbar is shadowed. :param state | <bool> """ self._shadowed = state if state: self._colored = False for child in self.findChildren(XToolButton): child.setSh...
[ "def", "setShadowed", "(", "self", ",", "state", ")", ":", "self", ".", "_shadowed", "=", "state", "if", "state", ":", "self", ".", "_colored", "=", "False", "for", "child", "in", "self", ".", "findChildren", "(", "XToolButton", ")", ":", "child", ".",...
26.833333
0.012012
def loadWallet(self, fpath): """Load wallet from specified localtion. Returns loaded wallet. Error cases: - ``fpath`` is not inside the keyrings base dir - ValueError raised - ``fpath`` exists and it's a directory - IsADirectoryError raised :param fpath: wallet...
[ "def", "loadWallet", "(", "self", ",", "fpath", ")", ":", "if", "not", "fpath", ":", "raise", "ValueError", "(", "\"empty path\"", ")", "_fpath", "=", "self", ".", "_normalize", "(", "fpath", ")", "_dpath", "=", "_fpath", ".", "parent", "try", ":", "_d...
29.068966
0.002296
def save_to_json(self): """The method saves data to json from object""" requestvalues = { 'id': self.dataset, 'publicationDate': self.publication_date.strftime('%Y-%m-%d'), 'source': self.source, 'refUrl': self.refernce_url, } ...
[ "def", "save_to_json", "(", "self", ")", ":", "requestvalues", "=", "{", "'id'", ":", "self", ".", "dataset", ",", "'publicationDate'", ":", "self", ".", "publication_date", ".", "strftime", "(", "'%Y-%m-%d'", ")", ",", "'source'", ":", "self", ".", "sourc...
34.8
0.008403
def copy(self, selection, smart_selection_adaption=True): """ Copy all selected items to the clipboard using smart selection adaptation by default :param selection: the current selection :param bool smart_selection_adaption: flag to enable smart selection adaptation mode :return...
[ "def", "copy", "(", "self", ",", "selection", ",", "smart_selection_adaption", "=", "True", ")", ":", "assert", "isinstance", "(", "selection", ",", "Selection", ")", "self", ".", "__create_core_and_model_object_copies", "(", "selection", ",", "smart_selection_adapt...
51.222222
0.012793
def force_unicode(raw): '''Try really really hard to get a Unicode copy of a string. First try :class:`BeautifulSoup.UnicodeDammit` to try to force to Unicode; if that fails, assume UTF-8 encoding, and ignore all errors. :param str raw: string to coerce :return: Unicode approximation of `raw` ...
[ "def", "force_unicode", "(", "raw", ")", ":", "converted", "=", "UnicodeDammit", "(", "raw", ",", "isHTML", "=", "True", ")", "if", "not", "converted", ".", "unicode", ":", "converted", ".", "unicode", "=", "unicode", "(", "raw", ",", "'utf8'", ",", "e...
30.695652
0.001374
def create_span( self, name, span_id, display_name, start_time, end_time, parent_span_id=None, attributes=None, stack_trace=None, time_events=None, links=None, status=None, same_process_as_parent_span=None, c...
[ "def", "create_span", "(", "self", ",", "name", ",", "span_id", ",", "display_name", ",", "start_time", ",", "end_time", ",", "parent_span_id", "=", "None", ",", "attributes", "=", "None", ",", "stack_trace", "=", "None", ",", "time_events", "=", "None", "...
46.266129
0.000512
def decode_input(text_in): """ Decodes `text_in` If text_in is is a string, then decode it as utf-8 string. If text_in is is a list of strings, then decode each string of it, then combine them into one outpust string. """ if type(text_in) == list: tex...
[ "def", "decode_input", "(", "text_in", ")", ":", "if", "type", "(", "text_in", ")", "==", "list", ":", "text_out", "=", "u' '", ".", "join", "(", "[", "t", ".", "decode", "(", "'utf-8'", ")", "for", "t", "in", "text_in", "]", ")", "else", ":", "t...
31.071429
0.011161
def save_config(config): """Save configuration file to users data location. - Linux: ~/.local/share/pyfilemail - OSX: ~/Library/Application Support/pyfilemail - Windows: C:\\\Users\\\{username}\\\AppData\\\Local\\\pyfilemail :rtype: str """ configfile = get_configfile() if not os...
[ "def", "save_config", "(", "config", ")", ":", "configfile", "=", "get_configfile", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "configfile", ")", ":", "configdir", "=", "os", ".", "path", ".", "dirname", "(", "configfile", ")", "if",...
24.772727
0.008834
def range(self, x_data=None): """ Generate the upper and lower bounds of a distribution. Args: x_data (numpy.ndarray) : The bounds might vary over the sample space. By providing x_data you can specify where in the space the bound should be ...
[ "def", "range", "(", "self", ",", "x_data", "=", "None", ")", ":", "if", "x_data", "is", "None", ":", "try", ":", "x_data", "=", "evaluation", ".", "evaluate_inverse", "(", "self", ",", "numpy", ".", "array", "(", "[", "[", "0.5", "]", "]", "*", ...
36.625
0.001663
def pickle_payload(self): """obtain stats payload in batches of pickle format""" tstamp = int(time.time()) payload = [] for item in self.counters: payload.append(("%s.%s%s" % (self.rate_prefix, item, self.rate_suffix), ...
[ "def", "pickle_payload", "(", "self", ")", ":", "tstamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "payload", "=", "[", "]", "for", "item", "in", "self", ".", "counters", ":", "payload", ".", "append", "(", "(", "\"%s.%s%s\"", "%", "(",...
41.085714
0.001359
def CheckSupportedFormat(cls, path, check_readable_only=False): """Checks if the storage file format is supported. Args: path (str): path to the storage file. check_readable_only (Optional[bool]): whether the store should only be checked to see if it can be read. If False, the store will ...
[ "def", "CheckSupportedFormat", "(", "cls", ",", "path", ",", "check_readable_only", "=", "False", ")", ":", "try", ":", "connection", "=", "sqlite3", ".", "connect", "(", "path", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", "|", "sqlite3", "....
28.69697
0.011236
def start_worker(self, row): '''为task新建一个后台下载线程, 并开始下载.''' def on_worker_started(worker, fs_id): pass def on_worker_received(worker, fs_id, received, received_total): GLib.idle_add(do_worker_received, fs_id, received, received_total) def do_worker_received(fs_id...
[ "def", "start_worker", "(", "self", ",", "row", ")", ":", "def", "on_worker_started", "(", "worker", ",", "fs_id", ")", ":", "pass", "def", "on_worker_received", "(", "worker", ",", "fs_id", ",", "received", ",", "received_total", ")", ":", "GLib", ".", ...
40.26087
0.000527
def _get_alignment_ranges(self): """A key method to extract the alignment data from the line""" if not self.is_aligned(): return None alignment_ranges = [] cig = [x[:] for x in self.cigar_array] target_pos = self.entries.pos query_pos = 1 while len(cig) > 0: c = cig.pop(0) if re....
[ "def", "_get_alignment_ranges", "(", "self", ")", ":", "if", "not", "self", ".", "is_aligned", "(", ")", ":", "return", "None", "alignment_ranges", "=", "[", "]", "cig", "=", "[", "x", "[", ":", "]", "for", "x", "in", "self", ".", "cigar_array", "]",...
38.041667
0.022436
def diamondTabularFormatToDicts(filename, fieldNames=None): """ Read DIAMOND tabular (--outfmt 6) output and convert lines to dictionaries. @param filename: Either a C{str} file name or an open file pointer. @param fieldNames: A C{list} or C{tuple} of C{str} DIAMOND field names. Run 'diamond -h...
[ "def", "diamondTabularFormatToDicts", "(", "filename", ",", "fieldNames", "=", "None", ")", ":", "fieldNames", "=", "fieldNames", "or", "FIELDS", ".", "split", "(", ")", "nFields", "=", "len", "(", "fieldNames", ")", "if", "not", "nFields", ":", "raise", "...
43.612245
0.000458
def send(self, request, stem=None): """Prepare and send a request Arguments: request: a Request object that is not yet prepared stem: a path to append to the root URL Returns: The response to the request """ if stem is not None: ...
[ "def", "send", "(", "self", ",", "request", ",", "stem", "=", "None", ")", ":", "if", "stem", "is", "not", "None", ":", "request", ".", "url", "=", "request", ".", "url", "+", "\"/\"", "+", "stem", ".", "lstrip", "(", "\"/\"", ")", "prepped", "="...
37.363636
0.002372
def remove(unique_id): """Remove a polygon filter from `PolygonFilter.instances`""" for p in PolygonFilter.instances: if p.unique_id == unique_id: PolygonFilter.instances.remove(p)
[ "def", "remove", "(", "unique_id", ")", ":", "for", "p", "in", "PolygonFilter", ".", "instances", ":", "if", "p", ".", "unique_id", "==", "unique_id", ":", "PolygonFilter", ".", "instances", ".", "remove", "(", "p", ")" ]
44
0.008929
def run(self): """ Child process. Repeatedly call :meth:`loop` method every :attribute:`interval` seconds. """ setproctitle.setproctitle("{:s}: {:s}".format( self.context.config.name, self.__class__.__name__)) self.logger.info( "Worker '%s' has bee...
[ "def", "run", "(", "self", ")", ":", "setproctitle", ".", "setproctitle", "(", "\"{:s}: {:s}\"", ".", "format", "(", "self", ".", "context", ".", "config", ".", "name", ",", "self", ".", "__class__", ".", "__name__", ")", ")", "self", ".", "logger", "....
39
0.001163
def _make_static_axis_non_negative_list(axis, ndims): """Convert possibly negatively indexed axis to non-negative list of ints. Args: axis: Integer Tensor. ndims: Number of dimensions into which axis indexes. Returns: A list of non-negative Python integers. Raises: ValueError: If `axis` is ...
[ "def", "_make_static_axis_non_negative_list", "(", "axis", ",", "ndims", ")", ":", "axis", "=", "distribution_util", ".", "make_non_negative_axis", "(", "axis", ",", "ndims", ")", "axis_const", "=", "tf", ".", "get_static_value", "(", "axis", ")", "if", "axis_co...
27.68
0.011173
def convert_directory_2_to_3(meas_fname="magic_measurements.txt", input_dir=".", output_dir=".", meas_only=False, data_model=None): """ Convert 2.0 measurements file into 3.0 measurements file. Merge and convert specimen, sample, site, and location data. Also translates crit...
[ "def", "convert_directory_2_to_3", "(", "meas_fname", "=", "\"magic_measurements.txt\"", ",", "input_dir", "=", "\".\"", ",", "output_dir", "=", "\".\"", ",", "meas_only", "=", "False", ",", "data_model", "=", "None", ")", ":", "convert", "=", "{", "'specimens'"...
44.973333
0.00116
def put_multi(entities): """Persist a set of entities to Datastore. Note: This uses the adapter that is tied to the first Entity in the list. If the entities have disparate adapters this function may behave in unexpected ways. Warning: You must pass a **list** and not a generator ...
[ "def", "put_multi", "(", "entities", ")", ":", "if", "not", "entities", ":", "return", "[", "]", "adapter", ",", "requests", "=", "None", ",", "[", "]", "for", "entity", "in", "entities", ":", "if", "adapter", "is", "None", ":", "adapter", "=", "enti...
27.525
0.001754
def local_subset(self, *args, **kwargs): ''' Run :ref:`execution modules <all-salt.modules>` against subsets of minions .. versionadded:: 2016.3.0 Wraps :py:meth:`salt.client.LocalClient.cmd_subset` ''' local = salt.client.get_local_client(mopts=self.opts) retur...
[ "def", "local_subset", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "local", "=", "salt", ".", "client", ".", "get_local_client", "(", "mopts", "=", "self", ".", "opts", ")", "return", "local", ".", "cmd_subset", "(", "*", "args"...
34.6
0.008451
def check_args(args): """ Parse arguments and check if the arguments are valid """ if not os.path.exists(args.fd): print("Not a valid path", args.fd, file=ERROR_LOG) return [], [], False if args.fl is not None: # we already ensure the file can be opened and opened the file ...
[ "def", "check_args", "(", "args", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "args", ".", "fd", ")", ":", "print", "(", "\"Not a valid path\"", ",", "args", ".", "fd", ",", "file", "=", "ERROR_LOG", ")", "return", "[", "]", ",", ...
36.551724
0.002297
def fit(self, pairs, y, calibration_params=None): """Learn the MMC model. The threshold will be calibrated on the trainset using the parameters `calibration_params`. Parameters ---------- pairs : array-like, shape=(n_constraints, 2, n_features) or (n_constraints, 2) 3D Array...
[ "def", "fit", "(", "self", ",", "pairs", ",", "y", ",", "calibration_params", "=", "None", ")", ":", "calibration_params", "=", "(", "calibration_params", "if", "calibration_params", "is", "not", "None", "else", "dict", "(", ")", ")", "self", ".", "_valida...
39.3
0.000828
def app_reverse(parser, token): """ Returns an absolute URL for applications integrated with ApplicationContent The tag mostly works the same way as Django's own {% url %} tag:: {% load leonardo_tags %} {% app_reverse "mymodel_detail" "myapp.urls" arg1 arg2 %} or {% load leon...
[ "def", "app_reverse", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "<", "3", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes at least two arguments\"", "\" (path to a view an...
39.916667
0.000509
def parallel_gen_timestamps(dview, max_em_rate, bg_rate): """Generate timestamps from a set of remote simulations in `dview`. Assumes that all the engines have an `S` object already containing an emission trace (`S.em`). The "photons" timestamps are generated from these emission traces and merged into a...
[ "def", "parallel_gen_timestamps", "(", "dview", ",", "max_em_rate", ",", "bg_rate", ")", ":", "dview", ".", "execute", "(", "'S.sim_timestamps_em_store(max_rate=%d, bg_rate=%d, '", "'seed=S.EID, overwrite=True)'", "%", "(", "max_em_rate", ",", "bg_rate", ")", ")", "dvie...
52.954545
0.000843
def word_ends(self): """The list of end positions representing ``words`` layer elements.""" if not self.is_tagged(WORDS): self.tokenize_words() return self.ends(WORDS)
[ "def", "word_ends", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "WORDS", ")", ":", "self", ".", "tokenize_words", "(", ")", "return", "self", ".", "ends", "(", "WORDS", ")" ]
39.8
0.009852
def _list_records(self, rtype=None, name=None, content=None): """List all record for the domain in the active Gandi zone.""" if self.protocol == 'rpc': return self.rpc_helper.list_records(rtype, name, content) try: if name is not None: if rtype is not Non...
[ "def", "_list_records", "(", "self", ",", "rtype", "=", "None", ",", "name", "=", "None", ",", "content", "=", "None", ")", ":", "if", "self", ".", "protocol", "==", "'rpc'", ":", "return", "self", ".", "rpc_helper", ".", "list_records", "(", "rtype", ...
44.195652
0.002406
def push_datapackage(descriptor, backend, **backend_options): """Push Data Package to storage. All parameters should be used as keyword arguments. Args: descriptor (str): path to descriptor backend (str): backend name like `sql` or `bigquery` backend_options (dict): backend options...
[ "def", "push_datapackage", "(", "descriptor", ",", "backend", ",", "*", "*", "backend_options", ")", ":", "# Deprecated", "warnings", ".", "warn", "(", "'Functions \"push/pull_datapackage\" are deprecated. '", "'Please use \"Package\" class'", ",", "UserWarning", ")", "# ...
28.734375
0.001052
def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]: """ Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = cr...
[ "def", "get_sqlserver_product_version", "(", "engine", ":", "\"Engine\"", ")", "->", "Tuple", "[", "int", "]", ":", "assert", "is_sqlserver", "(", "engine", ")", ",", "(", "\"Only call get_sqlserver_product_version() for Microsoft SQL Server \"", "\"instances.\"", ")", ...
38.068182
0.000582
def get_mnemonic(self, mnemonic, alias=None): """ Instead of picking curves by name directly from the data dict, you can pick them up with this method, which takes account of the alias dict you pass it. If you do not pass an alias dict, then you get the curve you asked for, if it...
[ "def", "get_mnemonic", "(", "self", ",", "mnemonic", ",", "alias", "=", "None", ")", ":", "alias", "=", "alias", "or", "{", "}", "aliases", "=", "alias", ".", "get", "(", "mnemonic", ",", "[", "mnemonic", "]", ")", "for", "a", "in", "aliases", ":",...
35.590909
0.002488
def fit(self, Z): """Compute k-means clustering. Parameters ---------- Z : ArrayRDD or DictRDD containing array-like or sparse matrix Train data. Returns ------- self """ X = Z[:, 'X'] if isinstance(Z, DictRDD) else Z check_rd...
[ "def", "fit", "(", "self", ",", "Z", ")", ":", "X", "=", "Z", "[", ":", ",", "'X'", "]", "if", "isinstance", "(", "Z", ",", "DictRDD", ")", "else", "Z", "check_rdd", "(", "X", ",", "(", "np", ".", "ndarray", ",", "sp", ".", "spmatrix", ")", ...
34.72
0.002242
def load_vectors(self, vectors, **kwargs): """ Arguments: vectors: one of or a list containing instantiations of the GloVe, CharNGram, or Vectors classes. Alternatively, one of or a list of available pretrained vectors: charngram.100d ...
[ "def", "load_vectors", "(", "self", ",", "vectors", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "vectors", ",", "list", ")", ":", "vectors", "=", "[", "vectors", "]", "for", "idx", ",", "vector", "in", "enumerate", "(", "vector...
43.020408
0.001391
def van(first_enc, first_frame, current_enc, gt_image, reuse=False, scope_prefix='', hparams=None): """Implements a VAN. Args: first_enc: The first encoding. first_frame: The first ground truth frame. current_enc: The encoding of the frame to generate. ...
[ "def", "van", "(", "first_enc", ",", "first_frame", ",", "current_enc", ",", "gt_image", ",", "reuse", "=", "False", ",", "scope_prefix", "=", "''", ",", "hparams", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope_prefix", "+", "'v...
32.173913
0.001967
def entity_to_protobuf(entity): """Converts an entity into a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to be turned into a protobuf. :rtype: :class:`.entity_pb2.Entity` :returns: The protobuf representing the entity. """ entity_pb = ent...
[ "def", "entity_to_protobuf", "(", "entity", ")", ":", "entity_pb", "=", "entity_pb2", ".", "Entity", "(", ")", "if", "entity", ".", "key", "is", "not", "None", ":", "key_pb", "=", "entity", ".", "key", ".", "to_protobuf", "(", ")", "entity_pb", ".", "k...
31.742857
0.000873
def _preformat( text, layers, markup_settings = None ): ''' Formats given text, adding a special ( ANSI-terminal compatible ) markup to the annotations of given layers, and returns formatted text as a string. *) layers is a list containing names of the layers to be preformatted in ...
[ "def", "_preformat", "(", "text", ",", "layers", ",", "markup_settings", "=", "None", ")", ":", "if", "markup_settings", "and", "len", "(", "layers", ")", "!=", "len", "(", "markup_settings", ")", ":", "raise", "Exception", "(", "' Input arguments layers and m...
44.27957
0.024703
def reduce_sequences(object_a, object_b): """Performs an element-wise addition of sequences into a new list. Both sequences must have the same length, and the addition operator must be defined for each element of the sequence. """ def is_seq(obj): """Returns true if the object passed is a s...
[ "def", "reduce_sequences", "(", "object_a", ",", "object_b", ")", ":", "def", "is_seq", "(", "obj", ")", ":", "\"\"\"Returns true if the object passed is a sequence.\"\"\"", "return", "hasattr", "(", "obj", ",", "\"__getitem__\"", ")", "or", "hasattr", "(", "obj", ...
38.952381
0.001193
def f_i18n_iso(isocode, lang="eng"): """ Replace isocode by its language equivalent :param isocode: Three character long language code :param lang: Lang in which to return the language name :return: Full Text Language Name """ if lang not in flask_nemo._data.AVAILABLE_TRANSLATIONS: lang...
[ "def", "f_i18n_iso", "(", "isocode", ",", "lang", "=", "\"eng\"", ")", ":", "if", "lang", "not", "in", "flask_nemo", ".", "_data", ".", "AVAILABLE_TRANSLATIONS", ":", "lang", "=", "\"eng\"", "try", ":", "return", "flask_nemo", ".", "_data", ".", "ISOCODES"...
30.5
0.002273
def _op_msg_no_header(flags, command, identifier, docs, check_keys, opts): """Get a OP_MSG message. Note: this method handles multiple documents in a type one payload but it does not perform batch splitting and the total message size is only checked *after* generating the entire message. """ # ...
[ "def", "_op_msg_no_header", "(", "flags", ",", "command", ",", "identifier", ",", "docs", ",", "check_keys", ",", "opts", ")", ":", "# Encode the command document in payload 0 without checking keys.", "encoded", "=", "_dict_to_bson", "(", "command", ",", "False", ",",...
43.48
0.0009
def stratify(self): """ Stratifies the sample based on propensity score. By default the sample is divided into five equal-sized bins. The number of bins can be set by modifying the object attribute named blocks. Alternatively, custom-sized bins can be created by setting blocks equal to a sorted list of ...
[ "def", "stratify", "(", "self", ")", ":", "Y", ",", "D", ",", "X", "=", "self", ".", "raw_data", "[", "'Y'", "]", ",", "self", ".", "raw_data", "[", "'D'", "]", ",", "self", ".", "raw_data", "[", "'X'", "]", "pscore", "=", "self", ".", "raw_dat...
34.517241
0.025267
def groupByHeaderIndex(self): """ Assigns the grouping to the current header index. """ index = self.headerMenuColumn() columnTitle = self.columnOf(index) tableType = self.tableType() if not tableType: return column...
[ "def", "groupByHeaderIndex", "(", "self", ")", ":", "index", "=", "self", ".", "headerMenuColumn", "(", ")", "columnTitle", "=", "self", ".", "columnOf", "(", "index", ")", "tableType", "=", "self", ".", "tableType", "(", ")", "if", "not", "tableType", "...
28.058824
0.010142
def send(tag, data=None, preload=None, with_env=False, with_grains=False, with_pillar=False, with_env_opts=False, timeout=60, **kwargs): ''' Send an event to the Salt Master .. versionadded:: 2014.7.0 :param tag: A tag to give the event. ...
[ "def", "send", "(", "tag", ",", "data", "=", "None", ",", "preload", "=", "None", ",", "with_env", "=", "False", ",", "with_grains", "=", "False", ",", "with_pillar", "=", "False", ",", "with_env_opts", "=", "False", ",", "timeout", "=", "60", ",", "...
38.282051
0.002394
def fitting_rmsd(w_fit, C_fit, r_fit, Xs): '''Calculate the RMSD of fitting.''' return np.sqrt(sum((geometry.point_line_distance(p, C_fit, w_fit) - r_fit) ** 2 for p in Xs) / len(Xs))
[ "def", "fitting_rmsd", "(", "w_fit", ",", "C_fit", ",", "r_fit", ",", "Xs", ")", ":", "return", "np", ".", "sqrt", "(", "sum", "(", "(", "geometry", ".", "point_line_distance", "(", "p", ",", "C_fit", ",", "w_fit", ")", "-", "r_fit", ")", "**", "2"...
52
0.014218
def currentMode( self ): """ Returns the current mode for this widget. :return <XOrbBrowserWidget.Mode> """ if ( self.uiCardACT.isChecked() ): return XOrbBrowserWidget.Mode.Card elif ( self.uiDetailsACT.isChecked() ): return X...
[ "def", "currentMode", "(", "self", ")", ":", "if", "(", "self", ".", "uiCardACT", ".", "isChecked", "(", ")", ")", ":", "return", "XOrbBrowserWidget", ".", "Mode", ".", "Card", "elif", "(", "self", ".", "uiDetailsACT", ".", "isChecked", "(", ")", ")", ...
33.75
0.021635
def pk_prom(word): '''Return the number of stressed light syllables.''' violations = 0 stressed = [] for w in extract_words(word): stressed += w.split('.')[2:-1:2] # odd syllables, excl. word-initial # (CVV = light) for syll in stressed: if phon.is_vowel(syll[-1]): ...
[ "def", "pk_prom", "(", "word", ")", ":", "violations", "=", "0", "stressed", "=", "[", "]", "for", "w", "in", "extract_words", "(", "word", ")", ":", "stressed", "+=", "w", ".", "split", "(", "'.'", ")", "[", "2", ":", "-", "1", ":", "2", "]", ...
26.15
0.001845
def extract_client_auth(request): """ Get client credentials using HTTP Basic Authentication method. Or try getting parameters via POST. See: http://tools.ietf.org/html/rfc6750#section-2.1 Return a tuple `(client_id, client_secret)`. """ auth_header = request.META.get('HTTP_AUTHORIZATION', ...
[ "def", "extract_client_auth", "(", "request", ")", ":", "auth_header", "=", "request", ".", "META", ".", "get", "(", "'HTTP_AUTHORIZATION'", ",", "''", ")", "if", "re", ".", "compile", "(", "'^Basic\\s{1}.+$'", ")", ".", "match", "(", "auth_header", ")", "...
35.681818
0.002481
def _groupby_and_merge(by, on, left, right, _merge_pieces, check_duplicates=True): """ groupby & merge; we are always performing a left-by type operation Parameters ---------- by: field to group on: duplicates field left: left frame right: right frame _merge_p...
[ "def", "_groupby_and_merge", "(", "by", ",", "on", ",", "left", ",", "right", ",", "_merge_pieces", ",", "check_duplicates", "=", "True", ")", ":", "pieces", "=", "[", "]", "if", "not", "isinstance", "(", "by", ",", "(", "list", ",", "tuple", ")", ")...
28.453333
0.000453
def update(self): """ Update this `~photutils.isophote.EllipseSample` instance. This method calls the :meth:`~photutils.isophote.EllipseSample.extract` method to get the values that match the current ``geometry`` attribute, and then computes the the mean intensity, local...
[ "def", "update", "(", "self", ")", ":", "step", "=", "self", ".", "geometry", ".", "astep", "# Update the mean value first, using extraction from main sample.", "s", "=", "self", ".", "extract", "(", ")", "self", ".", "mean", "=", "np", ".", "mean", "(", "s"...
42.040816
0.000949
def delete_files_in_folder(fldr): """ delete all files in folder 'fldr' """ fl = glob.glob(fldr + os.sep + '*.*') for f in fl: delete_file(f, True)
[ "def", "delete_files_in_folder", "(", "fldr", ")", ":", "fl", "=", "glob", ".", "glob", "(", "fldr", "+", "os", ".", "sep", "+", "'*.*'", ")", "for", "f", "in", "fl", ":", "delete_file", "(", "f", ",", "True", ")" ]
21.142857
0.045455
def convert_to_pixels(self, value): """ Convert value in the scale's unit into a position in pixels. :param value: value to convert :type value: float :return: the corresponding position in pixels :rtype: float """ percent = ((value - sel...
[ "def", "convert_to_pixels", "(", "self", ",", "value", ")", ":", "percent", "=", "(", "(", "value", "-", "self", ".", "_start", ")", "/", "self", ".", "_extent", ")", "return", "percent", "*", "(", "self", ".", "get_scale_length", "(", ")", "-", "sel...
35.916667
0.011312
def etree_to_dict(element): """Convert an eTree xml into dict imitating how Yahoo Pipes does it. todo: further investigate white space and multivalue handling """ i = dict(element.items()) content = element.text.strip() if element.text else None i.update({'content': content}) if content else No...
[ "def", "etree_to_dict", "(", "element", ")", ":", "i", "=", "dict", "(", "element", ".", "items", "(", ")", ")", "content", "=", "element", ".", "text", ".", "strip", "(", ")", "if", "element", ".", "text", "else", "None", "i", ".", "update", "(", ...
36.72
0.001062
def QA_data_ctptick_resample(tick, type_='1min'): """tick采样成任意级别分钟线 Arguments: tick {[type]} -- transaction Returns: [type] -- [description] """ resx = pd.DataFrame() _temp = set(tick.TradingDay) for item in _temp: _data = tick.query('TradingDay=="{}"'.format(ite...
[ "def", "QA_data_ctptick_resample", "(", "tick", ",", "type_", "=", "'1min'", ")", ":", "resx", "=", "pd", ".", "DataFrame", "(", ")", "_temp", "=", "set", "(", "tick", ".", "TradingDay", ")", "for", "item", "in", "_temp", ":", "_data", "=", "tick", "...
40.533333
0.000803
def receive_messages(self, on_message_received): """Receive messages. This function will run indefinitely, until the client closes either via timeout, error or forced interruption (e.g. keyboard interrupt). If the receive client is configured with `auto_complete=True` then the messages that ...
[ "def", "receive_messages", "(", "self", ",", "on_message_received", ")", ":", "self", ".", "open", "(", ")", "self", ".", "_received_messages", "=", "None", "self", ".", "_message_received_callback", "=", "on_message_received", "receiving", "=", "True", "try", "...
47.111111
0.008475
def sixteen_oscillator_two_stimulated_ensembles_grid(): "Not accurate false due to spikes are observed" parameters = legion_parameters(); parameters.teta_x = -1.1; template_dynamic_legion(16, 2000, 1500, conn_type = conn_type.GRID_FOUR, params = parameters, stimulus = [1, 1, 1, 0, ...
[ "def", "sixteen_oscillator_two_stimulated_ensembles_grid", "(", ")", ":", "parameters", "=", "legion_parameters", "(", ")", "parameters", ".", "teta_x", "=", "-", "1.1", "template_dynamic_legion", "(", "16", ",", "2000", ",", "1500", ",", "conn_type", "=", "conn_t...
83.5
0.025185
def make_table(self, renderable): """Makes unique anchor prefixes so that multiple tables may exist on the same page without conflict.""" self._make_prefix() diffs = renderable.diff._diff # set up iterator to wrap lines that exceed desired width if self._wrapcolumn: ...
[ "def", "make_table", "(", "self", ",", "renderable", ")", ":", "self", ".", "_make_prefix", "(", ")", "diffs", "=", "renderable", ".", "diff", ".", "_diff", "# set up iterator to wrap lines that exceed desired width", "if", "self", ".", "_wrapcolumn", ":", "diffs"...
44.533333
0.000977
def auto_delete_cohort(instance, **kwargs): "Deletes and auto-created cohort named after the instance." cohorts = Cohort.objects.filter(autocreated=True) if isinstance(instance, Project): cohorts = cohorts.filter(project=instance) elif isinstance(instance, Batch): cohorts = cohorts.filt...
[ "def", "auto_delete_cohort", "(", "instance", ",", "*", "*", "kwargs", ")", ":", "cohorts", "=", "Cohort", ".", "objects", ".", "filter", "(", "autocreated", "=", "True", ")", "if", "isinstance", "(", "instance", ",", "Project", ")", ":", "cohorts", "=",...
34.214286
0.002033
def gunzip(gzipfile, template=None, runas=None, options=None): ''' Uses the gunzip command to unpack gzip files template : None Can be set to 'jinja' or another supported template engine to render the command arguments before execution: .. code-block:: bash salt '*' ar...
[ "def", "gunzip", "(", "gzipfile", ",", "template", "=", "None", ",", "runas", "=", "None", ",", "options", "=", "None", ")", ":", "cmd", "=", "[", "'gunzip'", "]", "if", "options", ":", "cmd", ".", "append", "(", "options", ")", "cmd", ".", "append...
27.837838
0.000938
def scopes(self, **kwargs): """Scopes associated to the team.""" return self._client.scopes(team=self.id, **kwargs)
[ "def", "scopes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", ".", "scopes", "(", "team", "=", "self", ".", "id", ",", "*", "*", "kwargs", ")" ]
43
0.015267