text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def country_choices(first=None, default_country_first=True): """Return a list of (code, countries), alphabetically sorted on localized country name. :param first: Country code to be placed at the top :param default_country_first: :type default_country_first: bool """ locale = _get_locale() ...
[ "def", "country_choices", "(", "first", "=", "None", ",", "default_country_first", "=", "True", ")", ":", "locale", "=", "_get_locale", "(", ")", "territories", "=", "[", "(", "code", ",", "name", ")", "for", "code", ",", "name", "in", "locale", ".", "...
30.826087
0.002736
def handle_ChannelCloseOK(self, frame): """ AMQP server closed channel as per our request """ assert self.channel._closing, "received a not expected CloseOk" # Release the `close` method's future self.synchroniser.notify(spec.ChannelCloseOK) exc = ChannelClosed() self._c...
[ "def", "handle_ChannelCloseOK", "(", "self", ",", "frame", ")", ":", "assert", "self", ".", "channel", ".", "_closing", ",", "\"received a not expected CloseOk\"", "# Release the `close` method's future", "self", ".", "synchroniser", ".", "notify", "(", "spec", ".", ...
40.75
0.006006
def clr(args): """ %prog clr [bamfile|bedpefile] ref.fasta Use mates from BEDPE to extract ranges where the ref is covered by mates. This is useful in detection of chimeric contigs. """ p = OptionParser(clr.__doc__) p.set_bedpe() opts, args = p.parse_args(args) if len(args) != 2: ...
[ "def", "clr", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "clr", ".", "__doc__", ")", "p", ".", "set_bedpe", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", ...
29.255814
0.000769
def modify(self, dn: str, mod_list: dict) -> None: """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("modify", self, dn, mod_list) # need to work out how to reverse changes in mod_list; result in revlist ...
[ "def", "modify", "(", "self", ",", "dn", ":", "str", ",", "mod_list", ":", "dict", ")", "->", "None", ":", "_debug", "(", "\"modify\"", ",", "self", ",", "dn", ",", "mod_list", ")", "# need to work out how to reverse changes in mod_list; result in revlist", "rev...
37.7875
0.000967
def get_callback_url(self, provider): """Return the callback url for this provider.""" info = self.model._meta.app_label, self.model._meta.model_name return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id})
[ "def", "get_callback_url", "(", "self", ",", "provider", ")", ":", "info", "=", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "model_name", "return", "reverse", "(", "'admin:%s_%s_callback'", "%", "info...
62.5
0.011858
def update_handler(Model, name=None, **kwds): """ This factory returns an action handler that updates a new instance of the specified model when a update action is recieved, assuming the action follows nautilus convetions. Args: Model (nautilus.BaseModel): The model to u...
[ "def", "update_handler", "(", "Model", ",", "name", "=", "None", ",", "*", "*", "kwds", ")", ":", "async", "def", "action_handler", "(", "service", ",", "action_type", ",", "payload", ",", "props", ",", "notify", "=", "True", ",", "*", "*", "kwds", "...
39.72973
0.002655
def _get_unique(self, *args): """Generate a unique value using the assigned maker""" # Generate a unique values value = '' attempts = 0 while True: attempts += 1 value = self._maker(*args) if value not in self._used_values: bre...
[ "def", "_get_unique", "(", "self", ",", "*", "args", ")", ":", "# Generate a unique values", "value", "=", "''", "attempts", "=", "0", "while", "True", ":", "attempts", "+=", "1", "value", "=", "self", ".", "_maker", "(", "*", "args", ")", "if", "value...
27.894737
0.00365
def _apply(self, ctx: ExtensionContext) -> AugmentedDict: """ Performs the actual loading of an external resource into the current model. Args: ctx: The processing context. Returns: Returns a dictionary that gets incorporated into the actual model. """ ...
[ "def", "_apply", "(", "self", ",", "ctx", ":", "ExtensionContext", ")", "->", "AugmentedDict", ":", "def", "process", "(", "pattern", ":", "Pattern", "[", "str", "]", ",", "_str", ":", "str", ")", "->", "Any", ":", "_match", "=", "pattern", ".", "mat...
41.62069
0.003239
def readDoc(cur, URL, encoding, options): """parse an XML in-memory document and build a tree. """ ret = libxml2mod.xmlReadDoc(cur, URL, encoding, options) if ret is None:raise treeError('xmlReadDoc() failed') return xmlDoc(_obj=ret)
[ "def", "readDoc", "(", "cur", ",", "URL", ",", "encoding", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "xmlReadDoc", "(", "cur", ",", "URL", ",", "encoding", ",", "options", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(",...
49
0.012048
def should_log(self, logger_name: str, level: str) -> bool: """ Returns if a message for the logger should be logged. """ if (logger_name, level) not in self._should_log: log_level_per_rule = self._get_log_level(logger_name) log_level_per_rule_numeric = getattr(logging, log_level...
[ "def", "should_log", "(", "self", ",", "logger_name", ":", "str", ",", "level", ":", "str", ")", "->", "bool", ":", "if", "(", "logger_name", ",", "level", ")", "not", "in", "self", ".", "_should_log", ":", "log_level_per_rule", "=", "self", ".", "_get...
60.5
0.004886
def patch(self, path, data, **options): """ Parses PATCH request options and dispatches a request """ data, options = self._update_request(data, options) return self.request('patch', path, data=data, **options)
[ "def", "patch", "(", "self", ",", "path", ",", "data", ",", "*", "*", "options", ")", ":", "data", ",", "options", "=", "self", ".", "_update_request", "(", "data", ",", "options", ")", "return", "self", ".", "request", "(", "'patch'", ",", "path", ...
40.833333
0.008
def _update(self, dct): """ Update an async job status file. """ LOG.info('%r._update(%r, %r)', self, self.job_id, dct) dct.setdefault('ansible_job_id', self.job_id) dct.setdefault('data', '') fp = open(self.path + '.tmp', 'w') try: fp.write(j...
[ "def", "_update", "(", "self", ",", "dct", ")", ":", "LOG", ".", "info", "(", "'%r._update(%r, %r)'", ",", "self", ",", "self", ".", "job_id", ",", "dct", ")", "dct", ".", "setdefault", "(", "'ansible_job_id'", ",", "self", ".", "job_id", ")", "dct", ...
29.357143
0.004717
def remove_chunk_layer(self): """ Removes the chunk layer (if exists) of the object (in memory) """ if self.chunk_layer is not None: this_node = self.chunk_layer.get_node() self.root.remove(this_node) self.chunk_layer = None if self.header is ...
[ "def", "remove_chunk_layer", "(", "self", ")", ":", "if", "self", ".", "chunk_layer", "is", "not", "None", ":", "this_node", "=", "self", ".", "chunk_layer", ".", "get_node", "(", ")", "self", ".", "root", ".", "remove", "(", "this_node", ")", "self", ...
33
0.005362
def spec_fn(spec_dir='.'): """ Return the filename for a .spec file in this directory. """ specs = [f for f in os.listdir(spec_dir) if os.path.isfile(f) and f.endswith('.spec')] if not specs: raise exception.SpecFileNotFound() if len(specs) != 1: raise exception.Mult...
[ "def", "spec_fn", "(", "spec_dir", "=", "'.'", ")", ":", "specs", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "spec_dir", ")", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", "and", "f", ".", "endswith", "(", "'.spec'", "...
31.818182
0.002778
def connectSimPort(simUnit, subSimUnit, srcName, dstName, direction): """ Connect ports of simulation models by name """ if direction == DIRECTION.OUT: origPort = getattr(subSimUnit, srcName) newPort = getattr(simUnit, dstName) setattr(subSimUnit, srcName, newPort) else: ...
[ "def", "connectSimPort", "(", "simUnit", ",", "subSimUnit", ",", "srcName", ",", "dstName", ",", "direction", ")", ":", "if", "direction", "==", "DIRECTION", ".", "OUT", ":", "origPort", "=", "getattr", "(", "subSimUnit", ",", "srcName", ")", "newPort", "=...
34.714286
0.002004
def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' if 'keyfile' in kwargs: salt.utils.versions.warn_until( 'Neon', 'The \'keyfile\' argument has been deprecated and will be removed in Salt ' '{version}. ...
[ "def", "dec", "(", "data", ",", "*", "*", "kwargs", ")", ":", "if", "'keyfile'", "in", "kwargs", ":", "salt", ".", "utils", ".", "versions", ".", "warn_until", "(", "'Neon'", ",", "'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '", "'{...
33.34375
0.002732
def nth_child_production(self, lexeme, tokens): """Parse args and pass them to pclass_func_validator.""" args = self.match(tokens, 'expr') pat = self.nth_child_pat.match(args) if pat.group(5): a = 2 b = 1 if pat.group(5) == 'odd' else 0 elif pat.group(6...
[ "def", "nth_child_production", "(", "self", ",", "lexeme", ",", "tokens", ")", ":", "args", "=", "self", ".", "match", "(", "tokens", ",", "'expr'", ")", "pat", "=", "self", ".", "nth_child_pat", ".", "match", "(", "args", ")", "if", "pat", ".", "gro...
26.333333
0.001627
def _get_image_workaround_seek(self, idx): """Same as __getitem__ but seek through the video beforehand This is a workaround for an all-zero image returned by `imageio`. """ warnings.warn("imageio workaround used!") cap = self.video_handle mult = 50 for ii in ran...
[ "def", "_get_image_workaround_seek", "(", "self", ",", "idx", ")", ":", "warnings", ".", "warn", "(", "\"imageio workaround used!\"", ")", "cap", "=", "self", ".", "video_handle", "mult", "=", "50", "for", "ii", "in", "range", "(", "idx", "//", "mult", ")"...
34.333333
0.004728
def batch(args): """ %proj batch database.fasta project_dir output_dir Run bwa in batch mode. """ p = OptionParser(batch.__doc__) set_align_options(p) p.set_sam_options() opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) ref_fasta, proj_di...
[ "def", "batch", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "batch", ".", "__doc__", ")", "set_align_options", "(", "p", ")", "p", ".", "set_sam_options", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", ...
25.4
0.001896
def common_update_sys(self): """ update system package """ try: sudo('apt-get update -y --fix-missing') except Exception as e: print(e) print(green('System package is up to date.')) print()
[ "def", "common_update_sys", "(", "self", ")", ":", "try", ":", "sudo", "(", "'apt-get update -y --fix-missing'", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "print", "(", "green", "(", "'System package is up to date.'", ")", ")", "print...
24
0.007299
def snap(self, *args): """Records multiple values at once. It takes two to six arguments specifying which values should be recorded together. Valid arguments are 'x', 'y', 'r', 'theta', 'aux1', 'aux2', 'aux3', 'aux4', 'frequency', 'trace1', 'trace2', 'trace3' and 'trace4'. ...
[ "def", "snap", "(", "self", ",", "*", "args", ")", ":", "length", "=", "len", "(", "args", ")", "if", "not", "2", "<=", "length", "<=", "6", ":", "msg", "=", "'snap takes 2 to 6 arguments, {0} given.'", ".", "format", "(", "length", ")", "raise", "Type...
39
0.001614
def SetWeekdayService(self, has_service=True): """Set service as running (or not) on all of Monday through Friday.""" for i in range(0, 5): self.SetDayOfWeekHasService(i, has_service)
[ "def", "SetWeekdayService", "(", "self", ",", "has_service", "=", "True", ")", ":", "for", "i", "in", "range", "(", "0", ",", "5", ")", ":", "self", ".", "SetDayOfWeekHasService", "(", "i", ",", "has_service", ")" ]
48.5
0.010152
def set_mainswitch_state(self, state): """Turns output on or off. Also turns hardware on ir off""" if self.state.mainswitch == state: err_msg = "MainSwitch unchanged, already is {sState}".format(sState="On" if state else "Off") # fo obar lorem ipsum logging.debug(err_msg) # fo ob...
[ "def", "set_mainswitch_state", "(", "self", ",", "state", ")", ":", "if", "self", ".", "state", ".", "mainswitch", "==", "state", ":", "err_msg", "=", "\"MainSwitch unchanged, already is {sState}\"", ".", "format", "(", "sState", "=", "\"On\"", "if", "state", ...
55.8125
0.009912
def delete_refund_transaction_by_id(cls, refund_transaction_id, **kwargs): """Delete RefundTransaction Delete an instance of RefundTransaction by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thr...
[ "def", "delete_refund_transaction_by_id", "(", "cls", ",", "refund_transaction_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_...
47.095238
0.005946
def options(description, **kwargs): """Decorator to set some options on a method.""" def set_notes(function): function.refactor_notes = {'name': function.__name__, 'category': "Miscellaneous", 'description': description, ...
[ "def", "options", "(", "description", ",", "*", "*", "kwargs", ")", ":", "def", "set_notes", "(", "function", ")", ":", "function", ".", "refactor_notes", "=", "{", "'name'", ":", "function", ".", "__name__", ",", "'category'", ":", "\"Miscellaneous\"", ",...
46.666667
0.001751
def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, pr...
[ "def", "get_account_policy", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "...
30.857143
0.002994
def sort_aliases(self, aliases): """Sorts the given aliases list, returns a sorted list. :param list aliases: :return: sorted aliases list """ self._cache_init() if not aliases: return aliases parent_aliases = self._cache_get_entry(self.CACHE_NAME_PAR...
[ "def", "sort_aliases", "(", "self", ",", "aliases", ")", ":", "self", ".", "_cache_init", "(", ")", "if", "not", "aliases", ":", "return", "aliases", "parent_aliases", "=", "self", ".", "_cache_get_entry", "(", "self", ".", "CACHE_NAME_PARENTS", ")", ".", ...
37.636364
0.007075
def present(name, login=None, domain=None, database=None, roles=None, options=None, **kwargs): ''' Checks existance of the named user. If not present, creates the user with the specified roles and options. name The name of the user to manage login If not specified, will be created W...
[ "def", "present", "(", "name", ",", "login", "=", "None", ",", "domain", "=", "None", ",", "database", "=", "None", ",", "roles", "=", "None", ",", "options", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name",...
41.265306
0.005797
def new_reservoir(reservoir_type='uniform', *reservoir_args, **reservoir_kwargs): """ Build a new reservoir """ try: reservoir_cls = RESERVOIR_TYPES[reservoir_type] except KeyError: raise InvalidMetricError("Unknown reservoir type: {}".format(reservoir_type)) return reservoir_c...
[ "def", "new_reservoir", "(", "reservoir_type", "=", "'uniform'", ",", "*", "reservoir_args", ",", "*", "*", "reservoir_kwargs", ")", ":", "try", ":", "reservoir_cls", "=", "RESERVOIR_TYPES", "[", "reservoir_type", "]", "except", "KeyError", ":", "raise", "Invali...
31.727273
0.008357
def exit_with_error(format_, message): """ :param format_: :param message: """ if format_ == "text" or format_ == "markdown": log.error(message) elif format_ == "json": result = {"success": False, "error": str(message), "issues": []} print(json.dumps(result)) else: ...
[ "def", "exit_with_error", "(", "format_", ",", "message", ")", ":", "if", "format_", "==", "\"text\"", "or", "format_", "==", "\"markdown\"", ":", "log", ".", "error", "(", "message", ")", "elif", "format_", "==", "\"json\"", ":", "result", "=", "{", "\"...
27.583333
0.00292
def LeerContribuyente(self, pop=True): "Leeo el próximo contribuyente" # por compatibilidad hacia atras, la primera vez no remueve de la lista # (llamado de ConsultarContribuyentes con pop=False) if self.contribuyentes: contrib = self.contribuyentes[0] if pop: ...
[ "def", "LeerContribuyente", "(", "self", ",", "pop", "=", "True", ")", ":", "# por compatibilidad hacia atras, la primera vez no remueve de la lista", "# (llamado de ConsultarContribuyentes con pop=False)", "if", "self", ".", "contribuyentes", ":", "contrib", "=", "self", "."...
47.470588
0.00243
def set_led(self, state): """Set the LED state to state (True or False)""" if self.connected: reports = self.device.find_output_reports() for report in reports: if self.led_usage in report: report[self.led_usage] = state ...
[ "def", "set_led", "(", "self", ",", "state", ")", ":", "if", "self", ".", "connected", ":", "reports", "=", "self", ".", "device", ".", "find_output_reports", "(", ")", "for", "report", "in", "reports", ":", "if", "self", ".", "led_usage", "in", "repor...
42.875
0.011429
def _add_study(self,study): """ Adds a study to QuantFigure.studies Parameters: study : dict {'kind':study_kind, 'params':study_parameters, 'display':display_parameters} """ str='{study} {name}({period})' if study['params'].get('str',None)==None else study['params']['str'] study['params'][...
[ "def", "_add_study", "(", "self", ",", "study", ")", ":", "str", "=", "'{study} {name}({period})'", "if", "study", "[", "'params'", "]", ".", "get", "(", "'str'", ",", "None", ")", "==", "None", "else", "study", "[", "'params'", "]", "[", "'str'", "]",...
24.333333
0.069909
def _onMessageNotification(self, client, userdata, pahoMessage): """ Internal callback for gateway notification messages, parses source device from topic string and passes the information on to the registered device command callback """ try: note = Notification(pahoMe...
[ "def", "_onMessageNotification", "(", "self", ",", "client", ",", "userdata", ",", "pahoMessage", ")", ":", "try", ":", "note", "=", "Notification", "(", "pahoMessage", ",", "self", ".", "_messageCodecs", ")", "except", "InvalidEventException", "as", "e", ":",...
44.461538
0.005085
def __get_edges_by_vertex(self, vertex, keys=False): """ Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to i...
[ "def", "__get_edges_by_vertex", "(", "self", ",", "vertex", ",", "keys", "=", "False", ")", ":", "if", "vertex", "in", "self", ".", "bg", ":", "for", "vertex2", ",", "edges", "in", "self", ".", "bg", "[", "vertex", "]", ".", "items", "(", ")", ":",...
65
0.006498
def has_wrap_around_links(self, minimum_working=0.9): """Test if a machine has wrap-around connections installed. Since the Machine object does not explicitly define whether a machine has wrap-around links they must be tested for directly. This test performs a "fuzzy" test on the number...
[ "def", "has_wrap_around_links", "(", "self", ",", "minimum_working", "=", "0.9", ")", ":", "working", "=", "0", "for", "x", "in", "range", "(", "self", ".", "width", ")", ":", "if", "(", "x", ",", "0", ",", "Links", ".", "south", ")", "in", "self",...
37.326087
0.001135
def get_file_download(self, file_id): """ Get a file download object that contains temporary url settings needed to download the contents of a file. :param file_id: str: uuid of the file :return: FileDownload """ return self._create_item_response( self.data_se...
[ "def", "get_file_download", "(", "self", ",", "file_id", ")", ":", "return", "self", ".", "_create_item_response", "(", "self", ".", "data_service", ".", "get_file_url", "(", "file_id", ")", ",", "FileDownload", ")" ]
37.4
0.007833
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname...
[ "def", "parse", "(", "self", ",", "inputstring", ",", "document", ")", ":", "link", "=", "json", ".", "loads", "(", "inputstring", ")", "env", "=", "document", ".", "settings", ".", "env", "source_dir", "=", "os", ".", "path", ".", "dirname", "(", "e...
41.346939
0.001446
def glob(*args): """Returns list of paths matching one or more wildcard patterns. Args: include_dirs: Include directories in the output """ if len(args) is 1 and isinstance(args[0], list): args = args[0] matches = [] for pattern in args: for item in glob2.glob(pattern): ...
[ "def", "glob", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "is", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "list", ")", ":", "args", "=", "args", "[", "0", "]", "matches", "=", "[", "]", "for", "pattern", "in",...
28.571429
0.002421
def prep(s, p, o): ''' Prepare a triple for rdflib ''' def bnode_check(r): return isinstance(r, mock_bnode) or r.startswith('VERSABLANKNODE_') s = BNode() if bnode_check(s) else URIRef(s) p = URIRef(p) o = BNode() if bnode_check(o) else (URIRef(o) if isinstance(o, I) else Literal(o)...
[ "def", "prep", "(", "s", ",", "p", ",", "o", ")", ":", "def", "bnode_check", "(", "r", ")", ":", "return", "isinstance", "(", "r", ",", "mock_bnode", ")", "or", "r", ".", "startswith", "(", "'VERSABLANKNODE_'", ")", "s", "=", "BNode", "(", ")", "...
30
0.005882
def import_external_db(self, db_file, db_type=None): """ Import an external database for use in lcopt db_type must be one of ``technosphere`` or ``biosphere`` The best way to 'obtain' an external database is to 'export' it from brightway as a pickle file e.g.:: im...
[ "def", "import_external_db", "(", "self", ",", "db_file", ",", "db_type", "=", "None", ")", ":", "db", "=", "pickle", ".", "load", "(", "open", "(", "\"{}.pickle\"", ".", "format", "(", "db_file", ")", ",", "\"rb\"", ")", ")", "name", "=", "list", "(...
36.4
0.004682
def linearize_metrics(logged_metrics): """ Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_...
[ "def", "linearize_metrics", "(", "logged_metrics", ")", ":", "metrics_by_name", "=", "{", "}", "for", "metric_entry", "in", "logged_metrics", ":", "if", "metric_entry", ".", "name", "not", "in", "metrics_by_name", ":", "metrics_by_name", "[", "metric_entry", ".", ...
36.586207
0.000918
def raw_search(self, *args, **kwargs): """ Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search thr...
[ "def", "raw_search", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "limit", "=", "50", "try", ":", "limit", "=", "kwargs", "[", "'limit'", "]", "except", "KeyError", ":", "pass", "# Get first X messages.", "self", ".", "_mail", ".",...
31.64
0.004292
def _ggplot(df, out_file): """Plot faceted items with ggplot wrapper on top of matplotlib. XXX Not yet functional """ import ggplot as gg df["variant.type"] = [vtype_labels[x] for x in df["variant.type"]] df["category"] = [cat_labels[x] for x in df["category"]] df["caller"] = [caller_labels....
[ "def", "_ggplot", "(", "df", ",", "out_file", ")", ":", "import", "ggplot", "as", "gg", "df", "[", "\"variant.type\"", "]", "=", "[", "vtype_labels", "[", "x", "]", "for", "x", "in", "df", "[", "\"variant.type\"", "]", "]", "df", "[", "\"category\"", ...
44.25
0.001845
def new_email_marketing_campaign(self, name, email_content, from_email, from_name, reply_to_email, subject, text_content, address, is_view_as_webpage_enabled=False, view_as...
[ "def", "new_email_marketing_campaign", "(", "self", ",", "name", ",", "email_content", ",", "from_email", ",", "from_name", ",", "reply_to_email", ",", "subject", ",", "text_content", ",", "address", ",", "is_view_as_webpage_enabled", "=", "False", ",", "view_as_web...
47.76
0.003693
def add_argument(self, parser, set_default=False): """Add this :class:`Setting` to the ``parser``. The operation is carried out only if :attr:`flags` or :attr:`nargs` and :attr:`name` are defined. """ default = self.default if set_default else None kwargs = dict( ...
[ "def", "add_argument", "(", "self", ",", "parser", ",", "set_default", "=", "False", ")", ":", "default", "=", "self", ".", "default", "if", "set_default", "else", "None", "kwargs", "=", "dict", "(", "nargs", "=", "self", ".", "nargs", ",", "default", ...
35.896552
0.001871
def get_rows(self, indexes, as_list=False): """ For a list of indexes return the values of the indexes in that column. :param indexes: either a list of index values or a list of booleans with same length as all indexes :param as_list: if True return a list, if False return Series ...
[ "def", "get_rows", "(", "self", ",", "indexes", ",", "as_list", "=", "False", ")", ":", "if", "all", "(", "[", "isinstance", "(", "i", ",", "bool", ")", "for", "i", "in", "indexes", "]", ")", ":", "# boolean list", "if", "len", "(", "indexes", ")",...
55
0.005212
def _parse_iso8601(text): """ Maybe parse an ISO8601 datetime string into a datetime. :param text: Either a ``unicode`` string to parse or any other object (ideally a ``datetime`` instance) to pass through. :return: A ``datetime.datetime`` representing ``text``. Or ``text`` if it was ...
[ "def", "_parse_iso8601", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "unicode", ")", ":", "try", ":", "return", "parse_iso8601", "(", "text", ")", "except", "ValueError", ":", "raise", "CheckedValueTypeError", "(", "None", ",", "(", "datet...
32.842105
0.001558
def doOutages(self): """ Applies branch outtages. """ assert len(self.branchOutages) == len(self.market.case.branches) weights = [[(False, r), (True, 1 - (r))] for r in self.branchOutages] for i, ln in enumerate(self.market.case.branches): ln.online = weighted_choic...
[ "def", "doOutages", "(", "self", ")", ":", "assert", "len", "(", "self", ".", "branchOutages", ")", "==", "len", "(", "self", ".", "market", ".", "case", ".", "branches", ")", "weights", "=", "[", "[", "(", "False", ",", "r", ")", ",", "(", "True...
39.818182
0.011161
def items_at(self, depth): """ Iterate items at specified depth. """ if depth < 1: yield ROOT, self elif depth == 1: for key, value in self.items(): yield key, value else: for dict_tree in self.values(): ...
[ "def", "items_at", "(", "self", ",", "depth", ")", ":", "if", "depth", "<", "1", ":", "yield", "ROOT", ",", "self", "elif", "depth", "==", "1", ":", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", ":", "yield", "key", ",", "va...
30.230769
0.004938
def validate_input(self, input_string, validators): """ Validate the given input string against the specified list of validators. :param input_string: the input string to verify. :param validators: the list of validators. :raises InvalidValidator if the list of validators does no...
[ "def", "validate_input", "(", "self", ",", "input_string", ",", "validators", ")", ":", "validation_result", "=", "True", "if", "isinstance", "(", "validators", ",", "BaseValidator", ")", ":", "validators", "=", "[", "validators", "]", "elif", "validators", "i...
44.107143
0.006339
def LR_collection(hyper_lr, args): """This custom function implements a proprietary IntegralDefense Live Response collection package. 'None' will be immediately returned if you do no have this package. The location of the package is assumed to be defined by a 'lr_path' variable in the configuration file. ...
[ "def", "LR_collection", "(", "hyper_lr", ",", "args", ")", ":", "# Get configuration items", "config", "=", "ConfigParser", "(", ")", "config", ".", "read", "(", "CONFIG_PATH", ")", "lr_analysis_path", "=", "config", "[", "'ID-LR'", "]", "[", "'lr_package_path'"...
47.232558
0.005144
def not_right(self, num): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] """ if not self.list: self._build_list() if num == None: return self.list[:-1:] if num <= 0: return [] return self.list...
[ "def", "not_right", "(", "self", ",", "num", ")", ":", "if", "not", "self", ".", "list", ":", "self", ".", "_build_list", "(", ")", "if", "num", "==", "None", ":", "return", "self", ".", "list", "[", ":", "-", "1", ":", "]", "if", "num", "<=", ...
24.307692
0.012195
def raw(cls, exp, files=None): """ :param str|unicode exp: Haskell expression to evaluate. :param dict[str|unicode, str|unicode] files: Dictionary of file names->contents :rtype: dict """ payload = {'exp': exp} if files: # TODO: Implement stdin. ...
[ "def", "raw", "(", "cls", ",", "exp", ",", "files", "=", "None", ")", ":", "payload", "=", "{", "'exp'", ":", "exp", "}", "if", "files", ":", "# TODO: Implement stdin.", "stdin", "=", "[", "]", "payload", "[", "'args'", "]", "=", "json", ".", "dump...
36
0.00722
def userselect_increment(block): """Let user interactively select byte increment.""" print("Selected block:") print('\n ' + ('\n '.join(block['lines']))) print() increment = None while increment is None: increment = input("Choose store pointer increment (number of bytes): ") ...
[ "def", "userselect_increment", "(", "block", ")", ":", "print", "(", "\"Selected block:\"", ")", "print", "(", "'\\n '", "+", "(", "'\\n '", ".", "join", "(", "block", "[", "'lines'", "]", ")", ")", ")", "print", "(", ")", "increment", "=", "None",...
29.5
0.002053
def find_all(self, find_string, flags): """Return list of all positions of event_find_string in MainGrid. Only the code is searched. The result is not searched here. Parameters: ----------- gridpos: 3-tuple of Integer \tPosition at which the search starts find_s...
[ "def", "find_all", "(", "self", ",", "find_string", ",", "flags", ")", ":", "code_array", "=", "self", ".", "grid", ".", "code_array", "string_match", "=", "code_array", ".", "string_match", "find_keys", "=", "[", "]", "for", "key", "in", "code_array", ":"...
28.518519
0.002513
def cat_acc(y, z): """Classification accuracy for multi-categorical case """ weights = _cat_sample_weights(y) _acc = K.cast(K.equal(K.argmax(y, axis=-1), K.argmax(z, axis=-1)), K.floatx()) _acc = K.sum(_acc * weights) / K.sum(weights) return _acc
[ "def", "cat_acc", "(", "y", ",", "z", ")", ":", "weights", "=", "_cat_sample_weights", "(", "y", ")", "_acc", "=", "K", ".", "cast", "(", "K", ".", "equal", "(", "K", ".", "argmax", "(", "y", ",", "axis", "=", "-", "1", ")", ",", "K", ".", ...
34
0.003185
def curve_fit_unscaled(*args, **kwargs): """ Use the reduced chi square to unscale :mod:`scipy`'s scaled :func:`scipy.optimize.curve_fit`. *\*args* and *\*\*kwargs* are passed through to :func:`scipy.optimize.curve_fit`. The tuple *popt, pcov, chisq_red* is returned, where *popt* is the optimal values for the p...
[ "def", "curve_fit_unscaled", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extract verbosity", "verbose", "=", "kwargs", ".", "pop", "(", "'verbose'", ",", "False", ")", "# Do initial fit", "popt", ",", "pcov", "=", "_spopt", ".", "curve_fit", "(...
38.354839
0.005742
def argpack(args): """ Coerce a list of arguments to a tuple. Parameters ---------- args : tuple or nested tuple Pack arguments into a tuple, converting ((,...),) or (,) -> (,) """ if isinstance(args[0], (tuple, list, ndarray)): return tupleize(args[0]) elif isinstance(a...
[ "def", "argpack", "(", "args", ")", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "(", "tuple", ",", "list", ",", "ndarray", ")", ")", ":", "return", "tupleize", "(", "args", "[", "0", "]", ")", "elif", "isinstance", "(", "args", "[",...
32.6875
0.003717
def initWithComplexQuery(query): """ create a query using a complex article query """ q = QueryArticles() # provided an instance of ComplexArticleQuery if isinstance(query, ComplexArticleQuery): q._setVal("query", json.dumps(query.getQuery())) # provid...
[ "def", "initWithComplexQuery", "(", "query", ")", ":", "q", "=", "QueryArticles", "(", ")", "# provided an instance of ComplexArticleQuery", "if", "isinstance", "(", "query", ",", "ComplexArticleQuery", ")", ":", "q", ".", "_setVal", "(", "\"query\"", ",", "json",...
41.777778
0.003901
def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding de...
[ "def", "pool_start", "(", "name", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "try", ":", "pool", "=", "conn", ".", "storagePoolLookupByName", "(", "name", ")", "return", "not", "bool", "(", "pool", "."...
25.826087
0.001623
def cee_map_priority_table_map_cos7_pgid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name_key = ET.SubElement(cee_map, "name") name_key.text = kwargs.pop...
[ "def", "cee_map_priority_table_map_cos7_pgid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "cee_map", "=", "ET", ".", "SubElement", "(", "config", ",", "\"cee-map\"", ",", "xmlns", "=", "\"ur...
46.230769
0.004894
def close(self): """ Closes the stream. """ self.flush() try: if self.stream is not None: self.stream.flush() _name = self.stream.name self.stream.close() self.client.copy(_name, self.filename) ex...
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "try", ":", "if", "self", ".", "stream", "is", "not", "None", ":", "self", ".", "stream", ".", "flush", "(", ")", "_name", "=", "self", ".", "stream", ".", "name", "self", "...
26.5
0.005208
def find_module_egg_path(module_path): """ Find the path of the deployed egg package that may contain the specified module path. @param module_path: the path of a Python module. @return: the absolute path of the deployed egg package that contains the specified module path, or ``None`` if...
[ "def", "find_module_egg_path", "(", "module_path", ")", ":", "if", "module_path", ".", "find", "(", "'.egg'", ")", "==", "-", "1", ":", "return", "None", "_module_absolute_path", "=", "os", ".", "path", ".", "abspath", "(", "module_path", ")", "egg_paths", ...
32.708333
0.006188
def load_stream(filename): """Load a file stream from the package resources.""" rawfile = pkg_resources.resource_stream(__name__, filename) if six.PY2: return rawfile return io.TextIOWrapper(rawfile, 'utf-8')
[ "def", "load_stream", "(", "filename", ")", ":", "rawfile", "=", "pkg_resources", ".", "resource_stream", "(", "__name__", ",", "filename", ")", "if", "six", ".", "PY2", ":", "return", "rawfile", "return", "io", ".", "TextIOWrapper", "(", "rawfile", ",", "...
37.833333
0.00431
def prepend_bcbiopath(): """Prepend paths in the BCBIOPATH environment variable (if any) to PATH. Uses either a pre-sent global environmental variable (BCBIOPATH) or the local anaconda directory. """ if os.environ.get('BCBIOPATH'): os.environ['PATH'] = _prepend(os.environ.get('PATH', ''), ...
[ "def", "prepend_bcbiopath", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'BCBIOPATH'", ")", ":", "os", ".", "environ", "[", "'PATH'", "]", "=", "_prepend", "(", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "''", ")", ",", ...
43.083333
0.001894
def request(self, method, url, *args): """ Pass-thru method to make this class behave a little like HTTPConnection """ return self.http.request(method, url, *args)
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "*", "args", ")", ":", "return", "self", ".", "http", ".", "request", "(", "method", ",", "url", ",", "*", "args", ")" ]
37.4
0.010471
def params_to_blr(self, trans_handle, params): "Convert parameter array to BLR and values format." ln = len(params) * 2 blr = bs([5, 2, 4, 0, ln & 255, ln >> 8]) if self.accept_version < PROTOCOL_VERSION13: values = bs([]) else: # start with null indicator...
[ "def", "params_to_blr", "(", "self", ",", "trans_handle", ",", "params", ")", ":", "ln", "=", "len", "(", "params", ")", "*", "2", "blr", "=", "bs", "(", "[", "5", ",", "2", ",", "4", ",", "0", ",", "ln", "&", "255", ",", "ln", ">>", "8", "...
38.32
0.001272
def _write_headers(self, headers): """Yields the HTTP header text for some content. Parameters ---------- headers : dict The headers to yield """ if headers: for name in sorted(headers.keys()): yield name.encode("ascii") ...
[ "def", "_write_headers", "(", "self", ",", "headers", ")", ":", "if", "headers", ":", "for", "name", "in", "sorted", "(", "headers", ".", "keys", "(", ")", ")", ":", "yield", "name", ".", "encode", "(", "\"ascii\"", ")", "yield", "b': '", "yield", "h...
28.066667
0.004598
def to_match(self): """Return a unicode object with the MATCH representation of this ContextField.""" self.validate() mark_name, field_name = self.location.get_location_name() validate_safe_string(mark_name) if field_name is None: return u'$matched.%s' % (mark_name,...
[ "def", "to_match", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "mark_name", ",", "field_name", "=", "self", ".", "location", ".", "get_location_name", "(", ")", "validate_safe_string", "(", "mark_name", ")", "if", "field_name", "is", "None", ...
36
0.006772
def get_default_lab_path(self, config): """Generate a default laboratory path based on user environment.""" # Default path settings # Append project name if present (NCI-specific) default_project = os.environ.get('PROJECT', '') default_short_path = os.path.join('/short', default...
[ "def", "get_default_lab_path", "(", "self", ",", "config", ")", ":", "# Default path settings", "# Append project name if present (NCI-specific)", "default_project", "=", "os", ".", "environ", ".", "get", "(", "'PROJECT'", ",", "''", ")", "default_short_path", "=", "o...
38.368421
0.002677
def _bibliography(doc, terms, converters=[], format='html'): """ Render citations, from a document or a doct of dicts If the input is a dict, each key is the name of the citation, and the value is a BibTex formatted dict :param doc: A MetatabDoc, or a dict of BibTex dicts :return: """ ...
[ "def", "_bibliography", "(", "doc", ",", "terms", ",", "converters", "=", "[", "]", ",", "format", "=", "'html'", ")", ":", "output_backend", "=", "'latex'", "if", "format", "==", "'latex'", "else", "MetatabHtmlBackend", "def", "mk_cite", "(", "v", ")", ...
28.95
0.002506
def covar(self): """ The covariance matrix for the result :math:`\\beta` """ if self._covar is None: self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X)) return self._covar
[ "def", "covar", "(", "self", ")", ":", "if", "self", ".", "_covar", "is", "None", ":", "self", ".", "_covar", "=", "_np", ".", "linalg", ".", "inv", "(", "_np", ".", "dot", "(", "_np", ".", "transpose", "(", "self", ".", "X", ")", ",", "self", ...
33.428571
0.0125
def parse_email(self, email): """parse an email to an unicode name, email tuple """ splitted = safe_unicode(email).rsplit(",", 1) if len(splitted) == 1: return (False, splitted[0]) elif len(splitted) == 2: return (splitted[0], splitted[1]) else: ...
[ "def", "parse_email", "(", "self", ",", "email", ")", ":", "splitted", "=", "safe_unicode", "(", "email", ")", ".", "rsplit", "(", "\",\"", ",", "1", ")", "if", "len", "(", "splitted", ")", "==", "1", ":", "return", "(", "False", ",", "splitted", "...
38.1
0.005128
def get_metric_value_by_labels(messages, _metric, _m, metric_suffix): """ :param messages: dictionary as metric_name: {labels: {}, value: 10} :param _metric: dictionary as {labels: {le: '0.001', 'custom': 'value'}} :param _m: str as metric name :param metric_suffix: str must be i...
[ "def", "get_metric_value_by_labels", "(", "messages", ",", "_metric", ",", "_m", ",", "metric_suffix", ")", ":", "metric_name", "=", "'{}_{}'", ".", "format", "(", "_m", ",", "metric_suffix", ")", "expected_labels", "=", "set", "(", "[", "(", "k", ",", "v"...
52.857143
0.006195
def create(self, job_id, cluster_id, input_id=None, output_id=None, configs=None, interface=None, is_public=None, is_protected=None): """Launch a Job.""" url = "/jobs/%s/execute" % job_id data = { "cluster_id": cluster_id, } self._copy_...
[ "def", "create", "(", "self", ",", "job_id", ",", "cluster_id", ",", "input_id", "=", "None", ",", "output_id", "=", "None", ",", "configs", "=", "None", ",", "interface", "=", "None", ",", "is_public", "=", "None", ",", "is_protected", "=", "None", ")...
37.933333
0.006861
def setup_build(self, name, repo, config, tag=None, commit=None, recipe="Singularity", startup_script=None): '''setup the build based on the selected configuration file, meaning producing the configuration file filled in based on the user's input Parameters ========== ...
[ "def", "setup_build", "(", "self", ",", "name", ",", "repo", ",", "config", ",", "tag", "=", "None", ",", "commit", "=", "None", ",", "recipe", "=", "\"Singularity\"", ",", "startup_script", "=", "None", ")", ":", "manager", "=", "self", ".", "_get_and...
35.481013
0.004685
def default_language_from_metadata_and_ext(metadata, ext): """Return the default language given the notebook metadata, and a file extension""" default_from_ext = _SCRIPT_EXTENSIONS.get(ext, {}).get('language', 'python') language = (metadata.get('jupytext', {}).get('main_language') or metada...
[ "def", "default_language_from_metadata_and_ext", "(", "metadata", ",", "ext", ")", ":", "default_from_ext", "=", "_SCRIPT_EXTENSIONS", ".", "get", "(", "ext", ",", "{", "}", ")", ".", "get", "(", "'language'", ",", "'python'", ")", "language", "=", "(", "met...
39
0.006263
def get_dropout(x, rate=0.0, init=True): """Dropout x with dropout_rate = rate. Apply zero dropout during init or prediction time. Args: x: 4-D Tensor, shape=(NHWC). rate: Dropout rate. init: Initialization. Returns: x: activations after dropout. """ if init or rate == 0: return x re...
[ "def", "get_dropout", "(", "x", ",", "rate", "=", "0.0", ",", "init", "=", "True", ")", ":", "if", "init", "or", "rate", "==", "0", ":", "return", "x", "return", "tf", ".", "layers", ".", "dropout", "(", "x", ",", "rate", "=", "rate", ",", "tra...
23.8
0.010782
def appproperties(): """ Create app-specific properties. See docproperties() for more common document properties. """ appprops = makeelement('Properties', nsprefix='ep') appprops = etree.fromstring( '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Properties x' 'mlns="ht...
[ "def", "appproperties", "(", ")", ":", "appprops", "=", "makeelement", "(", "'Properties'", ",", "nsprefix", "=", "'ep'", ")", "appprops", "=", "etree", ".", "fromstring", "(", "'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Properties x'", "'mlns=\"http:/...
40.096774
0.000786
def getRfree(self): ''' Returns an array of size self.AgentCount with self.RfreeNow in every entry. Parameters ---------- None Returns ------- RfreeNow : np.array Array of size self.AgentCount with risk free interest rate for each agent. ...
[ "def", "getRfree", "(", "self", ")", ":", "RfreeNow", "=", "self", ".", "RfreeNow", "*", "np", ".", "ones", "(", "self", ".", "AgentCount", ")", "return", "RfreeNow" ]
26.4
0.009756
def wait_for_postgres(database, host, port, username, password): # type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> None """Waits for PostgreSQL database to be up Args: database (Optional[str]): Database name host (Optional[str...
[ "def", "wait_for_postgres", "(", "database", ",", "host", ",", "port", ",", "username", ",", "password", ")", ":", "# type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> None", "connecting_string", "=", "'Checking for PostgreSQL...'", "if"...
37.121212
0.003182
def _task_to_text(self, task): """ Return a standard formatting of a Task serialization. """ started = self._format_date(task.get('started_at', None)) completed = self._format_date(task.get('completed_at', None)) success = task.get('success', None) success_lu = {None: 'Not exec...
[ "def", "_task_to_text", "(", "self", ",", "task", ")", ":", "started", "=", "self", ".", "_format_date", "(", "task", ".", "get", "(", "'started_at'", ",", "None", ")", ")", "completed", "=", "self", ".", "_format_date", "(", "task", ".", "get", "(", ...
49.157895
0.002101
def do_shell(self, arg): "run a shell commad" print(">", arg) sub_cmd = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE) print(sub_cmd.communicate()[0])
[ "def", "do_shell", "(", "self", ",", "arg", ")", ":", "print", "(", "\">\"", ",", "arg", ")", "sub_cmd", "=", "subprocess", ".", "Popen", "(", "arg", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "print", "(", "sub_...
37.8
0.010363
def functions(self): """ A list of functions declared or defined in this module. """ return [v for v in self.globals.values() if isinstance(v, values.Function)]
[ "def", "functions", "(", "self", ")", ":", "return", "[", "v", "for", "v", "in", "self", ".", "globals", ".", "values", "(", ")", "if", "isinstance", "(", "v", ",", "values", ".", "Function", ")", "]" ]
33.833333
0.009615
def decode_content(self, rpb_content, sibling): """ Decodes a single sibling from the protobuf representation into a RiakObject. :param rpb_content: a single RpbContent message :type rpb_content: riak.pb.riak_pb2.RpbContent :param sibling: a RiakContent sibling container...
[ "def", "decode_content", "(", "self", ",", "rpb_content", ",", "sibling", ")", ":", "if", "rpb_content", ".", "HasField", "(", "\"deleted\"", ")", "and", "rpb_content", ".", "deleted", ":", "sibling", ".", "exists", "=", "False", "else", ":", "sibling", "....
42.928571
0.001085
def rename_collection(db, collection, new_name): ''' Renames a MongoDB collection. Arguments: db (Database): A pymongo Database object. Can be obtained with ``get_db``. collection (str): Name of the collection to be renamed. new_name (str, func): ``new_name`` can be o...
[ "def", "rename_collection", "(", "db", ",", "collection", ",", "new_name", ")", ":", "if", "hasattr", "(", "new_name", ",", "'__call__'", ")", ":", "_new", "=", "new_name", "(", "collection", ")", "if", "_new", "==", "''", ":", "return", "else", ":", "...
29.555556
0.001214
def use_federated_objective_bank_view(self): """Pass through to provider ObjectiveLookupSession.use_federated_objective_bank_view""" self._objective_bank_view = FEDERATED # self._get_provider_session('objective_lookup_session') # To make sure the session is tracked for session in self._g...
[ "def", "use_federated_objective_bank_view", "(", "self", ")", ":", "self", ".", "_objective_bank_view", "=", "FEDERATED", "# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", "_get_provider_sessions",...
52
0.008403
def get_backreferences(obj, relationship): """Returns the backreferences """ refs = get_backuidreferences(obj, relationship) # TODO remove after all ReferenceField get ported to UIDReferenceField # At this moment, there are still some content types that are using the # ReferenceField, so we nee...
[ "def", "get_backreferences", "(", "obj", ",", "relationship", ")", ":", "refs", "=", "get_backuidreferences", "(", "obj", ",", "relationship", ")", "# TODO remove after all ReferenceField get ported to UIDReferenceField", "# At this moment, there are still some content types that a...
35.538462
0.00211
async def _set_subscriptions(self, subscriptions): """ Set the subscriptions to a specific list of values """ url, params = self._get_subscriptions_endpoint() data = { 'object': 'page', 'callback_url': self.webhook_url, 'fields': ', '.join(su...
[ "async", "def", "_set_subscriptions", "(", "self", ",", "subscriptions", ")", ":", "url", ",", "params", "=", "self", ".", "_get_subscriptions_endpoint", "(", ")", "data", "=", "{", "'object'", ":", "'page'", ",", "'callback_url'", ":", "self", ".", "webhook...
25.25
0.002725
def main(): """ NAME fishqq.py DESCRIPTION makes qq plot from dec,inc input data INPUT FORMAT takes dec/inc pairs in space delimited file SYNTAX fishqq.py [command line options] OPTIONS -h help message -f FILE, specify file on command line ...
[ "def", "main", "(", ")", ":", "fmt", ",", "plot", "=", "'svg'", ",", "0", "outfile", "=", "\"\"", "if", "'-h'", "in", "sys", ".", "argv", ":", "# check if help is needed", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "# ...
35.69863
0.038641
def primary_keys_full(cls): """Get primary key properties for a SQLAlchemy cls. Taken from marshmallow_sqlalchemy """ mapper = cls.__mapper__ return [ mapper.get_property_by_column(column) for column in mapper.primary_key ]
[ "def", "primary_keys_full", "(", "cls", ")", ":", "mapper", "=", "cls", ".", "__mapper__", "return", "[", "mapper", ".", "get_property_by_column", "(", "column", ")", "for", "column", "in", "mapper", ".", "primary_key", "]" ]
31.888889
0.00678
def required_fields(self): """The normal required fields (eg, no magic fields like _id are included)""" return {f:v for f, v in self.normal_fields.items() if v.required}
[ "def", "required_fields", "(", "self", ")", ":", "return", "{", "f", ":", "v", "for", "f", ",", "v", "in", "self", ".", "normal_fields", ".", "items", "(", ")", "if", "v", ".", "required", "}" ]
61
0.021622
def group_comments_by_round(comments, ranking=0): """ Group comments by the round to which they belong """ comment_rounds = {} ordered_comment_round_names = [] for comment in comments: comment_round_name = ranking and comment[11] or comment[7] if comment_round_name not in comment...
[ "def", "group_comments_by_round", "(", "comments", ",", "ranking", "=", "0", ")", ":", "comment_rounds", "=", "{", "}", "ordered_comment_round_names", "=", "[", "]", "for", "comment", "in", "comments", ":", "comment_round_name", "=", "ranking", "and", "comment",...
44.928571
0.001558
def invoked_with(self): """Similar to :attr:`Context.invoked_with` except properly handles the case where :meth:`Context.send_help` is used. If the help command was used regularly then this returns the :attr:`Context.invoked_with` attribute. Otherwise, if it the help command was...
[ "def", "invoked_with", "(", "self", ")", ":", "command_name", "=", "self", ".", "_command_impl", ".", "name", "ctx", "=", "self", ".", "context", "if", "ctx", "is", "None", "or", "ctx", ".", "command", "is", "None", "or", "ctx", ".", "command", ".", ...
40.631579
0.003797
def rmse(y, p): """Root Mean Squared Error (RMSE). Args: y (numpy.array): target p (numpy.array): prediction Returns: e (numpy.float64): RMSE """ # check and get number of samples assert y.shape == p.shape return np.sqrt(mse(y, p))
[ "def", "rmse", "(", "y", ",", "p", ")", ":", "# check and get number of samples", "assert", "y", ".", "shape", "==", "p", ".", "shape", "return", "np", ".", "sqrt", "(", "mse", "(", "y", ",", "p", ")", ")" ]
18.2
0.003484
def unload_extension(self, name): """Unloads an extension. When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported. The extension can provide an optional global function, ``teardown``, to do miscellaneous clean-up...
[ "def", "unload_extension", "(", "self", ",", "name", ")", ":", "lib", "=", "self", ".", "__extensions", ".", "get", "(", "name", ")", "if", "lib", "is", "None", ":", "raise", "errors", ".", "ExtensionNotLoaded", "(", "name", ")", "self", ".", "_remove_...
34.433333
0.001883
def team_players(self, team): """Store output of team players to a CSV file""" headers = ['Jersey Number', 'Name', 'Position', 'Nationality', 'Date of Birth'] result = [headers] result.extend([player['shirtNumber'], player['name'], ...
[ "def", "team_players", "(", "self", ",", "team", ")", ":", "headers", "=", "[", "'Jersey Number'", ",", "'Name'", ",", "'Position'", ",", "'Nationality'", ",", "'Date of Birth'", "]", "result", "=", "[", "headers", "]", "result", ".", "extend", "(", "[", ...
39.076923
0.003846
def genes_by_name(self, gene_name): """ Get all the unqiue genes with the given name (there might be multiple due to copies in the genome), return a list containing a Gene object for each distinct ID. """ gene_ids = self.gene_ids_of_gene_name(gene_name) return [se...
[ "def", "genes_by_name", "(", "self", ",", "gene_name", ")", ":", "gene_ids", "=", "self", ".", "gene_ids_of_gene_name", "(", "gene_name", ")", "return", "[", "self", ".", "gene_by_id", "(", "gene_id", ")", "for", "gene_id", "in", "gene_ids", "]" ]
45
0.00545
def parse_result(cls, result): """ Parse a simple items result. May either be two item tuple containing items and a context dictionary (see: relation convention) or a list of items. """ if isinstance(result, tuple) == 2: items, context = result else:...
[ "def", "parse_result", "(", "cls", ",", "result", ")", ":", "if", "isinstance", "(", "result", ",", "tuple", ")", "==", "2", ":", "items", ",", "context", "=", "result", "else", ":", "context", "=", "{", "}", "items", "=", "result", "return", "items"...
27.785714
0.007463