text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def np2model_tensor(a): "Tranform numpy array `a` to a tensor of the same type." dtype = model_type(a.dtype) res = as_tensor(a) if not dtype: return res return res.type(dtype)
[ "def", "np2model_tensor", "(", "a", ")", ":", "dtype", "=", "model_type", "(", "a", ".", "dtype", ")", "res", "=", "as_tensor", "(", "a", ")", "if", "not", "dtype", ":", "return", "res", "return", "res", ".", "type", "(", "dtype", ")" ]
31.666667
0.010256
def tshift(self, periods=1, freq=None, axis=0): """ Shift the time index, using the index's frequency if available. Parameters ---------- periods : int Number of periods to move, can be positive or negative freq : DateOffset, timedelta, or time rule string, d...
[ "def", "tshift", "(", "self", ",", "periods", "=", "1", ",", "freq", "=", "None", ",", "axis", "=", "0", ")", ":", "index", "=", "self", ".", "_get_axis", "(", "axis", ")", "if", "freq", "is", "None", ":", "freq", "=", "getattr", "(", "index", ...
32.821429
0.001057
def watchdog(sleep_interval): """Watch project files, restart worker process if a change happened. :param sleep_interval: interval in second. :return: Nothing """ mtimes = {} worker_process = restart_with_reloader() signal.signal( signal.SIGTERM, lambda *args: kill_program_completly...
[ "def", "watchdog", "(", "sleep_interval", ")", ":", "mtimes", "=", "{", "}", "worker_process", "=", "restart_with_reloader", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "lambda", "*", "args", ":", "kill_program_completly", "(", "wo...
31.060606
0.000946
def check_for_env_url(self): """ First checks to see if a url argument was explicitly passed in. If so, that will be used. If not, it checks for the existence of the environment variable specified in ENV_URL. If this is set, it should contain a fully qualified URL to the ...
[ "def", "check_for_env_url", "(", "self", ")", ":", "url", "=", "self", ".", "args", ".", "get", "(", "'url'", ",", "None", ")", "if", "url", ":", "del", "self", ".", "args", "[", "'url'", "]", "if", "not", "url", "and", "self", ".", "EnvURL", "in...
36.777778
0.002208
def sigPerms(s): """Generate all possible signatures derived by upcasting the given signature. """ codes = 'bilfdc' if not s: yield '' elif s[0] in codes: start = codes.index(s[0]) for x in codes[start:]: for y in sigPerms(s[1:]): yield x + y ...
[ "def", "sigPerms", "(", "s", ")", ":", "codes", "=", "'bilfdc'", "if", "not", "s", ":", "yield", "''", "elif", "s", "[", "0", "]", "in", "codes", ":", "start", "=", "codes", ".", "index", "(", "s", "[", "0", "]", ")", "for", "x", "in", "codes...
26.470588
0.002146
def _build_query(self, uri, params=None, action_token_type=None): """Prepare query string""" if params is None: params = QueryParams() params['response_format'] = 'json' session_token = None if action_token_type in self._action_tokens: # Favor action t...
[ "def", "_build_query", "(", "self", ",", "uri", ",", "params", "=", "None", ",", "action_token_type", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "QueryParams", "(", ")", "params", "[", "'response_format'", "]", "=", "'json'"...
31.526316
0.001619
def groupIntoChoices(splitsOnWord, wordWidth: int, origin: OneOfTransaction): """ :param splitsOnWord: list of lists of parts (fields splited on word boundaries) :return: generators of ChoicesOfFrameParts for each word which are not crossing word boundaries """ def cmpWordIndex(a, b)...
[ "def", "groupIntoChoices", "(", "splitsOnWord", ",", "wordWidth", ":", "int", ",", "origin", ":", "OneOfTransaction", ")", ":", "def", "cmpWordIndex", "(", "a", ",", "b", ")", ":", "return", "a", ".", "startOfPart", "//", "wordWidth", "<", "b", ".", "sta...
36.324324
0.000725
def _parse_patient_variants(self, file): """ :param file: file handler :return: """ patient_var_map = self._convert_variant_file_to_dict(file) gene_coordinate_map = self._parse_gene_coordinates( self.map_files['gene_coord_map']) rs_map = self._parse_rs...
[ "def", "_parse_patient_variants", "(", "self", ",", "file", ")", ":", "patient_var_map", "=", "self", ".", "_convert_variant_file_to_dict", "(", "file", ")", "gene_coordinate_map", "=", "self", ".", "_parse_gene_coordinates", "(", "self", ".", "map_files", "[", "'...
45.535714
0.002047
def gradient_n_pal(colors, values=None, name='gradientn'): """ Create a n color gradient palette Parameters ---------- colors : list list of colors values : list, optional list of points in the range [0, 1] at which to place each color. Must be the same size as `...
[ "def", "gradient_n_pal", "(", "colors", ",", "values", "=", "None", ",", "name", "=", "'gradientn'", ")", ":", "# Note: For better results across devices and media types,", "# it would be better to do the interpolation in", "# Lab color space.", "if", "values", "is", "None", ...
30.181818
0.000729
def argsort(indexable, key=None, reverse=False): """ Returns the indices that would sort a indexable object. This is similar to `numpy.argsort`, but it is written in pure python and works on both lists and dictionaries. Args: indexable (Iterable or Mapping): indexable to sort by k...
[ "def", "argsort", "(", "indexable", ",", "key", "=", "None", ",", "reverse", "=", "False", ")", ":", "# Create an iterator of value/key pairs", "if", "isinstance", "(", "indexable", ",", "collections_abc", ".", "Mapping", ")", ":", "vk_iter", "=", "(", "(", ...
39.90566
0.000461
def create_application(self, full_layout=True): """ makes the application object and the buffers """ layout_manager = LayoutManager(self) if full_layout: layout = layout_manager.create_layout(ExampleLexer, ToolbarLexer) else: layout = layout_manager.create_tutoria...
[ "def", "create_application", "(", "self", ",", "full_layout", "=", "True", ")", ":", "layout_manager", "=", "LayoutManager", "(", "self", ")", "if", "full_layout", ":", "layout", "=", "layout_manager", ".", "create_layout", "(", "ExampleLexer", ",", "ToolbarLexe...
37.540541
0.001404
def get_coin_list(coins='all'): """ Get general information about all the coins available on cryptocompare.com. Args: coins: Default value of 'all' returns information about all the coins available on the site. Otherwise a single string or list of coin symbols can be used. Returns: The function retu...
[ "def", "get_coin_list", "(", "coins", "=", "'all'", ")", ":", "# convert single coins input to single element lists", "if", "not", "isinstance", "(", "coins", ",", "list", ")", "and", "coins", "!=", "'all'", ":", "coins", "=", "[", "coins", "]", "# load data", ...
27.673913
0.049317
def get_obj(self, name): """ Returns the AWS object associated with a given option. The heuristics used are a bit lame. If the option name contains the word 'bucket' it is assumed to be an S3 bucket, if the name contains the word 'queue' it is assumed to be an SQS queue and ...
[ "def", "get_obj", "(", "self", ",", "name", ")", ":", "val", "=", "self", ".", "get", "(", "name", ")", "if", "not", "val", ":", "return", "None", "if", "name", ".", "find", "(", "'queue'", ")", ">=", "0", ":", "obj", "=", "boto", ".", "lookup"...
37.423077
0.002004
def _to_narrow(self, terms, data, mask, dates, assets): """ Convert raw computed pipeline results into a DataFrame for public APIs. Parameters ---------- terms : dict[str -> Term] Dict mapping column names to terms. data : dict[str -> ndarray[ndim=2]] ...
[ "def", "_to_narrow", "(", "self", ",", "terms", ",", "data", ",", "mask", ",", "dates", ",", "assets", ")", ":", "if", "not", "mask", ".", "any", "(", ")", ":", "# Manually handle the empty DataFrame case. This is a workaround", "# to pandas failing to tz_localize a...
40.138462
0.000748
def create_manually(cls, validation_function_name, # type: str var_name, # type: str var_value, validation_outcome=None, # type: Any help_msg=None, # type: str ...
[ "def", "create_manually", "(", "cls", ",", "validation_function_name", ",", "# type: str", "var_name", ",", "# type: str", "var_value", ",", "validation_outcome", "=", "None", ",", "# type: Any", "help_msg", "=", "None", ",", "# type: str", "append_details", "=", "T...
43.228571
0.00905
def get_summary_stats(items, attr): """ Returns a dictionary of aggregated statistics for 'items' filtered by "attr'. For example, it will aggregate statistics for a host across all the playbook runs it has been a member of, with the following structure: data[host.id] = { 'ok': 4 ...
[ "def", "get_summary_stats", "(", "items", ",", "attr", ")", ":", "data", "=", "{", "}", "for", "item", "in", "items", ":", "stats", "=", "models", ".", "Stats", ".", "query", ".", "filter_by", "(", "*", "*", "{", "attr", ":", "item", ".", "id", "...
36.142857
0.000962
def to_dict(self): '''Represents the setup section in form of key-value pairs. Returns ------- dict ''' mapping = dict() for attr in dir(self): if attr.startswith('_'): continue if not isinstance(getattr(self.__class__, att...
[ "def", "to_dict", "(", "self", ")", ":", "mapping", "=", "dict", "(", ")", "for", "attr", "in", "dir", "(", "self", ")", ":", "if", "attr", ".", "startswith", "(", "'_'", ")", ":", "continue", "if", "not", "isinstance", "(", "getattr", "(", "self",...
31.888889
0.002255
def nnz(self): """ Returns the number of lower-triangular nonzeros. """ nnz = 0 for k in range(len(self.snpost)): nn = self.snptr[k+1]-self.snptr[k] na = self.relptr[k+1]-self.relptr[k] nnz += nn*(nn+1)/2 + nn*na return nnz
[ "def", "nnz", "(", "self", ")", ":", "nnz", "=", "0", "for", "k", "in", "range", "(", "len", "(", "self", ".", "snpost", ")", ")", ":", "nn", "=", "self", ".", "snptr", "[", "k", "+", "1", "]", "-", "self", ".", "snptr", "[", "k", "]", "n...
30.2
0.009646
def find_elb(name='', env='', region=''): """Get an application's AWS elb dns name. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS record """ LOG.info('Find %s ELB in %s [%s].', name, env, region) ...
[ "def", "find_elb", "(", "name", "=", "''", ",", "env", "=", "''", ",", "region", "=", "''", ")", ":", "LOG", ".", "info", "(", "'Find %s ELB in %s [%s].'", ",", "name", ",", "env", ",", "region", ")", "url", "=", "'{0}/applications/{1}/loadBalancers'", "...
28.655172
0.002328
def factorize(train, test, features, na_value=-9999, full=False, sort=True): """Factorize categorical features. Parameters ---------- train : pd.DataFrame test : pd.DataFrame features : list Column names in the DataFrame to be encoded. na_value : int, default -9999 full : boo...
[ "def", "factorize", "(", "train", ",", "test", ",", "features", ",", "na_value", "=", "-", "9999", ",", "full", "=", "False", ",", "sort", "=", "True", ")", ":", "for", "column", "in", "features", ":", "if", "full", ":", "vs", "=", "pd", ".", "co...
29.027778
0.000926
def subscribe(self, jid, node=None, *, subscription_jid=None, config=None): """ Subscribe to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to subscribe to. :type...
[ "def", "subscribe", "(", "self", ",", "jid", ",", "node", "=", "None", ",", "*", ",", "subscription_jid", "=", "None", ",", "config", "=", "None", ")", ":", "subscription_jid", "=", "subscription_jid", "or", "self", ".", "client", ".", "local_jid", ".", ...
39.884615
0.001882
def transform (list, pattern, indices = [1]): """ Matches all elements of 'list' agains the 'pattern' and returns a list of the elements indicated by indices of all successfull matches. If 'indices' is omitted returns a list of first paranthethised groups of all successfull matches. ...
[ "def", "transform", "(", "list", ",", "pattern", ",", "indices", "=", "[", "1", "]", ")", ":", "result", "=", "[", "]", "for", "e", "in", "list", ":", "m", "=", "re", ".", "match", "(", "pattern", ",", "e", ")", "if", "m", ":", "for", "i", ...
28.764706
0.013861
def run(tests=(), reporter=None, stop_after=None): """ Run the tests that are loaded by each of the strings provided. Arguments: tests (iterable): the collection of tests (specified as `str` s) to run reporter (Reporter): a `Reporter` to use for the run. If unpro...
[ "def", "run", "(", "tests", "=", "(", ")", ",", "reporter", "=", "None", ",", "stop_after", "=", "None", ")", ":", "if", "reporter", "is", "None", ":", "reporter", "=", "Counter", "(", ")", "if", "stop_after", "is", "not", "None", ":", "reporter", ...
26.641026
0.000929
def extract_paths(self, paths, ignore_nopath): """ Extract the given paths from the domain Attempt to extract all files defined in ``paths`` with the method defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`, if it fails, and `guestfs` is available it will try ex...
[ "def", "extract_paths", "(", "self", ",", "paths", ",", "ignore_nopath", ")", ":", "try", ":", "super", "(", ")", ".", "extract_paths", "(", "paths", "=", "paths", ",", "ignore_nopath", "=", "ignore_nopath", ",", ")", "except", "ExtractPathError", "as", "e...
33.891892
0.00155
def _download_mlu_data(tmp_dir, data_dir): """Downloads and extracts the dataset. Args: tmp_dir: temp directory to download and extract the dataset data_dir: The base directory where data and vocab files are stored. Returns: tmp_dir: temp directory containing the raw data. """ if not tf.gfile.Ex...
[ "def", "_download_mlu_data", "(", "tmp_dir", ",", "data_dir", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "data_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "data_dir", ")", "filename", "=", "os", ".", "path", ".", "ba...
32.192308
0.011601
def symbolic_part(z, s): r"""Get the real or imaginary part of a complex symbol.""" if s == 1: return symre(z) elif s == -1: return symim(z) elif s == 0: return z
[ "def", "symbolic_part", "(", "z", ",", "s", ")", ":", "if", "s", "==", "1", ":", "return", "symre", "(", "z", ")", "elif", "s", "==", "-", "1", ":", "return", "symim", "(", "z", ")", "elif", "s", "==", "0", ":", "return", "z" ]
34.8
0.022472
def print_vessel_errors(retdict): """ <Purpose> Prints out any errors that occurred while performing an action on vessels, in a human readable way. Errors will be printed out in the following format: description [reason] Affected vessels: nodelist To define a new error, add the following e...
[ "def", "print_vessel_errors", "(", "retdict", ")", ":", "ERROR_RESPONSES", "=", "{", "\"Node Manager error 'Insufficient Permissions'\"", ":", "{", "'error'", ":", "\"You lack sufficient permissions to perform this action.\"", ",", "'reason'", ":", "\"Did you release the resource...
35.838235
0.009183
def user_loc_string_to_value(axis_tag, user_loc): """Go from Glyphs UI strings to user space location. Returns None if the string is invalid. >>> user_loc_string_to_value('wght', 'ExtraLight') 200 >>> user_loc_string_to_value('wdth', 'SemiCondensed') 87.5 >>> user_loc_string_to_value('wdth'...
[ "def", "user_loc_string_to_value", "(", "axis_tag", ",", "user_loc", ")", ":", "if", "axis_tag", "==", "\"wght\"", ":", "try", ":", "value", "=", "_nospace_lookup", "(", "WEIGHT_CODES", ",", "user_loc", ")", "except", "KeyError", ":", "return", "None", "return...
33.2
0.001171
def range_distance(a, b, distmode='ss'): """ Returns the distance between two ranges. distmode is ss, se, es, ee and sets the place on read one and two to measure the distance (s = start, e = end) >>> range_distance(("1", 30, 45, '+'), ("1", 45, 55, '+')) (26, '++') >>> range_distanc...
[ "def", "range_distance", "(", "a", ",", "b", ",", "distmode", "=", "'ss'", ")", ":", "assert", "distmode", "in", "(", "'ss'", ",", "'ee'", ")", "a_chr", ",", "a_min", ",", "a_max", ",", "a_strand", "=", "a", "b_chr", ",", "b_min", ",", "b_max", ","...
30.3
0.001599
def Nu_vertical_cylinder_Griffiths_Davis_Morgan(Pr, Gr, turbulent=None): r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < R...
[ "def", "Nu_vertical_cylinder_Griffiths_Davis_Morgan", "(", "Pr", ",", "Gr", ",", "turbulent", "=", "None", ")", ":", "Ra", "=", "Pr", "*", "Gr", "if", "turbulent", "or", "(", "Ra", ">", "1E9", "and", "turbulent", "is", "None", ")", ":", "Nu", "=", "0.0...
34.368421
0.001985
def has_context_with(state, incorrect_msg, exact_names): """When dispatched on with statements, has_context loops over each context manager. Note: This is to allow people to call has_context on the with statement, rather than having to manually loop over each context manager. e.g. Ex().che...
[ "def", "has_context_with", "(", "state", ",", "incorrect_msg", ",", "exact_names", ")", ":", "for", "i", "in", "range", "(", "len", "(", "state", ".", "solution_parts", "[", "\"context\"", "]", ")", ")", ":", "ctxt_state", "=", "check_part_index", "(", "st...
45.285714
0.009274
def reshape_like(a, b): """Reshapes a to match the shape of b in all but the last dimension.""" ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a)[-1:]], 0)) if not tf.executing_eagerly(): ret.set_shape(b.get_shape().as_list()[:-1] + a.get_shape().as_list()[-1:]) return ret
[ "def", "reshape_like", "(", "a", ",", "b", ")", ":", "ret", "=", "tf", ".", "reshape", "(", "a", ",", "tf", ".", "concat", "(", "[", "tf", ".", "shape", "(", "b", ")", "[", ":", "-", "1", "]", ",", "tf", ".", "shape", "(", "a", ")", "[", ...
48.5
0.016892
def find_config_files(self): """Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions). There are three possible config file...
[ "def", "find_config_files", "(", "self", ")", ":", "files", "=", "[", "]", "check_environ", "(", ")", "# Where to look for the system-wide Distutils config file", "sys_dir", "=", "os", ".", "path", ".", "dirname", "(", "sys", ".", "modules", "[", "'distutils'", ...
32.788462
0.000569
def pip_uninstall(package, **options): """Uninstall a python package""" command = ["uninstall", "-q", "-y"] available_options = ('proxy', 'log', ) for option in parse_options(options, available_options): command.append(option) if isinstance(package, list): command.extend(package) ...
[ "def", "pip_uninstall", "(", "package", ",", "*", "*", "options", ")", ":", "command", "=", "[", "\"uninstall\"", ",", "\"-q\"", ",", "\"-y\"", "]", "available_options", "=", "(", "'proxy'", ",", "'log'", ",", ")", "for", "option", "in", "parse_options", ...
31.625
0.001919
def kde(self, term, bandwidth=2000, samples=1000, kernel='gaussian'): """ Estimate the kernel density of the instances of term in the text. Args: term (str): A stemmed term. bandwidth (int): The kernel bandwidth. samples (int): The number of evenly-spaced sa...
[ "def", "kde", "(", "self", ",", "term", ",", "bandwidth", "=", "2000", ",", "samples", "=", "1000", ",", "kernel", "=", "'gaussian'", ")", ":", "# Get the offsets of the term instances.", "terms", "=", "np", ".", "array", "(", "self", ".", "terms", "[", ...
34.703704
0.002077
def generate(env): """ Add builders and construction variables for the Doxygen tool. This is currently for Doxygen 1.4.6. """ doxyfile_scanner = env.Scanner( DoxySourceScan, "DoxySourceScan", scan_check = DoxySourceScanCheck, ) import SCons.Builder doxyfile_builder = SCons.Bu...
[ "def", "generate", "(", "env", ")", ":", "doxyfile_scanner", "=", "env", ".", "Scanner", "(", "DoxySourceScan", ",", "\"DoxySourceScan\"", ",", "scan_check", "=", "DoxySourceScanCheck", ",", ")", "import", "SCons", ".", "Builder", "doxyfile_builder", "=", "SCons...
23.62963
0.036145
def ramp_limits(network): """ Add ramping constraints to thermal power plants. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- """ carrier = ['coal', 'biomass', 'gas', 'oil', 'waste', 'lignite', 'urani...
[ "def", "ramp_limits", "(", "network", ")", ":", "carrier", "=", "[", "'coal'", ",", "'biomass'", ",", "'gas'", ",", "'oil'", ",", "'waste'", ",", "'lignite'", ",", "'uranium'", ",", "'geothermal'", "]", "data", "=", "{", "'start_up_cost'", ":", "[", "77"...
45.243243
0.012865
def _apply_memory_config(config_spec, memory): ''' Sets memory size to the given value config_spec vm.ConfigSpec object memory Memory size and unit ''' log.trace('Configuring virtual machine memory ' 'settings memory=%s', memory) if 'size' in memory and 'unit'...
[ "def", "_apply_memory_config", "(", "config_spec", ",", "memory", ")", ":", "log", ".", "trace", "(", "'Configuring virtual machine memory '", "'settings memory=%s'", ",", "memory", ")", "if", "'size'", "in", "memory", "and", "'unit'", "in", "memory", ":", "try", ...
34.888889
0.001033
def extract_to(self, *, stream=None, fileprefix=''): """Attempt to extract the image directly to a usable image file If possible, the compressed data is extracted and inserted into a compressed image file format without transcoding the compressed content. If this is not possible, the da...
[ "def", "extract_to", "(", "self", ",", "*", ",", "stream", "=", "None", ",", "fileprefix", "=", "''", ")", ":", "if", "bool", "(", "stream", ")", "==", "bool", "(", "fileprefix", ")", ":", "raise", "ValueError", "(", "\"Cannot set both stream and fileprefi...
38.931818
0.001139
def _parse_integrator(int_method): """parse the integrator method to pass to C""" #Pick integrator if int_method.lower() == 'rk4_c': int_method_c= 1 elif int_method.lower() == 'rk6_c': int_method_c= 2 elif int_method.lower() == 'symplec4_c': int_method_c= 3 elif int_metho...
[ "def", "_parse_integrator", "(", "int_method", ")", ":", "#Pick integrator", "if", "int_method", ".", "lower", "(", ")", "==", "'rk4_c'", ":", "int_method_c", "=", "1", "elif", "int_method", ".", "lower", "(", ")", "==", "'rk6_c'", ":", "int_method_c", "=", ...
30.277778
0.016014
def get(self, chargeback_id, **params): """Verify the chargeback ID and retrieve the chargeback from the API.""" if not chargeback_id or not chargeback_id.startswith(self.RESOURCE_ID_PREFIX): raise IdentifierError( "Invalid chargeback ID: '{id}'. A chargeback ID should start ...
[ "def", "get", "(", "self", ",", "chargeback_id", ",", "*", "*", "params", ")", ":", "if", "not", "chargeback_id", "or", "not", "chargeback_id", ".", "startswith", "(", "self", ".", "RESOURCE_ID_PREFIX", ")", ":", "raise", "IdentifierError", "(", "\"Invalid c...
61.375
0.01004
def get_email_templates(self, params=None): """ Get all e-mail templates This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param params: search params :return: list """...
[ "def", "get_email_templates", "(", "self", ",", "params", "=", "None", ")", ":", "if", "not", "params", ":", "params", "=", "{", "}", "return", "self", ".", "_iterate_through_pages", "(", "self", ".", "get_email_templates_per_page", ",", "resource", "=", "EM...
40.307692
0.009328
def process_casperjs_stdout(stdout): """Parse and digest capture script output. """ for line in stdout.splitlines(): bits = line.split(':', 1) if len(bits) < 2: bits = ('INFO', bits) level, msg = bits if level == 'FATAL': logger.fatal(msg) ...
[ "def", "process_casperjs_stdout", "(", "stdout", ")", ":", "for", "line", "in", "stdout", ".", "splitlines", "(", ")", ":", "bits", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "bits", "=", "...
27.0625
0.002232
def myfoo(i,s, course=['s'],gg=2,fdf=3,**d): """ return course id Keyword arguments, course, -- course object (default None) """ print ('data:',d) if course: print (course) return course.get('id') else: print("No Course!") return None
[ "def", "myfoo", "(", "i", ",", "s", ",", "course", "=", "[", "'s'", "]", ",", "gg", "=", "2", ",", "fdf", "=", "3", ",", "*", "*", "d", ")", ":", "print", "(", "'data:'", ",", "d", ")", "if", "course", ":", "print", "(", "course", ")", "r...
22
0.026846
def group_layout(path, files, **kwargs): """ Make a well layout in chunks of two from a list of files path: str Location to make the well html file files: list of pycbc.workflow.core.Files This list of images to show in order within the well layout html file. Every two are placed on...
[ "def", "group_layout", "(", "path", ",", "files", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "files", ")", ">", "0", ":", "two_column_layout", "(", "path", ",", "list", "(", "grouper", "(", "files", ",", "2", ")", ")", ",", "*", "*", ...
38.363636
0.002315
def p_expression_noteql(self, p): 'expression : expression NEL expression' p[0] = NotEql(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_expression_noteql", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "NotEql", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0"...
42.5
0.011561
def create_enhanced_plugin_builder(compulsory_objects=None, optional_objects=None, other_data=None): """ Creates a plugin builder function suitable to extract some specific objects (either compulsory or optional) and other simpler data ...
[ "def", "create_enhanced_plugin_builder", "(", "compulsory_objects", "=", "None", ",", "optional_objects", "=", "None", ",", "other_data", "=", "None", ")", ":", "from", "invenio_utils", ".", "washers", "import", "wash_urlargd", "def", "plugin_builder", "(", "the_plu...
42.027027
0.000209
def drop_zombies(feed: "Feed") -> "Feed": """ In the given "Feed", drop stops with no stop times, trips with no stop times, shapes with no trips, routes with no trips, and services with no trips, in that order. Return the resulting "Feed". """ feed = feed.copy() # Drop stops of location...
[ "def", "drop_zombies", "(", "feed", ":", "\"Feed\"", ")", "->", "\"Feed\"", ":", "feed", "=", "feed", ".", "copy", "(", ")", "# Drop stops of location type 0 that lack stop times", "ids", "=", "feed", ".", "stop_times", "[", "\"stop_id\"", "]", ".", "unique", ...
30.348837
0.000742
def from_datafile(hash_, path='./', ignore_timestamps=False, mode='r'): """Load simulation from disk trajectories and (when present) timestamps. """ path = Path(path) assert path.exists() file_traj = ParticlesSimulation.datafile_from_hash( hash_, prefix=ParticlesSimu...
[ "def", "from_datafile", "(", "hash_", ",", "path", "=", "'./'", ",", "ignore_timestamps", "=", "False", ",", "mode", "=", "'r'", ")", ":", "path", "=", "Path", "(", "path", ")", "assert", "path", ".", "exists", "(", ")", "file_traj", "=", "ParticlesSim...
43.454545
0.001535
def get_key(self, compressed=None): """Get the hex-encoded key. :param compressed: False if you want a standard 65 Byte key (the most standard option). True if you want the compressed 33 Byte form. Defaults to None, which in turn uses the self.compressed attribute. :type...
[ "def", "get_key", "(", "self", ",", "compressed", "=", "None", ")", ":", "if", "compressed", "is", "None", ":", "compressed", "=", "self", ".", "compressed", "if", "compressed", ":", "parity", "=", "2", "+", "(", "self", ".", "y", "&", "1", ")", "#...
39
0.001352
def first_address(self, skip_network_address=True): """ Return the first IP address of this network :param skip_network_address: this flag specifies whether this function returns address of the network \ or returns address that follows address of the network (address, that a host could have) :return: WIPV4Addr...
[ "def", "first_address", "(", "self", ",", "skip_network_address", "=", "True", ")", ":", "bin_address", "=", "self", ".", "__address", ".", "bin_address", "(", ")", "bin_address_length", "=", "len", "(", "bin_address", ")", "if", "self", ".", "__mask", ">", ...
35.210526
0.026201
def time_cache(time_add_setting): """ This decorator works as follows: Call it with a setting and after that use the function with a callable that returns the key. But: This function is only called if the key is not available. After a certain amount of time (`time_add_setting`) the cache is invalid. ...
[ "def", "time_cache", "(", "time_add_setting", ")", ":", "def", "_temp", "(", "key_func", ")", ":", "dct", "=", "{", "}", "_time_caches", ".", "append", "(", "dct", ")", "def", "wrapper", "(", "optional_callable", ",", "*", "args", ",", "*", "*", "kwarg...
37.416667
0.001086
def is_valid_ipv4_prefix(ipv4_prefix): """Returns True if *ipv4_prefix* is a valid prefix with mask. Samples: - valid prefix: 1.1.1.0/32, 244.244.244.1/10 - invalid prefix: 255.2.2.2/2, 2.2.2/22, etc. """ if not isinstance(ipv4_prefix, str): return False tokens = ipv4_prefi...
[ "def", "is_valid_ipv4_prefix", "(", "ipv4_prefix", ")", ":", "if", "not", "isinstance", "(", "ipv4_prefix", ",", "str", ")", ":", "return", "False", "tokens", "=", "ipv4_prefix", ".", "split", "(", "'/'", ")", "if", "len", "(", "tokens", ")", "!=", "2", ...
29.8125
0.002033
def polynomial2bezier(poly): """Converts a cubic or lower order Polynomial object (or a sequence of coefficients) to a CubicBezier, QuadraticBezier, or Line object as appropriate.""" if isinstance(poly, poly1d): c = poly.coeffs else: c = poly order = len(c)-1 if order == 3: ...
[ "def", "polynomial2bezier", "(", "poly", ")", ":", "if", "isinstance", "(", "poly", ",", "poly1d", ")", ":", "c", "=", "poly", ".", "coeffs", "else", ":", "c", "=", "poly", "order", "=", "len", "(", "c", ")", "-", "1", "if", "order", "==", "3", ...
36.2
0.001346
def pitch_shift(y, sr, n_steps, rbargs=None): '''Apply a pitch shift to an audio time series. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` n_steps : float Shift by `n_step...
[ "def", "pitch_shift", "(", "y", ",", "sr", ",", "n_steps", ",", "rbargs", "=", "None", ")", ":", "if", "n_steps", "==", "0", ":", "return", "y", "if", "rbargs", "is", "None", ":", "rbargs", "=", "dict", "(", ")", "rbargs", ".", "setdefault", "(", ...
19.558824
0.001433
def run_step(context): """Set new context keys from formatting expressions with substitutions. Context is a dictionary or dictionary-like. context['contextSetf'] must exist. It's a dictionary. Will iterate context['contextSetf'] and save the values as new keys to the context. For example, say ...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'contextSetf'", ",", "caller", "=", "__name__", ")", "for", "k", ",", "v", "in", "context", "[", "'con...
30.939394
0.00095
def registerUpgrader(upgrader, typeName, oldVersion, newVersion): """ Register a callable which can perform a schema upgrade between two particular versions. @param upgrader: A one-argument callable which will upgrade an object. It is invoked with an instance of the old version of the object. ...
[ "def", "registerUpgrader", "(", "upgrader", ",", "typeName", ",", "oldVersion", ",", "newVersion", ")", ":", "# assert (typeName, oldVersion, newVersion) not in _upgradeRegistry, \"duplicate upgrader\"", "# ^ this makes the tests blow up so it's just disabled for now; perhaps we", "# sho...
53.166667
0.002053
def ReadClientPostingLists(self, keywords): """Looks up all clients associated with any of the given keywords. Args: keywords: A list of keywords we are interested in. Returns: A dict mapping each keyword to a list of matching clients. """ start_time, filtered_keywords = self._Analyze...
[ "def", "ReadClientPostingLists", "(", "self", ",", "keywords", ")", ":", "start_time", ",", "filtered_keywords", "=", "self", ".", "_AnalyzeKeywords", "(", "keywords", ")", "return", "data_store", ".", "REL_DB", ".", "ListClientsForKeywords", "(", "filtered_keywords...
30.642857
0.002262
def set(self, n=None, ftype=None, colfac=None, lmfac=None, fid=0): """Set selected properties of the fitserver instance. All unset properties remain the same (in the :meth:`init` method all properties are (re-)initialized). Like in the constructor, the number of unknowns to be solved fo...
[ "def", "set", "(", "self", ",", "n", "=", "None", ",", "ftype", "=", "None", ",", "colfac", "=", "None", ",", "lmfac", "=", "None", ",", "fid", "=", "0", ")", ":", "self", ".", "_checkid", "(", "fid", ")", "if", "ftype", "is", "None", ":", "f...
38.431818
0.001153
def getCategoryContent(self, category, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None): """ Return items for a particular category """ return self._getFeedContent(category.fetchUrl, excludeRead, continuation, loadLimit, since, until)
[ "def", "getCategoryContent", "(", "self", ",", "category", ",", "excludeRead", "=", "False", ",", "continuation", "=", "None", ",", "loadLimit", "=", "20", ",", "since", "=", "None", ",", "until", "=", "None", ")", ":", "return", "self", ".", "_getFeedCo...
57.8
0.013652
def download_observations(observer_code): """ Downloads all variable star observations by a given observer. Performs a series of HTTP requests to AAVSO's WebObs search and downloads the results page by page. Each page is then passed to :py:class:`~pyaavso.parsers.webobs.WebObsResultsParser` and par...
[ "def", "download_observations", "(", "observer_code", ")", ":", "page_number", "=", "1", "observations", "=", "[", "]", "while", "True", ":", "logger", ".", "info", "(", "'Downloading page %d...'", ",", "page_number", ")", "response", "=", "requests", ".", "ge...
37.407407
0.000965
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Flexbox(self.get_context(), None, d.style)
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "Flexbox", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", ")" ]
28
0.011561
def disconnecting_interfaces(self, interfaces, **kwargs): """ Method to remove the link between interfaces. :param interfaces: List of ids. :return: 200 OK. """ url = 'api/v3/connections/' + str(interfaces[0]) + '/' + str(interfaces[1]) + '/' return super(ApiInt...
[ "def", "disconnecting_interfaces", "(", "self", ",", "interfaces", ",", "*", "*", "kwargs", ")", ":", "url", "=", "'api/v3/connections/'", "+", "str", "(", "interfaces", "[", "0", "]", ")", "+", "'/'", "+", "str", "(", "interfaces", "[", "1", "]", ")",...
36.9
0.010582
def stop_event(self, event_type): """ Stop dispatching the given event. It is not an error to attempt to stop an event that was never started, the request will just be silently ignored. """ if event_type in self.__timers: pyglet.clock.unschedule(self.__timer...
[ "def", "stop_event", "(", "self", ",", "event_type", ")", ":", "if", "event_type", "in", "self", ".", "__timers", ":", "pyglet", ".", "clock", ".", "unschedule", "(", "self", ".", "__timers", "[", "event_type", "]", ")" ]
36.222222
0.008982
def damping(self): """Strain-compatible damping.""" try: value = self._damping.value except AttributeError: value = self._damping return value
[ "def", "damping", "(", "self", ")", ":", "try", ":", "value", "=", "self", ".", "_damping", ".", "value", "except", "AttributeError", ":", "value", "=", "self", ".", "_damping", "return", "value" ]
27.428571
0.010101
def fit(self, X, y): """Fits the given model to the data and labels provided. Parameters: ----------- X : matrix, shape (n_samples, n_features) The samples, the train data. y : vector, shape (n_samples,) The target labels. Returns: ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", "=", "np", ".", "array", "(", "X", ",", "dtype", "=", "np", ".", "float32", ")", "y", "=", "np", ".", "array", "(", "y", ",", "dtype", "=", "np", ".", "float32", ")", "assert", ...
24.090909
0.009074
def unit_doomed(unit=None): """Determines if the unit is being removed from the model Requires Juju 2.4.1. :param unit: string unit name, defaults to local_unit :side effect: calls goal_state :side effect: calls local_unit :side effect: calls has_juju_version :return: True if the unit is b...
[ "def", "unit_doomed", "(", "unit", "=", "None", ")", ":", "if", "not", "has_juju_version", "(", "\"2.4.1\"", ")", ":", "# We cannot risk blindly returning False for 'we don't know',", "# because that could cause data loss; if call sites don't", "# need an accurate answer, they like...
38.178571
0.000912
def _output_result(cnf, outpath, otype, inpaths, itype, extra_opts=None): """ :param cnf: Configuration object to print out :param outpath: Output file path or None :param otype: Output type or None :param inpaths: List of input file paths :param itype: Input type or None ...
[ "def", "_output_result", "(", "cnf", ",", "outpath", ",", "otype", ",", "inpaths", ",", "itype", ",", "extra_opts", "=", "None", ")", ":", "fmsg", "=", "(", "\"Uknown file type and cannot detect appropriate backend \"", "\"from its extension, '%s'\"", ")", "if", "no...
37.954545
0.001168
def unfollow(ctx, nick): """Remove an existing source from your followings.""" source = ctx.obj['conf'].get_source_by_nick(nick) try: with Cache.discover() as cache: cache.remove_tweets(source.url) except OSError as e: logger.debug(e) ret_val = ctx.obj['conf'].remove_so...
[ "def", "unfollow", "(", "ctx", ",", "nick", ")", ":", "source", "=", "ctx", ".", "obj", "[", "'conf'", "]", ".", "get_source_by_nick", "(", "nick", ")", "try", ":", "with", "Cache", ".", "discover", "(", ")", "as", "cache", ":", "cache", ".", "remo...
32.470588
0.001761
def _init_values(self, context=None): """Retrieve field values from the server. May be used to restore the original values in the purpose to cancel all changes made. """ if context is None: context = self.env.context # Get basic fields (no relational ones) ...
[ "def", "_init_values", "(", "self", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "self", ".", "env", ".", "context", "# Get basic fields (no relational ones)", "basic_fields", "=", "[", "]", "for", "field_name", ...
43.111111
0.00126
def to_timezone(dt, timezone): """ Return an aware datetime which is ``dt`` converted to ``timezone``. If ``dt`` is naive, it is assumed to be UTC. For example, if ``dt`` is "06:00 UTC+0000" and ``timezone`` is "EDT-0400", then the result will be "02:00 EDT-0400". This method follows the guid...
[ "def", "to_timezone", "(", "dt", ",", "timezone", ")", ":", "if", "dt", ".", "tzinfo", "is", "None", ":", "dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "_UTC", ")", "return", "timezone", ".", "normalize", "(", "dt", ".", "astimezone", "(", "...
33.642857
0.002066
def export_csv(self, path, idx=None, header=None, formatted=False, sort_idx=True, fmt='%.18e'): """ Export to a csv file Parameters ---------- path : str path of the csv file to save idx : None or array-like, optional the indice...
[ "def", "export_csv", "(", "self", ",", "path", ",", "idx", "=", "None", ",", "header", "=", "None", ",", "formatted", "=", "False", ",", "sort_idx", "=", "True", ",", "fmt", "=", "'%.18e'", ")", ":", "if", "not", "idx", ":", "idx", "=", "self", "...
33.371429
0.002496
def verify(self, egg_path, gpg_key=constants.pub_gpg_path): """ Verifies the GPG signature of the egg. The signature is assumed to be in the same directory as the egg and named the same as the egg except with an additional ".asc" extension. returns (dict): {'gpg...
[ "def", "verify", "(", "self", ",", "egg_path", ",", "gpg_key", "=", "constants", ".", "pub_gpg_path", ")", ":", "# check if the provided files (egg and gpg) actually exist", "if", "egg_path", "and", "not", "os", ".", "path", ".", "isfile", "(", "egg_path", ")", ...
44.672727
0.001593
def dataset_search(q=None, type=None, keyword=None, owningOrg=None, publishingOrg=None, hostingOrg=None, decade=None, publishingCountry = None, facet = None, facetMincount=None, facetMultiselect = None, hl = False, limit = 100, offset = None, **kwargs): ''' Full text search across all datasets. Results are ordere...
[ "def", "dataset_search", "(", "q", "=", "None", ",", "type", "=", "None", ",", "keyword", "=", "None", ",", "owningOrg", "=", "None", ",", "publishingOrg", "=", "None", ",", "hostingOrg", "=", "None", ",", "decade", "=", "None", ",", "publishingCountry",...
49.115044
0.027552
def view(self): """Print package description by repository """ print("") # new line at start description, count = "", 0 if self.repo == "sbo": description = SBoGrep(self.name).description() else: PACKAGES_TXT = Utils().read_file(self.lib) ...
[ "def", "view", "(", "self", ")", ":", "print", "(", "\"\"", ")", "# new line at start", "description", ",", "count", "=", "\"\"", ",", "0", "if", "self", ".", "repo", "==", "\"sbo\"", ":", "description", "=", "SBoGrep", "(", "self", ".", "name", ")", ...
38.869565
0.002183
def register_to_openmath(self, py_class, converter): """Register a conversion from Python to OpenMath :param py_class: A Python class the conversion is attached to, or None :type py_class: None, type :param converter: A conversion function or an OpenMath object :type converter:...
[ "def", "register_to_openmath", "(", "self", ",", "py_class", ",", "converter", ")", ":", "if", "py_class", "is", "not", "None", "and", "not", "isclass", "(", "py_class", ")", ":", "raise", "TypeError", "(", "'Expected class, found %r'", "%", "py_class", ")", ...
50.413793
0.002013
def to_dict(self): """ convert the fields of the object into a dictionnary """ # all the attibutes defined by PKCS#11 all_attributes = PyKCS11.CKA.keys() # only use the integer values and not the strings like 'CKM_RSA_PKCS' all_attributes = [attr for attr in all_...
[ "def", "to_dict", "(", "self", ")", ":", "# all the attibutes defined by PKCS#11", "all_attributes", "=", "PyKCS11", ".", "CKA", ".", "keys", "(", ")", "# only use the integer values and not the strings like 'CKM_RSA_PKCS'", "all_attributes", "=", "[", "attr", "for", "att...
36.555556
0.001974
def mergeConfigObj(configObj, inputDict): """ Merge the inputDict values into an existing given configObj instance. The inputDict is a "flat" dict - it has no sections/sub-sections. The configObj may have sub-sections nested to any depth. This will raise a DuplicateKeyError if one of the inputDict key...
[ "def", "mergeConfigObj", "(", "configObj", ",", "inputDict", ")", ":", "# Expanded upon Warren's version in astrodrizzle", "# Verify that all inputDict keys in configObj are unique within configObj", "for", "key", "in", "inputDict", ":", "if", "countKey", "(", "configObj", ",",...
50.533333
0.001295
def handle_put_user(self, req): """Handles the PUT v2/<account>/<user> call for adding a user to an account. X-Auth-User-Key represents the user's key (url encoded), - OR - X-Auth-User-Key-Hash represents the user's hashed key (url encoded), X-Auth-User-Admin may be set ...
[ "def", "handle_put_user", "(", "self", ",", "req", ")", ":", "# Validate path info", "account", "=", "req", ".", "path_info_pop", "(", ")", "user", "=", "req", ".", "path_info_pop", "(", ")", "key", "=", "unquote", "(", "req", ".", "headers", ".", "get",...
44.337349
0.001063
def _maybe_deserialize_body(self): """Attempt to deserialize the message body based upon the content-type. :rtype: mixed """ if not self.content_type: return self._message_body ct = headers.parse_content_type(self.content_type) key = '{}/{}'.format(ct.conten...
[ "def", "_maybe_deserialize_body", "(", "self", ")", ":", "if", "not", "self", ".", "content_type", ":", "return", "self", ".", "_message_body", "ct", "=", "headers", ".", "parse_content_type", "(", "self", ".", "content_type", ")", "key", "=", "'{}/{}'", "."...
44.5
0.001833
def nancorr(a, b, method='pearson', min_periods=None): """ a, b: ndarrays """ if len(a) != len(b): raise AssertionError('Operands to nancorr must have same size') if min_periods is None: min_periods = 1 valid = notna(a) & notna(b) if not valid.all(): a = a[valid] ...
[ "def", "nancorr", "(", "a", ",", "b", ",", "method", "=", "'pearson'", ",", "min_periods", "=", "None", ")", ":", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "raise", "AssertionError", "(", "'Operands to nancorr must have same size'", ")...
21.05
0.002273
def bounds_corners(self): """ A list of points that represent the corners of the AABB of every geometry in the scene. This can be useful if you want to take the AABB in a specific frame. Returns ----------- corners: (n, 3) float, points in space ...
[ "def", "bounds_corners", "(", "self", ")", ":", "# the saved corners of each instance", "corners_inst", "=", "[", "]", "# (n, 3) float corners of each geometry", "corners_geom", "=", "{", "k", ":", "bounds_module", ".", "corners", "(", "v", ".", "bounds", ")", "for"...
36.735294
0.00156
def do_template(self,args): """Print the template for the current stack. template -h for detailed help""" parser = CommandArgumentParser("template") args = vars(parser.parse_args(args)) print "reading template for stack." rawStack = self.wrappedStack['rawStack'] template...
[ "def", "do_template", "(", "self", ",", "args", ")", ":", "parser", "=", "CommandArgumentParser", "(", "\"template\"", ")", "args", "=", "vars", "(", "parser", ".", "parse_args", "(", "args", ")", ")", "print", "\"reading template for stack.\"", "rawStack", "=...
47.333333
0.011521
def inplace_filter(func, sequence): """ Like Python's filter() builtin, but modifies the sequence in place. Example: >>> l = range(10) >>> inplace_filter(lambda x: x > 5, l) >>> l [6, 7, 8, 9] Performance considerations: the function iterates over the sequence, shuffling surviving members down and deleting...
[ "def", "inplace_filter", "(", "func", ",", "sequence", ")", ":", "target", "=", "0", "for", "source", "in", "xrange", "(", "len", "(", "sequence", ")", ")", ":", "if", "func", "(", "sequence", "[", "source", "]", ")", ":", "sequence", "[", "target", ...
26.826087
0.031299
def artboards(src_path): ''' Return artboards as a flat list ''' pages = list_artboards(src_path) artboards = [] for page in pages: artboards.extend(page.artboards) return artboards
[ "def", "artboards", "(", "src_path", ")", ":", "pages", "=", "list_artboards", "(", "src_path", ")", "artboards", "=", "[", "]", "for", "page", "in", "pages", ":", "artboards", ".", "extend", "(", "page", ".", "artboards", ")", "return", "artboards" ]
27
0.030769
def sentiment(text): """ Returns a float for sentiment strength based on the input text. Positive values are positive valence, negative value are negative valence. """ sentiment.valence_dict = load_valence_dict() if sentiment.valence_dict is None else sentiment_valence_dict wordsAndEmotico...
[ "def", "sentiment", "(", "text", ")", ":", "sentiment", ".", "valence_dict", "=", "load_valence_dict", "(", ")", "if", "sentiment", ".", "valence_dict", "is", "None", "else", "sentiment_valence_dict", "wordsAndEmoticons", "=", "str", "(", "text", ")", ".", "sp...
55.483146
0.012401
def frame(self, frame): """ Return a path go the given frame in the sequence. Integer or string digits are treated as a frame number and padding is applied, all other values are passed though. Examples: >>> seq.frame(1) /foo/bar.0001.exr >>> ...
[ "def", "frame", "(", "self", ",", "frame", ")", ":", "try", ":", "zframe", "=", "str", "(", "int", "(", "frame", ")", ")", ".", "zfill", "(", "self", ".", "_zfill", ")", "except", "ValueError", ":", "zframe", "=", "frame", "# There may have been no pla...
27.8125
0.002172
def solveFashion(solution_next,DiscFac,conformUtilityFunc,punk_utility,jock_utility,switchcost_J2P,switchcost_P2J,pGrid,pEvolution,pref_shock_mag): ''' Solves a single period of the fashion victim model. Parameters ---------- solution_next: FashionSolution A representation of the solution t...
[ "def", "solveFashion", "(", "solution_next", ",", "DiscFac", ",", "conformUtilityFunc", ",", "punk_utility", ",", "jock_utility", ",", "switchcost_J2P", ",", "switchcost_P2J", ",", "pGrid", ",", "pEvolution", ",", "pref_shock_mag", ")", ":", "# Unpack next period's so...
44.25
0.010263
def is_choked_turbulent_l(dP, P1, Psat, FF, FL=None, FLP=None, FP=None): r'''Calculates if a liquid flow in IEC 60534 calculations is critical or not, for use in IEC 60534 liquid valve sizing calculations. Either FL may be provided or FLP and FP, depending on the calculation process. .. math:: ...
[ "def", "is_choked_turbulent_l", "(", "dP", ",", "P1", ",", "Psat", ",", "FF", ",", "FL", "=", "None", ",", "FLP", "=", "None", ",", "FP", "=", "None", ")", ":", "if", "FLP", "and", "FP", ":", "return", "dP", ">=", "(", "FLP", "/", "FP", ")", ...
31.192308
0.001195
def has_add_permission(self, request): """ Returns True if the requesting user is allowed to add an object, False otherwise. """ perm_string = '%s.add_%s' % (self.model._meta.app_label, self.model._meta.object_name.lower() ) return request.user.has_perm(perm_s...
[ "def", "has_add_permission", "(", "self", ",", "request", ")", ":", "perm_string", "=", "'%s.add_%s'", "%", "(", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "object_name", ".", "lower", "(", ")", ...
39.875
0.015337
def mv(i): """ Input: { (repo_uoa) - repo UOA module_uoa - module UOA data_uoa - data UOA xcids[0] - {'repo_uoa', 'module_uoa', 'data_uoa'} - new CID or (new_repo_uoa) - new repo UOA (new_...
[ "def", "mv", "(", "i", ")", ":", "# Check if global writing is allowed", "r", "=", "check_writing", "(", "{", "'delete'", ":", "'yes'", "}", ")", "if", "r", "[", "'return'", "]", ">", "0", ":", "return", "r", "# Check if wild cards", "ruoa", "=", "i", "....
26.5
0.03169
def sumexp_stable(data): """Compute the sum of exponents for a list of samples Parameters ---------- data : array, shape=[features, samples] A data array containing samples. Returns ------- result_sum : array, shape=[samples,] The sum of exponents for each sample divided...
[ "def", "sumexp_stable", "(", "data", ")", ":", "max_value", "=", "data", ".", "max", "(", "axis", "=", "0", ")", "result_exp", "=", "np", ".", "exp", "(", "data", "-", "max_value", ")", "result_sum", "=", "np", ".", "sum", "(", "result_exp", ",", "...
28.441176
0.001
def list_related(self, request, pk=None, field_name=None): """Fetch related object(s), as if sideloaded (used to support link objects). This method gets mapped to `/<resource>/<pk>/<field_name>/` by DynamicRouter for all DynamicRelationField fields. Generally, this method probab...
[ "def", "list_related", "(", "self", ",", "request", ",", "pk", "=", "None", ",", "field_name", "=", "None", ")", ":", "# Explicitly disable support filtering. Applying filters to this", "# endpoint would require us to pass through sideload filters, which", "# can have unintended ...
43.416667
0.000751
def render_highstate(self, matches): ''' Gather the state files and render them into a single unified salt high data structure. ''' highstate = self.building_highstate all_errors = [] mods = set() statefiles = [] for saltenv, states in six.iteritem...
[ "def", "render_highstate", "(", "self", ",", "matches", ")", ":", "highstate", "=", "self", ".", "building_highstate", "all_errors", "=", "[", "]", "mods", "=", "set", "(", ")", "statefiles", "=", "[", "]", "for", "saltenv", ",", "states", "in", "six", ...
45.666667
0.001787
def Setup(self, event=None): """set up figure for printing. Using the standard wx Printer Setup Dialog. """ if hasattr(self, 'printerData'): data = wx.PageSetupDialogData() data.SetPrintData(self.printerData) else: data = wx.PageSetupDialogData() ...
[ "def", "Setup", "(", "self", ",", "event", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'printerData'", ")", ":", "data", "=", "wx", ".", "PageSetupDialogData", "(", ")", "data", ".", "SetPrintData", "(", "self", ".", "printerData", ")", ...
34.15
0.008547
def unset_env(): """Remove coverage info from env.""" os.environ.pop('COV_CORE_SOURCE', None) os.environ.pop('COV_CORE_DATA_FILE', None) os.environ.pop('COV_CORE_CONFIG', None)
[ "def", "unset_env", "(", ")", ":", "os", ".", "environ", ".", "pop", "(", "'COV_CORE_SOURCE'", ",", "None", ")", "os", ".", "environ", ".", "pop", "(", "'COV_CORE_DATA_FILE'", ",", "None", ")", "os", ".", "environ", ".", "pop", "(", "'COV_CORE_CONFIG'", ...
40.8
0.009615
def where(cond, a, b, use_numexpr=True): """ evaluate the where condition cond on a and b Parameters ---------- cond : a boolean array a : return if cond is True b : return if cond is False use_numexpr : whether to try to use numexpr (default True) """...
[ "def", "where", "(", "cond", ",", "a", ",", "b", ",", "use_numexpr", "=", "True", ")", ":", "if", "use_numexpr", ":", "return", "_where", "(", "cond", ",", "a", ",", "b", ")", "return", "_where_standard", "(", "cond", ",", "a", ",", "b", ")" ]
26.666667
0.002415
def run_create_sm(self, tenant_id, fw_dict, is_fw_virt): """Runs the create State Machine. Goes through every state function until the end or when one state returns failure. """ ret = True serv_obj = self.get_service_obj(tenant_id) state = serv_obj.get_state() ...
[ "def", "run_create_sm", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ")", ":", "ret", "=", "True", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "state", "=", "serv_obj", ".", "get_state", "(", ")", "# Preserv...
42.911765
0.00134
def make_tag(name, attrs, start_end=False): """ Build an HTML tag from the given name and attributes. Arguments: name -- the name of the tag (p, div, etc.) attrs -- a dict of attributes to apply to the tag start_end -- whether this tag should be self-closing """ text = '<' + name if ...
[ "def", "make_tag", "(", "name", ",", "attrs", ",", "start_end", "=", "False", ")", ":", "text", "=", "'<'", "+", "name", "if", "isinstance", "(", "attrs", ",", "dict", ")", ":", "attr_list", "=", "attrs", ".", "items", "(", ")", "elif", "isinstance",...
28.814815
0.001244
def make_dnsentryitem_recordname(dns_name, condition='contains', negate=False, preserve_case=False): """ Create a node for DnsEntryItem/RecordName :return: A IndicatorItem represented as an Element node """ document = 'DnsEntryItem' search = 'DnsEntryItem/RecordName' content_type = 'str...
[ "def", "make_dnsentryitem_recordname", "(", "dns_name", ",", "condition", "=", "'contains'", ",", "negate", "=", "False", ",", "preserve_case", "=", "False", ")", ":", "document", "=", "'DnsEntryItem'", "search", "=", "'DnsEntryItem/RecordName'", "content_type", "="...
41.692308
0.009025