text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def run(self, argv=None): """ Run the command-line application. This will dispatch to the specified function or raise a ``SystemExit`` and output the appropriate usage information if there is an error parsing the arguments. The default ``argv`` is equivalent to ``sys.ar...
[ "def", "run", "(", "self", ",", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "# pragma: no cover", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "argv", "=", "[", "str", "(", "v", ")", "for", "v", "in", "argv", "]", ...
37.736842
16.894737
def start_and_end_of_reference_axis(chains): """ Get start and end coordinates that approximate the reference axis for a collection of chains (not necessarily all the same length). Parameters ---------- chains : [Polypeptide] Returns ------- start, end : numpy.array 3D start a...
[ "def", "start_and_end_of_reference_axis", "(", "chains", ")", ":", "coords", "=", "[", "numpy", ".", "array", "(", "chains", "[", "0", "]", ".", "primitive", ".", "coordinates", ")", "]", "orient_vector", "=", "polypeptide_vector", "(", "chains", "[", "0", ...
40
20.875
def set_image(self, image): """Set display buffer to Python Image Library image. Red pixels (r=255, g=0, b=0) will map to red LEDs, green pixels (r=0, g=255, b=0) will map to green LEDs, and yellow pixels (r=255, g=255, b=0) will map to yellow LEDs. All other pixel values will map to an...
[ "def", "set_image", "(", "self", ",", "image", ")", ":", "imwidth", ",", "imheight", "=", "image", ".", "size", "if", "imwidth", "!=", "8", "or", "imheight", "!=", "8", ":", "raise", "ValueError", "(", "'Image must be an 8x8 pixels in size.'", ")", "# Conver...
48.6
11.28
def order_fmap(ncoef): """Compute order corresponding to a given number of coefficients. Parameters ---------- ncoef : int Number of coefficients. Returns ------- order : int Order corresponding to the provided number of coefficients. """ loop = True order = 1...
[ "def", "order_fmap", "(", "ncoef", ")", ":", "loop", "=", "True", "order", "=", "1", "while", "loop", ":", "loop", "=", "not", "(", "ncoef", "==", "ncoef_fmap", "(", "order", ")", ")", "if", "loop", ":", "order", "+=", "1", "if", "order", ">", "N...
23.923077
22.230769
def build_callbacks(self): '''Eventually, this should be configured, rather than hardcoded''' # checkpoint filepath = os.path.join(CHECKPOINT_DIR, 'weights.best.hdf5') checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto') ...
[ "def", "build_callbacks", "(", "self", ")", ":", "# checkpoint", "filepath", "=", "os", ".", "path", ".", "join", "(", "CHECKPOINT_DIR", ",", "'weights.best.hdf5'", ")", "checkpoint", "=", "ModelCheckpoint", "(", "filepath", ",", "monitor", "=", "'val_loss'", ...
50
23.25
def forvo(language, word, key): ''' Returns a list of suitable audiosamples for a given word from Forvo.com. ''' from requests import get url = 'http://apifree.forvo.com/action/word-pronunciations/format/json/word/%s/language/%s/key/%s/' % (word, language, key) urls = [] page = get(url) if page.status_code == ...
[ "def", "forvo", "(", "language", ",", "word", ",", "key", ")", ":", "from", "requests", "import", "get", "url", "=", "'http://apifree.forvo.com/action/word-pronunciations/format/json/word/%s/language/%s/key/%s/'", "%", "(", "word", ",", "language", ",", "key", ")", ...
40.681818
27.863636
def all_contents(self): '''Iterator over all contents''' translations_iterator = chain(*self.translations_lists()) return chain(translations_iterator, *(pair[i] for pair in self.contents_list_pairs() for i in (0, 1)))
[ "def", "all_contents", "(", "self", ")", ":", "translations_iterator", "=", "chain", "(", "*", "self", ".", "translations_lists", "(", ")", ")", "return", "chain", "(", "translations_iterator", ",", "*", "(", "pair", "[", "i", "]", "for", "pair", "in", "...
46.666667
12.333333
def to_dict(self): """ Returns: itself as a dictionary """ dictator = Script.to_dict(self) # the dynamically created ScriptIterator classes have a generic name # replace this with ScriptIterator to indicate that this class is of type ScriptIterator dictator[self.n...
[ "def", "to_dict", "(", "self", ")", ":", "dictator", "=", "Script", ".", "to_dict", "(", "self", ")", "# the dynamically created ScriptIterator classes have a generic name", "# replace this with ScriptIterator to indicate that this class is of type ScriptIterator", "dictator", "[",...
36.8
18.8
def dim(self, dim_index): """Get an SDim instance given a dimension index number. Args:: dim_index index number of the dimension (numbering starts at 0) C library equivalent : SDgetdimid """ id = _C.SDgetdimid(self._id, dim...
[ "def", "dim", "(", "self", ",", "dim_index", ")", ":", "id", "=", "_C", ".", "SDgetdimid", "(", "self", ".", "_id", ",", "dim_index", ")", "_checkErr", "(", "'dim'", ",", "id", ",", "'invalid SDS identifier or dimension index'", ")", "return", "SDim", "(",...
35.916667
19.583333
def from_tuple(tup): """Convert a tuple into a range with error handling. Parameters ---------- tup : tuple (len 2 or 3) The tuple to turn into a range. Returns ------- range : range The range from the tuple. Raises ------ ValueError Raised when the tup...
[ "def", "from_tuple", "(", "tup", ")", ":", "if", "len", "(", "tup", ")", "not", "in", "(", "2", ",", "3", ")", ":", "raise", "ValueError", "(", "'tuple must contain 2 or 3 elements, not: %d (%r'", "%", "(", "len", "(", "tup", ")", ",", "tup", ",", ")",...
20.961538
21.153846
async def create(cls, device='/dev/ttyUSB0', host=None, username=None, password=None, port=25010, hub_version=2, auto_reconnect=True, loop=None, workdir=None, poll_devices=True, load_aldb=True): """Create a connection to a specific device. ...
[ "async", "def", "create", "(", "cls", ",", "device", "=", "'/dev/ttyUSB0'", ",", "host", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "port", "=", "25010", ",", "hub_version", "=", "2", ",", "auto_reconnect", "=", "True...
35.827586
17.913793
def edit_release_notes(): """Use the default text $EDITOR to write release notes. If $EDITOR is not set, use 'nano'.""" from tempfile import mkstemp import os import shlex import subprocess text_editor = shlex.split(os.environ.get('EDITOR', 'nano')) fd, ...
[ "def", "edit_release_notes", "(", ")", ":", "from", "tempfile", "import", "mkstemp", "import", "os", "import", "shlex", "import", "subprocess", "text_editor", "=", "shlex", ".", "split", "(", "os", ".", "environ", ".", "get", "(", "'EDITOR'", ",", "'nano'", ...
34.913043
17.086957
def pop(self, timeout=0): """ Pop a request timeout not support in this queue class """ # use atomic range/remove using multi/exec pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count...
[ "def", "pop", "(", "self", ",", "timeout", "=", "0", ")", ":", "# use atomic range/remove using multi/exec", "pipe", "=", "self", ".", "server", ".", "pipeline", "(", ")", "pipe", ".", "multi", "(", ")", "pipe", ".", "zrange", "(", "self", ".", "key", ...
33.166667
11.166667
def username(self): """The name of the user that owns the process. On UNIX this is calculated by using *real* process uid. """ if os.name == 'posix': if pwd is None: # might happen if python was installed from sources raise ImportError("require...
[ "def", "username", "(", "self", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "if", "pwd", "is", "None", ":", "# might happen if python was installed from sources", "raise", "ImportError", "(", "\"requires pwd module shipped with standard python\"", ")", "r...
44.090909
18.363636
def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None): ''' Deletes a certificate from Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.delete_server_cert mycert_name ''' conn = _get_conn(region=region, key=ke...
[ "def", "delete_server_cert", "(", "cert_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",",...
28.842105
25.684211
def delete_property(self, key): """Remove a property from the document. Calling code should use this method to remove properties on the document instead of modifying ``properties`` directly. If there is a property with the name in ``key``, it will be removed. Otherwise, a ``Key...
[ "def", "delete_property", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "RESERVED_ATTRIBUTE_NAMES", ":", "raise", "KeyError", "(", "key", ")", "del", "self", ".", "o", "[", "key", "]" ]
34.538462
20.076923
def __build_option_parser(): """ Build the option parser for this script """ description = """ Tool to analyze Wireshark dumps of Sonos traffic. The files that are input to this script must be in the "Wireshark/tcpdump/...-libpcap" format, which can be exported from Wireshark. To use the o...
[ "def", "__build_option_parser", "(", ")", ":", "description", "=", "\"\"\"\n Tool to analyze Wireshark dumps of Sonos traffic.\n\n The files that are input to this script must be in the\n \"Wireshark/tcpdump/...-libpcap\" format, which can be exported from\n Wireshark.\n\n To use the op...
50.821429
23.982143
def check_active(url, element, **kwargs): '''check "active" url, apply css_class''' menu = yesno_to_bool(kwargs['menu'], 'menu') ignore_params = yesno_to_bool(kwargs['ignore_params'], 'ignore_params') # check missing href parameter if not url.attrib.get('href', None) is None: # get href att...
[ "def", "check_active", "(", "url", ",", "element", ",", "*", "*", "kwargs", ")", ":", "menu", "=", "yesno_to_bool", "(", "kwargs", "[", "'menu'", "]", ",", "'menu'", ")", "ignore_params", "=", "yesno_to_bool", "(", "kwargs", "[", "'ignore_params'", "]", ...
36.22619
17.75
def cleanup_full(self, trial_runner): """Cleans up bracket after bracket is completely finished. Lets the last trial continue to run until termination condition kicks in.""" for trial in self.current_trials(): if (trial.status == Trial.PAUSED): trial_runner.s...
[ "def", "cleanup_full", "(", "self", ",", "trial_runner", ")", ":", "for", "trial", "in", "self", ".", "current_trials", "(", ")", ":", "if", "(", "trial", ".", "status", "==", "Trial", ".", "PAUSED", ")", ":", "trial_runner", ".", "stop_trial", "(", "t...
41.125
11.125
def _get_cpv(cp, installed=True): ''' add version to category/package @cp - name of package in format category/name @installed - boolean value, if False, function returns cpv for latest available package ''' if installed: return _get_portage().db[portage.root]['vartree'].dep_bestmatc...
[ "def", "_get_cpv", "(", "cp", ",", "installed", "=", "True", ")", ":", "if", "installed", ":", "return", "_get_portage", "(", ")", ".", "db", "[", "portage", ".", "root", "]", "[", "'vartree'", "]", ".", "dep_bestmatch", "(", "cp", ")", "else", ":", ...
33.636364
19.090909
def _process_results(): """Process the results from an Async job.""" async = get_current_async() callbacks = async.get_callbacks() if not isinstance(async.result.payload, AsyncException): callback = callbacks.get('success') else: callback = callbacks.get('error') if not cal...
[ "def", "_process_results", "(", ")", ":", "async", "=", "get_current_async", "(", ")", "callbacks", "=", "async", ".", "get_callbacks", "(", ")", "if", "not", "isinstance", "(", "async", ".", "result", ".", "payload", ",", "AsyncException", ")", ":", "call...
31.133333
16.733333
def uninstall_handler(library, session, event_type, handler, user_handle=None): """Uninstalls handlers for events. Corresponds to viUninstallHandler function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param even...
[ "def", "uninstall_handler", "(", "library", ",", "session", ",", "event_type", ",", "handler", ",", "user_handle", "=", "None", ")", ":", "set_user_handle_type", "(", "library", ",", "user_handle", ")", "if", "user_handle", "!=", "None", ":", "user_handle", "=...
50
23
def setUp(self, tp): ''' {'xsd':['annotation', 'simpleContent', 'complexContent',\ 'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\ 'anyAttribute', 'any']} ''' # # TODO: Need a Recursive solution, this is incomplete will ignore many #...
[ "def", "setUp", "(", "self", ",", "tp", ")", ":", "# ", "# TODO: Need a Recursive solution, this is incomplete will ignore many", "# extensions, restrictions, etc.", "# ", "self", ".", "_item", "=", "tp", "# JRB HACK SUPPORTING element/no content.", "assert", "tp", ".", "i...
38.566667
23.788889
def btc_tx_der_encode_sequence(*encoded_pieces): """ Return a DER-encoded sequence Based on code from python-ecdsa (https://github.com/warner/python-ecdsa) by Brian Warner. Subject to the MIT license. """ # borrowed from python-ecdsa total_len = sum([len(p) for p in encoded_pieces]) re...
[ "def", "btc_tx_der_encode_sequence", "(", "*", "encoded_pieces", ")", ":", "# borrowed from python-ecdsa", "total_len", "=", "sum", "(", "[", "len", "(", "p", ")", "for", "p", "in", "encoded_pieces", "]", ")", "return", "b", "(", "'\\x30'", ")", "+", "btc_tx...
39.2
16.8
def flip(self): """Flip vector""" # added by Mostapha Sadeghipour self.x = -self.x self.y = -self.y self.z = -self.z return self
[ "def", "flip", "(", "self", ")", ":", "# added by Mostapha Sadeghipour", "self", ".", "x", "=", "-", "self", ".", "x", "self", ".", "y", "=", "-", "self", ".", "y", "self", ".", "z", "=", "-", "self", ".", "z", "return", "self" ]
24.285714
13.571429
def ucrss(v1, v2): """ Compute the normalized cross product of two 3-vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ucrss_c.html :param v1: Left vector for cross product. :type v1: 3-Element Array of floats :param v2: Right vector for cross product. :type v2: 3-Element Ar...
[ "def", "ucrss", "(", "v1", ",", "v2", ")", ":", "v1", "=", "stypes", ".", "toDoubleVector", "(", "v1", ")", "v2", "=", "stypes", ".", "toDoubleVector", "(", "v2", ")", "vout", "=", "stypes", ".", "emptyDoubleVector", "(", "3", ")", "libspice", ".", ...
33
12
def delete_user(self, recipient_email): """ Remove user from encryption """ emailid_list = self.list_user_emails() if recipient_email not in emailid_list: raise Exception("User {0} not present!".format(recipient_email)) else: emailid_list.remove(re...
[ "def", "delete_user", "(", "self", ",", "recipient_email", ")", ":", "emailid_list", "=", "self", ".", "list_user_emails", "(", ")", "if", "recipient_email", "not", "in", "emailid_list", ":", "raise", "Exception", "(", "\"User {0} not present!\"", ".", "format", ...
37.454545
9.636364
def set_using_network_time(enable): ''' Set whether network time is on or off. :param enable: True to enable, False to disable. Can also use 'on' or 'off' :type: str bool :return: True if successful, False if not :rtype: bool :raises: CommandExecutionError on failure CLI Example: ...
[ "def", "set_using_network_time", "(", "enable", ")", ":", "state", "=", "salt", ".", "utils", ".", "mac_utils", ".", "validate_enabled", "(", "enable", ")", "cmd", "=", "'systemsetup -setusingnetworktime {0}'", ".", "format", "(", "state", ")", "salt", ".", "u...
26
24.64
def config_cred(config, providers): """Read credentials from configfile.""" expected = ['aws', 'azure', 'gcp', 'alicloud'] cred = {} to_remove = [] for item in providers: if any(item.startswith(itemb) for itemb in expected): try: cred[item] = dict(list(config[item...
[ "def", "config_cred", "(", "config", ",", "providers", ")", ":", "expected", "=", "[", "'aws'", ",", "'azure'", ",", "'gcp'", ",", "'alicloud'", "]", "cred", "=", "{", "}", "to_remove", "=", "[", "]", "for", "item", "in", "providers", ":", "if", "any...
39.111111
16.277778
def build_functional(self, *pattern, **kwargs): """ Builds a new functional pattern :param pattern: :type pattern: :param kwargs: :type kwargs: :return: :rtype: """ set_defaults(self._functional_defaults, kwargs) set_defaults(self....
[ "def", "build_functional", "(", "self", ",", "*", "pattern", ",", "*", "*", "kwargs", ")", ":", "set_defaults", "(", "self", ".", "_functional_defaults", ",", "kwargs", ")", "set_defaults", "(", "self", ".", "_defaults", ",", "kwargs", ")", "return", "Func...
27
14.285714
async def save(self): """Save the object in MAAS.""" if hasattr(self._handler, "update"): if self._changed_data: update_data = dict(self._changed_data) update_data.update({ key: self._orig_data[key] for key in self._hand...
[ "async", "def", "save", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_handler", ",", "\"update\"", ")", ":", "if", "self", ".", "_changed_data", ":", "update_data", "=", "dict", "(", "self", ".", "_changed_data", ")", "update_data", ".", ...
40.846154
14.076923
def _BernI_to_FormFlavor_I(C, qq): """From BernI to FormFlavorI basis for $\Delta F=2$ operators. `qq` should be 'sb', 'db', 'ds' or 'uc'""" qqf = qq[::-1] # FormFlavour uses "bs" instead of "sb" etc. if qq in ['sb', 'db', 'ds']: return { 'CVLL_' + 2*qqf: C["1" + 2*qq], '...
[ "def", "_BernI_to_FormFlavor_I", "(", "C", ",", "qq", ")", ":", "qqf", "=", "qq", "[", ":", ":", "-", "1", "]", "# FormFlavour uses \"bs\" instead of \"sb\" etc.", "if", "qq", "in", "[", "'sb'", ",", "'db'", ",", "'ds'", "]", ":", "return", "{", "'CVLL_'...
47.178571
17.964286
def parse_genome_results(self, f): """ Parse the contents of the Qualimap BamQC genome_results.txt file """ regexes = { 'bam_file': r"bam file = (.+)", 'total_reads': r"number of reads = ([\d,]+)", 'mapped_reads': r"number of mapped reads = ([\d,]+)", 'mapped_bases': r"number of ...
[ "def", "parse_genome_results", "(", "self", ",", "f", ")", ":", "regexes", "=", "{", "'bam_file'", ":", "r\"bam file = (.+)\"", ",", "'total_reads'", ":", "r\"number of reads = ([\\d,]+)\"", ",", "'mapped_reads'", ":", "r\"number of mapped reads = ([\\d,]+)\"", ",", "'m...
45.136364
23.681818
def resolve_variables(variables, context, provider): """Given a list of variables, resolve all of them. Args: variables (list of :class:`stacker.variables.Variable`): list of variables context (:class:`stacker.context.Context`): stacker context provider (:class:`stacker.prov...
[ "def", "resolve_variables", "(", "variables", ",", "context", ",", "provider", ")", ":", "for", "variable", "in", "variables", ":", "variable", ".", "resolve", "(", "context", ",", "provider", ")" ]
35.307692
20.615385
def get_freesasa_annotations(self, outdir, include_hetatms=False, force_rerun=False): """Run ``freesasa`` on this structure and store the calculated properties in the corresponding ChainProps """ if self.file_type != 'pdb': log.error('{}: unable to run freesasa with "{}" file type. P...
[ "def", "get_freesasa_annotations", "(", "self", ",", "outdir", ",", "include_hetatms", "=", "False", ",", "force_rerun", "=", "False", ")", ":", "if", "self", ".", "file_type", "!=", "'pdb'", ":", "log", ".", "error", "(", "'{}: unable to run freesasa with \"{}\...
50.549296
28.43662
def log_config(verbose: bool) -> dict: """ Setup default config. for dictConfig. :param verbose: level: DEBUG if True, INFO if False :return: dict suitable for ``logging.config.dictConfig`` """ log_level = 'DEBUG' if verbose else 'INFO' return { 'version': 1, 'disable_existin...
[ "def", "log_config", "(", "verbose", ":", "bool", ")", "->", "dict", ":", "log_level", "=", "'DEBUG'", "if", "verbose", "else", "'INFO'", "return", "{", "'version'", ":", "1", ",", "'disable_existing_loggers'", ":", "False", ",", "'formatters'", ":", "{", ...
32.27027
14.324324
def segments(self, using=None, **kwargs): """ Provide low level segments information that a Lucene index (shard level) is built with. Any additional keyword arguments will be passed to ``Elasticsearch.indices.segments`` unchanged. """ return self._get_connection(...
[ "def", "segments", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "segments", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwa...
40.333333
18.111111
def generate(self, vars=None, env=None): """Generate this template with the given arguments.""" def defined(v, default=None): _v = default if v in vars: _v = vars[v] elif v in env: _v = env[v] return _v na...
[ "def", "generate", "(", "self", ",", "vars", "=", "None", ",", "env", "=", "None", ")", ":", "def", "defined", "(", "v", ",", "default", "=", "None", ")", ":", "_v", "=", "default", "if", "v", "in", "vars", ":", "_v", "=", "vars", "[", "v", "...
41.322581
14.83871
def send_keyevents_long_press(self, keyevent: int) -> None: '''Simulates typing keyevents long press.''' self._execute('-s', self.device_sn, 'shell', 'input', 'keyevent', '--longpress', str(keyevent))
[ "def", "send_keyevents_long_press", "(", "self", ",", "keyevent", ":", "int", ")", "->", "None", ":", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", "device_sn", ",", "'shell'", ",", "'input'", ",", "'keyevent'", ",", "'--longpress'", ",", "str", ...
58.75
18.75
def process_files(self, path, recursive=False): """Apply normalizations over all files in the given directory. Iterate over all files in a given directory. Normalizations will be applied to each file, storing the result in a new file. The extension for the new file will be the one defin...
[ "def", "process_files", "(", "self", ",", "path", ",", "recursive", "=", "False", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Processing files in \"%s\"'", ",", "path", ")", "for", "(", "path", ",", "file", ")", "in", "files_generator", "(", "p...
41.235294
20.352941
def _launch_stack(self, stack, **kwargs): """Handles the creating or updating of a stack in CloudFormation. Also makes sure that we don't try to create or update a stack while it is already updating or creating. """ old_status = kwargs.get("status") wait_time = 0 if old...
[ "def", "_launch_stack", "(", "self", ",", "stack", ",", "*", "*", "kwargs", ")", ":", "old_status", "=", "kwargs", ".", "get", "(", "\"status\"", ")", "wait_time", "=", "0", "if", "old_status", "is", "PENDING", "else", "STACK_POLL_TIME", "if", "self", "....
41.561983
19.016529
def data(self, root): '''Convert etree.Element into a dictionary''' value = self.dict() # Add attributes specific 'attributes' key if root.attrib: value['attributes'] = self.dict() for attr, attrval in root.attrib.items(): value['attributes'][uni...
[ "def", "data", "(", "self", ",", "root", ")", ":", "value", "=", "self", ".", "dict", "(", ")", "# Add attributes specific 'attributes' key", "if", "root", ".", "attrib", ":", "value", "[", "'attributes'", "]", "=", "self", ".", "dict", "(", ")", "for", ...
34.194444
20.083333
def advanced_indexing_op(inputs, index): """Advanced Indexing for Sequences, returns the outputs by given sequence lengths. When return the last output :class:`DynamicRNNLayer` uses it to get the last outputs with the sequence lengths. Parameters ----------- inputs : tensor for data With sh...
[ "def", "advanced_indexing_op", "(", "inputs", ",", "index", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "inputs", ")", "[", "0", "]", "# max_length = int(inputs.get_shape()[1]) # for fixed length rnn, length is given", "max_length", "=", "tf", ".", "shape...
41.061224
22.591837
def mesh(**kwargs): """ Create parameters for a new mesh dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parame...
[ "def", "mesh", "(", "*", "*", "kwargs", ")", ":", "obs_params", "=", "[", "]", "syn_params", ",", "constraints", "=", "mesh_syn", "(", "syn", "=", "False", ",", "*", "*", "kwargs", ")", "obs_params", "+=", "syn_params", ".", "to_list", "(", ")", "obs...
42.782609
33.826087
def csv_to_dict(file_name, file_location): """ Function to import a csv as a dictionary Args: file_name: The name of the csv file file_location: The location of the file, derive from the os module Returns: returns a dictionary """ file = __os.path.join(file_location, file_name)...
[ "def", "csv_to_dict", "(", "file_name", ",", "file_location", ")", ":", "file", "=", "__os", ".", "path", ".", "join", "(", "file_location", ",", "file_name", ")", "try", ":", "csv_read", "=", "open", "(", "file", ",", "\"r\"", ")", "except", "Exception"...
32.24
18.4
def cut_blockquote(html_message): ''' Cuts the last non-nested blockquote with wrapping elements.''' quote = html_message.xpath( '(.//blockquote)' '[not(@class="gmail_quote") and not(ancestor::blockquote)]' '[last()]') if quote: quote = quote[0] quote.getparent().rem...
[ "def", "cut_blockquote", "(", "html_message", ")", ":", "quote", "=", "html_message", ".", "xpath", "(", "'(.//blockquote)'", "'[not(@class=\"gmail_quote\") and not(ancestor::blockquote)]'", "'[last()]'", ")", "if", "quote", ":", "quote", "=", "quote", "[", "0", "]", ...
30.909091
19.454545
def eta_letters(seconds, shortest=False, leading_zero=False): """Converts seconds remaining into human readable strings (e.g. '1s' or '5h 22m 2s'). Positional arguments: seconds -- integer/float indicating seconds remaining. Keyword arguments: shortest -- show the shortest possible string length b...
[ "def", "eta_letters", "(", "seconds", ",", "shortest", "=", "False", ",", "leading_zero", "=", "False", ")", ":", "if", "not", "seconds", ":", "return", "'00s'", "if", "leading_zero", "else", "'0s'", "# Convert seconds to other units.", "final_weeks", ",", "fina...
39.237288
21.881356
def get_var(script_path, var): """ Given a script, and the name of an environment variable, returns the value of the environment variable. :param script_path: Path the a shell script :type script_path: str or unicode :param var: environment variable name :type var: str or unicode :return...
[ "def", "get_var", "(", "script_path", ",", "var", ")", ":", "if", "path", ".", "isfile", "(", "script_path", ")", ":", "input", "=", "'. \"%s\"; echo -n \"$%s\"\\n'", "%", "(", "script_path", ",", "var", ")", "pipe", "=", "Popen", "(", "[", "\"bash\"", "...
36.5
14.1
def convert_value_to_es(value, ranges, obj, method=None): """ Takes an value and converts it to an elasticsearch representation args: value: the value to convert ranges: the list of ranges method: convertion method to use 'None': default -> converts the value to its ...
[ "def", "convert_value_to_es", "(", "value", ",", "ranges", ",", "obj", ",", "method", "=", "None", ")", ":", "def", "sub_convert", "(", "val", ")", ":", "\"\"\"\n Returns the json value for a simple datatype or the subject uri if the\n value is a rdfclass\n\n ...
35.309524
16.785714
def generate_password(length=16): """ Generate a password using random characters from uppercase, lowercase, digits, and symbols :param length: Length of the password to be generated :return: The random password """ chars = string.ascii_letters + ...
[ "def", "generate_password", "(", "length", "=", "16", ")", ":", "chars", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'!@#$%^&*()_+-=[]{};:,<.>?|'", "modulus", "=", "len", "(", "chars", ")", "pchars", "=", "os", ".", "urandom", ...
40.714286
22.571429
def get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False): """ Get a list of suggestions from the AutoCompleter, for a given prefix ### Parameters: - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8** - **fuzzy**:...
[ "def", "get_suggestions", "(", "self", ",", "prefix", ",", "fuzzy", "=", "False", ",", "num", "=", "10", ",", "with_scores", "=", "False", ",", "with_payloads", "=", "False", ")", ":", "args", "=", "[", "AutoCompleter", ".", "SUGGET_COMMAND", ",", "self"...
48.419355
31.258065
def derivative(self, point): """Return the derivative in ``point``. The derivative of the gradient is often called the Hessian. Parameters ---------- point : `domain` `element-like` The point that the derivative should be taken in. Returns ------- ...
[ "def", "derivative", "(", "self", ",", "point", ")", ":", "return", "NumericalDerivative", "(", "self", ",", "point", ",", "method", "=", "self", ".", "method", ",", "step", "=", "np", ".", "sqrt", "(", "self", ".", "step", ")", ")" ]
33.361111
21.611111
def loads(content, dict_=dict): """Parse a toml string An additional argument `dict_` is used to specify the output type """ if not isinstance(content, basestring): raise ValueError('The first parameter needs to be a string object, ', '%r is passed' % type(content)) ...
[ "def", "loads", "(", "content", ",", "dict_", "=", "dict", ")", ":", "if", "not", "isinstance", "(", "content", ",", "basestring", ")", ":", "raise", "ValueError", "(", "'The first parameter needs to be a string object, '", ",", "'%r is passed'", "%", "type", "(...
38.8
13.5
def init_config(self, app): """Initialize configuration.""" for k in dir(config): if k.startswith('OAUTHCLIENT_'): app.config.setdefault(k, getattr(config, k)) @app.before_first_request def override_template_configuration(): """Override template c...
[ "def", "init_config", "(", "self", ",", "app", ")", ":", "for", "k", "in", "dir", "(", "config", ")", ":", "if", "k", ".", "startswith", "(", "'OAUTHCLIENT_'", ")", ":", "app", ".", "config", ".", "setdefault", "(", "k", ",", "getattr", "(", "confi...
43.7
15.35
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{...
[ "def", "setup_graph", "(", "self", ")", ":", "all_vars", "=", "tfv1", ".", "global_variables", "(", ")", "+", "tfv1", ".", "local_variables", "(", ")", "for", "v", "in", "all_vars", ":", "if", "v", ".", "name", "==", "self", ".", "var_name", ":", "se...
41
18.444444
def run_optimization(self): """Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise """ penalty_val = self.params['init_penalty'] # Don't use smoothing initially - very inaccurate for large dimension self.smooth_on...
[ "def", "run_optimization", "(", "self", ")", ":", "penalty_val", "=", "self", ".", "params", "[", "'init_penalty'", "]", "# Don't use smoothing initially - very inaccurate for large dimension", "self", ".", "smooth_on", "=", "False", "smooth_val", "=", "0", "learning_ra...
44.6
21.3
def neighbors(self) -> List['Node']: """ The list of neighbors of the node. """ self._load_neighbors() return [edge.source if edge.source != self else edge.target for edge in self._neighbors.values()]
[ "def", "neighbors", "(", "self", ")", "->", "List", "[", "'Node'", "]", ":", "self", ".", "_load_neighbors", "(", ")", "return", "[", "edge", ".", "source", "if", "edge", ".", "source", "!=", "self", "else", "edge", ".", "target", "for", "edge", "in"...
36.571429
8
def sign_transaction(self, txins: Union[TxOut], tx: MutableTransaction) -> MutableTransaction: '''sign the parent txn outputs P2PKH''' solver = P2pkhSolver(self._private_key) return tx.spend(txins, [solver for i in txins])
[ "def", "sign_transaction", "(", "self", ",", "txins", ":", "Union", "[", "TxOut", "]", ",", "tx", ":", "MutableTransaction", ")", "->", "MutableTransaction", ":", "solver", "=", "P2pkhSolver", "(", "self", ".", "_private_key", ")", "return", "tx", ".", "sp...
44.5
17.833333
def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='...
[ "def", "acl_info", "(", "consul_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "data", "=", "{", "}", "if", "not", "consul_url", ":", "consul_url", "=", "_get_config", "(", ")", "if", "not", "consul_url", ":", "log", "....
25.944444
20.222222
def _enumeration_info(self, pattern): """ returns (pattern, limits) taking a regular pattern and finding out which parts of it correspond to start/stop offsets. limits is a tuple of (start, stop) or None """ if not "[" in pattern or pattern.startswith('~'): ...
[ "def", "_enumeration_info", "(", "self", ",", "pattern", ")", ":", "if", "not", "\"[\"", "in", "pattern", "or", "pattern", ".", "startswith", "(", "'~'", ")", ":", "return", "(", "pattern", ",", "None", ")", "(", "first", ",", "rest", ")", "=", "patt...
35.8125
11.6875
def tap(self, interceptor): """ Invokes interceptor with the obj, and then returns obj. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. """ interceptor(self.obj) return se...
[ "def", "tap", "(", "self", ",", "interceptor", ")", ":", "interceptor", "(", "self", ".", "obj", ")", "return", "self", ".", "_wrap", "(", "self", ".", "obj", ")" ]
41.375
15.875
def _extract_columns(self, table_name): ''' a method to extract the column properties of an existing table ''' import re from sqlalchemy import MetaData, VARCHAR, INTEGER, BLOB, BOOLEAN, FLOAT from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION, BIT, BYTEA ...
[ "def", "_extract_columns", "(", "self", ",", "table_name", ")", ":", "import", "re", "from", "sqlalchemy", "import", "MetaData", ",", "VARCHAR", ",", "INTEGER", ",", "BLOB", ",", "BOOLEAN", ",", "FLOAT", "from", "sqlalchemy", ".", "dialects", ".", "postgresq...
45.268293
18.146341
def alignmentGraph(titlesAlignments, title, addQueryLines=True, showFeatures=True, logLinearXAxis=False, logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE, rankScores=False, colorQueryBases=False, createFigure=True, showFigure=True, readsAx=None, imageFil...
[ "def", "alignmentGraph", "(", "titlesAlignments", ",", "title", ",", "addQueryLines", "=", "True", ",", "showFeatures", "=", "True", ",", "logLinearXAxis", "=", "False", ",", "logBase", "=", "DEFAULT_LOG_LINEAR_X_AXIS_BASE", ",", "rankScores", "=", "False", ",", ...
43.315245
21.346253
def capability_installed(name, source=None, limit_access=False, image=None, restart=False): ''' Install a DISM capability Args: name (str): The capability to install source (str): The optiona...
[ "def", "capability_installed", "(", "name", ",", "source", "=", "None", ",", "limit_access", "=", "False", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "...
31.758065
21.274194
def _render_select(selections): """Render the selection part of a query. Parameters ---------- selections : dict Selections for a table Returns ------- str A string for the "select" part of a query See Also -------- render_query : Further clarification of `sele...
[ "def", "_render_select", "(", "selections", ")", ":", "if", "not", "selections", ":", "return", "'SELECT *'", "rendered_selections", "=", "[", "]", "for", "name", ",", "options", "in", "selections", ".", "items", "(", ")", ":", "if", "not", "isinstance", "...
24.717949
20.846154
def get_config(self, section=None): """ Return the merged end-user configuration for this command or a specific section if set in `section`. """ config = self.session.config section = self.config_section() if section is None else section try: return config[section] ...
[ "def", "get_config", "(", "self", ",", "section", "=", "None", ")", ":", "config", "=", "self", ".", "session", ".", "config", "section", "=", "self", ".", "config_section", "(", ")", "if", "section", "is", "None", "else", "section", "try", ":", "retur...
40.8
9.7
def start_resolver(finder=None, wheel_cache=None): """Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.oper...
[ "def", "start_resolver", "(", "finder", "=", "None", ",", "wheel_cache", "=", "None", ")", ":", "pip_command", "=", "get_pip_command", "(", ")", "pip_options", "=", "get_pip_options", "(", "pip_command", "=", "pip_command", ")", "if", "not", "finder", ":", "...
34.875
18.875
def on_ready_to_stop(self): """Invoked when the consumer is ready to stop.""" # Set the state to shutting down if it wasn't set as that during loop self.set_state(self.STATE_SHUTTING_DOWN) # Reset any signal handlers signal.signal(signal.SIGABRT, signal.SIG_IGN) signal....
[ "def", "on_ready_to_stop", "(", "self", ")", ":", "# Set the state to shutting down if it wasn't set as that during loop", "self", ".", "set_state", "(", "self", ".", "STATE_SHUTTING_DOWN", ")", "# Reset any signal handlers", "signal", ".", "signal", "(", "signal", ".", "...
34.185185
18.518519
def gov_orgs(): """ Returns a list of the names of US Government GitHub organizations Based on: https://government.github.com/community/ Exmample return: {'llnl', '18f', 'gsa', 'dhs-ncats', 'spack', ...} """ us_gov_github_orgs = set() gov_orgs = requests.get('https://government.gi...
[ "def", "gov_orgs", "(", ")", ":", "us_gov_github_orgs", "=", "set", "(", ")", "gov_orgs", "=", "requests", ".", "get", "(", "'https://government.github.com/organizations.json'", ")", ".", "json", "(", ")", "us_gov_github_orgs", ".", "update", "(", "gov_orgs", "[...
33.944444
26.5
def normalized(self): '归一化' res = self.groupby('code').apply(lambda x: x / x.iloc[0]) return res
[ "def", "normalized", "(", "self", ")", ":", "res", "=", "self", ".", "groupby", "(", "'code'", ")", ".", "apply", "(", "lambda", "x", ":", "x", "/", "x", ".", "iloc", "[", "0", "]", ")", "return", "res" ]
29.25
23.25
def _compile_template_re(delimiters): """ Return a regular expression object (re.RegexObject) instance. """ # The possible tag type characters following the opening tag, # excluding "=" and "{". tag_types = "!>&/#^" # TODO: are we following this in the spec? # # The tag's content...
[ "def", "_compile_template_re", "(", "delimiters", ")", ":", "# The possible tag type characters following the opening tag,", "# excluding \"=\" and \"{\".", "tag_types", "=", "\"!>&/#^\"", "# TODO: are we following this in the spec?", "#", "# The tag's content MUST be a non-whitespace ch...
31.692308
18.384615
def zero_handling(x): """ This function handle the issue with zero values if the are exposed to become an argument for any log function. :param x: The vector. :return: The vector with zeros substituted with epsilon values. """ return np.where(x == 0, np.finfo(float).eps, x)
[ "def", "zero_handling", "(", "x", ")", ":", "return", "np", ".", "where", "(", "x", "==", "0", ",", "np", ".", "finfo", "(", "float", ")", ".", "eps", ",", "x", ")" ]
36.875
13.625
def _read(self, max_tries=40): """ - read the bit stream from HX711 and convert to an int value. - validates the acquired data :param max_tries: how often to try to get data :type max_tries: int :return raw data :rtype: int """ # start by setting t...
[ "def", "_read", "(", "self", ",", "max_tries", "=", "40", ")", ":", "# start by setting the pd_sck to false", "GPIO", ".", "output", "(", "self", ".", "_pd_sck", ",", "False", ")", "# init the counter", "ready_counter", "=", "0", "# loop until HX711 is ready", "# ...
40.794521
20.191781
def parse_rule(rule): """Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, arguments, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one. :internal: """ pos = 0 end = len(rule) do_match = _rule_re.ma...
[ "def", "parse_rule", "(", "rule", ")", ":", "pos", "=", "0", "end", "=", "len", "(", "rule", ")", "do_match", "=", "_rule_re", ".", "match", "used_names", "=", "set", "(", ")", "while", "pos", "<", "end", ":", "m", "=", "do_match", "(", "rule", "...
33.733333
16.1
def trace_sql_database_request(self, database, sql): '''Create a tracer for the given database info and SQL statement. :param DbInfoHandle database: Database information (see :meth:`create_database_info`). :param str sql: The SQL statement to trace. :rtype: tracers.DatabaseR...
[ "def", "trace_sql_database_request", "(", "self", ",", "database", ",", "sql", ")", ":", "assert", "isinstance", "(", "database", ",", "DbInfoHandle", ")", "return", "tracers", ".", "DatabaseRequestTracer", "(", "self", ".", "_nsdk", ",", "self", ".", "_nsdk",...
44.333333
18.666667
def request_session(self): """ Performs initial request to initialize session and get session id necessary to construct all future requests. :return: Session ID to be placed in header of all other requests. """ concierge_request_header = self.construct_concierge_header( ...
[ "def", "request_session", "(", "self", ")", ":", "concierge_request_header", "=", "self", ".", "construct_concierge_header", "(", "url", "=", "\"http://membersuite.com/contracts/IConciergeAPIService/WhoAmI\"", ")", "result", "=", "self", ".", "client", ".", "service", "...
36.842105
20.210526
def _import_platform_generator(platform): ''' Given a specific platform (under the Capirca conventions), return the generator class. The generator class is identified looking under the <platform> module for a class inheriting the `ACLGenerator` class. ''' log.debug('Using platform: %s', plat...
[ "def", "_import_platform_generator", "(", "platform", ")", ":", "log", ".", "debug", "(", "'Using platform: %s'", ",", "platform", ")", "for", "mod_name", ",", "mod_obj", "in", "inspect", ".", "getmembers", "(", "capirca", ".", "aclgen", ")", ":", "if", "mod...
57.266667
27.933333
def _getTextType(self, lineData, column): """Get text type (letter) """ if lineData is None: return ' ' # default is code textTypeMap = lineData[1] if column >= len(textTypeMap): # probably, not actual data, not updated yet return ' ' return te...
[ "def", "_getTextType", "(", "self", ",", "lineData", ",", "column", ")", ":", "if", "lineData", "is", "None", ":", "return", "' '", "# default is code", "textTypeMap", "=", "lineData", "[", "1", "]", "if", "column", ">=", "len", "(", "textTypeMap", ")", ...
29.727273
15.363636
def solve_series(self, x0, params, varied_data, varied_idx, internal_x0=None, solver=None, propagate=True, **kwargs): """ Solve system for a set of parameters in which one is varied Parameters ---------- x0 : array_like Guess (subject to ``self.post_proc...
[ "def", "solve_series", "(", "self", ",", "x0", ",", "params", ",", "varied_data", ",", "varied_idx", ",", "internal_x0", "=", "None", ",", "solver", "=", "None", ",", "propagate", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "x_...
43.184211
17.078947
def create(cls, class_name, **attributes): """ 根据参数创建一个 leancloud.Object 的子类的实例化对象 :param class_name: 子类名称 :type class_name: string_types :param attributes: 对象属性 :return: 派生子类的实例 :rtype: Object """ object_class = cls.extend(class_name) ret...
[ "def", "create", "(", "cls", ",", "class_name", ",", "*", "*", "attributes", ")", ":", "object_class", "=", "cls", ".", "extend", "(", "class_name", ")", "return", "object_class", "(", "*", "*", "attributes", ")" ]
28.25
8.75
def configure(project_path, config_file=None): """Get the configuration of the test and return it as a config object :return: the configured config object :rtype: Object """ if config_file is None: config_file = os.path.join(project_path, 'config.json') try: with open(config_fil...
[ "def", "configure", "(", "project_path", ",", "config_file", "=", "None", ")", ":", "if", "config_file", "is", "None", ":", "config_file", "=", "os", ".", "path", ".", "join", "(", "project_path", ",", "'config.json'", ")", "try", ":", "with", "open", "(...
38.529412
17.941176
def enable_analog_reporting(self, pin): """ Enables analog reporting. By turning reporting on for a single pin. :param pin: Analog pin number. For example for A0, the number is 0. :return: No return value """ command = [self._command_handler.REPORT_ANALOG + pin, self.RE...
[ "def", "enable_analog_reporting", "(", "self", ",", "pin", ")", ":", "command", "=", "[", "self", ".", "_command_handler", ".", "REPORT_ANALOG", "+", "pin", ",", "self", ".", "REPORTING_ENABLE", "]", "self", ".", "_command_handler", ".", "send_command", "(", ...
37.8
21.4
def format_returnvalue(self, value): """Format the return value of this function as a string. Args: value (object): The return value that we are supposed to format. Returns: str: The formatted return value, or None if this function indicates that it does...
[ "def", "format_returnvalue", "(", "self", ",", "value", ")", ":", "self", ".", "_ensure_loaded", "(", ")", "if", "not", "self", ".", "return_info", ".", "is_data", ":", "return", "None", "# If the return value is typed, use the type_system to format it", "if", "self...
36.318182
25.909091
def _validate_example(rh, method, example_type): """Validates example against schema :returns: Formatted example if example exists and validates, otherwise None :raises ValidationError: If example does not validate against the schema """ example = getattr(method, example_type + "_example") sche...
[ "def", "_validate_example", "(", "rh", ",", "method", ",", "example_type", ")", ":", "example", "=", "getattr", "(", "method", ",", "example_type", "+", "\"_example\"", ")", "schema", "=", "getattr", "(", "method", ",", "example_type", "+", "\"_schema\"", ")...
32.636364
22.636364
def clean_retinotopy_potential(hemi, retinotopy=Ellipsis, mask=Ellipsis, weight=Ellipsis, surface='midgray', min_weight=Ellipsis, min_eccentricity=0.75, visual_area=None, map_visual_areas=Ellipsis, visual_area_field_signs=Ellip...
[ "def", "clean_retinotopy_potential", "(", "hemi", ",", "retinotopy", "=", "Ellipsis", ",", "mask", "=", "Ellipsis", ",", "weight", "=", "Ellipsis", ",", "surface", "=", "'midgray'", ",", "min_weight", "=", "Ellipsis", ",", "min_eccentricity", "=", "0.75", ",",...
65.096639
31.886555
def north_pole_uvw(self): """location of the north pole in the global/system frame""" # TODO: is this rpole scaling true for all distortion_methods?? rpole = self.instantaneous_rpole*self.sma return self.polar_direction_uvw*rpole+self.mesh._pos
[ "def", "north_pole_uvw", "(", "self", ")", ":", "# TODO: is this rpole scaling true for all distortion_methods??", "rpole", "=", "self", ".", "instantaneous_rpole", "*", "self", ".", "sma", "return", "self", ".", "polar_direction_uvw", "*", "rpole", "+", "self", ".", ...
54.4
15
def patch_project(self, owner, id, **kwargs): """ Update a project Update an existing project. Note that only elements, files or linked datasets included in the request will be updated. All omitted elements, files or linked datasets will remain untouched. This method makes a synchronous ...
[ "def", "patch_project", "(", "self", ",", "owner", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "patch_project_w...
69.444444
42.851852
def _iter_module_subclasses(package, module_name, base_cls): """inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709 """ module = importlib.import_module('.' + module_name, package) for name, obj in inspect.getme...
[ "def", "_iter_module_subclasses", "(", "package", ",", "module_name", ",", "base_cls", ")", ":", "module", "=", "importlib", ".", "import_module", "(", "'.'", "+", "module_name", ",", "package", ")", "for", "name", ",", "obj", "in", "inspect", ".", "getmembe...
51.5
16
def check_initializers(initializers, keys): """Checks the given initializers. This checks that `initializers` is a dictionary that only contains keys in `keys`, and furthermore the entries in `initializers` are functions or further dictionaries (the latter used, for example, in passing initializers to module...
[ "def", "check_initializers", "(", "initializers", ",", "keys", ")", ":", "if", "initializers", "is", "None", ":", "return", "{", "}", "_assert_is_dictlike", "(", "initializers", ",", "valid_keys", "=", "keys", ")", "keys", "=", "set", "(", "keys", ")", "if...
34.282051
23.974359
def extract_crypto_data(github_path): """ github_path can must be path on github, such as "bitcoin/bitcoin" or "litecoin-project/litecoin" """ data = {'github_link': 'https://github.com/%s' % github_path} content = get_content_from_github(github_path, "chainparams.cpp") if content: ...
[ "def", "extract_crypto_data", "(", "github_path", ")", ":", "data", "=", "{", "'github_link'", ":", "'https://github.com/%s'", "%", "github_path", "}", "content", "=", "get_content_from_github", "(", "github_path", ",", "\"chainparams.cpp\"", ")", "if", "content", "...
31.75
20.05
def job(job_id=None): '''Submit a job. If no id is provided, a random id will be generated. :param job_type: Which kind of job should be run. Has to be one of the available job types. :type job_type: string :param api_key: An API key that is needed to execute the job. This could be a CK...
[ "def", "job", "(", "job_id", "=", "None", ")", ":", "if", "not", "job_id", ":", "job_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "# key required for job administration", "job_key", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ...
37.575758
22.060606
def duplicate(self, event): "create a copy of each selected object" # duplicate the selected objects (if any) new_selection = [] for obj in self.selection: if obj: if DEBUG: print "duplicating", obj.name obj.sel_marker.destroy() ...
[ "def", "duplicate", "(", "self", ",", "event", ")", ":", "# duplicate the selected objects (if any)", "new_selection", "=", "[", "]", "for", "obj", "in", "self", ".", "selection", ":", "if", "obj", ":", "if", "DEBUG", ":", "print", "\"duplicating\"", ",", "o...
41.466667
9.866667
def object_issubclass(node, class_or_seq, context=None): """Check if a type is a subclass of any node in class_or_seq :param node: A given node :param class_or_seq: Union[Nodes.NodeNG, Sequence[nodes.NodeNG]] :rtype: bool :raises AstroidTypeError: if the given ``classes_or_seq`` are not types ...
[ "def", "object_issubclass", "(", "node", ",", "class_or_seq", ",", "context", "=", "None", ")", ":", "if", "not", "isinstance", "(", "node", ",", "nodes", ".", "ClassDef", ")", ":", "raise", "TypeError", "(", "\"{node} needs to be a ClassDef node\"", ".", "for...
44.428571
21.785714
def log_exception(self, typ, value, tb): """Override implementation to report all exceptions to sentry. log_exception() is added in Tornado v3.1. """ rv = super(SentryMixin, self).log_exception(typ, value, tb) # Do not capture tornado.web.HTTPErrors outside the 500 range. ...
[ "def", "log_exception", "(", "self", ",", "typ", ",", "value", ",", "tb", ")", ":", "rv", "=", "super", "(", "SentryMixin", ",", "self", ")", ".", "log_exception", "(", "typ", ",", "value", ",", "tb", ")", "# Do not capture tornado.web.HTTPErrors outside the...
50.1
18.4
def batch_map_mean(func, batch_iter, progress_iter_func=None, sum_axis=None, n_batches=None, prepend_args=None): """ Apply a function to all the samples that are accessed as mini-batches obtained from an iterator. Returns the across-samples mean of the results returned by `func` ...
[ "def", "batch_map_mean", "(", "func", ",", "batch_iter", ",", "progress_iter_func", "=", "None", ",", "sum_axis", "=", "None", ",", "n_batches", "=", "None", ",", "prepend_args", "=", "None", ")", ":", "# Accumulator for results and number of samples", "results_accu...
44.151685
20.61236
def _gen_reference(fixed_image, moving_image, fov_mask=None, out_file=None, message=None, force_xform_code=None): """ Generates a sampling reference, and makes sure xform matrices/codes are correct """ if out_file is None: out_file = fname_presuffix(fixed_image, ...
[ "def", "_gen_reference", "(", "fixed_image", ",", "moving_image", ",", "fov_mask", "=", "None", ",", "out_file", "=", "None", ",", "message", "=", "None", ",", "force_xform_code", "=", "None", ")", ":", "if", "out_file", "is", "None", ":", "out_file", "=",...
40.402439
20.329268
def get_memes_gallery(self, sort='viral', window='week', limit=None): """ Return a list of gallery albums/images submitted to the memes gallery The url for the memes gallery is: http://imgur.com/g/memes :param sort: viral | time | top - defaults to viral :param window: Change t...
[ "def", "get_memes_gallery", "(", "self", ",", "sort", "=", "'viral'", ",", "window", "=", "'week'", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_base_url", "+", "\"/3/gallery/g/memes/{0}/{1}/{2}\"", ".", "format", "(", "sort", ",", ...
47.733333
22.933333
def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) except EnvironmentError as e: raise ExtractErro...
[ "def", "utime", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "not", "hasattr", "(", "os", ",", "'utime'", ")", ":", "return", "try", ":", "os", ".", "utime", "(", "targetpath", ",", "(", "tarinfo", ".", "mtime", ",", "tarinfo", "...
39
12.444444
def load_quota(self, quota, TTL, interval): """ Load new quota with a TTL. If the input is None, the reservoir will continue using old quota until it expires or has a non-None quota/TTL in a future load. """ if quota is not None: self._quota = quota if...
[ "def", "load_quota", "(", "self", ",", "quota", ",", "TTL", ",", "interval", ")", ":", "if", "quota", "is", "not", "None", ":", "self", ".", "_quota", "=", "quota", "if", "TTL", "is", "not", "None", ":", "self", ".", "_TTL", "=", "TTL", "if", "in...
36.416667
10.25
def get_label ( self, object ): """ Gets the label to display for a specified object. """ label = self.label if label[:1] == '=': return label[1:] label = xgetattr( object, label, '' ) if self.formatter is None: return label return self....
[ "def", "get_label", "(", "self", ",", "object", ")", ":", "label", "=", "self", ".", "label", "if", "label", "[", ":", "1", "]", "==", "'='", ":", "return", "label", "[", "1", ":", "]", "label", "=", "xgetattr", "(", "object", ",", "label", ",", ...
25.692308
15.384615