text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _with_context(self, *args, **kwargs): """As the `with_context` class method but for recordset.""" context = dict(args[0] if args else self.env.context, **kwargs) return self.with_env(self.env(context=context))
[ "def", "_with_context", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "context", "=", "dict", "(", "args", "[", "0", "]", "if", "args", "else", "self", ".", "env", ".", "context", ",", "*", "*", "kwargs", ")", "return", "self"...
58.5
0.008439
def _complete_history(self, cmd, args, text): """Find candidates for the 'history' command.""" if args: return return [ x for x in { 'clear', 'clearall' } \ if x.startswith(text) ]
[ "def", "_complete_history", "(", "self", ",", "cmd", ",", "args", ",", "text", ")", ":", "if", "args", ":", "return", "return", "[", "x", "for", "x", "in", "{", "'clear'", ",", "'clearall'", "}", "if", "x", ".", "startswith", "(", "text", ")", "]" ...
37.833333
0.034483
def getcomments(self): """ Returns an array of comment dictionaries for this bug """ comment_list = self.bugzilla.get_comments([self.bug_id]) return comment_list['bugs'][str(self.bug_id)]['comments']
[ "def", "getcomments", "(", "self", ")", ":", "comment_list", "=", "self", ".", "bugzilla", ".", "get_comments", "(", "[", "self", ".", "bug_id", "]", ")", "return", "comment_list", "[", "'bugs'", "]", "[", "str", "(", "self", ".", "bug_id", ")", "]", ...
39
0.008368
def token_operation_put_account_payment_info(token_op, account_addr, token_type, amount): """ Call this in a @token_operation-decorated method. Identifies the account to be debited """ assert isinstance(amount, (int,long)), "BUG: amount is {} (type {})".format(amount, type(amount)) assert isinst...
[ "def", "token_operation_put_account_payment_info", "(", "token_op", ",", "account_addr", ",", "token_type", ",", "amount", ")", ":", "assert", "isinstance", "(", "amount", ",", "(", "int", ",", "long", ")", ")", ",", "\"BUG: amount is {} (type {})\"", ".", "format...
53.769231
0.011252
def get(self, _create=False, **ctx_options): """ NOTE: `ctx_options` are ignored """ if _create: return self._kind_factory.create(key=self) else: return self._kind_factory(key=self)
[ "def", "get", "(", "self", ",", "_create", "=", "False", ",", "*", "*", "ctx_options", ")", ":", "if", "_create", ":", "return", "self", ".", "_kind_factory", ".", "create", "(", "key", "=", "self", ")", "else", ":", "return", "self", ".", "_kind_fac...
29.75
0.008163
def ShortCadenceStatistics(campaign=None, clobber=False, model='nPLD', plot=True, **kwargs): ''' Computes and plots the CDPP statistics comparison between short cadence and long cadence de-trended light curves :param campaign: The campaign number or list of campaign numbers. ...
[ "def", "ShortCadenceStatistics", "(", "campaign", "=", "None", ",", "clobber", "=", "False", ",", "model", "=", "'nPLD'", ",", "plot", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Check campaign", "if", "campaign", "is", "None", ":", "campaign", "=...
38.237179
0.000817
def register_blueprint(self, blueprint, register_with_babel=True, **options): """ Like :meth:`~flask.Flask.register_blueprint`, but if ``register_with_babel`` is True, then we also allow the Babel Bundle an opportunity to register language code prefixed URLs. """ if self....
[ "def", "register_blueprint", "(", "self", ",", "blueprint", ",", "register_with_babel", "=", "True", ",", "*", "*", "options", ")", ":", "if", "self", ".", "unchained", ".", "babel_bundle", "and", "register_with_babel", ":", "self", ".", "unchained", ".", "b...
56.666667
0.009653
def create_organization( user, name, slug=None, is_active=None, org_defaults=None, org_user_defaults=None, **kwargs ): """ Returns a new organization, also creating an initial organization user who is the owner. The specific models can be specified if a custom organization a...
[ "def", "create_organization", "(", "user", ",", "name", ",", "slug", "=", "None", ",", "is_active", "=", "None", ",", "org_defaults", "=", "None", ",", "org_user_defaults", "=", "None", ",", "*", "*", "kwargs", ")", ":", "org_model", "=", "kwargs", ".", ...
30.775862
0.000543
def _sm_cleanup(self, *args, **kwargs): """ Delete all state associated with the chaos session """ if self._done_notification_func is not None: self._done_notification_func() self._timer.cancel()
[ "def", "_sm_cleanup", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_done_notification_func", "is", "not", "None", ":", "self", ".", "_done_notification_func", "(", ")", "self", ".", "_timer", ".", "cancel", "(", ...
34.428571
0.008097
def toggle_view(self, *args, **kwargs): """ Toggles the view between different groups """ group_to_display = self.views.popleft() self.cur_view.value = group_to_display for repo in self.tools_tc: for tool in self.tools_tc[repo]: t_groups = self.manifest.option...
[ "def", "toggle_view", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "group_to_display", "=", "self", ".", "views", ".", "popleft", "(", ")", "self", ".", "cur_view", ".", "value", "=", "group_to_display", "for", "repo", "in", "self"...
45.888889
0.002372
def handle_response(self, ts, resp): """ Passes a response message to the corresponding event handler, and also takes care of handling errors raised by the _raise_error handler. :param ts: timestamp, declares when data was received by the client :param resp: dict, containing info...
[ "def", "handle_response", "(", "self", ",", "ts", ",", "resp", ")", ":", "log", ".", "info", "(", "\"handle_response: Handling response %s\"", ",", "resp", ")", "event", "=", "resp", "[", "'event'", "]", "try", ":", "self", ".", "_event_handlers", "[", "ev...
39.25
0.001554
def setStimReps(self): """Sets the reps of the StimulusModel from values pulled from this widget""" reps = self.ui.nrepsSpnbx.value() self.stimModel.setRepCount(reps)
[ "def", "setStimReps", "(", "self", ")", ":", "reps", "=", "self", ".", "ui", ".", "nrepsSpnbx", ".", "value", "(", ")", "self", ".", "stimModel", ".", "setRepCount", "(", "reps", ")" ]
38.8
0.010101
def generate_general_header(headerfields, fieldtypes, firstfield, oldheader, group_by_field): """From headerfield object, this generates a full header as a list, ready to write to a TSV file E.g: headerfield = {precusroquant: {HEADER_AREA: OD([(set1, set1_HEAD), (set2, se...
[ "def", "generate_general_header", "(", "headerfields", ",", "fieldtypes", ",", "firstfield", ",", "oldheader", ",", "group_by_field", ")", ":", "if", "not", "oldheader", ":", "header", "=", "[", "firstfield", "]", "else", ":", "header", "=", "[", "firstfield",...
40.97561
0.001163
def gzip_file(self, target_path, html): """ Zips up the provided HTML as a companion for the provided path. Intended to take advantage of the peculiarities of Amazon S3's GZIP service. mtime, an option that writes a timestamp to the output file is set to 0, to avoid hav...
[ "def", "gzip_file", "(", "self", ",", "target_path", ",", "html", ")", ":", "logger", ".", "debug", "(", "\"Gzipping to {}{}\"", ".", "format", "(", "self", ".", "fs_name", ",", "target_path", ")", ")", "# Write GZIP data to an in-memory buffer", "data_buffer", ...
35.862069
0.001873
def parse_top_level(self): """The top level parser will do a loop where it looks for a single contact parse and then eats all whitespace until there is no more input left or another contact is found to be parsed and stores them. """ contacts = [] while not self.eos: ...
[ "def", "parse_top_level", "(", "self", ")", ":", "contacts", "=", "[", "]", "while", "not", "self", ".", "eos", ":", "contact", "=", "self", ".", "parse_contact", "(", ")", "# match a contact expression.", "if", "not", "contact", ":", "# There was no contact s...
47.333333
0.002301
def put(self, relpath=None, params=None, data=None, contenttype=None): """ Invoke the PUT method on a resource. @param relpath: Optional. A relative path to this resource's path. @param params: Key-value data. @param data: Optional. Body of the request. @param contenttype: Optional. @return...
[ "def", "put", "(", "self", ",", "relpath", "=", "None", ",", "params", "=", "None", ",", "data", "=", "None", ",", "contenttype", "=", "None", ")", ":", "return", "self", ".", "invoke", "(", "\"PUT\"", ",", "relpath", ",", "params", ",", "data", ",...
38.333333
0.002123
def check_global_attributes(self, ds): """ Check all global NC attributes for existence. :param netCDF4.Dataset ds: An open netCDF dataset """ return [ self._has_attr(ds, 'acknowledgement', 'Platform Sponsor'), self._has_attr(ds, 'publisher_email', 'Stati...
[ "def", "check_global_attributes", "(", "self", ",", "ds", ")", ":", "return", "[", "self", ".", "_has_attr", "(", "ds", ",", "'acknowledgement'", ",", "'Platform Sponsor'", ")", ",", "self", ".", "_has_attr", "(", "ds", ",", "'publisher_email'", ",", "'Stati...
53.466667
0.008578
async def on_ctcp_version(self, by, target, contents): """ Built-in CTCP version as some networks seem to require it. """ import pydle version = '{name} v{ver}'.format(name=pydle.__name__, ver=pydle.__version__) self.ctcp_reply(by, 'VERSION', version)
[ "async", "def", "on_ctcp_version", "(", "self", ",", "by", ",", "target", ",", "contents", ")", ":", "import", "pydle", "version", "=", "'{name} v{ver}'", ".", "format", "(", "name", "=", "pydle", ".", "__name__", ",", "ver", "=", "pydle", ".", "__versio...
46.5
0.010563
def unixtime_to_datetime(ut): """Convert a unixtime timestamp to a datetime object. The function converts a timestamp in Unix format to a datetime object. UTC timezone will also be set. :param ut: Unix timestamp to convert :returns: a datetime object :raises InvalidDateError: when the given time...
[ "def", "unixtime_to_datetime", "(", "ut", ")", ":", "dt", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "ut", ")", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "tz", ".", "tzutc", "(", ")", ")", "return", "dt" ]
36.076923
0.002079
def spectral_clustering(geom, K, eigen_solver = 'dense', random_state = None, solver_kwds = None, renormalize = True, stabalize = True, additional_vectors = 0): """ Spectral clustering for find K clusters by using the eigenvectors of a matrix which is derived from a set of similari...
[ "def", "spectral_clustering", "(", "geom", ",", "K", ",", "eigen_solver", "=", "'dense'", ",", "random_state", "=", "None", ",", "solver_kwds", "=", "None", ",", "renormalize", "=", "True", ",", "stabalize", "=", "True", ",", "additional_vectors", "=", "0", ...
47.82
0.012497
def create_hadoopcli_client(): """ Given that we want one of the hadoop cli clients (unlike snakebite), this one will return the right one. """ version = hdfs_config.get_configured_hadoop_version() if version == "cdh4": return HdfsClient() elif version == "cdh3": return HdfsC...
[ "def", "create_hadoopcli_client", "(", ")", ":", "version", "=", "hdfs_config", ".", "get_configured_hadoop_version", "(", ")", "if", "version", "==", "\"cdh4\"", ":", "return", "HdfsClient", "(", ")", "elif", "version", "==", "\"cdh3\"", ":", "return", "HdfsCli...
34.866667
0.001862
def _convert_angle_from_pypot(angle, joint, **kwargs): """Converts an angle to a PyPot-compatible format""" angle_internal = angle + joint["offset"] if joint["orientation-convention"] == "indirect": angle_internal = -1 * angle_internal # UGLY if joint["name"].startswith("l_shoulder_x"): ...
[ "def", "_convert_angle_from_pypot", "(", "angle", ",", "joint", ",", "*", "*", "kwargs", ")", ":", "angle_internal", "=", "angle", "+", "joint", "[", "\"offset\"", "]", "if", "joint", "[", "\"orientation-convention\"", "]", "==", "\"indirect\"", ":", "angle_in...
30.642857
0.002262
def colors( self, name ): """ Returns all the colors in order for the inputed color name. :return [<QColor>, ..] """ output = [] colors = self._colors.get(name, {}) for colorType in self._colorGroups: output.append(colors.get(colorType, QC...
[ "def", "colors", "(", "self", ",", "name", ")", ":", "output", "=", "[", "]", "colors", "=", "self", ".", "_colors", ".", "get", "(", "name", ",", "{", "}", ")", "for", "colorType", "in", "self", ".", "_colorGroups", ":", "output", ".", "append", ...
30.909091
0.014286
def split_emails(msg): """ Given a message (which may consist of an email conversation thread with multiple emails), mark the lines to identify split lines, content lines and empty lines. Correct the split line markers inside header blocks. Header blocks are identified by the regular expression...
[ "def", "split_emails", "(", "msg", ")", ":", "msg_body", "=", "_replace_link_brackets", "(", "msg", ")", "# don't process too long messages", "lines", "=", "msg_body", ".", "splitlines", "(", ")", "[", ":", "MAX_LINES_COUNT", "]", "markers", "=", "remove_initial_s...
32.26087
0.001309
def fetch_withdrawals_since(self, since: int) -> List[Withdrawal]: """Fetch all withdrawals since the given timestamp.""" return self._transactions_since(self._withdrawals_since, 'withdrawals', since)
[ "def", "fetch_withdrawals_since", "(", "self", ",", "since", ":", "int", ")", "->", "List", "[", "Withdrawal", "]", ":", "return", "self", ".", "_transactions_since", "(", "self", ".", "_withdrawals_since", ",", "'withdrawals'", ",", "since", ")" ]
71.333333
0.013889
def get_popular_decks(self, **params: keys): """Get a list of most queried decks \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the ...
[ "def", "get_popular_decks", "(", "self", ",", "*", "*", "params", ":", "keys", ")", ":", "url", "=", "self", ".", "api", ".", "POPULAR", "+", "'/decks'", "return", "self", ".", "_get_model", "(", "url", ",", "*", "*", "params", ")" ]
38.052632
0.016194
def get_error_probability(self): """This means for the base we are talking about how many errors between 0 and 1 do we attribute to it? For the 'unobserved' errors, these can only count when one is adjacent to base :returns: error probability p(error_observed)+(1-p_error_observed)*error_unobserved :...
[ "def", "get_error_probability", "(", "self", ")", ":", "a", "=", "self", ".", "_observable", ".", "get_error_probability", "(", ")", "b", "=", "self", ".", "_unobservable", ".", "get_error_probability", "(", ")", "return", "a", "+", "(", "1", "-", "a", "...
41.090909
0.008658
def compute_voltages(grid, configs_raw, potentials_raw): """Given a list of potential distribution and corresponding four-point spreads, compute the voltages Parameters ---------- grid: crt_grid object the grid is used to infer electrode positions configs_raw: Nx4 array containi...
[ "def", "compute_voltages", "(", "grid", ",", "configs_raw", ",", "potentials_raw", ")", ":", "# we operate on 0-indexed arrays, config holds 1-indexed values", "# configs = configs_raw - 1", "voltages", "=", "[", "]", "for", "config", ",", "potentials", "in", "zip", "(", ...
38.481481
0.000939
def register(adapter): '''Register a search adapter''' # register the class in the catalog if adapter.model and adapter.model not in adapter_catalog: adapter_catalog[adapter.model] = adapter # Automatically (re|un)index objects on save/delete post_save.connect(reindex_model_on_save, ...
[ "def", "register", "(", "adapter", ")", ":", "# register the class in the catalog", "if", "adapter", ".", "model", "and", "adapter", ".", "model", "not", "in", "adapter_catalog", ":", "adapter_catalog", "[", "adapter", ".", "model", "]", "=", "adapter", "# Autom...
47.444444
0.002299
def getUserSignupDate(self): """ Returns the human readable date of when the user signed up for google reader. """ userinfo = self.getUserInfo() timestamp = int(float(userinfo["signupTimeSec"])) return time.strftime("%m/%d/%Y %H:%M", time.gmtime(timestamp))
[ "def", "getUserSignupDate", "(", "self", ")", ":", "userinfo", "=", "self", ".", "getUserInfo", "(", ")", "timestamp", "=", "int", "(", "float", "(", "userinfo", "[", "\"signupTimeSec\"", "]", ")", ")", "return", "time", ".", "strftime", "(", "\"%m/%d/%Y %...
42.714286
0.009836
def mousePressEvent( self, event ): """ Overloads the mouse press event to handle special cases and \ bypass when the scene is in view mode. :param event <QMousePressEvent> """ event.setAccepted(False) self._hotspotPressed = False # ignore ...
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "event", ".", "setAccepted", "(", "False", ")", "self", ".", "_hotspotPressed", "=", "False", "# ignore events when the scene is in view mode", "scene", "=", "self", ".", "scene", "(", ")", "if", "...
34.209302
0.011897
def read_graph(filename): """! @brief Read graph from file in GRPR format. @param[in] filename (string): Path to file with graph in GRPR format. @return (graph) Graph that is read from file. """ file = open(filename, 'r'); comments = ""; space_descr ...
[ "def", "read_graph", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "'r'", ")", "comments", "=", "\"\"", "space_descr", "=", "[", "]", "data", "=", "[", "]", "data_type", "=", "None", "map_data_repr", "=", "dict", "(", ")", "# ...
38.901099
0.027824
def save(self, filename=None): """Write config to file.""" if self.__fname is None and filename is None: raise ValueError('Config loaded from string, no filename specified') conf = self.__config cpa = dict_to_cp(conf) with open(self.__fname if filename is None else fi...
[ "def", "save", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "self", ".", "__fname", "is", "None", "and", "filename", "is", "None", ":", "raise", "ValueError", "(", "'Config loaded from string, no filename specified'", ")", "conf", "=", "self", ...
44.5
0.008264
def _call_pyfftw(self, x, out, **kwargs): """Implement ``self(x[, out, **kwargs])`` for pyfftw back-end. Parameters ---------- x : `numpy.ndarray` Array representing the function to be transformed out : `numpy.ndarray` Array to which the output is written...
[ "def", "_call_pyfftw", "(", "self", ",", "x", ",", "out", ",", "*", "*", "kwargs", ")", ":", "# We pop some kwargs options here so that we always use the ones", "# given during init or implicitly assumed.", "kwargs", ".", "pop", "(", "'axes'", ",", "None", ")", "kwarg...
41.962963
0.000862
async def log_transaction(self, **params): """Writing transaction to database """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} coinid = params.get("coinid") if not coinid in ["QTUM", "PUT"]: re...
[ "async", "def", "log_transaction", "(", "self", ",", "*", "*", "params", ")", ":", "if", "params", ".", "get", "(", "\"message\"", ")", ":", "params", "=", "json", ".", "loads", "(", "params", ".", "get", "(", "\"message\"", ",", "\"{}\"", ")", ")", ...
29.541667
0.047814
def iter_custom_errors(catalog): """Realiza validaciones sin usar el jsonschema. En esta función se agregan bloques de código en python que realizan validaciones complicadas o imposibles de especificar usando jsonschema. """ try: # chequea que no se repiten los ids de la taxonomía específi...
[ "def", "iter_custom_errors", "(", "catalog", ")", ":", "try", ":", "# chequea que no se repiten los ids de la taxonomía específica", "if", "\"themeTaxonomy\"", "in", "catalog", ":", "theme_ids", "=", "[", "theme", "[", "\"id\"", "]", "for", "theme", "in", "catalog", ...
42.45283
0.000434
def register_cls_list(self, cls_and_handler): """ register a class to singledispatch """ for cls, handler in cls_and_handler: self._single_dispatch.register(cls, handler) self.dispatch.cache_clear()
[ "def", "register_cls_list", "(", "self", ",", "cls_and_handler", ")", ":", "for", "cls", ",", "handler", "in", "cls_and_handler", ":", "self", ".", "_single_dispatch", ".", "register", "(", "cls", ",", "handler", ")", "self", ".", "dispatch", ".", "cache_cle...
46
0.008547
def simxGetDialogResult(clientID, dialogHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' result = ct.c_int() return c_GetDialogResult(clientID, dialogHandle, ct.byref(result), operationMode), result.value
[ "def", "simxGetDialogResult", "(", "clientID", ",", "dialogHandle", ",", "operationMode", ")", ":", "result", "=", "ct", ".", "c_int", "(", ")", "return", "c_GetDialogResult", "(", "clientID", ",", "dialogHandle", ",", "ct", ".", "byref", "(", "result", ")",...
48
0.010239
def interact(banner=None, readfunc=None, my_locals=None, my_globals=None): """Almost a copy of code.interact Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readl...
[ "def", "interact", "(", "banner", "=", "None", ",", "readfunc", "=", "None", ",", "my_locals", "=", "None", ",", "my_globals", "=", "None", ")", ":", "console", "=", "code", ".", "InteractiveConsole", "(", "my_locals", ",", "filename", "=", "'<trepan>'", ...
35.888889
0.001005
def process_rst_and_summaries(content_generators): """ Ensure mathjax script is applied to RST and summaries are corrected if specified in user settings. Handles content attached to ArticleGenerator and PageGenerator objects, since the plugin doesn't know how to handle other Generator types. F...
[ "def", "process_rst_and_summaries", "(", "content_generators", ")", ":", "for", "generator", "in", "content_generators", ":", "if", "isinstance", "(", "generator", ",", "generators", ".", "ArticlesGenerator", ")", ":", "for", "article", "in", "(", "generator", "."...
41.516129
0.001519
def first_(self): """ Select the first row """ try: val = self.df.iloc[0] return val except Exception as e: self.err(e, "Can not select first row")
[ "def", "first_", "(", "self", ")", ":", "try", ":", "val", "=", "self", ".", "df", ".", "iloc", "[", "0", "]", "return", "val", "except", "Exception", "as", "e", ":", "self", ".", "err", "(", "e", ",", "\"Can not select first row\"", ")" ]
23.888889
0.008969
def make_roi_plots(self, gta, mcube_tot, **kwargs): """Make various diagnostic plots for the 1D and 2D counts/model distributions. Parameters ---------- prefix : str Prefix that will be appended to all filenames. """ fmt = kwargs.get('format', self...
[ "def", "make_roi_plots", "(", "self", ",", "gta", ",", "mcube_tot", ",", "*", "*", "kwargs", ")", ":", "fmt", "=", "kwargs", ".", "get", "(", "'format'", ",", "self", ".", "config", "[", "'format'", "]", ")", "figsize", "=", "kwargs", ".", "get", "...
40.44086
0.001557
def freeNSynapses(self, numToFree, inactiveSynapseIndices, verbosity= 0): """Free up some synapses in this segment. We always free up inactive synapses (lowest permanence freed up first) before we start to free up active ones. @param numToFree number of synapses to free up @param inact...
[ "def", "freeNSynapses", "(", "self", ",", "numToFree", ",", "inactiveSynapseIndices", ",", "verbosity", "=", "0", ")", ":", "# Make sure numToFree isn't larger than the total number of syns we have", "assert", "(", "numToFree", "<=", "len", "(", "self", ".", "syns", "...
37.235294
0.010775
def elapsed(t0=0.0): """get elapsed time from the give time Returns: now: the absolute time now dt_str: elapsed time in string """ now = time() dt = now - t0 dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN) if dt_sec <= 1: dt_str = str(dt...
[ "def", "elapsed", "(", "t0", "=", "0.0", ")", ":", "now", "=", "time", "(", ")", "dt", "=", "now", "-", "t0", "dt_sec", "=", "Decimal", "(", "str", "(", "dt", ")", ")", ".", "quantize", "(", "Decimal", "(", "'.0001'", ")", ",", "rounding", "=",...
26.533333
0.002427
def coerce_to_dtypes(result, dtypes): """ given a dtypes and a result set, coerce the result elements to the dtypes """ if len(result) != len(dtypes): raise AssertionError("_coerce_to_dtypes requires equal len arrays") def conv(r, dtype): try: if isna(r): ...
[ "def", "coerce_to_dtypes", "(", "result", ",", "dtypes", ")", ":", "if", "len", "(", "result", ")", "!=", "len", "(", "dtypes", ")", ":", "raise", "AssertionError", "(", "\"_coerce_to_dtypes requires equal len arrays\"", ")", "def", "conv", "(", "r", ",", "d...
29.774194
0.001049
def log(self, *args, **kwargs): """Convenience function for printing indenting debug output.""" if self.verbose: print(' ' * self.depth, *args, **kwargs)
[ "def", "log", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "' '", "*", "self", ".", "depth", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
45
0.010929
def safe_filename(name, extension=None, digest=None, max_length=_MAX_FILENAME_LENGTH): """Creates filename from name and extension ensuring that the final length is within the max_length constraint. By default the length is capped to work on most filesystems and the fallback to achieve shortening is a sha1 has...
[ "def", "safe_filename", "(", "name", ",", "extension", "=", "None", ",", "digest", "=", "None", ",", "max_length", "=", "_MAX_FILENAME_LENGTH", ")", ":", "if", "os", ".", "path", ".", "basename", "(", "name", ")", "!=", "name", ":", "raise", "ValueError"...
43.119048
0.008639
def matchBlocks(self, blocks, threshold=.5, *args, **kwargs): """ Partitions blocked data and generates a sequence of clusters, where each cluster is a tuple of record ids Keyword arguments: blocks -- Sequence of tuples of records, where each tuple is a set of...
[ "def", "matchBlocks", "(", "self", ",", "blocks", ",", "threshold", "=", ".5", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "candidate_records", "=", "self", ".", "_blockedPairs", "(", "blocks", ")", "matches", "=", "core", ".", "scoreGazette", ...
38.9
0.001672
def egg2dist(self, egginfo_path, distinfo_path): """Convert an .egg-info directory into a .dist-info directory""" def adios(p): """Appropriately delete directory, file or link.""" if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p): shutil.rmtree(p...
[ "def", "egg2dist", "(", "self", ",", "egginfo_path", ",", "distinfo_path", ")", ":", "def", "adios", "(", "p", ")", ":", "\"\"\"Appropriately delete directory, file or link.\"\"\"", "if", "os", ".", "path", ".", "exists", "(", "p", ")", "and", "not", "os", "...
43.517241
0.001937
def post_publication_processing(event, cursor): """Process post-publication events coming out of the database.""" module_ident, ident_hash = event.module_ident, event.ident_hash celery_app = get_current_registry().celery_app # Check baking is not already queued. cursor.execute('SELECT result_id::t...
[ "def", "post_publication_processing", "(", "event", ",", "cursor", ")", ":", "module_ident", ",", "ident_hash", "=", "event", ".", "module_ident", ",", "event", ".", "ident_hash", "celery_app", "=", "get_current_registry", "(", ")", ".", "celery_app", "# Check bak...
44.818182
0.000662
def create(self, name, targetUrl, resource, event, filter=None, secret=None, **request_parameters): """Create a webhook. Args: name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for e...
[ "def", "create", "(", "self", ",", "name", ",", "targetUrl", ",", "resource", ",", "event", ",", "filter", "=", "None", ",", "secret", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "name", ",", "basestring", ",", "may_b...
39.222222
0.001658
def _call_cli(self, command, cwd=None, universal_newlines=False, redirect_stderr=False): """ Executes the given command, internally using Popen. The output of stdout and stderr are returned as a tuple. The returned tuple looks like: (stdout, stderr, returncode) Parameters ---------- command: string Th...
[ "def", "_call_cli", "(", "self", ",", "command", ",", "cwd", "=", "None", ",", "universal_newlines", "=", "False", ",", "redirect_stderr", "=", "False", ")", ":", "command", "=", "str", "(", "command", ".", "encode", "(", "\"utf-8\"", ")", ".", "decode",...
37.04
0.027368
def count_open_fds(): """return the number of open file descriptors for current process. .. warning: will only work on UNIX-like os-es. http://stackoverflow.com/a/7142094 """ pid = os.getpid() procs = subprocess.check_output( ['lsof', '-w', '-Ff', '-p', str(pid)]) nprocs = len( ...
[ "def", "count_open_fds", "(", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "procs", "=", "subprocess", ".", "check_output", "(", "[", "'lsof'", ",", "'-w'", ",", "'-Ff'", ",", "'-p'", ",", "str", "(", "pid", ")", "]", ")", "nprocs", "=", ...
23.941176
0.002364
def parse_at_root( self, root, # type: ET.Element state # type: _ProcessorState ): # type: (...) -> Any """Parse the given element as the root of the document.""" xml_value = self._processor.parse_at_root(root, state) return _hooks_apply_after_pa...
[ "def", "parse_at_root", "(", "self", ",", "root", ",", "# type: ET.Element", "state", "# type: _ProcessorState", ")", ":", "# type: (...) -> Any", "xml_value", "=", "self", ".", "_processor", ".", "parse_at_root", "(", "root", ",", "state", ")", "return", "_hooks_...
38.444444
0.011299
def store_transition(self, frame, action, reward, done, extra_info=None): """ Store given transition in the backend """ self.backend.store_transition(frame=frame, action=action, reward=reward, done=done, extra_info=extra_info)
[ "def", "store_transition", "(", "self", ",", "frame", ",", "action", ",", "reward", ",", "done", ",", "extra_info", "=", "None", ")", ":", "self", ".", "backend", ".", "store_transition", "(", "frame", "=", "frame", ",", "action", "=", "action", ",", "...
80
0.012397
def set_index(self, keys, drop=True, append=False, inplace=False, verify_integrity=False): """Set the DataFrame index (row labels) using one or more existing columns. Wrapper around the :meth:`pandas.DataFrame.set_index` method. """ if drop is True: ...
[ "def", "set_index", "(", "self", ",", "keys", ",", "drop", "=", "True", ",", "append", "=", "False", ",", "inplace", "=", "False", ",", "verify_integrity", "=", "False", ")", ":", "if", "drop", "is", "True", ":", "try", ":", "assert", "type", "(", ...
43.366667
0.002256
def choose(self): """Choose repositories """ keys = """ Choose repositories at the right side for enable or to the left side for disable. Keys: SPACE select or deselect the highlighted repositories, move it between the left and right lists ^ move the focus to the ...
[ "def", "choose", "(", "self", ")", ":", "keys", "=", "\"\"\"\nChoose repositories at the right side for enable or to the\nleft side for disable.\n\nKeys: SPACE select or deselect the highlighted repositories,\n move it between the left and right lists\n ^ move the focus ...
35.884615
0.002088
def heating_stats(self): """Calculate some heating data stats.""" local_5 = [] local_10 = [] for i in range(0, 10): level = self.past_heating_level(i) if level == 0: _LOGGER.debug('Cant calculate stats yet...') return i...
[ "def", "heating_stats", "(", "self", ")", ":", "local_5", "=", "[", "]", "local_10", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "10", ")", ":", "level", "=", "self", ".", "past_heating_level", "(", "i", ")", "if", "level", "==", "0"...
38.944444
0.002088
def get_variation(self, experiment, user_id, attributes, ignore_user_profile=False): """ Top-level function to help determine variation user should be put in. First, check if experiment is running. Second, check if user is forced in a variation. Third, check if there is a stored decision for the user a...
[ "def", "get_variation", "(", "self", ",", "experiment", ",", "user_id", ",", "attributes", ",", "ignore_user_profile", "=", "False", ")", ":", "# Check if experiment is running", "if", "not", "experiment_helper", ".", "is_experiment_running", "(", "experiment", ")", ...
40.621622
0.009743
def get_namespace( self, namespace_id, include_history=True ): """ Given a namespace ID, get the ready namespace op for it. Return the dict with the parameters on success. Return None if the namespace has not yet been revealed. """ cur = self.db.cursor() return ...
[ "def", "get_namespace", "(", "self", ",", "namespace_id", ",", "include_history", "=", "True", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_namespace_ready", "(", "cur", ",", "namespace_id", ",", "include_history", ...
39.1
0.0175
def delay_or_run(self, *args, **kwargs): """ Attempt to call self.delay, or if that fails, call self.run. Returns a tuple, (result, required_fallback). ``result`` is the result of calling delay or run. ``required_fallback`` is True if the broker failed we had to resort to `self....
[ "def", "delay_or_run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"delay_or_run is deprecated. Please use delay_or_eager\"", ",", "DeprecationWarning", ",", ")", "possible_broker_errors", "=", "self", ".", "_g...
40.35
0.002421
def normalize_outputdir(outputdir=None): """ if output dir is None try using the ./drivers directory if it already exists, otherwise use the current working directory """ normalized = '' cwd = os.getcwd() if not outputdir: outputdir_drivers = os.path.join(cwd, 'drivers') if os.pa...
[ "def", "normalize_outputdir", "(", "outputdir", "=", "None", ")", ":", "normalized", "=", "''", "cwd", "=", "os", ".", "getcwd", "(", ")", "if", "not", "outputdir", ":", "outputdir_drivers", "=", "os", ".", "path", ".", "join", "(", "cwd", ",", "'drive...
34.666667
0.001873
def rename_categories(self, new_categories, inplace=False): """ Rename categories. Parameters ---------- new_categories : list-like, dict-like or callable * list-like: all items must be unique and the number of items in the new categories must match the ...
[ "def", "rename_categories", "(", "self", ",", "new_categories", ",", "inplace", "=", "False", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "cat", "=", "self", "if", "inplace", "else", "self", ".", "copy", "(", ")"...
34.569892
0.000605
def normalize_modpath(modpath, hide_init=True, hide_main=False): """ Normalizes __init__ and __main__ paths. Notes: Adds __init__ if reasonable, but only removes __main__ by default Args: hide_init (bool): if True, always return package modules as __init__.py files otherwise...
[ "def", "normalize_modpath", "(", "modpath", ",", "hide_init", "=", "True", ",", "hide_main", "=", "False", ")", ":", "if", "six", ".", "PY2", ":", "if", "modpath", ".", "endswith", "(", "'.pyc'", ")", ":", "modpath", "=", "modpath", "[", ":", "-", "1...
39.4
0.000991
def _SkipVarint(buffer, pos, end): """Skip a varint value. Returns the new position.""" # Previously ord(buffer[pos]) raised IndexError when pos is out of range. # With this code, ord(b'') raises TypeError. Both are handled in # python_message.py to generate a 'Truncated message' error. while ord(buffer[pos...
[ "def", "_SkipVarint", "(", "buffer", ",", "pos", ",", "end", ")", ":", "# Previously ord(buffer[pos]) raised IndexError when pos is out of range.", "# With this code, ord(b'') raises TypeError. Both are handled in", "# python_message.py to generate a 'Truncated message' error.", "while", ...
38.545455
0.020737
def color_range(color, N=20): """ Generates a scale of colours from a base colour Parameters: ----------- color : string Color representation in hex N : int number of colours to generate Example: color_range('#ff9933',20...
[ "def", "color_range", "(", "color", ",", "N", "=", "20", ")", ":", "color", "=", "normalize", "(", "color", ")", "org", "=", "color", "color", "=", "hex_to_hsv", "(", "color", ")", "HSV_tuples", "=", "[", "(", "color", "[", "0", "]", ",", "x", ",...
30.4
0.001063
def pts_relative(pts=[], shift=[0.0, 0.0], angle=[0.0]): '''Convenience shift+rotate combination. ''' assert isinstance(pts, list) and len(pts) > 0 l_pt_prev = None for pt in pts: assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: ass...
[ "def", "pts_relative", "(", "pts", "=", "[", "]", ",", "shift", "=", "[", "0.0", ",", "0.0", "]", ",", "angle", "=", "[", "0.0", "]", ")", ":", "assert", "isinstance", "(", "pts", ",", "list", ")", "and", "len", "(", "pts", ")", ">", "0", "l_...
29.037037
0.001235
def __initialize_languages_model(self): """ Initializes the languages Model. """ languages = [PYTHON_LANGUAGE, LOGGING_LANGUAGE, TEXT_LANGUAGE] existingGrammarFiles = [os.path.normpath(language.file) for language in languages] for directory in RuntimeGlobals.resources_d...
[ "def", "__initialize_languages_model", "(", "self", ")", ":", "languages", "=", "[", "PYTHON_LANGUAGE", ",", "LOGGING_LANGUAGE", ",", "TEXT_LANGUAGE", "]", "existingGrammarFiles", "=", "[", "os", ".", "path", ".", "normpath", "(", "language", ".", "file", ")", ...
43.727273
0.008138
def parse_string(cls, content, basedir=None, resolve=True, unresolved_value=DEFAULT_SUBSTITUTION): """Parse URL :param content: content to parse :type content: basestring :param resolve: If true, resolve substitutions :param resolve: if true, resolve substitutions :type ...
[ "def", "parse_string", "(", "cls", ",", "content", ",", "basedir", "=", "None", ",", "resolve", "=", "True", ",", "unresolved_value", "=", "DEFAULT_SUBSTITUTION", ")", ":", "return", "ConfigParser", "(", ")", ".", "parse", "(", "content", ",", "basedir", "...
51.5625
0.008333
def iterfd(fd, size=10000000): ''' Generator which yields bytes from a file descriptor. Args: fd (file): A file-like object to read bytes from. size (int): Size, in bytes, of the number of bytes to read from the fd at a given time. Notes: If the first read call on the f...
[ "def", "iterfd", "(", "fd", ",", "size", "=", "10000000", ")", ":", "fd", ".", "seek", "(", "0", ")", "byts", "=", "fd", ".", "read", "(", "size", ")", "# Fast path to yield b''", "if", "len", "(", "byts", ")", "==", "0", ":", "yield", "byts", "r...
28.888889
0.001241
def reset_password(server_context, email, container_path=None): """ Change password for a user (Requires Admin privileges on the LabKey server) :param server_context: A LabKey server context. See utils.create_server_context. :param email: :param container_path: :return: """ url = server...
[ "def", "reset_password", "(", "server_context", ",", "email", ",", "container_path", "=", "None", ")", ":", "url", "=", "server_context", ".", "build_url", "(", "security_controller", ",", "'adminRotatePassword.api'", ",", "container_path", ")", "return", "server_co...
35.923077
0.008351
def sndread_chunked(path:str, frames:int=_CHUNKSIZE) -> Iterator[np.ndarray]: """ Returns a generator yielding numpy arrays (float64) of at most `frames` frames """ backend = _getBackend(path, key=lambda backend: backend.can_read_chunked) if backend: logger.debug(f"sndread_chunked: using...
[ "def", "sndread_chunked", "(", "path", ":", "str", ",", "frames", ":", "int", "=", "_CHUNKSIZE", ")", "->", "Iterator", "[", "np", ".", "ndarray", "]", ":", "backend", "=", "_getBackend", "(", "path", ",", "key", "=", "lambda", "backend", ":", "backend...
44
0.012146
def __add_sentence_to_document(self, sentence): """ Converts a sentence into a TigerSentenceGraph and adds all its nodes, edges (and their features) to this document graph. This also adds a ``dominance_relation`` edge from the root node of this document graph to the root node of...
[ "def", "__add_sentence_to_document", "(", "self", ",", "sentence", ")", ":", "sentence_graph", "=", "TigerSentenceGraph", "(", "sentence", ")", "self", ".", "tokens", ".", "extend", "(", "sentence_graph", ".", "tokens", ")", "sentence_root_node_id", "=", "sentence...
43.666667
0.001867
def make_path(phase) -> str: """ Create the path to the folder at which the metadata and optimizer pickle should be saved """ return "{}/{}{}{}".format(conf.instance.output_path, phase.phase_path, phase.phase_name, phase.phase_tag)
[ "def", "make_path", "(", "phase", ")", "->", "str", ":", "return", "\"{}/{}{}{}\"", ".", "format", "(", "conf", ".", "instance", ".", "output_path", ",", "phase", ".", "phase_path", ",", "phase", ".", "phase_name", ",", "phase", ".", "phase_tag", ")" ]
48.6
0.012146
def _wet_message_received(self, msg): """Report a wet state.""" for callback in self._dry_wet_callbacks: callback(LeakSensorState.WET) self._update_subscribers(0x13)
[ "def", "_wet_message_received", "(", "self", ",", "msg", ")", ":", "for", "callback", "in", "self", ".", "_dry_wet_callbacks", ":", "callback", "(", "LeakSensorState", ".", "WET", ")", "self", ".", "_update_subscribers", "(", "0x13", ")" ]
39.4
0.00995
def push(self, stream, reading): """Push a reading into a stream, updating any associated stream walkers. Args: stream (DataStream): the stream to push the reading into reading (IOTileReading): the reading to push """ # Make sure the stream is correct re...
[ "def", "push", "(", "self", ",", "stream", ",", "reading", ")", ":", "# Make sure the stream is correct", "reading", "=", "copy", ".", "copy", "(", "reading", ")", "reading", ".", "stream", "=", "stream", ".", "encode", "(", ")", "if", "stream", ".", "bu...
37.304348
0.002271
def fnmatchcase(name, pat): """Test whether FILENAME matches PATTERN, including case. This is a version of fnmatch() which doesn't case-normalize its arguments. """ try: re_pat = _cache[pat] except KeyError: res = translate(pat) if len(_cache) >= _MAXCACHE: ...
[ "def", "fnmatchcase", "(", "name", ",", "pat", ")", ":", "try", ":", "re_pat", "=", "_cache", "[", "pat", "]", "except", "KeyError", ":", "res", "=", "translate", "(", "pat", ")", "if", "len", "(", "_cache", ")", ">=", "_MAXCACHE", ":", "# _cache.cle...
27.9375
0.002165
def timespan_type(arg): """An argparse type representing a timespan such as 6h for 6 hours.""" try: arg = parse_timespan(arg) except ValueError: raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg))) return arg
[ "def", "timespan_type", "(", "arg", ")", ":", "try", ":", "arg", "=", "parse_timespan", "(", "arg", ")", "except", "ValueError", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"{0} is not a valid time span\"", ".", "format", "(", "repr", "(", "arg"...
34.285714
0.03252
def nn_poll(fds, timeout=-1): """ nn_pollfds :param fds: dict (file descriptor => pollmode) :param timeout: timeout in milliseconds :return: """ polls = [] for i, entry in enumerate(fds.items()): s = PollFds() fd, event = entry s.fd = fd s.events = event ...
[ "def", "nn_poll", "(", "fds", ",", "timeout", "=", "-", "1", ")", ":", "polls", "=", "[", "]", "for", "i", ",", "entry", "in", "enumerate", "(", "fds", ".", "items", "(", ")", ")", ":", "s", "=", "PollFds", "(", ")", "fd", ",", "event", "=", ...
26.047619
0.001764
def infer_ast_from_something(self, obj, context=None): """infer astroid for the given class""" if hasattr(obj, "__class__") and not isinstance(obj, type): klass = obj.__class__ else: klass = obj try: modname = klass.__module__ except AttributeE...
[ "def", "infer_ast_from_something", "(", "self", ",", "obj", ",", "context", "=", "None", ")", ":", "if", "hasattr", "(", "obj", ",", "\"__class__\"", ")", "and", "not", "isinstance", "(", "obj", ",", "type", ")", ":", "klass", "=", "obj", ".", "__class...
39.697674
0.001715
def get_exported(self): """Get a new dict with the exported variables.""" return dict((k, self.vars[k]) for k in self.exported_vars)
[ "def", "get_exported", "(", "self", ")", ":", "return", "dict", "(", "(", "k", ",", "self", ".", "vars", "[", "k", "]", ")", "for", "k", "in", "self", ".", "exported_vars", ")" ]
48.666667
0.013514
def facade(projectmainfn, **kwargs): # (Callable[[None], None], Any) -> None """Facade to simplify project setup that calls project main function Args: projectmainfn ((None) -> None): main function of project **kwargs: configuration parameters to pass to HDX Configuration class Returns...
[ "def", "facade", "(", "projectmainfn", ",", "*", "*", "kwargs", ")", ":", "# (Callable[[None], None], Any) -> None", "#", "# Setting up configuration", "#", "site_url", "=", "Configuration", ".", "_create", "(", "*", "*", "kwargs", ")", "logger", ".", "info", "(...
28.625
0.001408
def validate_rpc_sha(repo_dir, commit): """Validate/update a SHA given for the rpc-openstack repo.""" # Is the commit valid? Just in case the commit is a # PR ref, we try both the ref given and the ref prepended # with the remote 'origin'. try: osa_differ.validate_commits(repo_dir, [commit]...
[ "def", "validate_rpc_sha", "(", "repo_dir", ",", "commit", ")", ":", "# Is the commit valid? Just in case the commit is a", "# PR ref, we try both the ref given and the ref prepended", "# with the remote 'origin'.", "try", ":", "osa_differ", ".", "validate_commits", "(", "repo_dir"...
39.8
0.001637
def get_travis_branch(): """Get current branch per Travis environment variables If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the name of the branch corresponding to the PR is stored in the TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the branch is stored ...
[ "def", "get_travis_branch", "(", ")", ":", "# noqa E501", "try", ":", "travis_pull_request", "=", "get_travis_env_or_fail", "(", "'TRAVIS_PULL_REQUEST'", ")", "if", "truthy", "(", "travis_pull_request", ")", ":", "travis_pull_request_branch", "=", "get_travis_env_or_fail"...
44.142857
0.001056
def _finalize_iteration(self, yk, resnorm): '''Compute solution, error norm and residual norm if required. :return: the residual norm or ``None``. ''' self.xk = None # compute error norm if asked for if self.linear_system.exact_solution is not None: self.xk =...
[ "def", "_finalize_iteration", "(", "self", ",", "yk", ",", "resnorm", ")", ":", "self", ".", "xk", "=", "None", "# compute error norm if asked for", "if", "self", ".", "linear_system", ".", "exact_solution", "is", "not", "None", ":", "self", ".", "xk", "=", ...
43.377358
0.000851
def _set_links_job_archive(self): """Pass self._job_archive along to links""" for link in self._links.values(): link._job_archive = self._job_archive
[ "def", "_set_links_job_archive", "(", "self", ")", ":", "for", "link", "in", "self", ".", "_links", ".", "values", "(", ")", ":", "link", ".", "_job_archive", "=", "self", ".", "_job_archive" ]
43.5
0.011299
def irf(self, ts_length=100, shock=None): """ Create Impulse Response Functions Parameters ---------- ts_length : scalar(int) Number of periods to calculate IRF Shock : array_like(float) Vector of shocks to calculate IRF to. Default is first ele...
[ "def", "irf", "(", "self", ",", "ts_length", "=", "100", ",", "shock", "=", "None", ")", ":", "if", "type", "(", "shock", ")", "!=", "np", ".", "ndarray", ":", "# Default is to select first element of w", "shock", "=", "np", ".", "vstack", "(", "(", "n...
40.489362
0.001026
def _facts(self, pk, pk_att, target, visited=set(), parent_table='', parent_pk=''): ''' Returns the facts for the given entity with pk in `target`. ''' facts = [] cols = self.db.cols[target] if target != self.db.target_table: # Skip the class attribute ...
[ "def", "_facts", "(", "self", ",", "pk", ",", "pk_att", ",", "target", ",", "visited", "=", "set", "(", ")", ",", "parent_table", "=", "''", ",", "parent_pk", "=", "''", ")", ":", "facts", "=", "[", "]", "cols", "=", "self", ".", "db", ".", "co...
51.383838
0.001543
def plotSpikeStats (include = ['allCells', 'eachPop'], statDataIn = {}, timeRange = None, graphType='boxplot', stats = ['rate', 'isicv'], bins = 50, popColors = [], histlogy = False, histlogx = False, histmin = 0.0, density = False, includeRate0=False, legendLabels = None, normfit = False, ...
[ "def", "plotSpikeStats", "(", "include", "=", "[", "'allCells'", ",", "'eachPop'", "]", ",", "statDataIn", "=", "{", "}", ",", "timeRange", "=", "None", ",", "graphType", "=", "'boxplot'", ",", "stats", "=", "[", "'rate'", ",", "'isicv'", "]", ",", "bi...
47.474138
0.015355
def send_activation_email(self, user, profile, password, site): """ Custom send email method to supplied the activation link and new generated password. """ ctx_dict = { 'password': password, 'site': site, 'activation_key': profile.act...
[ "def", "send_activation_email", "(", "self", ",", "user", ",", "profile", ",", "password", ",", "site", ")", ":", "ctx_dict", "=", "{", "'password'", ":", "password", ",", "'site'", ":", "site", ",", "'activation_key'", ":", "profile", ".", "activation_key",...
39.73913
0.010684
def range(cls, start=None, stop=None, step=None, inclusive=False): """Generator of a date range Args: start (Date): stop (Date or datetime.timedelta)! step (timedelta): Keyword Args: inclusive (bool): If ``False``, the stopping date is not include...
[ "def", "range", "(", "cls", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ",", "inclusive", "=", "False", ")", ":", "def", "sign", "(", "x", ")", ":", "\"\"\"Inner function for determining the sign of a float\n \"\"\...
29.74359
0.001669
def smooth_angle_channels(self, channels): """Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions.""" for vertex in self.vertices: for col in vertex.meta['rot_ind']: if col: ...
[ "def", "smooth_angle_channels", "(", "self", ",", "channels", ")", ":", "for", "vertex", "in", "self", ".", "vertices", ":", "for", "col", "in", "vertex", ".", "meta", "[", "'rot_ind'", "]", ":", "if", "col", ":", "for", "k", "in", "range", "(", "1",...
58.454545
0.012251
def _WorkerCommand_options(self): """Return list of options for bootstrap""" worker = self.workersArguments c = [] # If broker is on localhost if self.hostname == worker.brokerHostname: broker = "127.0.0.1" else: broker = worker.brokerHostname ...
[ "def", "_WorkerCommand_options", "(", "self", ")", ":", "worker", "=", "self", ".", "workersArguments", "c", "=", "[", "]", "# If broker is on localhost", "if", "self", ".", "hostname", "==", "worker", ".", "brokerHostname", ":", "broker", "=", "\"127.0.0.1\"", ...
37.212121
0.001587
def enable_all_breakpoints(self): """ Enables all disabled breakpoints in all processes. @see: enable_code_breakpoint, enable_page_breakpoint, enable_hardware_breakpoint """ # disable code breakpoints for (pid, bp) in self.get_all_cod...
[ "def", "enable_all_breakpoints", "(", "self", ")", ":", "# disable code breakpoints", "for", "(", "pid", ",", "bp", ")", "in", "self", ".", "get_all_code_breakpoints", "(", ")", ":", "if", "bp", ".", "is_disabled", "(", ")", ":", "self", ".", "enable_code_br...
33.875
0.002392
def firsts(properties): """ Transform a dictionary of {name: [(elt, value)+]} (resulting from get_properties) to a dictionary of {name, value} where names are first encountered in input properties. :param dict properties: properties to firsts. :return: dictionary of parameter values by ...
[ "def", "firsts", "(", "properties", ")", ":", "result", "=", "{", "}", "# parse elts", "for", "name", "in", "properties", ":", "elt_properties", "=", "properties", "[", "name", "]", "# add property values in result[name]", "result", "[", "name", "]", "=", "elt...
27.3
0.00177
def uniq(container): """ Check if all of a container's elements are unique. Successively tries first to rely that the elements are hashable, then falls back on them being sortable, and finally falls back on brute force. """ try: return len(set(unbool(i) for i in container)) == len...
[ "def", "uniq", "(", "container", ")", ":", "try", ":", "return", "len", "(", "set", "(", "unbool", "(", "i", ")", "for", "i", "in", "container", ")", ")", "==", "len", "(", "container", ")", "except", "TypeError", ":", "try", ":", "sort", "=", "s...
29.444444
0.001218
async def handle(self, msg: Any) -> Any: """ Handle both sync and async functions. :param msg: a message :return: the result of execution of the function corresponding to this message's type """ res = self.handleSync(msg) if isawaitable(res): return a...
[ "async", "def", "handle", "(", "self", ",", "msg", ":", "Any", ")", "->", "Any", ":", "res", "=", "self", ".", "handleSync", "(", "msg", ")", "if", "isawaitable", "(", "res", ")", ":", "return", "await", "res", "else", ":", "return", "res" ]
29.5
0.008219
def rpoplpush(self, source, destination): """Emulate rpoplpush""" transfer_item = self.rpop(source) if transfer_item is not None: self.lpush(destination, transfer_item) return transfer_item
[ "def", "rpoplpush", "(", "self", ",", "source", ",", "destination", ")", ":", "transfer_item", "=", "self", ".", "rpop", "(", "source", ")", "if", "transfer_item", "is", "not", "None", ":", "self", ".", "lpush", "(", "destination", ",", "transfer_item", ...
38
0.008584
def set(self, interval, callback, repeat=False, force=True): """ 添加timer """ if self.timer: if force: # 如果已经存在,那么先要把现在的清空 self.clear() else: # 已经存在的话,就返回了 return def callback_wrapper(): ...
[ "def", "set", "(", "self", ",", "interval", ",", "callback", ",", "repeat", "=", "False", ",", "force", "=", "True", ")", ":", "if", "self", ".", "timer", ":", "if", "force", ":", "# 如果已经存在,那么先要把现在的清空", "self", ".", "clear", "(", ")", "else", ":", ...
29.333333
0.002445
def initialize(self, params, repetition): """ Initialize experiment parameters and default values from configuration file. Called by reset() at the beginning of each experiment and each repetition. """ self.name = params["name"] self.dataDir = params.get("datadir", "data") self.seed = params...
[ "def", "initialize", "(", "self", ",", "params", ",", "repetition", ")", ":", "self", ".", "name", "=", "params", "[", "\"name\"", "]", "self", ".", "dataDir", "=", "params", ".", "get", "(", "\"datadir\"", ",", "\"data\"", ")", "self", ".", "seed", ...
46.661017
0.001067