text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_generic_type(type_tag): """Map type tag to generic type.""" return { # Alarm DEVICE_ALARM: TYPE_ALARM, # Binary Sensors - Connectivity DEVICE_GLASS_BREAK: TYPE_CONNECTIVITY, DEVICE_KEYPAD: TYPE_CONNECTIVITY, DEVICE_REMOTE_CONTROLLER: TYPE_CONNECTIVITY, ...
[ "def", "get_generic_type", "(", "type_tag", ")", ":", "return", "{", "# Alarm", "DEVICE_ALARM", ":", "TYPE_ALARM", ",", "# Binary Sensors - Connectivity", "DEVICE_GLASS_BREAK", ":", "TYPE_CONNECTIVITY", ",", "DEVICE_KEYPAD", ":", "TYPE_CONNECTIVITY", ",", "DEVICE_REMOTE_C...
29.207547
0.000625
def color_ramp(number_of_colour): """Generate list of color in hexadecimal. This will generate colors using hsl model by playing around with the hue see: https://coderwall.com/p/dvsxwg/smoothly-transition-from-green-to-red :param number_of_colour: The number of intervals between R and G spectrum. ...
[ "def", "color_ramp", "(", "number_of_colour", ")", ":", "if", "number_of_colour", "<", "1", ":", "raise", "Exception", "(", "'The number of colours should be > 0'", ")", "colors", "=", "[", "]", "if", "number_of_colour", "==", "1", ":", "hue_interval", "=", "1",...
33.035714
0.00105
def request_data(self): """ (0,'cpu_percent'), (1,'virtual_memory_total'), (2,'virtual_memory_available'), (3,'virtual_memory_percent'), (4,'virtual_memory_used'), (5,'virtual_memory_free'), (6,'virtual_memory_active'), (7,'virtual_memory_inactive'...
[ "def", "request_data", "(", "self", ")", ":", "if", "not", "driver_ok", ":", "return", "None", "output", "=", "[", "]", "apcupsd_status_is_queried", "=", "False", "for", "item", "in", "self", ".", "variables", ":", "timestamp", "=", "time", "(", ")", "va...
45.131737
0.000389
def api_walk(uri, per_page=100, key="login"): """ For a GitHub URI, walk all the pages until there's no more content """ page = 1 result = [] while True: response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page)) if len(response) == 0: break else: ...
[ "def", "api_walk", "(", "uri", ",", "per_page", "=", "100", ",", "key", "=", "\"login\"", ")", ":", "page", "=", "1", "result", "=", "[", "]", "while", "True", ":", "response", "=", "get_json", "(", "uri", "+", "\"?page=%d&per_page=%d\"", "%", "(", "...
26.65
0.001812
def __remove_actions(self): """ Removes actions. """ LOGGER.debug("> Removing '{0}' Component actions.".format(self.__class__.__name__)) remove_project_action = "Actions|Umbra|Components|factory.script_editor|&File|Remove Project" self.__script_editor.command_menu.remov...
[ "def", "__remove_actions", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"> Removing '{0}' Component actions.\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "remove_project_action", "=", "\"Actions|Umbra|Components|factory.script_ed...
46.2
0.010616
def extract_cab (archive, compression, cmd, verbosity, interactive, outdir): """Extract a CAB archive.""" cmdlist = [cmd, '-d', outdir] if verbosity > 0: cmdlist.append('-v') cmdlist.append(archive) return cmdlist
[ "def", "extract_cab", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "cmdlist", "=", "[", "cmd", ",", "'-d'", ",", "outdir", "]", "if", "verbosity", ">", "0", ":", "cmdlist", ".", "append"...
33.571429
0.008299
def convert_jams(jams_file, output_prefix, csv=False, comment_char='#', namespaces=None): '''Convert jams to labs. Parameters ---------- jams_file : str The path on disk to the jams file in question output_prefix : str The file path prefix of the outputs csv : bool Whe...
[ "def", "convert_jams", "(", "jams_file", ",", "output_prefix", ",", "csv", "=", "False", ",", "comment_char", "=", "'#'", ",", "namespaces", "=", "None", ")", ":", "if", "namespaces", "is", "None", ":", "raise", "ValueError", "(", "'No namespaces provided. Try...
26.616667
0.001812
def cell_array_generator(self, key): """Generator traversing cells specified in key Parameters ---------- key: Iterable of Integer or slice \tThe key specifies the cell keys of the generator """ for i, key_ele in enumerate(key): # Get first element...
[ "def", "cell_array_generator", "(", "self", ",", "key", ")", ":", "for", "i", ",", "key_ele", "in", "enumerate", "(", "key", ")", ":", "# Get first element of key that is a slice", "if", "type", "(", "key_ele", ")", "is", "SliceType", ":", "slc_keys", "=", "...
30
0.001957
def _JImportFactory(spec, javaname, cls=_JImport): """ (internal) Factory for creating java modules dynamically. This is needed to create a new type node to hold static methods. """ def init(self, name): # Call the base class cls.__init__(self, name) def getall(self): globa...
[ "def", "_JImportFactory", "(", "spec", ",", "javaname", ",", "cls", "=", "_JImport", ")", ":", "def", "init", "(", "self", ",", "name", ")", ":", "# Call the base class", "cls", ".", "__init__", "(", "self", ",", "name", ")", "def", "getall", "(", "sel...
32.829268
0.001443
def statistics(self): """ Access the statistics :returns: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.WorkspaceStatisticsList """ if self._statistics is None: ...
[ "def", "statistics", "(", "self", ")", ":", "if", "self", ".", "_statistics", "is", "None", ":", "self", ".", "_statistics", "=", "WorkspaceStatisticsList", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'sid'", "]...
44.1
0.011111
def joined(name, host, user='rabbit', ram_node=None, runas='root'): ''' Ensure the current node joined to a cluster with node user@host name Irrelevant, not used (recommended: user@host) user The user of node to join to (default: rabbit) host The host of node to join to ...
[ "def", "joined", "(", "name", ",", "host", ",", "user", "=", "'rabbit'", ",", "ram_node", "=", "None", ",", "runas", "=", "'root'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", ...
31.795455
0.000693
def parseExtensionArgs(self, args): """Set the state of this request to be that expressed in these PAPE arguments @param args: The PAPE arguments without a namespace @rtype: None @raises ValueError: When the max_auth_age is not parseable as an integer """ ...
[ "def", "parseExtensionArgs", "(", "self", ",", "args", ")", ":", "# preferred_auth_policies is a space-separated list of policy URIs", "self", ".", "preferred_auth_policies", "=", "[", "]", "policies_str", "=", "args", ".", "get", "(", "'preferred_auth_policies'", ")", ...
32.133333
0.002014
def list_from_document(cls, doc): """Returns a list of TMDDEventConverter elements. doc is an XML Element containing one or more <FEU> events """ objs = [] for feu in doc.xpath('//FEU'): detail_els = feu.xpath('event-element-details/event-element-detail') ...
[ "def", "list_from_document", "(", "cls", ",", "doc", ")", ":", "objs", "=", "[", "]", "for", "feu", "in", "doc", ".", "xpath", "(", "'//FEU'", ")", ":", "detail_els", "=", "feu", ".", "xpath", "(", "'event-element-details/event-element-detail'", ")", "for"...
42.363636
0.008403
def where(self, inplace=False, **kwargs): """Return indices over every dimension that met the conditions. Condition syntax: *attribute* = value Return indices that satisfy the condition where the attribute is equal to the value e.g. ty...
[ "def", "where", "(", "self", ",", "inplace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "masks", "=", "{", "k", ":", "np", ".", "ones", "(", "v", ",", "dtype", "=", "'bool'", ")", "for", "k", ",", "v", "in", "self", ".", "dimensions", "...
32.066667
0.015129
def bcs_parameters(n_site, n_fermi, u, t) : """Generate the parameters for the BCS ground state, i.e., the superconducting gap and the rotational angles in the Bogoliubov transformation. Args: n_site: the number of sites in the Hubbard model n_fermi: the number of fermions u: t...
[ "def", "bcs_parameters", "(", "n_site", ",", "n_fermi", ",", "u", ",", "t", ")", ":", "# The wave numbers satisfy the periodic boundary condition.", "wave_num", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "n_site", ",", "endpoint", "=", "False", ")", ...
32.227273
0.001369
def match(self, *command_tokens, **command_env): """ :meth:`.WCommandProto.match` implementation """ command = self.command() if len(command_tokens) >= len(command): return command_tokens[:len(command)] == command return False
[ "def", "match", "(", "self", ",", "*", "command_tokens", ",", "*", "*", "command_env", ")", ":", "command", "=", "self", ".", "command", "(", ")", "if", "len", "(", "command_tokens", ")", ">=", "len", "(", "command", ")", ":", "return", "command_tokens...
33.285714
0.033473
def load_module(name, filename): '''Load a module into name given its filename''' if sys.version_info < (3, 5): import imp import warnings with warnings.catch_warnings(): # Required for Python 2.7 warnings.simplefilter("ignore", RuntimeWarning) return imp.load_so...
[ "def", "load_module", "(", "name", ",", "filename", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "5", ")", ":", "import", "imp", "import", "warnings", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "# Required for Python 2.7",...
40.166667
0.002028
def CMOVGE(cpu, dest, src): """ Conditional move - Greater or equal/not less. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current ...
[ "def", "CMOVGE", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "(", "cpu", ".", "SF", "^", "cpu", ".", "OF", ")", "==", "0", ",", "src", ".", "read", "(", ...
38.307692
0.009804
def create_widget(self): """ Create the underlying widget. """ self.init_options() #: Retrieve the actual map MapFragment.newInstance(self.options).then( self.on_map_fragment_created) # Holder for the fragment self.widget = FrameLayout(self.get_cont...
[ "def", "create_widget", "(", "self", ")", ":", "self", ".", "init_options", "(", ")", "#: Retrieve the actual map", "MapFragment", ".", "newInstance", "(", "self", ".", "options", ")", ".", "then", "(", "self", ".", "on_map_fragment_created", ")", "# Holder for ...
46.84
0.001674
def _elu(attrs, inputs, proto_obj): """Elu function""" if 'alpha' in attrs: new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'}) else: new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 1.0}) new_attrs = translation_utils._add_extra_attributes(...
[ "def", "_elu", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "if", "'alpha'", "in", "attrs", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'alpha'", ":", "'slope'", "}", ")", "else", ":", "ne...
48.25
0.012723
def read_line(self, line): """ Match a line of input according to the format specified and return a tuple of the resulting values """ if not self._read_line_init: self.init_read_line() match = self._re.match(line) assert match is not None, f"Format m...
[ "def", "read_line", "(", "self", ",", "line", ")", ":", "if", "not", "self", ".", "_read_line_init", ":", "self", ".", "init_read_line", "(", ")", "match", "=", "self", ".", "_re", ".", "match", "(", "line", ")", "assert", "match", "is", "not", "None...
31.9
0.001521
async def command_callback(self, ctx, *, command=None): """|coro| The actual implementation of the help command. It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched. - :meth:`send_bot_help` - :...
[ "async", "def", "command_callback", "(", "self", ",", "ctx", ",", "*", ",", "command", "=", "None", ")", ":", "await", "self", ".", "prepare_help_command", "(", "ctx", ",", "command", ")", "bot", "=", "ctx", ".", "bot", "if", "command", "is", "None", ...
36.559322
0.002257
def view_portfolio_losses(token, dstore): """ The losses for the full portfolio, for each realization and loss type, extracted from the event loss table. """ oq = dstore['oqparam'] loss_dt = oq.loss_dt() data = portfolio_loss(dstore).view(loss_dt)[:, 0] rlzids = [str(r) for r in range(le...
[ "def", "view_portfolio_losses", "(", "token", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "loss_dt", "=", "oq", ".", "loss_dt", "(", ")", "data", "=", "portfolio_loss", "(", "dstore", ")", ".", "view", "(", "loss_dt", ")", "[",...
41.916667
0.001946
def __get_permissions(self, res, **kwargs): """ This call returns current login user's permissions. """ response = res._(**kwargs) return response.get('permissions', None)
[ "def", "__get_permissions", "(", "self", ",", "res", ",", "*", "*", "kwargs", ")", ":", "response", "=", "res", ".", "_", "(", "*", "*", "kwargs", ")", "return", "response", ".", "get", "(", "'permissions'", ",", "None", ")" ]
34.333333
0.009479
def t_TITLE(self, token): ur'\#\s+<wca-title>(?P<title>.+)\n' token.value = token.lexer.lexmatch.group("title").decode("utf8") token.lexer.lineno += 1 return token
[ "def", "t_TITLE", "(", "self", ",", "token", ")", ":", "token", ".", "value", "=", "token", ".", "lexer", ".", "lexmatch", ".", "group", "(", "\"title\"", ")", ".", "decode", "(", "\"utf8\"", ")", "token", ".", "lexer", ".", "lineno", "+=", "1", "r...
38.2
0.020513
def connection_factory(self, endpoint, *args, **kwargs): """ Called to create a new connection with proper configuration. Intended for internal use only. """ kwargs = self._make_connection_kwargs(endpoint, kwargs) return self.connection_class.factory(endpoint, self.connec...
[ "def", "connection_factory", "(", "self", ",", "endpoint", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_make_connection_kwargs", "(", "endpoint", ",", "kwargs", ")", "return", "self", ".", "connection_class", ".", "fac...
48.714286
0.008646
def dataset_docs_str(datasets=None): """Create dataset documentation string for given datasets. Args: datasets: list of datasets for which to create documentation. If None, then all available datasets will be used. Returns: string describing the datasets (in the MarkDown format). """ m...
[ "def", "dataset_docs_str", "(", "datasets", "=", "None", ")", ":", "module_to_builder", "=", "make_module_to_builder_dict", "(", "datasets", ")", "sections", "=", "sorted", "(", "list", "(", "module_to_builder", ".", "keys", "(", ")", ")", ")", "section_tocs", ...
34.233333
0.00947
def evolved_transformer_base_tpu(): """Base parameters for Evolved Transformer model on TPU.""" hparams = add_evolved_transformer_hparams(transformer.transformer_tpu()) hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*single_cycle_...
[ "def", "evolved_transformer_base_tpu", "(", ")", ":", "hparams", "=", "add_evolved_transformer_hparams", "(", "transformer", ".", "transformer_tpu", "(", ")", ")", "hparams", ".", "learning_rate_constant", "=", "1", "/", "hparams", ".", "learning_rate_warmup_steps", "...
48.857143
0.020115
def load_library(self,libname): """Given the name of a library, load it.""" paths = self.getpaths(libname) for path in paths: if os.path.exists(path): return self.load(path) raise ImportError("%s not found." % libname)
[ "def", "load_library", "(", "self", ",", "libname", ")", ":", "paths", "=", "self", ".", "getpaths", "(", "libname", ")", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "self", ".", "load...
30.222222
0.010714
def lookup(word): ''' Get a definition for a word (uses Wordnik) ''' _patch_wordnik() # Jason's key - do not abuse key = 'edc4b9b94b341eeae350e087c2e05d2f5a2a9e0478cefc6dc' client = wordnik.swagger.ApiClient(key, 'http://api.wordnik.com/v4') words = wordnik.WordApi.WordApi(client) definitions = words.getDefini...
[ "def", "lookup", "(", "word", ")", ":", "_patch_wordnik", "(", ")", "# Jason's key - do not abuse", "key", "=", "'edc4b9b94b341eeae350e087c2e05d2f5a2a9e0478cefc6dc'", "client", "=", "wordnik", ".", "swagger", ".", "ApiClient", "(", "key", ",", "'http://api.wordnik.com/v...
29.642857
0.03271
def manhattan(x, y): """Manhatten, taxicab, or l1 distance. ..math:: D(x, y) = \sum_i |x_i - y_i| """ result = 0.0 for i in range(x.shape[0]): result += np.abs(x[i] - y[i]) return result
[ "def", "manhattan", "(", "x", ",", "y", ")", ":", "result", "=", "0.0", "for", "i", "in", "range", "(", "x", ".", "shape", "[", "0", "]", ")", ":", "result", "+=", "np", ".", "abs", "(", "x", "[", "i", "]", "-", "y", "[", "i", "]", ")", ...
19.818182
0.008772
def lookup_class(fully_qualified_name): """ Given its fully qualified name, finds the desired class and imports it. Returns the Class object if found. """ module_name, class_name = str(fully_qualified_name).rsplit(".", 1) module = __import__(module_name, globals(), locals(), [class_name], 0) ...
[ "def", "lookup_class", "(", "fully_qualified_name", ")", ":", "module_name", ",", "class_name", "=", "str", "(", "fully_qualified_name", ")", ".", "rsplit", "(", "\".\"", ",", "1", ")", "module", "=", "__import__", "(", "module_name", ",", "globals", "(", ")...
35.214286
0.001976
def frequency2fractional(frequency, mean_frequency=-1): """ Convert frequency in Hz to fractional frequency Parameters ---------- frequency: np.array Data array of frequency in Hz mean_frequency: float (optional) The nominal mean frequency, in Hz if omitted, defaults to mean...
[ "def", "frequency2fractional", "(", "frequency", ",", "mean_frequency", "=", "-", "1", ")", ":", "if", "mean_frequency", "==", "-", "1", ":", "mu", "=", "np", ".", "mean", "(", "frequency", ")", "else", ":", "mu", "=", "mean_frequency", "y", "=", "[", ...
25.545455
0.001715
def find_agent_host_id(this_host): """Returns the neutron agent host id for RHEL-OSP6 HA setup.""" host_id = this_host try: for root, dirs, files in os.walk('/run/resource-agents'): for fi in files: if 'neutron-scale-' in fi: host_id = 'neutron-n-' + ...
[ "def", "find_agent_host_id", "(", "this_host", ")", ":", "host_id", "=", "this_host", "try", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "'/run/resource-agents'", ")", ":", "for", "fi", "in", "files", ":", "if", "'neutron...
32.230769
0.00232
def placement_group_setup(group_name): """Creates placement_group group if necessary. Returns True if new placement_group group was created, False otherwise.""" existing_placement_groups = u.get_placement_group_dict() group = existing_placement_groups.get(group_name, None) if group: assert group.state =...
[ "def", "placement_group_setup", "(", "group_name", ")", ":", "existing_placement_groups", "=", "u", ".", "get_placement_group_dict", "(", ")", "group", "=", "existing_placement_groups", ".", "get", "(", "group_name", ",", "None", ")", "if", "group", ":", "assert",...
33.941176
0.016863
def encode(string): """ Encode the given string as an OID. >>> import snmp_passpersist as snmp >>> snmp.PassPersist.encode("hello") '5.104.101.108.108.111' >>> """ result=".".join([ str(ord(s)) for s in string ]) return "%s." % (len(string)) + result
[ "def", "encode", "(", "string", ")", ":", "result", "=", "\".\"", ".", "join", "(", "[", "str", "(", "ord", "(", "s", ")", ")", "for", "s", "in", "string", "]", ")", "return", "\"%s.\"", "%", "(", "len", "(", "string", ")", ")", "+", "result" ]
21.666667
0.055351
def idf2txt(txt): """convert the idf text to a simple text""" astr = nocomment(txt) objs = astr.split(';') objs = [obj.split(',') for obj in objs] objs = [[line.strip() for line in obj] for obj in objs] objs = [[_tofloat(line) for line in obj] for obj in objs] objs = [tuple(obj) for obj in o...
[ "def", "idf2txt", "(", "txt", ")", ":", "astr", "=", "nocomment", "(", "txt", ")", "objs", "=", "astr", ".", "split", "(", "';'", ")", "objs", "=", "[", "obj", ".", "split", "(", "','", ")", "for", "obj", "in", "objs", "]", "objs", "=", "[", ...
29.470588
0.001934
def _addr(self): """ Assign dae addresses for algebraic and state variables. Addresses are stored in ``self.__dict__[var]``. ``dae.m`` and ``dae.n`` are updated accordingly. Returns ------- None """ group_by = self._config['address_group_by'] ...
[ "def", "_addr", "(", "self", ")", ":", "group_by", "=", "self", ".", "_config", "[", "'address_group_by'", "]", "assert", "not", "self", ".", "_flags", "[", "'address'", "]", ",", "\"{} address already assigned\"", ".", "format", "(", "self", ".", "_name", ...
34.487805
0.002063
def shortcut_delete(self, shortcut_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/shortcuts#delete-shortcut" api_path = "/api/v2/shortcuts/{shortcut_id}" api_path = api_path.format(shortcut_id=shortcut_id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "shortcut_delete", "(", "self", ",", "shortcut_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/shortcuts/{shortcut_id}\"", "api_path", "=", "api_path", ".", "format", "(", "shortcut_id", "=", "shortcut_id", ")", "return", "self", ".", ...
61
0.009709
def create(self, specify_uri=False, ignore_tombstone=False, serialization_format=None, stream=False, auto_refresh=None): ''' Primary method to create resources. Args: specify_uri (bool): If True, uses PUT verb and sets the URI during creation. If False, uses POST and gets repository minted URI ignore_tom...
[ "def", "create", "(", "self", ",", "specify_uri", "=", "False", ",", "ignore_tombstone", "=", "False", ",", "serialization_format", "=", "None", ",", "stream", "=", "False", ",", "auto_refresh", "=", "None", ")", ":", "# if resource claims existence, raise excepti...
38.782609
0.02515
def multiple_subplots(rows=1, cols=1, maxplots=None, n=1, delete=True, for_maps=False, *args, **kwargs): """ Function to create subplots. This function creates so many subplots on so many figures until the specified number `n` is reached. Parameters ---------- rows: i...
[ "def", "multiple_subplots", "(", "rows", "=", "1", ",", "cols", "=", "1", ",", "maxplots", "=", "None", ",", "n", "=", "1", ",", "delete", "=", "True", ",", "for_maps", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", ...
35.192982
0.000485
def select(self, selection_specs=None, selection_mode='edges', **selection): """ Allows selecting data by the slices, sets and scalar values along a particular dimension. The indices should be supplied as keywords mapping between the selected dimension and value. Additionally sel...
[ "def", "select", "(", "self", ",", "selection_specs", "=", "None", ",", "selection_mode", "=", "'edges'", ",", "*", "*", "selection", ")", ":", "selection", "=", "{", "dim", ":", "sel", "for", "dim", ",", "sel", "in", "selection", ".", "items", "(", ...
45.333333
0.002399
def hline(level, **kwargs): """Draws a horizontal line at the given level. Parameters ---------- level: float The level at which to draw the horizontal line. preserve_domain: boolean (default: False) If true, the line does not affect the domain of the 'y' scale. """ kwargs.s...
[ "def", "hline", "(", "level", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'colors'", ",", "[", "'dodgerblue'", "]", ")", "kwargs", ".", "setdefault", "(", "'stroke_width'", ",", "1", ")", "scales", "=", "kwargs", ".", "pop", ...
30.888889
0.001163
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameHouseStatusMonitorDisableConfirmation): return False self.success = True return True
[ "async", "def", "handle_frame", "(", "self", ",", "frame", ")", ":", "if", "not", "isinstance", "(", "frame", ",", "FrameHouseStatusMonitorDisableConfirmation", ")", ":", "return", "False", "self", ".", "success", "=", "True", "return", "True" ]
44.5
0.011029
def atomic_copy(src, dst): """Copy the file src to dst, overwriting dst atomically.""" with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst: shutil.copyfile(src, tmp_dst.name) os.chmod(tmp_dst.name, os.stat(src).st_mode) os.rename(tmp_dst.name, dst)
[ "def", "atomic_copy", "(", "src", ",", "dst", ")", ":", "with", "temporary_file", "(", "root_dir", "=", "os", ".", "path", ".", "dirname", "(", "dst", ")", ")", "as", "tmp_dst", ":", "shutil", ".", "copyfile", "(", "src", ",", "tmp_dst", ".", "name",...
44.833333
0.010949
def lattice_array_to_unit_cell(lattice_array): """Return crystallographic param. from unit cell lattice matrix.""" cell_lengths = np.sqrt(np.sum(lattice_array**2, axis=0)) gamma_r = np.arccos(lattice_array[0][1] / cell_lengths[1]) beta_r = np.arccos(lattice_array[0][2] / cell_lengths[2]) alpha_r = n...
[ "def", "lattice_array_to_unit_cell", "(", "lattice_array", ")", ":", "cell_lengths", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "lattice_array", "**", "2", ",", "axis", "=", "0", ")", ")", "gamma_r", "=", "np", ".", "arccos", "(", "lattice_array...
44.692308
0.001686
def get_status(*nrs): """Returns a list of Bugreport objects. Given a list of bugnumbers this method returns a list of Bugreport objects. Parameters ---------- nrs : int or list of ints the bugnumbers Returns ------- bugs : list of Bugreport objects """ # If we ca...
[ "def", "get_status", "(", "*", "nrs", ")", ":", "# If we called get_status with one single bug, we get a single bug,", "# if we called it with a list of bugs, we get a list,", "# No available bugreports returns an empty list", "bugs", "=", "[", "]", "list_", "=", "[", "]", "for",...
32.410256
0.000768
def load_children(self): """ Load the subelements from the xml_element in its correspondent classes. :returns: List of child objects. :rtype: list :raises CardinalityException: If there is more than one Version child. """ # Containers children = list() ...
[ "def", "load_children", "(", "self", ")", ":", "# Containers", "children", "=", "list", "(", ")", "statuses", "=", "list", "(", ")", "version", "=", "None", "titles", "=", "list", "(", ")", "descriptions", "=", "list", "(", ")", "platforms", "=", "list...
32.145833
0.001258
def find_trivial_constructor(type_): """ Returns reference to trivial constructor. Args: type_ (declarations.class_t): the class to be searched. Returns: declarations.constructor_t: the trivial constructor """ assert isinstance(type_, class_declaration.class_t) trivial = ...
[ "def", "find_trivial_constructor", "(", "type_", ")", ":", "assert", "isinstance", "(", "type_", ",", "class_declaration", ".", "class_t", ")", "trivial", "=", "type_", ".", "constructors", "(", "lambda", "x", ":", "is_trivial_constructor", "(", "x", ")", ",",...
22.571429
0.002024
def get_new_client(request_session=False): """Return a new ConciergeClient, pulling secrets from the environment. """ from .client import ConciergeClient client = ConciergeClient(access_key=os.environ["MS_ACCESS_KEY"], secret_key=os.environ["MS_SECRET_KEY"], ...
[ "def", "get_new_client", "(", "request_session", "=", "False", ")", ":", "from", ".", "client", "import", "ConciergeClient", "client", "=", "ConciergeClient", "(", "access_key", "=", "os", ".", "environ", "[", "\"MS_ACCESS_KEY\"", "]", ",", "secret_key", "=", ...
40.545455
0.002193
def put_retention_policy(awsclient, log_group_name, retention_in_days): """Sets the retention of the specified log group if the log group does not yet exist than it will be created first. :param log_group_name: log group name :param retention_in_days: log group name :return: """ try: ...
[ "def", "put_retention_policy", "(", "awsclient", ",", "log_group_name", ",", "retention_in_days", ")", ":", "try", ":", "# Note: for AWS Lambda the log_group is created once the first", "# log event occurs. So if the log_group does not exist we create it", "create_log_group", "(", "a...
35.565217
0.00119
def count_unique_relations(graph: BELGraph) -> Counter: """Return a histogram of the different types of relations present in a graph. Note: this operation only counts each type of edge once for each pair of nodes """ return Counter(itt.chain.from_iterable(get_edge_relations(graph).values()))
[ "def", "count_unique_relations", "(", "graph", ":", "BELGraph", ")", "->", "Counter", ":", "return", "Counter", "(", "itt", ".", "chain", ".", "from_iterable", "(", "get_edge_relations", "(", "graph", ")", ".", "values", "(", ")", ")", ")" ]
50.666667
0.009709
def check_lazy_load_gebouw(f): ''' Decorator function to lazy load a :class:`Gebouw`. ''' def wrapper(*args): gebouw = args[0] if ( gebouw._methode_id is None or gebouw._geometrie is None or gebouw._metadata is None ): log.debug('Lazy loading G...
[ "def", "check_lazy_load_gebouw", "(", "f", ")", ":", "def", "wrapper", "(", "*", "args", ")", ":", "gebouw", "=", "args", "[", "0", "]", "if", "(", "gebouw", ".", "_methode_id", "is", "None", "or", "gebouw", ".", "_geometrie", "is", "None", "or", "ge...
33.111111
0.001631
def _load_polygon(tokens, string): """ Has similar inputs and return value to to :func:`_load_point`, except is for handling POLYGON geometry. :returns: A GeoJSON `dict` Polygon representation of the WKT ``string``. """ open_parens = next(tokens), next(tokens) if not open_parens == ...
[ "def", "_load_polygon", "(", "tokens", ",", "string", ")", ":", "open_parens", "=", "next", "(", "tokens", ")", ",", "next", "(", "tokens", ")", "if", "not", "open_parens", "==", "(", "'('", ",", "'('", ")", ":", "raise", "ValueError", "(", "INVALID_WK...
29.489796
0.00067
def limit(self, limit): """ Apply a LIMIT to the query and return the newly resulting Query. """ query = self._copy() query._limit = limit return query
[ "def", "limit", "(", "self", ",", "limit", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "_limit", "=", "limit", "return", "query" ]
27.571429
0.01005
def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None, lock_class=None, thread_local=True): """ Return a new Lock object using key ``name`` that mimics the behavior of threading.Lock. If specified, ``timeout`` indicates a maximum life for the lock. By ...
[ "def", "lock", "(", "self", ",", "name", ",", "timeout", "=", "None", ",", "sleep", "=", "0.1", ",", "blocking_timeout", "=", "None", ",", "lock_class", "=", "None", ",", "thread_local", "=", "True", ")", ":", "if", "lock_class", "is", "None", ":", "...
53.34
0.001105
def from_config(config): """Return a Recruiter instance based on the configuration. Default is HotAirRecruiter in debug mode (unless we're using the bot recruiter, which can be used in debug mode) and the MTurkRecruiter in other modes. """ debug_mode = config.get("mode") == "debug" name = c...
[ "def", "from_config", "(", "config", ")", ":", "debug_mode", "=", "config", ".", "get", "(", "\"mode\"", ")", "==", "\"debug\"", "name", "=", "config", ".", "get", "(", "\"recruiter\"", ",", "None", ")", "recruiter", "=", "None", "# Special case 1: Don't use...
31.891892
0.000822
def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ''' conf = Config(filename=conf_dict.get('__file__', '')) for k, v in six.iteritems(conf_dict): if k.startswith('__'): continue e...
[ "def", "conf_from_dict", "(", "conf_dict", ")", ":", "conf", "=", "Config", "(", "filename", "=", "conf_dict", ".", "get", "(", "'__file__'", ",", "''", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "conf_dict", ")", ":", "if", ...
24.1875
0.002488
def get_pypi_version(): """ Returns the version info from pypi for this app. """ try: response = requests.get(PYPI_URL, timeout=HALF_SECOND_TIMEOUT) response.raise_for_status() data = response.json() version_str = data["info"]["version"] return _parse_version_str(...
[ "def", "get_pypi_version", "(", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "PYPI_URL", ",", "timeout", "=", "HALF_SECOND_TIMEOUT", ")", "response", ".", "raise_for_status", "(", ")", "data", "=", "response", ".", "json", "(", ")", ...
39.428571
0.00177
def package_regex_filter(config, message, pattern=None, *args, **kw): """ All packages matching a regular expression Use this rule to include messages that relate to packages that match particular regular expressions (*i.e., (maven|javapackages-tools|maven-surefire)*). """ pattern = kw.get('pa...
[ "def", "package_regex_filter", "(", "config", ",", "message", ",", "pattern", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "pattern", "=", "kw", ".", "get", "(", "'pattern'", ",", "pattern", ")", "if", "pattern", ":", "packages", "="...
42.307692
0.001779
def unregister_message_callback(self, type_, from_): """ Unregister a callback previously registered with :meth:`register_message_callback`. :param type_: Message type to listen for. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen f...
[ "def", "unregister_message_callback", "(", "self", ",", "type_", ",", "from_", ")", ":", "if", "type_", "is", "not", "None", ":", "type_", "=", "self", ".", "_coerce_enum", "(", "type_", ",", "structs", ".", "MessageType", ")", "warnings", ".", "warn", "...
40.472727
0.000877
def increment(self, gold_set, test_set): "Add examples from sets." self.gold += len(gold_set) self.test += len(test_set) self.correct += len(gold_set & test_set)
[ "def", "increment", "(", "self", ",", "gold_set", ",", "test_set", ")", ":", "self", ".", "gold", "+=", "len", "(", "gold_set", ")", "self", ".", "test", "+=", "len", "(", "test_set", ")", "self", ".", "correct", "+=", "len", "(", "gold_set", "&", ...
37.8
0.010363
def update_parent_sequence_map(child_part, delete=False): """Updates the child map of a simple sequence assessment assessment part""" if child_part.has_parent_part(): object_map = child_part.get_assessment_part()._my_map database = 'assessment_authoring' collection_type = 'AssessmentPart...
[ "def", "update_parent_sequence_map", "(", "child_part", ",", "delete", "=", "False", ")", ":", "if", "child_part", ".", "has_parent_part", "(", ")", ":", "object_map", "=", "child_part", ".", "get_assessment_part", "(", ")", ".", "_my_map", "database", "=", "'...
46.2
0.00106
def summarize_sequence_file(source_file, file_type=None): """ Summarizes a sequence file, returning a tuple containing the name, whether the file is an alignment, minimum sequence length, maximum sequence length, average length, number of sequences. """ is_alignment = True avg_length = None ...
[ "def", "summarize_sequence_file", "(", "source_file", ",", "file_type", "=", "None", ")", ":", "is_alignment", "=", "True", "avg_length", "=", "None", "min_length", "=", "sys", ".", "maxsize", "max_length", "=", "0", "sequence_count", "=", "0", "# Get an iterato...
35.869565
0.00059
def update_ckan_ini(self, skin=True): """ Use config-tool to update development.ini with our environment settings :param skin: use environment template skin plugin True/False """ command = [ '/usr/lib/ckan/bin/paster', '--plugin=ckan', 'config-tool', '/pr...
[ "def", "update_ckan_ini", "(", "self", ",", "skin", "=", "True", ")", ":", "command", "=", "[", "'/usr/lib/ckan/bin/paster'", ",", "'--plugin=ckan'", ",", "'config-tool'", ",", "'/project/development.ini'", ",", "'-e'", ",", "'sqlalchemy.url = postgresql://<hidden>'", ...
47.083333
0.001735
def read_files(self, condition='*'): """Read specific files from archive into memory. If "condition" is a list of numbers, then return files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" ...
[ "def", "read_files", "(", "self", ",", "condition", "=", "'*'", ")", ":", "checker", "=", "condition2checker", "(", "condition", ")", "return", "RarFileImplementation", ".", "read_files", "(", "self", ",", "checker", ")" ]
58.916667
0.009749
def node_path_transforms(self, node): """Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the last transform should be applied first when mapping from this node to the other. Parameters -------...
[ "def", "node_path_transforms", "(", "self", ",", "node", ")", ":", "a", ",", "b", "=", "self", ".", "node_path", "(", "node", ")", "return", "(", "[", "n", ".", "transform", "for", "n", "in", "a", "[", ":", "-", "1", "]", "]", "+", "[", "n", ...
30.95
0.009404
def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects): """ called when user wants serial downloading """ # create directory to save files if not os.path.exists(directory): os.makedirs(directory) app = progress_class(frame, urls, directory, min_file_size, max_file_size, no_...
[ "def", "download_series_gui", "(", "frame", ",", "urls", ",", "directory", ",", "min_file_size", ",", "max_file_size", ",", "no_redirects", ")", ":", "# create directory to save files", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", ...
35.777778
0.030303
def load(self): """ Get load time series (only active power) Returns ------- dict or :pandas:`pandas.DataFrame<dataframe>` See class definition for details. """ try: return self._load.loc[[self.timeindex], :] except: r...
[ "def", "load", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_load", ".", "loc", "[", "[", "self", ".", "timeindex", "]", ",", ":", "]", "except", ":", "return", "self", ".", "_load", ".", "loc", "[", "self", ".", "timeindex", ",", ...
24.714286
0.008357
def force_list(data): """Force ``data`` to become a list. You should use this method whenever you don't want to deal with the fact that ``NoneType`` can't be iterated over. For example, instead of writing:: bar = foo.get('bar') if bar is not None: for el in bar: ...
[ "def", "force_list", "(", "data", ")", ":", "if", "data", "is", "None", ":", "return", "[", "]", "elif", "not", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "return", "[", "data", "]", "elif", "isinstance", ...
22.487805
0.00104
def disks(self): """Instance depends on the API version: * 2016-04-30-preview: :class:`DisksOperations<azure.mgmt.compute.v2016_04_30_preview.operations.DisksOperations>` * 2017-03-30: :class:`DisksOperations<azure.mgmt.compute.v2017_03_30.operations.DisksOperations>` * 2018-04...
[ "def", "disks", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'disks'", ")", "if", "api_version", "==", "'2016-04-30-preview'", ":", "from", ".", "v2016_04_30_preview", ".", "operations", "import", "DisksOperations", "as", "Op...
67.652174
0.008872
def as_manager(cls, obj): """ Convert obj into TaskManager instance. Accepts string, filepath, dictionary, `TaskManager` object. If obj is None, the manager is initialized from the user config file. """ if isinstance(obj, cls): return obj if obj is None: return cls.from_u...
[ "def", "as_manager", "(", "cls", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "cls", ")", ":", "return", "obj", "if", "obj", "is", "None", ":", "return", "cls", ".", "from_user_config", "(", ")", "if", "is_string", "(", "obj", ")", ":...
37.944444
0.008571
def create_clusters(provider, context, **kwargs): """Creates ECS clusters. Expects a "clusters" argument, which should contain a list of cluster names to create. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.contex...
[ "def", "create_clusters", "(", "provider", ",", "context", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "get_session", "(", "provider", ".", "region", ")", ".", "client", "(", "'ecs'", ")", "try", ":", "clusters", "=", "kwargs", "[", "\"clusters\"", ...
30.129032
0.001037
def create_udf_node(name, fields): """Create a new UDF node type. Parameters ---------- name : str Then name of the UDF node fields : OrderedDict Mapping of class member name to definition Returns ------- result : type A new BigQueryUDFNode subclass """ ...
[ "def", "create_udf_node", "(", "name", ",", "fields", ")", ":", "definition", "=", "next", "(", "_udf_name_cache", "[", "name", "]", ")", "external_name", "=", "'{}_{:d}'", ".", "format", "(", "name", ",", "definition", ")", "return", "type", "(", "externa...
25.388889
0.00211
def overview(index, start, end): """Compute metrics in the overview section for enriched github issues indexes. Returns a dictionary. Each key in the dictionary is the name of a metric, the value is the value of that metric. Value can be a complex object (eg, a time series). :param index: index...
[ "def", "overview", "(", "index", ",", "start", ",", "end", ")", ":", "results", "=", "{", "\"activity_metrics\"", ":", "[", "SubmittedPRs", "(", "index", ",", "start", ",", "end", ")", ",", "ClosedPRs", "(", "index", ",", "start", ",", "end", ")", "]...
35.434783
0.001195
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": """Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned b...
[ "def", "render", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"Future[None]\"", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot render() after finish()\"", ")", "html", "="...
40.22973
0.001311
def provider(cls, note, provider=None, name=False): """Register a provider, either a Provider class or a generator. Provider class:: from jeni import Injector as BaseInjector from jeni import Provider class Injector(BaseInjector): pass ...
[ "def", "provider", "(", "cls", ",", "note", ",", "provider", "=", "None", ",", "name", "=", "False", ")", ":", "def", "decorator", "(", "provider", ")", ":", "if", "inspect", ".", "isgeneratorfunction", "(", "provider", ")", ":", "# Automatically adapt gen...
30.18
0.001284
def logToConsole(level=logging.INFO): """ Create a log handler that logs to the console. """ logger = logging.getLogger() logger.setLevel(level) formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s %(message)s') handler = logging.StreamHandler() handler.setFormatter...
[ "def", "logToConsole", "(", "level", "=", "logging", ".", "INFO", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "setLevel", "(", "level", ")", "formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s %(name)s %(level...
32.642857
0.002128
def percent_encode(text, encode_set=DEFAULT_ENCODE_SET, encoding='utf-8'): '''Percent encode text. Unlike Python's ``quote``, this function accepts a blacklist instead of a whitelist of safe characters. ''' byte_string = text.encode(encoding) try: mapping = _percent_encoder_map_cache[e...
[ "def", "percent_encode", "(", "text", ",", "encode_set", "=", "DEFAULT_ENCODE_SET", ",", "encoding", "=", "'utf-8'", ")", ":", "byte_string", "=", "text", ".", "encode", "(", "encoding", ")", "try", ":", "mapping", "=", "_percent_encoder_map_cache", "[", "enco...
34.133333
0.001901
def get_cache_base(suffix=None): """ Return the default base location for distlib caches. If the directory does not exist, it is created. Use the suffix provided for the base directory, and default to '.distlib' if it isn't provided. On Windows, if LOCALAPPDATA is defined in the environment, then i...
[ "def", "get_cache_base", "(", "suffix", "=", "None", ")", ":", "if", "suffix", "is", "None", ":", "suffix", "=", "'.distlib'", "if", "os", ".", "name", "==", "'nt'", "and", "'LOCALAPPDATA'", "in", "os", ".", "environ", ":", "result", "=", "os", ".", ...
40.641026
0.000616
def get_bool(self, name, default=None): """Retrieves an environment variable value as ``bool``. Integer values are converted as expected: zero evaluates to ``False``, and non-zero to ``True``. String values of ``'true'`` and ``'false'`` are evaluated case insensitive. Args: ...
[ "def", "get_bool", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "name", "not", "in", "self", ":", "if", "default", "is", "not", "None", ":", "return", "default", "raise", "EnvironmentError", ".", "not_found", "(", "self", ".",...
38.518519
0.001876
def xform(self, left, right, repeating, base, sign): """ Return prefixes for tuple. :param str left: left of the radix :param str right: right of the radix :param str repeating: repeating part :param int base: the base in which value is displayed :param int sign:...
[ "def", "xform", "(", "self", ",", "left", ",", "right", ",", "repeating", ",", "base", ",", "sign", ")", ":", "# pylint: disable=too-many-arguments", "base_prefix", "=", "''", "if", "self", ".", "CONFIG", ".", "use_prefix", ":", "if", "base", "==", "8", ...
32.324324
0.008117
def hmac_hex_key(self, hmac_hex_key): """ Sets the hmac_hex_key of this CfsslAuthCredentials. The key that is used to compute the HMAC of the request using the HMAC-SHA-256 algorithm. Must contain an even number of hexadecimal characters. :param hmac_hex_key: The hmac_hex_key of this C...
[ "def", "hmac_hex_key", "(", "self", ",", "hmac_hex_key", ")", ":", "if", "hmac_hex_key", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `hmac_hex_key`, must not be `None`\"", ")", "if", "hmac_hex_key", "is", "not", "None", "and", "len", "(", "...
58.375
0.00843
def _landsat_get_mtl(sceneid): """ Get Landsat-8 MTL metadata. Attributes ---------- sceneid : str Landsat sceneid. For scenes after May 2017, sceneid have to be LANDSAT_PRODUCT_ID. Returns ------- out : dict returns a JSON like object with the metadata. ""...
[ "def", "_landsat_get_mtl", "(", "sceneid", ")", ":", "scene_params", "=", "_landsat_parse_scene_id", "(", "sceneid", ")", "meta_file", "=", "\"http://landsat-pds.s3.amazonaws.com/{}_MTL.txt\"", ".", "format", "(", "scene_params", "[", "\"key\"", "]", ")", "metadata", ...
25.454545
0.001721
def to_gmfs(shakemap, spatialcorr, crosscorr, site_effects, trunclevel, num_gmfs, seed, imts=None): """ :returns: (IMT-strings, array of GMFs of shape (R, N, E, M) """ N = len(shakemap) # number of sites std = shakemap['std'] if imts is None or len(imts) == 0: imts = std.dty...
[ "def", "to_gmfs", "(", "shakemap", ",", "spatialcorr", ",", "crosscorr", ",", "site_effects", ",", "trunclevel", ",", "num_gmfs", ",", "seed", ",", "imts", "=", "None", ")", ":", "N", "=", "len", "(", "shakemap", ")", "# number of sites", "std", "=", "sh...
45.775
0.000535
def power_tick(val, pos, times_sign=r'\times'): """Custom power ticker function. """ if val == 0: return r'$\mathregular{0}$' elif val < 0: exponent = int(np.log10(-val)) else: exponent = int(np.log10(val)) coeff = val / 10**exponent return r'$\mathregular{{{:.1f} {} 10^...
[ "def", "power_tick", "(", "val", ",", "pos", ",", "times_sign", "=", "r'\\times'", ")", ":", "if", "val", "==", "0", ":", "return", "r'$\\mathregular{0}$'", "elif", "val", "<", "0", ":", "exponent", "=", "int", "(", "np", ".", "log10", "(", "-", "val...
36.076923
0.002079
def rename(from_path, to_path, user=None): """ See :meth:`fs.hdfs.rename`. """ fhost, fport, fpath = path.split(from_path, user) thost, tport, tpath = path.split(to_path, user) with hdfs(thost, tport, user) as fs: chost, cport = fs.host, fs.port with hdfs(fhost, fport, user) as fs: ...
[ "def", "rename", "(", "from_path", ",", "to_path", ",", "user", "=", "None", ")", ":", "fhost", ",", "fport", ",", "fpath", "=", "path", ".", "split", "(", "from_path", ",", "user", ")", "thost", ",", "tport", ",", "tpath", "=", "path", ".", "split...
38
0.002141
def cmdLine(useBasename=False): """Return full command line with any necessary quoting.""" qargv = [] cmdwords = list(sys.argv) if useBasename: cmdwords[0] = os.path.basename(cmdwords[0]) for s in cmdwords: # any white space or special characters in word so we need quoting? i...
[ "def", "cmdLine", "(", "useBasename", "=", "False", ")", ":", "qargv", "=", "[", "]", "cmdwords", "=", "list", "(", "sys", ".", "argv", ")", "if", "useBasename", ":", "cmdwords", "[", "0", "]", "=", "os", ".", "path", ".", "basename", "(", "cmdword...
33.882353
0.001689
def _check_release_done_processing(release): """Moves a release candidate to reviewing if all runs are done.""" if release.status != models.Release.PROCESSING: # NOTE: This statement also guards for situations where the user has # prematurely specified that the release is good or bad. Once the u...
[ "def", "_check_release_done_processing", "(", "release", ")", ":", "if", "release", ".", "status", "!=", "models", ".", "Release", ".", "PROCESSING", ":", "# NOTE: This statement also guards for situations where the user has", "# prematurely specified that the release is good or ...
43.317073
0.000551
def is_relation_made(relation, keys='private-address'): ''' Determine whether a relation is established by checking for presence of key(s). If a list of keys is provided, they must all be present for the relation to be identified as made ''' if isinstance(keys, str): keys = [keys] f...
[ "def", "is_relation_made", "(", "relation", ",", "keys", "=", "'private-address'", ")", ":", "if", "isinstance", "(", "keys", ",", "str", ")", ":", "keys", "=", "[", "keys", "]", "for", "r_id", "in", "relation_ids", "(", "relation", ")", ":", "for", "u...
37
0.00155
def get_all_available_leaves(self, language=None, forbidden_item_ids=None): """ Get all available leaves. """ return self.get_all_leaves(language=language, forbidden_item_ids=forbidden_item_ids)
[ "def", "get_all_available_leaves", "(", "self", ",", "language", "=", "None", ",", "forbidden_item_ids", "=", "None", ")", ":", "return", "self", ".", "get_all_leaves", "(", "language", "=", "language", ",", "forbidden_item_ids", "=", "forbidden_item_ids", ")" ]
44.4
0.013274
def get_repo(self, repo: str, branch: str, *, depth: Optional[int]=1, reference: Optional[Path]=None ) -> Repo: """ Returns a :class:`Repo <git.repo.base.Repo>` instance for the branch. See :meth:`run` for arguments descriptions. """ gi...
[ "def", "get_repo", "(", "self", ",", "repo", ":", "str", ",", "branch", ":", "str", ",", "*", ",", "depth", ":", "Optional", "[", "int", "]", "=", "1", ",", "reference", ":", "Optional", "[", "Path", "]", "=", "None", ")", "->", "Repo", ":", "g...
37.181818
0.026253
def add_xmlid(cr, module, xmlid, model, res_id, noupdate=False): """ Adds an entry in ir_model_data. Typically called in the pre script. One usage example is when an entry has been add in the XML and there is a high probability that the user has already created the entry manually. For example, a cur...
[ "def", "add_xmlid", "(", "cr", ",", "module", ",", "xmlid", ",", "model", ",", "res_id", ",", "noupdate", "=", "False", ")", ":", "# Check if the XMLID doesn't already exists", "cr", ".", "execute", "(", "\"SELECT id FROM ir_model_data WHERE module=%s AND name=%s \"", ...
46.322581
0.000682
def normalized_log_entries(raw_entries): '''Mimic the format returned by LambdaManager.logs()''' entry_start = r'([0-9:, \-]+) - .* - (\w+) - (.*)$' entry = None # process start/end here - avoid parsing log entries twice for line in raw_entries: m = re.match(entry_start, line) if m: ...
[ "def", "normalized_log_entries", "(", "raw_entries", ")", ":", "entry_start", "=", "r'([0-9:, \\-]+) - .* - (\\w+) - (.*)$'", "entry", "=", "None", "# process start/end here - avoid parsing log entries twice", "for", "line", "in", "raw_entries", ":", "m", "=", "re", ".", ...
38.37037
0.000942
def plugins(self): """ Retrieve a list of installed plugins. Returns: A list of dicts, one per plugin """ url = self._url('/plugins') return self._result(self._get(url), True)
[ "def", "plugins", "(", "self", ")", ":", "url", "=", "self", ".", "_url", "(", "'/plugins'", ")", "return", "self", ".", "_result", "(", "self", ".", "_get", "(", "url", ")", ",", "True", ")" ]
26.666667
0.008065
def binary_cross_entropy_cost( outputs, targets, derivative=False, epsilon=1e-11 ): """ The output signals should be in the range [0, 1] """ # Prevent overflow outputs = np.clip(outputs, epsilon, 1 - epsilon) divisor = np.maximum(outputs * (1 - outputs), epsilon) if derivative: ...
[ "def", "binary_cross_entropy_cost", "(", "outputs", ",", "targets", ",", "derivative", "=", "False", ",", "epsilon", "=", "1e-11", ")", ":", "# Prevent overflow", "outputs", "=", "np", ".", "clip", "(", "outputs", ",", "epsilon", ",", "1", "-", "epsilon", ...
38.5
0.016913
def evaluate_response(json_response): """Evaluate rest response.""" if 'errors' in json_response and json_response['errors']: Interface.evaluate_errors(json_response) elif 'result' not in json_response: raise PyVLXException('no element result found in response: {0}'.form...
[ "def", "evaluate_response", "(", "json_response", ")", ":", "if", "'errors'", "in", "json_response", "and", "json_response", "[", "'errors'", "]", ":", "Interface", ".", "evaluate_errors", "(", "json_response", ")", "elif", "'result'", "not", "in", "json_response"...
59.25
0.008316
def decryption_statem(self, ciphertext_in, key_in, reset): """ Builds a multiple cycle AES Decryption state machine circuit :param reset: a one bit signal telling the state machine to reset and accept the current plaintext and key :return ready, plain_text: ready is a one bit ...
[ "def", "decryption_statem", "(", "self", ",", "ciphertext_in", ",", "key_in", ",", "reset", ")", ":", "if", "len", "(", "key_in", ")", "!=", "len", "(", "ciphertext_in", ")", ":", "raise", "pyrtl", ".", "PyrtlError", "(", "\"AES key and ciphertext should be th...
39.054545
0.002271
def ld_prune(df, ld_beds, snvs=None): """ Prune set of GWAS based on LD and significance. A graph of all SNVs is constructed with edges for LD >= 0.8 and the most significant SNV per connected component is kept. Parameters ---------- df : pandas.DataFrame Pandas dataframe with ...
[ "def", "ld_prune", "(", "df", ",", "ld_beds", ",", "snvs", "=", "None", ")", ":", "import", "networkx", "as", "nx", "import", "tabix", "if", "snvs", ":", "df", "=", "df", ".", "ix", "[", "set", "(", "df", ".", "index", ")", "&", "set", "(", "sn...
42.168539
0.002343
def fromtimestamp(cls, t): "Construct a date from a POSIX timestamp (like time.time())." y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t) return cls(y, m, d)
[ "def", "fromtimestamp", "(", "cls", ",", "t", ")", ":", "y", ",", "m", ",", "d", ",", "hh", ",", "mm", ",", "ss", ",", "weekday", ",", "jday", ",", "dst", "=", "_time", ".", "localtime", "(", "t", ")", "return", "cls", "(", "y", ",", "m", "...
47.5
0.010363