text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def write_template_file(source, target, content): """Write a new file from a given pystache template file and content""" # print(formatTemplateFile(source, content)) print(target) data = format_template_file(source, content) with open(target, 'w') as f: for line in data: if type...
[ "def", "write_template_file", "(", "source", ",", "target", ",", "content", ")", ":", "# print(formatTemplateFile(source, content))", "print", "(", "target", ")", "data", "=", "format_template_file", "(", "source", ",", "content", ")", "with", "open", "(", "target...
35.818182
0.002475
def convert(self, argument): """Returns the float value of argument.""" if (_is_integer_type(argument) or isinstance(argument, float) or isinstance(argument, six.string_types)): return float(argument) else: raise TypeError( 'Expect argument to be a string, int, or float, found ...
[ "def", "convert", "(", "self", ",", "argument", ")", ":", "if", "(", "_is_integer_type", "(", "argument", ")", "or", "isinstance", "(", "argument", ",", "float", ")", "or", "isinstance", "(", "argument", ",", "six", ".", "string_types", ")", ")", ":", ...
39.333333
0.01105
def play(song, artist=None, album=None): """Tells iTunes to play a given song/artist/album - MACOSX ONLY""" if not settings.platformCompatible(): return False if song and not artist and not album: (output, error) = subprocess.Popen(["osascript", "-e", DEFAULT_ITUNES_PLAY % (song, song, song)], stdout=subproces...
[ "def", "play", "(", "song", ",", "artist", "=", "None", ",", "album", "=", "None", ")", ":", "if", "not", "settings", ".", "platformCompatible", "(", ")", ":", "return", "False", "if", "song", "and", "not", "artist", "and", "not", "album", ":", "(", ...
40.1
0.023737
def add_picture(self, p): """ needs to look like this (under draw:page) <draw:frame draw:style-name="gr2" draw:text-style-name="P2" draw:layer="layout" svg:width="19.589cm" svg:height="13.402cm" svg:x="3.906cm" svg:y="4.378cm"> <draw:image xlink:href="Pictures/10000201000002F800000208188B22AE.png" ...
[ "def", "add_picture", "(", "self", ",", "p", ")", ":", "# pictures should be added the the draw:frame element", "self", ".", "pic_frame", "=", "PictureFrame", "(", "self", ",", "p", ")", "self", ".", "pic_frame", ".", "add_node", "(", "\"draw:image\"", ",", "att...
39.541667
0.014403
def handle_line(self, frame, arg): """This function is called when we stop or break at this line.""" log.info('Stopping at line %s' % pretty_frame(frame)) self.interaction(frame)
[ "def", "handle_line", "(", "self", ",", "frame", ",", "arg", ")", ":", "log", ".", "info", "(", "'Stopping at line %s'", "%", "pretty_frame", "(", "frame", ")", ")", "self", ".", "interaction", "(", "frame", ")" ]
49.75
0.009901
def get_current_tournaments(): """Get the next 200 tournaments from pokerstars.""" schedule_page = requests.get(TOURNAMENTS_XML_URL) root = etree.XML(schedule_page.content) for tour in root.iter('{*}tournament'): yield _Tournament( start_date=tour.findtext('{*}start_date'), ...
[ "def", "get_current_tournaments", "(", ")", ":", "schedule_page", "=", "requests", ".", "get", "(", "TOURNAMENTS_XML_URL", ")", "root", "=", "etree", ".", "XML", "(", "schedule_page", ".", "content", ")", "for", "tour", "in", "root", ".", "iter", "(", "'{*...
34.642857
0.002008
def commit(self, if_match=None, wait=True, timeout=None): """Apply all the changes on the current model. :param wait: Whether to wait until the operation is completed :param timeout: The maximum amount of time required for this operation to be completed. If o...
[ "def", "commit", "(", "self", ",", "if_match", "=", "None", ",", "wait", "=", "True", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "_changes", ":", "LOG", ".", "debug", "(", "\"No changes available for %s: %s\"", ",", "self", ".", "...
44.183673
0.000904
def readline(self, size=None): """ Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the tr...
[ "def", "readline", "(", "self", ",", "size", "=", "None", ")", ":", "# it's almost silly how complex this function is.", "if", "self", ".", "_closed", ":", "raise", "IOError", "(", "'File is closed'", ")", "if", "not", "(", "self", ".", "_flags", "&", "self", ...
44.695122
0.001335
def download_to_path(self, gsuri, localpath, binary_mode=False, tmpdir=None): """ This method is analogous to "gsutil cp gsuri localpath", but in a programatically accesible way. The only difference is that we have to make a guess about the encoding of the file to not upset downs...
[ "def", "download_to_path", "(", "self", ",", "gsuri", ",", "localpath", ",", "binary_mode", "=", "False", ",", "tmpdir", "=", "None", ")", ":", "bucket_name", ",", "gs_rel_path", "=", "self", ".", "parse_uri", "(", "gsuri", ")", "# And now request the handles ...
52.95
0.001391
def show(): """Try showing the most desirable GUI This function cycles through the currently registered graphical user interfaces, if any, and presents it to the user. """ parent = None current = QtWidgets.QApplication.activeWindow() while current: parent = current cur...
[ "def", "show", "(", ")", ":", "parent", "=", "None", "current", "=", "QtWidgets", ".", "QApplication", ".", "activeWindow", "(", ")", "while", "current", ":", "parent", "=", "current", "current", "=", "parent", ".", "parent", "(", ")", "window", "=", "...
22.222222
0.002398
def _computeP(self): """ m._computeP() -- [utility] Compute the probability matrix (from the internal log-probability matrix) """ P = [] for i in range(self.width): #print i, _p = {} for L in ACGT: _p[L] = math.pow(2.0,self.logP[i][L]) ...
[ "def", "_computeP", "(", "self", ")", ":", "P", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "width", ")", ":", "#print i,", "_p", "=", "{", "}", "for", "L", "in", "ACGT", ":", "_p", "[", "L", "]", "=", "math", ".", "pow", "(...
29.916667
0.018919
def stansummary(fit, pars=None, probs=(0.025, 0.25, 0.5, 0.75, 0.975), digits_summary=2): """ Summary statistic table. Parameters ---------- fit : StanFit4Model object pars : str or sequence of str, optional Parameter names. By default use all parameters probs : sequence of float, o...
[ "def", "stansummary", "(", "fit", ",", "pars", "=", "None", ",", "probs", "=", "(", "0.025", ",", "0.25", ",", "0.5", ",", "0.75", ",", "0.975", ")", ",", "digits_summary", "=", "2", ")", ":", "if", "fit", ".", "mode", "==", "1", ":", "return", ...
45
0.002455
def data(self,data): """Given a 2D numpy array, fill colData with it.""" assert type(data) is np.ndarray assert data.shape[1] == self.nCols for i in range(self.nCols): self.colData[i]=data[:,i].tolist()
[ "def", "data", "(", "self", ",", "data", ")", ":", "assert", "type", "(", "data", ")", "is", "np", ".", "ndarray", "assert", "data", ".", "shape", "[", "1", "]", "==", "self", ".", "nCols", "for", "i", "in", "range", "(", "self", ".", "nCols", ...
40.166667
0.020325
def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start with a zero digits.extend([random.randint(0...
[ "def", "generate_random_nhs_number", "(", ")", "->", "int", ":", "check_digit", "=", "10", "# NHS numbers with this check digit are all invalid", "while", "check_digit", "==", "10", ":", "digits", "=", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "]",...
40.615385
0.001852
def read_config_environment(self, config_data=None, quiet=False): """read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a uniqu...
[ "def", "read_config_environment", "(", "self", ",", "config_data", "=", "None", ",", "quiet", "=", "False", ")", ":", "# Add all variables that start with KAGGLE_ to config data", "if", "config_data", "is", "None", ":", "config_data", "=", "{", "}", "for", "key", ...
39.727273
0.002235
def photos_search(user_id='', auth=False, tags='', tag_mode='', text='',\ min_upload_date='', max_upload_date='',\ min_taken_date='', max_taken_date='', \ license='', per_page='', page='', sort=''): """Returns a list of Photo objects. If auth=True then wil...
[ "def", "photos_search", "(", "user_id", "=", "''", ",", "auth", "=", "False", ",", "tags", "=", "''", ",", "tag_mode", "=", "''", ",", "text", "=", "''", ",", "min_upload_date", "=", "''", ",", "max_upload_date", "=", "''", ",", "min_taken_date", "=", ...
41.5
0.009814
def Terminate(self): """ Close all open connections Loop though all the connections and commit all queries and close all the connections. This should be called at the end of your application. @author: Nick Verbeck @since: 5/12/2008 """ self.lock.acquire() try: for bucket in self.connectio...
[ "def", "Terminate", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "l...
21.5
0.055644
def guess_version(redeem_script): ''' str -> int Bitcoin uses tx version 2 for nSequence signaling. Zcash uses tx version 2 for joinsplits. We want to signal nSequence if we're using OP_CSV. Unless we're in zcash. ''' n = riemann.get_current_network_name() if 'sprout' in n: ...
[ "def", "guess_version", "(", "redeem_script", ")", ":", "n", "=", "riemann", ".", "get_current_network_name", "(", ")", "if", "'sprout'", "in", "n", ":", "return", "1", "if", "'overwinter'", "in", "n", ":", "return", "3", "if", "'sapling'", "in", "n", ":...
25.181818
0.001739
def x5t_calculation(cert): """ base64url-encoded SHA-1 thumbprint (a.k.a. digest) of the DER encoding of an X.509 certificate. :param cert: DER encoded X.509 certificate :return: x5t value """ if isinstance(cert, str): der_cert = base64.b64decode(cert.encode('ascii')) else: ...
[ "def", "x5t_calculation", "(", "cert", ")", ":", "if", "isinstance", "(", "cert", ",", "str", ")", ":", "der_cert", "=", "base64", ".", "b64decode", "(", "cert", ".", "encode", "(", "'ascii'", ")", ")", "else", ":", "der_cert", "=", "base64", ".", "b...
28.142857
0.002457
def wait_pidfile(rundir, process_type=PROCESS_TYPE, name=None): """ Wait for the given process type and name to have started and created a pid file. Return the pid. """ # getting it from the start avoids an unneeded time.sleep pid = get_pid(rundir, process_type, name) while not pid: ...
[ "def", "wait_pidfile", "(", "rundir", ",", "process_type", "=", "PROCESS_TYPE", ",", "name", "=", "None", ")", ":", "# getting it from the start avoids an unneeded time.sleep", "pid", "=", "get_pid", "(", "rundir", ",", "process_type", ",", "name", ")", "while", "...
26.2
0.002457
def get_account_entitlement(self): """GetAccountEntitlement. [Preview API] Gets the account entitlement of the current user it is mapped to _apis/licensing/entitlements/me so specifically is looking for the user of the request :rtype: :class:`<AccountEntitlement> <azure.devops.v5_0.licensing.mod...
[ "def", "get_account_entitlement", "(", "self", ")", ":", "response", "=", "self", ".", "_send", "(", "http_method", "=", "'GET'", ",", "location_id", "=", "'c01e9fd5-0d8c-4d5e-9a68-734bd8da6a38'", ",", "version", "=", "'5.0-preview.1'", ")", "return", "self", ".",...
66.555556
0.008237
def _check_list_weights(parameter, name): ''' Checks that the weights in a list of tuples sums to 1.0 ''' if not isinstance(parameter, list): raise ValueError('%s must be formatted with a list of tuples' % name) weight = np.sum([val[1] for val in parameter]) if fabs(weight - 1.) > 1E-8: ...
[ "def", "_check_list_weights", "(", "parameter", ",", "name", ")", ":", "if", "not", "isinstance", "(", "parameter", ",", "list", ")", ":", "raise", "ValueError", "(", "'%s must be formatted with a list of tuples'", "%", "name", ")", "weight", "=", "np", ".", "...
39.6
0.002469
def uniqify_once(func): """Make sure that a method returns a unique name.""" @six.wraps(func) def unique_once(self, *args, **kwargs): return self.unique_once(func(self, *args, **kwargs)) return unique_once
[ "def", "uniqify_once", "(", "func", ")", ":", "@", "six", ".", "wraps", "(", "func", ")", "def", "unique_once", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "unique_once", "(", "func", "(", "self", ",", ...
35.333333
0.023041
def location(self, tag=None, fromdate=None, todate=None): """ Gets an overview of which part of the email links were clicked from (HTML or Text). This is only recorded when Link Tracking is enabled for that email. """ return self.call("GET", "/stats/outbound/clicks/location", tag...
[ "def", "location", "(", "self", ",", "tag", "=", "None", ",", "fromdate", "=", "None", ",", "todate", "=", "None", ")", ":", "return", "self", ".", "call", "(", "\"GET\"", ",", "\"/stats/outbound/clicks/location\"", ",", "tag", "=", "tag", ",", "fromdate...
59
0.011142
def signOp(self, op: Dict, identifier: Identifier=None) -> Request: """ Signs the message if a signer is configured :param identifier: signing identifier; if not supplied the default for the wallet is used. :param op: Operation to be signed ...
[ "def", "signOp", "(", "self", ",", "op", ":", "Dict", ",", "identifier", ":", "Identifier", "=", "None", ")", "->", "Request", ":", "request", "=", "Request", "(", "operation", "=", "op", ",", "protocolVersion", "=", "CURRENT_PROTOCOL_VERSION", ")", "retur...
36.857143
0.011342
def find_json(raw): ''' Pass in a raw string and load the json when it starts. This allows for a string to start with garbage and end with json but be cleanly loaded ''' ret = {} lines = __split(raw) for ind, _ in enumerate(lines): try: working = '\n'.join(lines[ind:]) ...
[ "def", "find_json", "(", "raw", ")", ":", "ret", "=", "{", "}", "lines", "=", "__split", "(", "raw", ")", "for", "ind", ",", "_", "in", "enumerate", "(", "lines", ")", ":", "try", ":", "working", "=", "'\\n'", ".", "join", "(", "lines", "[", "i...
29.636364
0.001486
def iter(self, start=0, stop=-1, withscores=False, reverse=None): """ Return a range of values from sorted set name between @start and @end sorted in ascending order unless @reverse or :prop:reversed. @start and @end: #int, can be negative, indicating the end of ...
[ "def", "iter", "(", "self", ",", "start", "=", "0", ",", "stop", "=", "-", "1", ",", "withscores", "=", "False", ",", "reverse", "=", "None", ")", ":", "reverse", "=", "reverse", "if", "reverse", "is", "not", "None", "else", "self", ".", "reversed"...
46.454545
0.001918
def set_visible_region(self, rectangles, count): """Suggests a new visible region to this frame buffer. This region represents the area of the VM display which is a union of regions of all top-level windows of the guest operating system running inside the VM (if the Guest Additions for t...
[ "def", "set_visible_region", "(", "self", ",", "rectangles", ",", "count", ")", ":", "if", "not", "isinstance", "(", "rectangles", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"rectangles can only be an instance of type basestring\"", ")", "if", "not", ...
40.1875
0.008352
def install_templates(srcroot, destroot, prefix='', excludes=None, includes=None, path_prefix=None): #pylint:disable=too-many-arguments,too-many-statements """ Expand link to compiled assets all templates in *srcroot* and its subdirectories. """ #pylint: disable=too-many-lo...
[ "def", "install_templates", "(", "srcroot", ",", "destroot", ",", "prefix", "=", "''", ",", "excludes", "=", "None", ",", "includes", "=", "None", ",", "path_prefix", "=", "None", ")", ":", "#pylint:disable=too-many-arguments,too-many-statements", "#pylint: disable=...
48.860656
0.002466
def msconcat(names, newname, concatTime=False): """Virtually concatenate multiple MeasurementSets. Multiple MeasurementSets are concatenated into a single MeasurementSet. The concatenation is done in an entirely or almost entirely virtual way, so hardly any data are copied. It makes the command very fa...
[ "def", "msconcat", "(", "names", ",", "newname", ",", "concatTime", "=", "False", ")", ":", "if", "len", "(", "names", ")", "==", "0", ":", "raise", "ValueError", "(", "'No input MSs given'", ")", "# Concatenation in time is straightforward.", "if", "concatTime"...
44.197279
0.000151
def dumps(self, with_defaults=False): """ Generate a string representing all the configuration values. Args: with_defaults (bool): if ``True``, values of items with no custom values will be included in the output if they have a default value set. """ ...
[ "def", "dumps", "(", "self", ",", "with_defaults", "=", "False", ")", ":", "return", "self", ".", "_rw", ".", "dump_config_to_string", "(", "self", ".", "_config", ",", "with_defaults", "=", "with_defaults", ")" ]
43.555556
0.01
def list_sinks(self, page_size=None, page_token=None): """List sinks for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/list :type page_size: int :param page_size: Optional. The maximum number o...
[ "def", "list_sinks", "(", "self", ",", "page_size", "=", "None", ",", "page_token", "=", "None", ")", ":", "return", "self", ".", "sinks_api", ".", "list_sinks", "(", "self", ".", "project", ",", "page_size", ",", "page_token", ")" ]
43.269231
0.001739
def filtered_dir(module_name, *, additions={}, **kwargs): """Return a callable appropriate for __dir__(). All values specified in **kwargs get passed directly to filtered_attrs(). The 'additions' argument should be an iterable which is added to the final results. """ module = importlib.import_...
[ "def", "filtered_dir", "(", "module_name", ",", "*", ",", "additions", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "def", "__dir__", "(", ")", ":", "attr_names", "=", "set...
30.875
0.001965
def get_config(self, name, default=_MISSING): """Get a configuration setting from this DeviceAdapter. See :meth:`AbstractDeviceAdapter.get_config`. """ val = self._config.get(name, default) if val is _MISSING: raise ArgumentError("DeviceAdapter config {} did not exi...
[ "def", "get_config", "(", "self", ",", "name", ",", "default", "=", "_MISSING", ")", ":", "val", "=", "self", ".", "_config", ".", "get", "(", "name", ",", "default", ")", "if", "val", "is", "_MISSING", ":", "raise", "ArgumentError", "(", "\"DeviceAdap...
32.909091
0.008065
def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True, key=None): """ Create new str field on a model. :param regex: regex validation string (e.g. "[^@]+@[^@]+" for email) :param default: any string value :param bool required: whether or not the object is invalid ...
[ "def", "RegexField", "(", "regex", ",", "default", "=", "NOTHING", ",", "required", "=", "True", ",", "repr", "=", "True", ",", "cmp", "=", "True", ",", "key", "=", "None", ")", ":", "default", "=", "_init_fields", ".", "init_default", "(", "required",...
50.833333
0.001073
def namedb_get_namespace_by_preorder_hash( cur, preorder_hash, include_history=True ): """ Get a namespace by its preorder hash (regardless of whether or not it was expired.) """ select_query = "SELECT * FROM namespaces WHERE preorder_hash = ?;" namespace_rows = namedb_query_execute( cur, select_qu...
[ "def", "namedb_get_namespace_by_preorder_hash", "(", "cur", ",", "preorder_hash", ",", "include_history", "=", "True", ")", ":", "select_query", "=", "\"SELECT * FROM namespaces WHERE preorder_hash = ?;\"", "namespace_rows", "=", "namedb_query_execute", "(", "cur", ",", "se...
33.590909
0.017105
async def stop_live_location(self, reply_markup=None) -> typing.Union[Message, base.Boolean]: """ Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. Source: https://core.telegram.org/bots/api#stopmessagel...
[ "async", "def", "stop_live_location", "(", "self", ",", "reply_markup", "=", "None", ")", "->", "typing", ".", "Union", "[", "Message", ",", "base", ".", "Boolean", "]", ":", "return", "await", "self", ".", "bot", ".", "stop_message_live_location", "(", "c...
58.933333
0.010022
def polyroots(p, realroots=False, condition=lambda r: True): """ Returns the roots of a polynomial with coefficients given in p. p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] INPUT: p - Rank-1 array-like object of polynomial coefficients. realroots - a boolean. If true, only real root...
[ "def", "polyroots", "(", "p", ",", "realroots", "=", "False", ",", "condition", "=", "lambda", "r", ":", "True", ")", ":", "roots", "=", "np", ".", "roots", "(", "p", ")", "if", "realroots", ":", "roots", "=", "[", "r", ".", "real", "for", "r", ...
43.708333
0.000933
def frequency_noise_from_psd(psd, seed=None): """ Create noise with a given psd. Return noise coloured with the given psd. The returned noise FrequencySeries has the same length and frequency step as the given psd. Note that if unique noise is desired a unique seed should be provided. Parameters ...
[ "def", "frequency_noise_from_psd", "(", "psd", ",", "seed", "=", "None", ")", ":", "sigma", "=", "0.5", "*", "(", "psd", "/", "psd", ".", "delta_f", ")", "**", "(", "0.5", ")", "if", "seed", "is", "not", "None", ":", "numpy", ".", "random", ".", ...
31.205128
0.000797
def connect(db='', **kwargs): """ db 접속 공통 인자들 채워서 접속, schema만 넣으면 됩니다. db connection 객체 반환이지만 with 문과 같이 쓰이면 cursor임에 주의 (MySQLdb의 구현이 그렇습니다.) ex1) import snipy.database as db conn = db.connect('my_db') cursor = conn.cursor() ex2) import snipy.database as db with db.connect...
[ "def", "connect", "(", "db", "=", "''", ",", "*", "*", "kwargs", ")", ":", "arg", "=", "db_config", "(", "db", ")", "arg", ".", "update", "(", "kwargs", ")", "return", "MySQLdb", ".", "connect", "(", "*", "*", "arg", ")" ]
24.136364
0.001812
def qteStartRecordingHook(self, msgObj): """ Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately. """...
[ "def", "qteStartRecordingHook", "(", "self", ",", "msgObj", ")", ":", "if", "self", ".", "qteRecording", ":", "self", ".", "qteMain", ".", "qteStatus", "(", "'Macro recording already enabled'", ")", "return", "# Update status flag.", "self", ".", "qteRecording", "...
33.916667
0.002389
def put(self, pid, record): """Handle the sort of the files through the PUT deposit files. Expected input in body PUT: .. code-block:: javascript [ { "id": 1 }, { "id": 2 }, ...
[ "def", "put", "(", "self", ",", "pid", ",", "record", ")", ":", "try", ":", "ids", "=", "[", "data", "[", "'id'", "]", "for", "data", "in", "json", ".", "loads", "(", "request", ".", "data", ".", "decode", "(", "'utf-8'", ")", ")", "]", "except...
25.909091
0.002255
def get_database(self, override=None): """ Convenience function for obtaining a handle to the Redis database. By default, uses the connection options from the '[redis]' section. However, if the override parameter is given, it specifies a section containing overrides for the ...
[ "def", "get_database", "(", "self", ",", "override", "=", "None", ")", ":", "# Grab the database connection arguments", "redis_args", "=", "self", "[", "'redis'", "]", "# If we have an override, read some overrides from that", "# section", "if", "override", ":", "redis_ar...
36.925
0.001319
def call_missing_reference(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, node, contnode, ): """ On doctree-resolved, do callbacks""" for callback in EventAction.g...
[ "def", "call_missing_reference", "(", "cls", ",", "kb_app", ",", "sphinx_app", ":", "Sphinx", ",", "sphinx_env", ":", "BuildEnvironment", ",", "node", ",", "contnode", ",", ")", ":", "for", "callback", "in", "EventAction", ".", "get_callbacks", "(", "kb_app", ...
47.4
0.012422
def competition_submit(self, file_name, message, competition, quiet=False): """ submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quie...
[ "def", "competition_submit", "(", "self", ",", "file_name", ",", "message", ",", "competition", ",", "quiet", "=", "False", ")", ":", "if", "competition", "is", "None", ":", "competition", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_...
47.272727
0.000754
async def create(self, session, *, dc=None): """Creates a new session Parameters: session (Object): Session definition dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. Returns: Object: ID of the ...
[ "async", "def", "create", "(", "self", ",", "session", ",", "*", ",", "dc", "=", "None", ")", ":", "response", "=", "await", "self", ".", "_api", ".", "put", "(", "\"/v1/session/create\"", ",", "data", "=", "session", ",", "params", "=", "{", "\"dc\"...
41.050847
0.000806
def receive_oaiharvest_job(request, records, name, **kwargs): """Receive a list of harvested OAI-PMH records and schedule crawls.""" spider = kwargs.get('spider') workflow = kwargs.get('workflow') if not spider or not workflow: return files_created, _ = write_to_dir( records, ...
[ "def", "receive_oaiharvest_job", "(", "request", ",", "records", ",", "name", ",", "*", "*", "kwargs", ")", ":", "spider", "=", "kwargs", ".", "get", "(", "'spider'", ")", "workflow", "=", "kwargs", ".", "get", "(", "'workflow'", ")", "if", "not", "spi...
35.9375
0.001695
def _get_filtered_study_ids(shard, include_aliases=False): """Optionally filters out aliases from standard doc-id list""" from peyotl.phylesystem.helper import DIGIT_PATTERN k = shard.get_doc_ids() if shard.has_aliases and (not include_aliases): x = [] for i in k: if DIGIT_PA...
[ "def", "_get_filtered_study_ids", "(", "shard", ",", "include_aliases", "=", "False", ")", ":", "from", "peyotl", ".", "phylesystem", ".", "helper", "import", "DIGIT_PATTERN", "k", "=", "shard", ".", "get_doc_ids", "(", ")", "if", "shard", ".", "has_aliases", ...
37.083333
0.002193
def _read(self, ti, try_number, metadata=None): """ Read logs of given task instance and try_number from GCS. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from :param meta...
[ "def", "_read", "(", "self", ",", "ti", ",", "try_number", ",", "metadata", "=", "None", ")", ":", "# Explicitly getting log relative path is necessary as the given", "# task instance might be different than task instance passed in", "# in set_context method.", "log_relative_path",...
45.888889
0.001581
def create_zip_file(source_dir, outfile): # type: (str, str) -> None """Create a zip file from a source input directory. This function is intended to be an equivalent to `zip -r`. You give it a source directory, `source_dir`, and it will recursively zip up the files into a zipfile specified by...
[ "def", "create_zip_file", "(", "source_dir", ",", "outfile", ")", ":", "# type: (str, str) -> None", "with", "zipfile", ".", "ZipFile", "(", "outfile", ",", "'w'", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "as", "z", ":", "for", "root", "...
41.823529
0.001376
def t_ARROW(self, t): r"\-\>" t.endlexpos = t.lexpos + len(t.value) return t
[ "def", "t_ARROW", "(", "self", ",", "t", ")", ":", "t", ".", "endlexpos", "=", "t", ".", "lexpos", "+", "len", "(", "t", ".", "value", ")", "return", "t" ]
24.25
0.02
def right(self, expand=None): """ Returns a new Region right of the current region with a width of ``expand`` pixels. Does not include the current region. If range is omitted, it reaches to the right border of the screen. The new region has the same height and y-position as the current region. ...
[ "def", "right", "(", "self", ",", "expand", "=", "None", ")", ":", "if", "expand", "==", "None", ":", "x", "=", "self", ".", "x", "+", "self", ".", "w", "y", "=", "self", ".", "y", "w", "=", "self", ".", "getScreen", "(", ")", ".", "getBounds...
37.529412
0.009174
def deco_optional(decorator): """ optional argument 를 포함하는 decorator를 만드는 decorator """ @functools.wraps(decorator) def dispatcher(*args, **kwargs): one_arg = len(args) == 1 and not kwargs if one_arg and inspect.isfunction(args[0]): decor_obj = decorator() re...
[ "def", "deco_optional", "(", "decorator", ")", ":", "@", "functools", ".", "wraps", "(", "decorator", ")", "def", "dispatcher", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "one_arg", "=", "len", "(", "args", ")", "==", "1", "and", "not", "...
27.466667
0.002347
def _new_packet_cb(self, packet): """Handle a newly arrived packet""" chan = packet.channel if (chan != 0): return payload = packet.data[1:] if (self.state == GET_TOC_INFO): if self._useV2: [self.nbr_of_items, self._crc] = struct.unpack( ...
[ "def", "_new_packet_cb", "(", "self", ",", "packet", ")", ":", "chan", "=", "packet", ".", "channel", "if", "(", "chan", "!=", "0", ")", ":", "return", "payload", "=", "packet", ".", "data", "[", "1", ":", "]", "if", "(", "self", ".", "state", "=...
41.64
0.000939
def validate_table_name(name): """ :param str name: Table name to validate. :raises NameValidationError: |raises_validate_table_name| """ try: validate_sqlite_table_name(name) except (InvalidCharError, InvalidReservedNameError) as e: raise NameValidationError(e) except NullN...
[ "def", "validate_table_name", "(", "name", ")", ":", "try", ":", "validate_sqlite_table_name", "(", "name", ")", "except", "(", "InvalidCharError", ",", "InvalidReservedNameError", ")", "as", "e", ":", "raise", "NameValidationError", "(", "e", ")", "except", "Nu...
30.071429
0.002304
def ogr2pg( self, in_file, in_layer=None, out_layer=None, schema="public", s_srs=None, t_srs="EPSG:3005", sql=None, dim=2, cmd_only=False, index=True ): """ Load a layer to provided pgdata database connection usi...
[ "def", "ogr2pg", "(", "self", ",", "in_file", ",", "in_layer", "=", "None", ",", "out_layer", "=", "None", ",", "schema", "=", "\"public\"", ",", "s_srs", "=", "None", ",", "t_srs", "=", "\"EPSG:3005\"", ",", "sql", "=", "None", ",", "dim", "=", "2",...
29.736842
0.001285
def compile_pillar(self): ''' Return a future which will contain the pillar data from the master ''' load = {'id': self.minion_id, 'grains': self.grains, 'saltenv': self.opts['saltenv'], 'pillarenv': self.opts['pillarenv'], ...
[ "def", "compile_pillar", "(", "self", ")", ":", "load", "=", "{", "'id'", ":", "self", ".", "minion_id", ",", "'grains'", ":", "self", ".", "grains", ",", "'saltenv'", ":", "self", ".", "opts", "[", "'saltenv'", "]", ",", "'pillarenv'", ":", "self", ...
39.833333
0.001634
def get(self, url, fromfile=None, params={}, headers={}): '''Get SDMX message from REST service or local file Args: url(str): URL of the REST service without the query part If None, fromfile must be set. Default is None params(dict): will be appended as q...
[ "def", "get", "(", "self", ",", "url", ",", "fromfile", "=", "None", ",", "params", "=", "{", "}", ",", "headers", "=", "{", "}", ")", ":", "if", "fromfile", ":", "try", ":", "# Load data from local file\r", "# json files must be opened in text mode, all other...
40.044444
0.001625
def wind_speed(self, value=999.0): """Corresponds to IDD Field `wind_speed` Args: value (float): value for IDD Field `wind_speed` Unit: m/s value >= 0.0 value <= 40.0 Missing value: 999.0 if `value` is None it w...
[ "def", "wind_speed", "(", "self", ",", "value", "=", "999.0", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type fl...
36.033333
0.001802
def cancel_link_unlink_mode(self): """Cancel linking or unlinking mode""" self.logger.info("cancel_link_unlink_mode") self.scene_command('08') # should send http://0.0.0.0/0?08=I=0 ## TODO check return status status = self.hub.get_buffer_status() return status
[ "def", "cancel_link_unlink_mode", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"cancel_link_unlink_mode\"", ")", "self", ".", "scene_command", "(", "'08'", ")", "# should send http://0.0.0.0/0?08=I=0", "## TODO check return status", "status", "=", ...
34.333333
0.009464
def connectMsToNet(Facility_presence=0, ConnectedSubaddress_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """CONNECT Section 9.3.5.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x7) # 00000111 packet = a / b if Facility_presence is 1: c = FacilityHdr(ie...
[ "def", "connectMsToNet", "(", "Facility_presence", "=", "0", ",", "ConnectedSubaddress_presence", "=", "0", ",", "UserUser_presence", "=", "0", ",", "SsVersionIndicator_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", ...
39.368421
0.001305
def append_cluster_attribute(self, index_canvas, index_cluster, data, marker = None, markersize = None): """! @brief Append cluster attribure for cluster on specific canvas. @details Attribute it is data that is visualized for specific cluster using its color, marker and markersize if last tw...
[ "def", "append_cluster_attribute", "(", "self", ",", "index_canvas", ",", "index_cluster", ",", "data", ",", "marker", "=", "None", ",", "markersize", "=", "None", ")", ":", "cluster_descr", "=", "self", ".", "__canvas_clusters", "[", "index_canvas", "]", "[",...
55.692308
0.012899
def get_all_dbinstances(self, instance_id=None, max_records=None, marker=None): """ Retrieve all the DBInstances in your account. :type instance_id: str :param instance_id: DB Instance identifier. If supplied, only information thi...
[ "def", "get_all_dbinstances", "(", "self", ",", "instance_id", "=", "None", ",", "max_records", "=", "None", ",", "marker", "=", "None", ")", ":", "params", "=", "{", "}", "if", "instance_id", ":", "params", "[", "'DBInstanceIdentifier'", "]", "=", "instan...
40.75
0.002247
def from_las(cls, fname, remap=None, funcs=None, data=True, req=None, alias=None, encoding=None, printfname=False ): """ Constructor. Essentially just ...
[ "def", "from_las", "(", "cls", ",", "fname", ",", "remap", "=", "None", ",", "funcs", "=", "None", ",", "data", "=", "True", ",", "req", "=", "None", ",", "alias", "=", "None", ",", "encoding", "=", "None", ",", "printfname", "=", "False", ")", "...
34.555556
0.00813
def iter_endpoints(graph, match_func): """ Iterate through matching endpoints. The `match_func` is expected to have a signature of: def matches(operation, ns, rule): return True :returns: a generator over (`Operation`, `Namespace`, rule, func) tuples. """ for rule in grap...
[ "def", "iter_endpoints", "(", "graph", ",", "match_func", ")", ":", "for", "rule", "in", "graph", ".", "flask", ".", "url_map", ".", "iter_rules", "(", ")", ":", "try", ":", "operation", ",", "ns", "=", "Namespace", ".", "parse_endpoint", "(", "rule", ...
36.391304
0.002328
def belongs_to_module(t, module_name): "Check if `t` belongs to `module_name`." if hasattr(t, '__func__'): return belongs_to_module(t.__func__, module_name) if not inspect.getmodule(t): return False return inspect.getmodule(t).__name__.startswith(module_name)
[ "def", "belongs_to_module", "(", "t", ",", "module_name", ")", ":", "if", "hasattr", "(", "t", ",", "'__func__'", ")", ":", "return", "belongs_to_module", "(", "t", ".", "__func__", ",", "module_name", ")", "if", "not", "inspect", ".", "getmodule", "(", ...
54.2
0.014545
def _sync_download(self, url, destination_path): """Synchronous version of `download` method.""" proxies = { 'http': os.environ.get('TFDS_HTTP_PROXY', None), 'https': os.environ.get('TFDS_HTTPS_PROXY', None), 'ftp': os.environ.get('TFDS_FTP_PROXY', None) } if kaggle.KaggleFile.is...
[ "def", "_sync_download", "(", "self", ",", "url", ",", "destination_path", ")", ":", "proxies", "=", "{", "'http'", ":", "os", ".", "environ", ".", "get", "(", "'TFDS_HTTP_PROXY'", ",", "None", ")", ",", "'https'", ":", "os", ".", "environ", ".", "get"...
35.338462
0.008471
def _parse_result(self, result): u""" This method parses validation results. If result is True, then do nothing. if include even one false to result, this method parse result and raise Exception. """ if result is not True: for section, errors in result...
[ "def", "_parse_result", "(", "self", ",", "result", ")", ":", "if", "result", "is", "not", "True", ":", "for", "section", ",", "errors", "in", "result", ".", "iteritems", "(", ")", ":", "for", "key", ",", "value", "in", "errors", ".", "iteritems", "(...
35.166667
0.002307
def fetch_data(files, folder): """Downloads files to folder and checks their md5 checksums Parameters ---------- files : dictionary For each file in `files` the value should be (url, md5). The file will be downloaded from url if the file does not already exist or if the file exi...
[ "def", "fetch_data", "(", "files", ",", "folder", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "folder", ")", ":", "_log", "(", "\"Creating new folder %s\"", "%", "(", "folder", ")", ")", "os", ".", "makedirs", "(", "folder", ")", "a...
35.363636
0.000625
def validate(self): """ Verify that the contents of the SecretData object are valid. Raises: TypeError: if the types of any SecretData attributes are invalid. """ if not isinstance(self.value, bytes): raise TypeError("secret value must be bytes") ...
[ "def", "validate", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "value", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"secret value must be bytes\"", ")", "elif", "not", "isinstance", "(", "self", ".", "data_type", ",", "enum...
42.103448
0.001601
def log_method(log, level=logging.DEBUG): """Logs a method and its arguments when entered.""" def decorator(func): func_name = func.__name__ @six.wraps(func) def wrapper(self, *args, **kwargs): if log.isEnabledFor(level): pretty_args = [] if ...
[ "def", "log_method", "(", "log", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "def", "decorator", "(", "func", ")", ":", "func_name", "=", "func", ".", "__name__", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ...
32.285714
0.001433
def _shuffled_order(w, h): """ Generator for the order of 4-byte values. 32bit channels are also encoded using delta encoding, but it make no sense to apply delta compression to bytes. It is possible to apply delta compression to 2-byte or 4-byte words, but it seems it is not the best way eithe...
[ "def", "_shuffled_order", "(", "w", ",", "h", ")", ":", "rowsize", "=", "4", "*", "w", "for", "row", "in", "range", "(", "0", ",", "rowsize", "*", "h", ",", "rowsize", ")", ":", "for", "offset", "in", "range", "(", "row", ",", "row", "+", "w", ...
40.1
0.001218
def to_css_class(s): """ Given a string (e.g. a table name) returns a valid unique CSS class. For simple cases, just returns the string again. If the string is not a valid CSS class (we disallow - and _ prefixes even though they are valid as they may be confused with browser prefixes) we strip inval...
[ "def", "to_css_class", "(", "s", ")", ":", "if", "css_class_re", ".", "match", "(", "s", ")", ":", "return", "s", "md5_suffix", "=", "hashlib", ".", "md5", "(", "s", ".", "encode", "(", "'utf8'", ")", ")", ".", "hexdigest", "(", ")", "[", ":", "6...
42.666667
0.001092
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Read the data encoding the CapabilityInformation structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporti...
[ "def", "read", "(", "self", ",", "input_buffer", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_3", ")", ":", "if", "kmip_version", "<", "enums", ".", "KMIPVersion", ".", "KMIP_1_3", ":", "raise", "exceptions", ".", "VersionNotSupported", ...
39.550847
0.000418
def state_category(value): """Parse categories.""" if value == re.sre_parse.CATEGORY_DIGIT: return (yield '0') if value == re.sre_parse.CATEGORY_WORD: return (yield 'x')
[ "def", "state_category", "(", "value", ")", ":", "if", "value", "==", "re", ".", "sre_parse", ".", "CATEGORY_DIGIT", ":", "return", "(", "yield", "'0'", ")", "if", "value", "==", "re", ".", "sre_parse", ".", "CATEGORY_WORD", ":", "return", "(", "yield", ...
30.285714
0.009174
def _zset_to_keys(self, key, values=None, alpha=False): """ Convert a redis sorted set to a list of keys, to be used by sort. Each key is on the following format, for each value in the sorted set: ramdom_string:value-in-the-sorted-set => score-of-the-value The random string i...
[ "def", "_zset_to_keys", "(", "self", ",", "key", ",", "values", "=", "None", ",", "alpha", "=", "False", ")", ":", "conn", "=", "self", ".", "cls", ".", "get_connection", "(", ")", "default", "=", "''", "if", "alpha", "else", "'-inf'", "if", "values"...
43.618182
0.001631
def xpath(source_xml, xpath_expr, req_format='string'): """ Filter xml based on an xpath expression. Purpose: This function applies an Xpath expression to the XML | supplied by source_xml. Returns a string subtree or | subtrees that match the Xpath expression. It can also return ...
[ "def", "xpath", "(", "source_xml", ",", "xpath_expr", ",", "req_format", "=", "'string'", ")", ":", "tree", "=", "source_xml", "if", "not", "isinstance", "(", "source_xml", ",", "ET", ".", "Element", ")", ":", "tree", "=", "objectify", ".", "fromstring", ...
40.02439
0.000595
def tag_versions(repo_path): """ Given a repo will add a tag for each major version. Args: repo_path(str): path to the git repository to tag. """ repo = dulwich.repo.Repo(repo_path) tags = get_tags(repo) maj_version = 0 feat_version = 0 fix_version = 0 last_maj_version =...
[ "def", "tag_versions", "(", "repo_path", ")", ":", "repo", "=", "dulwich", ".", "repo", ".", "Repo", "(", "repo_path", ")", "tags", "=", "get_tags", "(", "repo", ")", "maj_version", "=", "0", "feat_version", "=", "0", "fix_version", "=", "0", "last_maj_v...
29.044444
0.00074
def __fetch_issue_messages(self, issue_id): """Get messages of an issue""" for messages_raw in self.client.issue_collection(issue_id, "messages"): messages = json.loads(messages_raw) for msg in messages['entries']: msg['owner_data'] = self.__fetch_user_data('{OW...
[ "def", "__fetch_issue_messages", "(", "self", ",", "issue_id", ")", ":", "for", "messages_raw", "in", "self", ".", "client", ".", "issue_collection", "(", "issue_id", ",", "\"messages\"", ")", ":", "messages", "=", "json", ".", "loads", "(", "messages_raw", ...
40.333333
0.008086
def create_file_in_fs(file_data, file_name, file_system, static_dir): """ Writes file in specific file system. Arguments: file_data (str): Data to store into the file. file_name (str): File name of the file to be created. file_system (OSFS): Import file system. static_dir (s...
[ "def", "create_file_in_fs", "(", "file_data", ",", "file_name", ",", "file_system", ",", "static_dir", ")", ":", "with", "file_system", ".", "open", "(", "combine", "(", "static_dir", ",", "file_name", ")", ",", "'wb'", ")", "as", "f", ":", "f", ".", "wr...
39.75
0.002049
def deserialize(self, apic_frame): """Convert APIC frame into Image.""" return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
[ "def", "deserialize", "(", "self", ",", "apic_frame", ")", ":", "return", "Image", "(", "data", "=", "apic_frame", ".", "data", ",", "desc", "=", "apic_frame", ".", "desc", ",", "type", "=", "apic_frame", ".", "type", ")" ]
46
0.010695
def passthrough_context_definition(context_params): '''Create a context definition from a pre-existing context. This can be useful in testing contexts where you may want to create a context manually and then pass it into a one-off PipelineDefinition Args: context (ExecutionC...
[ "def", "passthrough_context_definition", "(", "context_params", ")", ":", "check", ".", "inst_param", "(", "context_params", ",", "'context'", ",", "ExecutionContext", ")", "context_definition", "=", "PipelineContextDefinition", "(", "context_fn", "=", "lambda", "*", ...
49.5
0.008499
def is_win_python35_or_earlier(): """ Convenience method to determine if the current platform is Windows and Python version 3.5 or earlier. Returns: bool: True if the current platform is Windows and the Python interpreter is 3.5 or earlier; False otherwise. """ retu...
[ "def", "is_win_python35_or_earlier", "(", ")", ":", "return", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", "and", "sys", ".", "version_info", ".", "major", "<", "3", "or", "(", "sys", ".", "version_info", ".", "major", "==", "3", "and"...
46
0.010661
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
[ "def", "get_memory_info", "(", "self", ")", ":", "rss", ",", "vms", "=", "_psutil_bsd", ".", "get_process_memory_info", "(", "self", ".", "pid", ")", "[", ":", "2", "]", "return", "nt_meminfo", "(", "rss", ",", "vms", ")" ]
48.25
0.010204
def from_files(cls, filepaths, specie, step_skip=10, ncores=None, initial_disp=None, initial_structure=None, **kwargs): """ Convenient constructor that takes in a list of vasprun.xml paths to perform diffusion analysis. Args: filepaths ([str]): List of pat...
[ "def", "from_files", "(", "cls", ",", "filepaths", ",", "specie", ",", "step_skip", "=", "10", ",", "ncores", "=", "None", ",", "initial_disp", "=", "None", ",", "initial_structure", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ncores", "is",...
52.442623
0.001227
def copy_data(data_length, blocksize, infp, outfp): # type: (int, int, BinaryIO, BinaryIO) -> None ''' A utility function to copy data from the input file object to the output file object. This function will use the most efficient copy method available, which is often sendfile. Parameters: ...
[ "def", "copy_data", "(", "data_length", ",", "blocksize", ",", "infp", ",", "outfp", ")", ":", "# type: (int, int, BinaryIO, BinaryIO) -> None", "use_sendfile", "=", "False", "if", "have_sendfile", ":", "# Python 3 implements the fileno method for all file-like objects, so", ...
43.677966
0.001518
def dynamic_import_class(name): """Import a class from a module string, e.g. ``my.module.ClassName``.""" import importlib module_name, class_name = name.rsplit(".", 1) try: module = importlib.import_module(module_name) except Exception as e: _logger.exception("Dynamic import of {!r}...
[ "def", "dynamic_import_class", "(", "name", ")", ":", "import", "importlib", "module_name", ",", "class_name", "=", "name", ".", "rsplit", "(", "\".\"", ",", "1", ")", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "...
34.75
0.002336
def user_structure(user, site): """ An user structure. """ full_name = user.get_full_name().split() first_name = full_name[0] try: last_name = full_name[1] except IndexError: last_name = '' return {'userid': user.pk, 'email': user.email, 'nickname'...
[ "def", "user_structure", "(", "user", ",", "site", ")", ":", "full_name", "=", "user", ".", "get_full_name", "(", ")", ".", "split", "(", ")", "first_name", "=", "full_name", "[", "0", "]", "try", ":", "last_name", "=", "full_name", "[", "1", "]", "e...
28.5
0.001887
def sensor(self, sensor_type): """Update and return sensor value.""" _LOGGER.debug("Reading %s sensor.", sensor_type) return self._session.read_sensor(self.device_id, sensor_type)
[ "def", "sensor", "(", "self", ",", "sensor_type", ")", ":", "_LOGGER", ".", "debug", "(", "\"Reading %s sensor.\"", ",", "sensor_type", ")", "return", "self", ".", "_session", ".", "read_sensor", "(", "self", ".", "device_id", ",", "sensor_type", ")" ]
50
0.009852
def _interpret_lines(self, lines, compare_all=False): """Interprets the set of lines. PARAMTERS: lines -- list of str; lines of code compare_all -- bool; if True, check for no output for lines that are not followed by a CodeAnswer RETURNS: b...
[ "def", "_interpret_lines", "(", "self", ",", "lines", ",", "compare_all", "=", "False", ")", ":", "current", "=", "[", "]", "for", "line", "in", "lines", "+", "[", "''", "]", ":", "if", "isinstance", "(", "line", ",", "str", ")", ":", "if", "curren...
38.5
0.002111
def _py_outvar(parameter, lparams, tab): """Returns the code to produce a ctypes output variable for interacting with fortran. """ if ("out" in parameter.direction and parameter.D > 0 and ":" in parameter.dimension and ("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)): ...
[ "def", "_py_outvar", "(", "parameter", ",", "lparams", ",", "tab", ")", ":", "if", "(", "\"out\"", "in", "parameter", ".", "direction", "and", "parameter", ".", "D", ">", "0", "and", "\":\"", "in", "parameter", ".", "dimension", "and", "(", "\"allocatabl...
66.625
0.011111
def do_set(self, line): ''' Set repository attributes on the active repo. set attribute=value # intended use: # directory repos: work_on developer-repo set type=directory set directory=package-directory # http repos: work_on company-pri...
[ "def", "do_set", "(", "self", ",", "line", ")", ":", "self", ".", "abort_on_invalid_active_repo", "(", "'set'", ")", "repo", "=", "self", ".", "network", ".", "active_repo", "attribute", ",", "eq", ",", "value", "=", "line", ".", "partition", "(", "'='",...
28.655172
0.002328
def isfortran(env, source): """Return 1 if any of code in source has fortran files in it, 0 otherwise.""" try: fsuffixes = env['FORTRANSUFFIXES'] except KeyError: # If no FORTRANSUFFIXES, no fortran tool, so there is no need to look # for fortran sources. return 0 if...
[ "def", "isfortran", "(", "env", ",", "source", ")", ":", "try", ":", "fsuffixes", "=", "env", "[", "'FORTRANSUFFIXES'", "]", "except", "KeyError", ":", "# If no FORTRANSUFFIXES, no fortran tool, so there is no need to look", "# for fortran sources.", "return", "0", "if"...
29.631579
0.001721
def abbreviate(labels, rfill=' '): """ Abbreviate labels without introducing ambiguities. """ max_len = max(len(l) for l in labels) for i in range(1, max_len): abbrev = [l[:i].ljust(i, rfill) for l in labels] if len(abbrev) == len(set(abbrev)): break return abbrev
[ "def", "abbreviate", "(", "labels", ",", "rfill", "=", "' '", ")", ":", "max_len", "=", "max", "(", "len", "(", "l", ")", "for", "l", "in", "labels", ")", "for", "i", "in", "range", "(", "1", ",", "max_len", ")", ":", "abbrev", "=", "[", "l", ...
30.7
0.009494
def list_databases(self, instance, limit=None, marker=None): """Returns all databases for the specified instance.""" return instance.list_databases(limit=limit, marker=marker)
[ "def", "list_databases", "(", "self", ",", "instance", ",", "limit", "=", "None", ",", "marker", "=", "None", ")", ":", "return", "instance", ".", "list_databases", "(", "limit", "=", "limit", ",", "marker", "=", "marker", ")" ]
63
0.010471
def data(self, **kwargs): """ If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and ...
[ "def", "data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "key", "=", "kwargs", ".", "pop", "(", "'key'", ",", "None", ")", "value", "=", "kwargs", ".", "pop", "(", "'value'", ",", "None", ")", "dictionary", "=", "kwargs", ".", "pop", "(", ...
37.30303
0.001584
def get_rx_distance(self, mesh): """ Compute distance between each point of mesh and surface's great circle arc. Distance is measured perpendicular to the rupture strike, from the surface projection of the updip edge of the rupture, with the down dip direction being posi...
[ "def", "get_rx_distance", "(", "self", ",", "mesh", ")", ":", "top_edge", "=", "self", ".", "mesh", "[", "0", ":", "1", "]", "dists", "=", "[", "]", "if", "top_edge", ".", "lons", ".", "shape", "[", "1", "]", "<", "3", ":", "i", "=", "0", "p1...
34.447059
0.000664
def checkValid(cls, reason): """ Raises ValueError if the reason is not one of the valid enumerations """ if reason not in cls.__VALID_REASONS: raise ValueError("reason must be one of {}, got {}".format(cls.__VALID_REASONS, reason))
[ "def", "checkValid", "(", "cls", ",", "reason", ")", ":", "if", "reason", "not", "in", "cls", ".", "__VALID_REASONS", ":", "raise", "ValueError", "(", "\"reason must be one of {}, got {}\"", ".", "format", "(", "cls", ".", "__VALID_REASONS", ",", "reason", ")"...
52.8
0.014925
def module_degree_zscore(W, ci, flag=0): ''' The within-module degree z-score is a within-module version of degree centrality. Parameters ---------- W : NxN np.narray binary/weighted directed/undirected connection matrix ci : Nx1 np.array_like community affiliation vector ...
[ "def", "module_degree_zscore", "(", "W", ",", "ci", ",", "flag", "=", "0", ")", ":", "_", ",", "ci", "=", "np", ".", "unique", "(", "ci", ",", "return_inverse", "=", "True", ")", "ci", "+=", "1", "if", "flag", "==", "2", ":", "W", "=", "W", "...
26.025
0.000926
def _context_callbacks(app, key, original_context=_CONTEXT_MISSING): """Register the callbacks we need to properly pop and push the app-local context for a component. Args: app (flask.Flask): The app who this context belongs to. This is the only sender our Blinker si...
[ "def", "_context_callbacks", "(", "app", ",", "key", ",", "original_context", "=", "_CONTEXT_MISSING", ")", ":", "def", "_get_context", "(", "dummy_app", ")", ":", "\"\"\"Set the context proxy so that it points to a specific context.\n \"\"\"", "_CONTEXT_LOCALS", "...
43.591837
0.001374