text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def const_variable(name, shape, value, trainable): """ :param name: string :param shape: 1D array :param value: float :return: tf variable """ return tf.get_variable(name, shape, initializer=tf.constant_initializer(value), trainable=trainable)
[ "def", "const_variable", "(", "name", ",", "shape", ",", "value", ",", "trainable", ")", ":", "return", "tf", ".", "get_variable", "(", "name", ",", "shape", ",", "initializer", "=", "tf", ".", "constant_initializer", "(", "value", ")", ",", "trainable", ...
36.5
0.010033
def half_mag_amplitude_ratio2(self, mag, avg): """ Return ratio of amplitude of higher and lower magnitudes. A ratio of amplitude of higher and lower magnitudes than average, considering weights. This ratio, by definition, should be higher for EB than for others. Param...
[ "def", "half_mag_amplitude_ratio2", "(", "self", ",", "mag", ",", "avg", ")", ":", "# For lower (fainter) magnitude than average.", "index", "=", "np", ".", "where", "(", "mag", ">", "avg", ")", "fainter_mag", "=", "mag", "[", "index", "]", "lower_sum", "=", ...
29.25
0.001838
def mach_o_change(path, what, value): """ Replace a given name (what) in any LC_LOAD_DYLIB command found in the given binary with a new name (value), provided it's shorter. """ def do_macho(file, bits, endian): # Read Mach-O header (the magic number is assumed read by the caller) cp...
[ "def", "mach_o_change", "(", "path", ",", "what", ",", "value", ")", ":", "def", "do_macho", "(", "file", ",", "bits", ",", "endian", ")", ":", "# Read Mach-O header (the magic number is assumed read by the caller)", "cputype", ",", "cpusubtype", ",", "filetype", ...
41.701754
0.001233
def stack_pop(self, num_items: int=1, type_hint: str=None) -> Any: # TODO: Needs to be replaced with # `Union[int, bytes, Tuple[Union[int, bytes], ...]]` if done properly """ Pop and return a number of items equal to ``num_items`` from the stack. ``type_hint`` can be either ``'ui...
[ "def", "stack_pop", "(", "self", ",", "num_items", ":", "int", "=", "1", ",", "type_hint", ":", "str", "=", "None", ")", "->", "Any", ":", "# TODO: Needs to be replaced with", "# `Union[int, bytes, Tuple[Union[int, bytes], ...]]` if done properly", "return", "self", "...
48.076923
0.017268
def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. """ data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decima...
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "data", "=", "smart_text", "(", "data", ")", ".", "strip", "(", ")", "if", "len", "(", "data", ")", ">", "self", ".", "MAX_STRING_LENGTH", ":", "self", ".", "fail", "(", "'max_string_lengt...
32.416667
0.002497
def mangle(self, name, x): """ Mangle the name by hashing the I{name} and appending I{x}. @return: the mangled name. """ h = hashlib.md5(name.encode('utf8')).hexdigest() return '%s-%s' % (h, x)
[ "def", "mangle", "(", "self", ",", "name", ",", "x", ")", ":", "h", "=", "hashlib", ".", "md5", "(", "name", ".", "encode", "(", "'utf8'", ")", ")", ".", "hexdigest", "(", ")", "return", "'%s-%s'", "%", "(", "h", ",", "x", ")" ]
33.571429
0.008299
def _fftshift_single(d_g, res_g, ax = 0): """ basic fftshift of an OCLArray shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k] = [N1, N, N2] the we can address each element in the flat buffer by index = i + N2*j + N2*N*k where i = 1 .. N2 j = 1 .. N k = 1 .. N1 ...
[ "def", "_fftshift_single", "(", "d_g", ",", "res_g", ",", "ax", "=", "0", ")", ":", "dtype_kernel_name", "=", "{", "np", ".", "float32", ":", "\"fftshift_1_f\"", ",", "np", ".", "complex64", ":", "\"fftshift_1_c\"", "}", "N", "=", "d_g", ".", "shape", ...
23.918919
0.014115
def close(self): """Close open resources.""" super(RarExtFile, self).close() if self._fd: self._fd.close() self._fd = None
[ "def", "close", "(", "self", ")", ":", "super", "(", "RarExtFile", ",", "self", ")", ".", "close", "(", ")", "if", "self", ".", "_fd", ":", "self", ".", "_fd", ".", "close", "(", ")", "self", ".", "_fd", "=", "None" ]
20.625
0.011628
def add_line(self, window, text, row=None, col=None, attr=None): """ Unicode aware version of curses's built-in addnstr method. Safely draws a line of text on the window starting at position (row, col). Checks the boundaries of the window and cuts off the text if it exceeds the ...
[ "def", "add_line", "(", "self", ",", "window", ",", "text", ",", "row", "=", "None", ",", "col", "=", "None", ",", "attr", "=", "None", ")", ":", "# The following arg combos must be supported to conform with addnstr", "# (window, text)", "# (window, text, attr)", "#...
40.323529
0.001425
def centering_centroid(data, xi, yi, box, nloop=10, toldist=1e-3, maxdist=10.0): ''' returns x, y, background, status, message status is: * 0: not recentering * 1: recentering successful * 2: maximum distance reached * 3: not converged ...
[ "def", "centering_centroid", "(", "data", ",", "xi", ",", "yi", ",", "box", ",", "nloop", "=", "10", ",", "toldist", "=", "1e-3", ",", "maxdist", "=", "10.0", ")", ":", "# Store original center", "cxy", "=", "(", "xi", ",", "yi", ")", "origin", "=", ...
30.5
0.000836
def depth(self, pair, limit=150, ignore_invalid=0): """ This method provides the information about active orders on the pair. :param str or iterable pair: pair (ex. 'btc_usd' or ['btc_usd', 'eth_usd']) :param limit: how many orders should be displayed (150 by default, max 5000) :...
[ "def", "depth", "(", "self", ",", "pair", ",", "limit", "=", "150", ",", "ignore_invalid", "=", "0", ")", ":", "return", "self", ".", "_public_api_call", "(", "'depth'", ",", "pair", "=", "pair", ",", "limit", "=", "limit", ",", "ignore_invalid", "=", ...
59.625
0.010331
def set_transmitters(transmitters, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- transmitters: iterable yielding ints device: str address: str Notes ----- No attempt is m...
[ "def", "set_transmitters", "(", "transmitters", ",", "device", "=", "None", ",", "address", "=", "None", ")", ":", "args", "=", "[", "'set_transmitters'", "]", "+", "[", "str", "(", "i", ")", "for", "i", "in", "transmitters", "]", "_call", "(", "args",...
28.631579
0.001779
def retranslateUi(self): _translate = QtCore.QCoreApplication.translate self.talk= _translate('MainWindow','You are using GeoPyTool ') + version +'\n'+ _translate('MainWindow','released on ') + date + '\n' self.menuFile.setTitle(_translate('MainWindow', u'Data File')) self.menuGeoChem....
[ "def", "retranslateUi", "(", "self", ")", ":", "_translate", "=", "QtCore", ".", "QCoreApplication", ".", "translate", "self", ".", "talk", "=", "_translate", "(", "'MainWindow'", ",", "'You are using GeoPyTool '", ")", "+", "version", "+", "'\\n'", "+", "_tra...
56.25
0.015105
def service_present(name, service_type, description=None, profile=None, **connection_args): ''' Ensure service present in Keystone catalog name The name of the service service_type The type of Openstack Service description (optional) Description of the ...
[ "def", "service_present", "(", "name", ",", "service_type", ",", "description", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result...
32.075
0.000756
def populate_classified_values( unassigned_values, assigned_values, default_classes, list_unique_values, tree_mapping_widget): """Populate lstUniqueValues and treeClasses.from the parameters. :param unassigned_values: List of values that haven't been assigned to a cl...
[ "def", "populate_classified_values", "(", "unassigned_values", ",", "assigned_values", ",", "default_classes", ",", "list_unique_values", ",", "tree_mapping_widget", ")", ":", "# Populate the unique values list", "list_unique_values", ".", "clear", "(", ")", "list_unique_valu...
43.485714
0.000642
def getAggregation(self): """Returns: str : URIRef of the Aggregation entity """ self._check_initialized() return [ o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.Aggregation) ][0]
[ "def", "getAggregation", "(", "self", ")", ":", "self", ".", "_check_initialized", "(", ")", "return", "[", "o", "for", "o", "in", "self", ".", "subjects", "(", "predicate", "=", "rdflib", ".", "RDF", ".", "type", ",", "object", "=", "ORE", ".", "Agg...
24.9
0.011628
def convert_from_latlon_to_utm(points=None, latitudes=None, longitudes=None, false_easting=None, false_northing=None): """Convert latitude and longitude data to UTM as a list of coordinates. ...
[ "def", "convert_from_latlon_to_utm", "(", "points", "=", "None", ",", "latitudes", "=", "None", ",", "longitudes", "=", "None", ",", "false_easting", "=", "None", ",", "false_northing", "=", "None", ")", ":", "old_geo", "=", "Geo_reference", "(", ")", "utm_p...
31.088889
0.002079
def build(self): """Builds the app in the app's environment. Only builds if the build is out-of-date and is non-empty. Builds in 3 stages: requirements, dev requirements, and app. pip is used to install requirements, and setup.py is used to install the app itself. Raise...
[ "def", "build", "(", "self", ")", ":", "if", "self", ".", "exists", ":", "self", ".", "_build", "(", "'requirements'", ",", "self", ".", "requirements_last_modified", ",", "'pip install -U -r %s'", "%", "self", ".", "requirements_file", ")", "try", ":", "sel...
35.361702
0.001171
def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None, fit_cachefile=None, include_prefix=False): ''' Given model name & stan model code/file, compute path to cached stan fit if include_prefix, returns (model_prefix, model_cachefile) '''...
[ "def", "cached_model_file", "(", "model_name", "=", "'anon_model'", ",", "file", "=", "None", ",", "model_code", "=", "None", ",", "cache_dir", "=", "None", ",", "fit_cachefile", "=", "None", ",", "include_prefix", "=", "False", ")", ":", "cache_dir", "=", ...
53.388889
0.008176
def create_account( self, account_name, registrar=None, referrer="1.2.0", referrer_percent=50, owner_key=None, active_key=None, memo_key=None, password=None, additional_owner_keys=[], additional_active_keys=[], additional_ow...
[ "def", "create_account", "(", "self", ",", "account_name", ",", "registrar", "=", "None", ",", "referrer", "=", "\"1.2.0\"", ",", "referrer_percent", "=", "50", ",", "owner_key", "=", "None", ",", "active_key", "=", "None", ",", "memo_key", "=", "None", ",...
41.066667
0.000576
def organization(self): """ | Comment: The ID of the organization associated with this user, in this membership """ if self.api and self.organization_id: return self.api._get_organization(self.organization_id)
[ "def", "organization", "(", "self", ")", ":", "if", "self", ".", "api", "and", "self", ".", "organization_id", ":", "return", "self", ".", "api", ".", "_get_organization", "(", "self", ".", "organization_id", ")" ]
41.5
0.011811
def makeDoubleLinked(dom, parent=None): """ Standard output from `dhtmlparser` is single-linked tree. This will make it double-linked. Args: dom (obj): :class:`.HTMLElement` instance. parent (obj, default None): Don't use this, it is used in recursive call. """ do...
[ "def", "makeDoubleLinked", "(", "dom", ",", "parent", "=", "None", ")", ":", "dom", ".", "parent", "=", "parent", "for", "child", "in", "dom", ".", "childs", ":", "child", ".", "parent", "=", "dom", "makeDoubleLinked", "(", "child", ",", "dom", ")" ]
27.8
0.00232
def requires_pytango(min_version=None, conflicts=(), software_name="Software"): """ Determines if the required PyTango version for the running software is present. If not an exception is thrown. Example usage:: from tango import requires_pytango requires_pytango('7...
[ "def", "requires_pytango", "(", "min_version", "=", "None", ",", "conflicts", "=", "(", ")", ",", "software_name", "=", "\"Software\"", ")", ":", "return", "__requires", "(", "\"pytango\"", ",", "min_version", "=", "min_version", ",", "conflicts", "=", "confli...
35.363636
0.000834
def paging(self): """ Gets the pagination type; compatible with entry.archive(page_type=...) """ if 'date' in self.spec: _, date_span, _ = utils.parse_date(self.spec['date']) return date_span return 'offset'
[ "def", "paging", "(", "self", ")", ":", "if", "'date'", "in", "self", ".", "spec", ":", "_", ",", "date_span", ",", "_", "=", "utils", ".", "parse_date", "(", "self", ".", "spec", "[", "'date'", "]", ")", "return", "date_span", "return", "'offset'" ]
41.666667
0.011765
def removeItem(self, index): """Alias for removeComponent""" self._stim.removeComponent(index.row(), index.column())
[ "def", "removeItem", "(", "self", ",", "index", ")", ":", "self", ".", "_stim", ".", "removeComponent", "(", "index", ".", "row", "(", ")", ",", "index", ".", "column", "(", ")", ")" ]
43.333333
0.015152
def readMNIST(sc, output, format): """Reads/verifies previously created output""" output_images = output + "/images" output_labels = output + "/labels" imageRDD = None labelRDD = None if format == "pickle": imageRDD = sc.pickleFile(output_images) labelRDD = sc.pickleFile(output_labels) elif form...
[ "def", "readMNIST", "(", "sc", ",", "output", ",", "format", ")", ":", "output_images", "=", "output", "+", "\"/images\"", "output_labels", "=", "output", "+", "\"/labels\"", "imageRDD", "=", "None", "labelRDD", "=", "None", "if", "format", "==", "\"pickle\"...
39.296296
0.014719
def _isProtein(self): """ check if blockSizes and scores are in the protein space or not """ last = self.blockCount - 1 return ((self.tEnd == self.tStarts[last] + 3 * self.blockSizes[last]) \ and self.strand == "+") or \ ((self.tStart == self.tSize...
[ "def", "_isProtein", "(", "self", ")", ":", "last", "=", "self", ".", "blockCount", "-", "1", "return", "(", "(", "self", ".", "tEnd", "==", "self", ".", "tStarts", "[", "last", "]", "+", "3", "*", "self", ".", "blockSizes", "[", "last", "]", ")"...
45
0.016949
def add_transition(self, output, probability_func=lambda index: np.ones(len(index), dtype=float), triggered=Trigger.NOT_TRIGGERED): """Builds a transition from this state to the given state. output : State The end state after the transition. ...
[ "def", "add_transition", "(", "self", ",", "output", ",", "probability_func", "=", "lambda", "index", ":", "np", ".", "ones", "(", "len", "(", "index", ")", ",", "dtype", "=", "float", ")", ",", "triggered", "=", "Trigger", ".", "NOT_TRIGGERED", ")", "...
42.363636
0.012605
def parse_emails(emails): """ A function that returns a list of valid email addresses. This function will also convert a single email address into a list of email addresses. None value is also converted into an empty list. """ if isinstance(emails, string_types): emails = [emails] ...
[ "def", "parse_emails", "(", "emails", ")", ":", "if", "isinstance", "(", "emails", ",", "string_types", ")", ":", "emails", "=", "[", "emails", "]", "elif", "emails", "is", "None", ":", "emails", "=", "[", "]", "for", "email", "in", "emails", ":", "t...
27.75
0.001742
def inatoms(self, reverse=False): """Yield the singleton for every non-member.""" if reverse: return filterfalse(self.__and__, reversed(self._atoms)) return filterfalse(self.__and__, self._atoms)
[ "def", "inatoms", "(", "self", ",", "reverse", "=", "False", ")", ":", "if", "reverse", ":", "return", "filterfalse", "(", "self", ".", "__and__", ",", "reversed", "(", "self", ".", "_atoms", ")", ")", "return", "filterfalse", "(", "self", ".", "__and_...
45.4
0.008658
def main(): """Main function creates the cvloop.functions example notebook.""" notebook = { 'cells': [ { 'cell_type': 'markdown', 'metadata': {}, 'source': [ '# cvloop functions\n\n', 'This notebook shows...
[ "def", "main", "(", ")", ":", "notebook", "=", "{", "'cells'", ":", "[", "{", "'cell_type'", ":", "'markdown'", ",", "'metadata'", ":", "{", "}", ",", "'source'", ":", "[", "'# cvloop functions\\n\\n'", ",", "'This notebook shows an overview over all cvloop '", ...
35.403846
0.000529
def with_code(self, code): """ Sets a unique error code. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param code: a unique error code :return: this exception object """ self.code = code if code != None ...
[ "def", "with_code", "(", "self", ",", "code", ")", ":", "self", ".", "code", "=", "code", "if", "code", "!=", "None", "else", "'UNKNOWN'", "self", ".", "name", "=", "code", "return", "self" ]
30.666667
0.010554
def search(self, category, term='', index=0, count=100): """Search for an item in a category. Args: category (str): The search category to use. Standard Sonos search categories are 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not ...
[ "def", "search", "(", "self", ",", "category", ",", "term", "=", "''", ",", "index", "=", "0", ",", "count", "=", "100", ")", ":", "search_category", "=", "self", ".", "_get_search_prefix_map", "(", ")", ".", "get", "(", "category", ",", "None", ")",...
41.125
0.001485
def lv_voltage_deviation(network, mode=None, voltage_levels='mv_lv'): """ Checks for voltage stability issues in LV grids. Parameters ---------- network : :class:`~.grid.network.Network` mode : None or String If None voltage at all nodes in LV grid is checked. If mode is set to ...
[ "def", "lv_voltage_deviation", "(", "network", ",", "mode", "=", "None", ",", "voltage_levels", "=", "'mv_lv'", ")", ":", "crit_nodes", "=", "{", "}", "v_dev_allowed_per_case", "=", "{", "}", "if", "voltage_levels", "==", "'mv_lv'", ":", "offset", "=", "netw...
43.237805
0.000414
def restart_on_change_helper(lambda_f, restart_map, stopstart=False, restart_functions=None): """Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation...
[ "def", "restart_on_change_helper", "(", "lambda_f", ",", "restart_map", ",", "stopstart", "=", "False", ",", "restart_functions", "=", "None", ")", ":", "if", "restart_functions", "is", "None", ":", "restart_functions", "=", "{", "}", "checksums", "=", "{", "p...
44.575758
0.000665
def draw_path(data, path, draw_options=None, simplify=None): """Adds code for drawing an ordinary path in PGFPlots (TikZ). """ # For some reasons, matplotlib sometimes adds void paths which consist of # only one point and have 0 fill opacity. To not let those clutter the # output TeX file, bail out ...
[ "def", "draw_path", "(", "data", ",", "path", ",", "draw_options", "=", "None", ",", "simplify", "=", "None", ")", ":", "# For some reasons, matplotlib sometimes adds void paths which consist of", "# only one point and have 0 fill opacity. To not let those clutter the", "# output...
36.254717
0.000253
def project(self, from_shape, to_shape): """ Project the bounding box onto a differently shaped image. E.g. if the bounding box is on its original image at x1=(10 of 100 pixels) and y1=(20 of 100 pixels) and is projected onto a new image with size (width=200, height=200), its ne...
[ "def", "project", "(", "self", ",", "from_shape", ",", "to_shape", ")", ":", "coords_proj", "=", "project_coords", "(", "[", "(", "self", ".", "x1", ",", "self", ".", "y1", ")", ",", "(", "self", ".", "x2", ",", "self", ".", "y2", ")", "]", ",", ...
35.352941
0.001619
def create_response_pdu(self, data): """ Create response pdu. :param data: A list with 0's and/or 1's. :return: Byte array of at least 3 bytes. """ log.debug('Create single bit response pdu {0}.'.format(data)) bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)] ...
[ "def", "create_response_pdu", "(", "self", ",", "data", ")", ":", "log", ".", "debug", "(", "'Create single bit response pdu {0}.'", ".", "format", "(", "data", ")", ")", "bytes_", "=", "[", "data", "[", "i", ":", "i", "+", "8", "]", "for", "i", "in", ...
48.045455
0.001855
def get_threads(session, query): """ Get one or more threads """ # GET /api/messages/0.1/threads response = make_get_request(session, 'threads', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise ThreadsNo...
[ "def", "get_threads", "(", "session", ",", "query", ")", ":", "# GET /api/messages/0.1/threads", "response", "=", "make_get_request", "(", "session", ",", "'threads'", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", ...
31.266667
0.00207
def apply_delta(op, time_struct, delta): """ Apply a `relativedelta` to a `struct_time` data structure. `op` is an operator function, probably always `add` or `sub`tract to correspond to `a_date + a_delta` and `a_date - a_delta`. This function is required because we cannot use standard `datetime` ...
[ "def", "apply_delta", "(", "op", ",", "time_struct", ",", "delta", ")", ":", "if", "not", "delta", ":", "return", "time_struct", "# No work to do", "try", ":", "dt_result", "=", "op", "(", "datetime", "(", "*", "time_struct", "[", ":", "6", "]", ")", "...
39.918919
0.000661
def _get_flag_value_from_var(flag, var, delim=' '): """ Extract flags from an environment variable. Parameters ---------- flag : str The flag to extract, for example '-I' or '-L' var : str The environment variable to extract the flag from, e.g. CFLAGS or LDFLAGS. delim : str...
[ "def", "_get_flag_value_from_var", "(", "flag", ",", "var", ",", "delim", "=", "' '", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "return", "None", "# Simple input validation", "if", "not", "var", "or", "not", "flag",...
26.320755
0.001382
def get_pg_connection(host, user, port, password, database, ssl={}): """ PostgreSQL connection """ return psycopg2.connect(host=host, user=user, port=port, password=password, dbname=database, ...
[ "def", "get_pg_connection", "(", "host", ",", "user", ",", "port", ",", "password", ",", "database", ",", "ssl", "=", "{", "}", ")", ":", "return", "psycopg2", ".", "connect", "(", "host", "=", "host", ",", "user", "=", "user", ",", "port", "=", "p...
44.923077
0.001678
def get_comparison_methods(): """ makes methods for >, <, =, etc... """ method_list = [] def _register(func): method_list.append(func) return func # Comparison operators for sorting and uniqueness @_register def __lt__(self, other): return compare_instance(op.lt, self, o...
[ "def", "get_comparison_methods", "(", ")", ":", "method_list", "=", "[", "]", "def", "_register", "(", "func", ")", ":", "method_list", ".", "append", "(", "func", ")", "return", "func", "# Comparison operators for sorting and uniqueness", "@", "_register", "def",...
24.30303
0.002398
def create_waveform_generator(variable_params, data, recalibration=None, gates=None, **static_params): """Creates a waveform generator for use with a model. Parameters ---------- variable_params : list of str The names of the parameter...
[ "def", "create_waveform_generator", "(", "variable_params", ",", "data", ",", "recalibration", "=", "None", ",", "gates", "=", "None", ",", "*", "*", "static_params", ")", ":", "# figure out what generator to use based on the approximant", "try", ":", "approximant", "...
41.288462
0.000455
def _gen_machine_graph(start, end, force_overwrite=False): """ Pie chart comparing machines usage. """ filename = graphs.get_machine_graph_filename(start, end) csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv') png_filename = os.path.join(GRAPH_ROOT, filename + '.png') _check_directory_exis...
[ "def", "_gen_machine_graph", "(", "start", ",", "end", ",", "force_overwrite", "=", "False", ")", ":", "filename", "=", "graphs", ".", "get_machine_graph_filename", "(", "start", ",", "end", ")", "csv_filename", "=", "os", ".", "path", ".", "join", "(", "G...
30.342105
0.00084
def _write_pair_information(gsd_file, structure): """Write the special pairs in the system. Parameters ---------- gsd_file : The file object of the GSD file being written structure : parmed.Structure Parmed structure object holding system information """ pair_types = [] ...
[ "def", "_write_pair_information", "(", "gsd_file", ",", "structure", ")", ":", "pair_types", "=", "[", "]", "pair_typeid", "=", "[", "]", "pairs", "=", "[", "]", "for", "ai", "in", "structure", ".", "atoms", ":", "for", "aj", "in", "ai", ".", "dihedral...
34
0.0022
def map_dict(key_map, *dicts, copy=False, base=None): """ Returns a dict with new key values. :param key_map: A dictionary that maps the dict keys ({old key: new key} :type key_map: dict :param dicts: A sequence of dicts. :type dicts: dict :param copy: If True, it ...
[ "def", "map_dict", "(", "key_map", ",", "*", "dicts", ",", "copy", "=", "False", ",", "base", "=", "None", ")", ":", "it", "=", "combine_dicts", "(", "*", "dicts", ")", ".", "items", "(", ")", "# Combine dicts.", "get", "=", "key_map", ".", "get", ...
24.189189
0.001074
def setUp(self, item): ''' Parameters: item -- WSDLTools BindingOperation instance. ''' if not isinstance(item, WSDLTools.OperationBinding): raise TypeError, 'Expecting WSDLTools Operation instance' if not item.input: raise WSDLFormatError('No...
[ "def", "setUp", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "WSDLTools", ".", "OperationBinding", ")", ":", "raise", "TypeError", ",", "'Expecting WSDLTools Operation instance'", "if", "not", "item", ".", "input", ":", "r...
40.791045
0.009646
def efron_endpoints_for_abc_confidence_interval(conf_percentage, model_obj, init_vals, bias_correction, acceleration, ...
[ "def", "efron_endpoints_for_abc_confidence_interval", "(", "conf_percentage", ",", "model_obj", ",", "init_vals", ",", "bias_correction", ",", "acceleration", ",", "std_error", ",", "empirical_influence", ",", "*", "*", "fit_kwargs", ")", ":", "# Calculate the percentiles...
51.795181
0.000228
def proxy_methods(base, include_underscore=None, exclude=None, supers=True): """class decorator. Modifies `Remote` subclasses to add proxy methods and attributes that mimic those defined in class `base`. Example: @proxy_methods(Tree) class RemoteTree(Remote, Tree) The decorator registers ...
[ "def", "proxy_methods", "(", "base", ",", "include_underscore", "=", "None", ",", "exclude", "=", "None", ",", "supers", "=", "True", ")", ":", "always_exclude", "=", "(", "'__new__'", ",", "'__init__'", ",", "'__getattribute__'", ",", "'__class__'", ",", "'...
46.571429
0.00236
def create_message_dialog(self, text, buttons=Gtk.ButtonsType.CLOSE, icon=Gtk.MessageType.WARNING): """ Function creates a message dialog with text and relevant buttons """ dialog = Gtk.MessageDialog(None, Gtk.DialogFlags.DESTROY_WITH_PARENT, ...
[ "def", "create_message_dialog", "(", "self", ",", "text", ",", "buttons", "=", "Gtk", ".", "ButtonsType", ".", "CLOSE", ",", "icon", "=", "Gtk", ".", "MessageType", ".", "WARNING", ")", ":", "dialog", "=", "Gtk", ".", "MessageDialog", "(", "None", ",", ...
38.583333
0.008439
def do_GET(self): """GET method implementation for BaseHTTPRequestHandler.""" if not self._client_allowed(): return try: (_, _, path, query, _) = urlsplit(self.path) params = parse_qs(query) # Give each handler a chance to respond. for prefix, handler in self._GET_handlers: ...
[ "def", "do_GET", "(", "self", ")", ":", "if", "not", "self", ".", "_client_allowed", "(", ")", ":", "return", "try", ":", "(", "_", ",", "_", ",", "path", ",", "query", ",", "_", ")", "=", "urlsplit", "(", "self", ".", "path", ")", "params", "=...
33.190476
0.016736
def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs): """Check that a source exists and that a quantity isn't erroneous.""" # Make sure that a source is given source = kwargs.get(cat_dict_class._KEYS.SOURCE, None) if source is None: raise CatDictError( ...
[ "def", "_check_cat_dict_source", "(", "self", ",", "cat_dict_class", ",", "key_in_self", ",", "*", "*", "kwargs", ")", ":", "# Make sure that a source is given", "source", "=", "kwargs", ".", "get", "(", "cat_dict_class", ".", "_KEYS", ".", "SOURCE", ",", "None"...
47.92
0.001637
def orchestrate(mods, saltenv='base', test=None, exclude=None, pillar=None, pillarenv=None): ''' .. versionadded:: 2016.11.0 Execute the orchestrate runner from a masterless minion. .. seealso:: More Orchestrate documentat...
[ "def", "orchestrate", "(", "mods", ",", "saltenv", "=", "'base'", ",", "test", "=", "None", ",", "exclude", "=", "None", ",", "pillar", "=", "None", ",", "pillarenv", "=", "None", ")", ":", "return", "_orchestrate", "(", "mods", "=", "mods", ",", "sa...
31.2
0.001036
def get_intersectionsbysubsets(df,cols_fracby2vals,cols_subset,col_ids): """ cols_fracby: cols_subset: """ for col_fracby in cols_fracby2vals: val=cols_fracby2vals[col_fracby] ids=df.loc[(df[col_fracby]==val),col_ids].dropna().unique() for col_subset in cols_subset: ...
[ "def", "get_intersectionsbysubsets", "(", "df", ",", "cols_fracby2vals", ",", "cols_subset", ",", "col_ids", ")", ":", "for", "col_fracby", "in", "cols_fracby2vals", ":", "val", "=", "cols_fracby2vals", "[", "col_fracby", "]", "ids", "=", "df", ".", "loc", "["...
45.538462
0.02649
def _lookup_vpc_allocs(query_type, session=None, order=None, **bfilter): """Look up 'query_type' Nexus VPC Allocs matching the filter. :param query_type: 'all', 'one' or 'first' :param session: db session :param order: select what field to order data :param bfilter: filter for mappings query :r...
[ "def", "_lookup_vpc_allocs", "(", "query_type", ",", "session", "=", "None", ",", "order", "=", "None", ",", "*", "*", "bfilter", ")", ":", "if", "session", "is", "None", ":", "session", "=", "bc", ".", "get_reader_session", "(", ")", "if", "order", ":...
30.354839
0.00103
def get_batch_header_values(self): """Scrape the "Batch Header" values from the original input file """ lines = self.getOriginalFile().data.splitlines() reader = csv.reader(lines) batch_headers = batch_data = [] for row in reader: if not any(row): ...
[ "def", "get_batch_header_values", "(", "self", ")", ":", "lines", "=", "self", ".", "getOriginalFile", "(", ")", ".", "data", ".", "splitlines", "(", ")", "reader", "=", "csv", ".", "reader", "(", "lines", ")", "batch_headers", "=", "batch_data", "=", "[...
38.826087
0.002186
def call_senders(self, routing, clients_list, *args, **kwargs): """ Calls senders callbacks """ for func, routings, routings_re in self.senders: call_callback = False # Message is published globally if routing is None or (routings is None and routings...
[ "def", "call_senders", "(", "self", ",", "routing", ",", "clients_list", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "func", ",", "routings", ",", "routings_re", "in", "self", ".", "senders", ":", "call_callback", "=", "False", "# Message...
35.125
0.002309
def timed(name=None, file=sys.stdout, callback=None, wall_clock=True): """ Context manager to make it easy to time the execution of a piece of code. This timer will never run your code several times and is meant more for simple in-production timing, instead of benchmarking. Reports the wall-clock ti...
[ "def", "timed", "(", "name", "=", "None", ",", "file", "=", "sys", ".", "stdout", ",", "callback", "=", "None", ",", "wall_clock", "=", "True", ")", ":", "start", "=", "time", ".", "time", "(", ")", "yield", "end", "=", "time", ".", "time", "(", ...
35.759259
0.000504
def create(self, interface): """ Method to add an interface. :param interface: List containing interface's desired to be created on database. :return: Id. """ data = {'interfaces': interface} return super(ApiInterfaceRequest, self).post('api/v3/interface/', data)
[ "def", "create", "(", "self", ",", "interface", ")", ":", "data", "=", "{", "'interfaces'", ":", "interface", "}", "return", "super", "(", "ApiInterfaceRequest", ",", "self", ")", ".", "post", "(", "'api/v3/interface/'", ",", "data", ")" ]
34.666667
0.009375
def filter_mutation_status(stmts_in, mutations, deletions, **kwargs): """Filter statements based on existing mutations/deletions This filter helps to contextualize a set of statements to a given cell type. Given a list of deleted genes, it removes statements that refer to these genes. It also takes a l...
[ "def", "filter_mutation_status", "(", "stmts_in", ",", "mutations", ",", "deletions", ",", "*", "*", "kwargs", ")", ":", "if", "'remove_bound'", "in", "kwargs", "and", "kwargs", "[", "'remove_bound'", "]", ":", "remove_bound", "=", "True", "else", ":", "remo...
34.969231
0.000856
def get_fpath(self, cfgstr=None): """ Reports the filepath that the cacher will use. It will attempt to use '{fname}_{cfgstr}{ext}' unless that is too long. Then cfgstr will be hashed. Example: >>> from ubelt.util_cache import Cacher >>> import pytest ...
[ "def", "get_fpath", "(", "self", ",", "cfgstr", "=", "None", ")", ":", "condensed", "=", "self", ".", "_condense_cfgstr", "(", "cfgstr", ")", "fname_cfgstr", "=", "'{}_{}{}'", ".", "format", "(", "self", ".", "fname", ",", "condensed", ",", "self", ".", ...
39.181818
0.002265
def _get_all_forums(self): """ Returns all forums. """ if not hasattr(self, '_all_forums'): self._all_forums = list(Forum.objects.all()) return self._all_forums
[ "def", "_get_all_forums", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_all_forums'", ")", ":", "self", ".", "_all_forums", "=", "list", "(", "Forum", ".", "objects", ".", "all", "(", ")", ")", "return", "self", ".", "_all_forums"...
38.4
0.010204
def check_name(name, safe_chars): ''' Check whether the specified name contains invalid characters ''' regexp = re.compile('[^{0}]'.format(safe_chars)) if regexp.search(name): raise SaltCloudException( '{0} contains characters not supported by this cloud provider. ' '...
[ "def", "check_name", "(", "name", ",", "safe_chars", ")", ":", "regexp", "=", "re", ".", "compile", "(", "'[^{0}]'", ".", "format", "(", "safe_chars", ")", ")", "if", "regexp", ".", "search", "(", "name", ")", ":", "raise", "SaltCloudException", "(", "...
33.333333
0.002433
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho): ''' Perform line search ''' iter_max = 20 norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2 f = np.zeros(iter_max + 1) f[0] = F_t(X, Y, S, M_E, E, m0, rho) t = -1e-1 for i in range(iter_max): f[i + ...
[ "def", "getoptT", "(", "X", ",", "W", ",", "Y", ",", "Z", ",", "S", ",", "M_E", ",", "E", ",", "m0", ",", "rho", ")", ":", "iter_max", "=", "20", "norm2WZ", "=", "np", ".", "linalg", ".", "norm", "(", "W", ",", "ord", "=", "'fro'", ")", "...
28.6875
0.00211
def append(self, x, y, scatter_kwargs, hist_kwargs=None, xhist_kwargs=None, yhist_kwargs=None, num_ticks=3, labels=None, hist_share=False, marginal_histograms=True): """ Adds a new scatter to self.scatter_ax as well as marginal histograms for the same data, borrowin...
[ "def", "append", "(", "self", ",", "x", ",", "y", ",", "scatter_kwargs", ",", "hist_kwargs", "=", "None", ",", "xhist_kwargs", "=", "None", ",", "yhist_kwargs", "=", "None", ",", "num_ticks", "=", "3", ",", "labels", "=", "None", ",", "hist_share", "="...
34.790909
0.001524
def promotePrefixes(self): """ Push prefix declarations up the tree as far as possible. Prefix mapping are pushed to its parent unless the parent has the prefix mapped to another URI or the parent has the prefix. This is propagated up the tree until the top is reached. ...
[ "def", "promotePrefixes", "(", "self", ")", ":", "for", "c", "in", "self", ".", "children", ":", "c", ".", "promotePrefixes", "(", ")", "if", "self", ".", "parent", "is", "None", ":", "return", "for", "p", ",", "u", "in", "self", ".", "nsprefixes", ...
32.307692
0.002312
def branch(self, root, parts): """ Traverse the path until a leaf is reached. @param parts: A list of path parts. @type parts: [str,..] @param root: The root. @type root: L{xsd.sxbase.SchemaObject} @return: The end of the branch. @rtype: L{xsd.sxbase.Schem...
[ "def", "branch", "(", "self", ",", "root", ",", "parts", ")", ":", "result", "=", "root", "for", "part", "in", "parts", "[", "1", ":", "-", "1", "]", ":", "name", "=", "splitPrefix", "(", "part", ")", "[", "1", "]", "log", ".", "debug", "(", ...
38.714286
0.002401
def add_var_condor_cmd(self, command): """ Add a condor command to the submit file that allows variable (macro) arguments to be passes to the executable. """ if command not in self.__var_cmds: self.__var_cmds.append(command) macro = self.__bad_macro_chars.sub( r'', command ) ...
[ "def", "add_var_condor_cmd", "(", "self", ",", "command", ")", ":", "if", "command", "not", "in", "self", ".", "__var_cmds", ":", "self", ".", "__var_cmds", ".", "append", "(", "command", ")", "macro", "=", "self", ".", "__bad_macro_chars", ".", "sub", "...
40.555556
0.008043
def read(self, table): """...""" # Table exists if table in self.by_id: return self.by_id[table].values() if table in self.cache: return self.cache[table] # Read table cls = self.FACTORIES[table] key = cls.KEY if key: if table not in self.by_id: self.by_id[table...
[ "def", "read", "(", "self", ",", "table", ")", ":", "# Table exists", "if", "table", "in", "self", ".", "by_id", ":", "return", "self", ".", "by_id", "[", "table", "]", ".", "values", "(", ")", "if", "table", "in", "self", ".", "cache", ":", "retur...
25.521739
0.014778
def bind_kernel(**kwargs): """Bind an Engine's Kernel to be used as a full IPython kernel. This allows a running Engine to be used simultaneously as a full IPython kernel with the QtConsole or other frontends. This function returns immediately. """ from IPython.zmq.ipkernel import IPKe...
[ "def", "bind_kernel", "(", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "zmq", ".", "ipkernel", "import", "IPKernelApp", "from", "IPython", ".", "parallel", ".", "apps", ".", "ipengineapp", "import", "IPEngineApp", "# first check for IPKernelApp, in which...
35.08
0.008879
def date(self) -> datetime.datetime: """Date of the experiment (start of exposure)""" return self._data['Date'] - datetime.timedelta(0, float(self.exposuretime), 0)
[ "def", "date", "(", "self", ")", "->", "datetime", ".", "datetime", ":", "return", "self", ".", "_data", "[", "'Date'", "]", "-", "datetime", ".", "timedelta", "(", "0", ",", "float", "(", "self", ".", "exposuretime", ")", ",", "0", ")" ]
59.333333
0.016667
def _xpath_to_dict(self, element, property_map, namespace_map): """ property_map = { u'name' : { u'xpath' : u't:Mailbox/t:Name'}, u'email' : { u'xpath' : u't:Mailbox/t:EmailAddress'}, u'response' : { u'xpath' : u't:ResponseType'}, u'last_response': { u'xpath' : u't:Las...
[ "def", "_xpath_to_dict", "(", "self", ",", "element", ",", "property_map", ",", "namespace_map", ")", ":", "result", "=", "{", "}", "log", ".", "info", "(", "etree", ".", "tostring", "(", "element", ",", "pretty_print", "=", "True", ")", ")", "for", "k...
31.66
0.011029
def reload(self, cascadeObjects=True): ''' reload - Reload this object from the database, overriding any local changes and merging in any updates. @param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have changed since last save/fe...
[ "def", "reload", "(", "self", ",", "cascadeObjects", "=", "True", ")", ":", "_id", "=", "self", ".", "_id", "if", "not", "_id", ":", "raise", "KeyError", "(", "'Object has never been saved! Cannot reload.'", ")", "currentData", "=", "self", ".", "asDict", "(...
37.794118
0.026925
def _get_asn1_time(timestamp): """ Retrieve the time value of an ASN1 time object. @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to that type) from which the time value will be retrieved. @return: The time value from C{timestamp} as a L{bytes} string in a certain ...
[ "def", "_get_asn1_time", "(", "timestamp", ")", ":", "string_timestamp", "=", "_ffi", ".", "cast", "(", "'ASN1_STRING*'", ",", "timestamp", ")", "if", "_lib", ".", "ASN1_STRING_length", "(", "string_timestamp", ")", "==", "0", ":", "return", "None", "elif", ...
45.657895
0.000564
def _serve_runs(self, request): """Serve a JSON array of run names, ordered by run started time. Sort order is by started time (aka first event time) with empty times sorted last, and then ties are broken by sorting on the run name. """ if self._db_connection_provider: db = self._db_connectio...
[ "def", "_serve_runs", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_db_connection_provider", ":", "db", "=", "self", ".", "_db_connection_provider", "(", ")", "cursor", "=", "db", ".", "execute", "(", "'''\n SELECT\n run_name,\n ...
40.419355
0.012471
def process_marked_lines(lines, markers, return_flags=[False, -1, -1]): """Run regexes against message's marked lines to strip quotations. Return only last message lines. >>> mark_message_lines(['Hello', 'From: foo@bar.com', '', '> Hi', 'tsem']) ['Hello'] Also returns return_flags. return_flag...
[ "def", "process_marked_lines", "(", "lines", ",", "markers", ",", "return_flags", "=", "[", "False", ",", "-", "1", ",", "-", "1", "]", ")", ":", "markers", "=", "''", ".", "join", "(", "markers", ")", "# if there are no splitter there should be no markers", ...
37.877551
0.000525
def get_outliers_percentage(pronac): """ Returns the percentage of items of the project that are outliers. """ items = ( data.items_with_price .groupby(['PRONAC']) .get_group(pronac) ) df = data.aggregated_relevant_items outlier_items = {} url_prefix = '/pre...
[ "def", "get_outliers_percentage", "(", "pronac", ")", ":", "items", "=", "(", "data", ".", "items_with_price", ".", "groupby", "(", "[", "'PRONAC'", "]", ")", ".", "get_group", "(", "pronac", ")", ")", "df", "=", "data", ".", "aggregated_relevant_items", "...
26.536585
0.000887
def generate(request): """ Create a new DataItem. """ models.DataItem.create( content=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)) ) return muffin.HTTPFound('/')
[ "def", "generate", "(", "request", ")", ":", "models", ".", "DataItem", ".", "create", "(", "content", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "_", "in", "...
36.166667
0.009009
def to_foreign(self, obj, name, value): # pylint:disable=unused-argument """Transform to a MongoDB-safe value.""" namespace = self.namespace try: explicit = self.explicit except AttributeError: explicit = not namespace if not isinstance(value, (str, unicode)): value = canon(value) if n...
[ "def", "to_foreign", "(", "self", ",", "obj", ",", "name", ",", "value", ")", ":", "# pylint:disable=unused-argument", "namespace", "=", "self", ".", "namespace", "try", ":", "explicit", "=", "self", ".", "explicit", "except", "AttributeError", ":", "explicit"...
26.735294
0.048832
def changePermissionsRecursively(path, uid, gid): """ Function to recursively change the user id and group id. It sets 700 permissions. """ os.chown(path, uid, gid) for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isfile(itempath): # Setti...
[ "def", "changePermissionsRecursively", "(", "path", ",", "uid", ",", "gid", ")", ":", "os", ".", "chown", "(", "path", ",", "uid", ",", "gid", ")", "for", "item", "in", "os", ".", "listdir", "(", "path", ")", ":", "itempath", "=", "os", ".", "path"...
37.354839
0.000842
def plot_eigh1(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first eigenvalue of the horizontal tensor. Usage ----- x.plot_eigh1([tick_interval, xlabel, ylabel, ax, colorbar, ...
[ "def", "plot_eigh1", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", ...
40.245614
0.001702
def getMetricDetails(self, metricLabel): """ Gets detailed info about a given metric, in addition to its value. This may including any statistics or auxilary data that are computed for a given metric. :param metricLabel: (string) label of the given metric (see :class:`~nupic.frameworks...
[ "def", "getMetricDetails", "(", "self", ",", "metricLabel", ")", ":", "try", ":", "metricIndex", "=", "self", ".", "__metricLabels", ".", "index", "(", "metricLabel", ")", "except", "IndexError", ":", "return", "None", "return", "self", ".", "__metrics", "["...
35.111111
0.009245
def read_long(self, signed=True): """Reads a long integer (8 bytes) value.""" return int.from_bytes(self.read(8), byteorder='little', signed=signed)
[ "def", "read_long", "(", "self", ",", "signed", "=", "True", ")", ":", "return", "int", ".", "from_bytes", "(", "self", ".", "read", "(", "8", ")", ",", "byteorder", "=", "'little'", ",", "signed", "=", "signed", ")" ]
54
0.012195
def Print(self, output_writer): """Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer. """ if self._date_time_ranges: for date_time_range in self._date_time_ranges: if date_time_range.start_date_time is None: end_time_string...
[ "def", "Print", "(", "self", ",", "output_writer", ")", ":", "if", "self", ".", "_date_time_ranges", ":", "for", "date_time_range", "in", "self", ".", "_date_time_ranges", ":", "if", "date_time_range", ".", "start_date_time", "is", "None", ":", "end_time_string"...
42.961538
0.009632
def register_download_command(self, download_func): """ Add 'download' command for downloading a project to a directory. For non empty directories it will download remote files replacing local files. :param download_func: function to run when user choses this option """ d...
[ "def", "register_download_command", "(", "self", ",", "download_func", ")", ":", "description", "=", "\"Download the contents of a remote remote project to a local folder.\"", "download_parser", "=", "self", ".", "subparsers", ".", "add_parser", "(", "'download'", ",", "des...
60.642857
0.008121
def parseBasicOptions(parser): """Setups the standard things from things added by getBasicOptionParser. """ options = parser.parse_args() setLoggingFromOptions(options) #Set up the temp dir root if options.tempDirRoot == "None": # FIXME: Really, a string containing the word None? optio...
[ "def", "parseBasicOptions", "(", "parser", ")", ":", "options", "=", "parser", ".", "parse_args", "(", ")", "setLoggingFromOptions", "(", "options", ")", "#Set up the temp dir root", "if", "options", ".", "tempDirRoot", "==", "\"None\"", ":", "# FIXME: Really, a str...
30.583333
0.010582
def is_unit_upgrading_set(): """Return the state of the kv().get('unit-upgrading'). To help with units that don't have HookData() (testing) if it excepts, return False """ try: with unitdata.HookData()() as t: kv = t[0] # transform something truth-y into a Boolean. ...
[ "def", "is_unit_upgrading_set", "(", ")", ":", "try", ":", "with", "unitdata", ".", "HookData", "(", ")", "(", ")", "as", "t", ":", "kv", "=", "t", "[", "0", "]", "# transform something truth-y into a Boolean.", "return", "not", "(", "not", "(", "kv", "....
31
0.00241
def best_match( self, req, working_set, installer=None, replace_conflicting=False): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ...
[ "def", "best_match", "(", "self", ",", "req", ",", "working_set", ",", "installer", "=", "None", ",", "replace_conflicting", "=", "False", ")", ":", "try", ":", "dist", "=", "working_set", ".", "find", "(", "req", ")", "except", "VersionConflict", ":", "...
43.444444
0.001668
def _build(value, property_path=None): """ The generic schema definition build method. :param value: The value to build a schema definition for :param List[str] property_path: The property path of the current type, defaults to None, optional :return: The built schema definition :rtype: Dict...
[ "def", "_build", "(", "value", ",", "property_path", "=", "None", ")", ":", "if", "not", "property_path", ":", "property_path", "=", "[", "]", "if", "is_config_type", "(", "value", ")", ":", "return", "_build_config", "(", "value", ",", "property_path", "=...
40.24
0.000971
def computeUniquePointsSensed(nCols, nPoints, s): """ If a network with nCols columns senses an object s times, how many unique points are actually sensed? The number is generally <= nCols * s because features may be repeated across sensations. """ if nCols == 1: return min(s, nPoints) elif nCols < n...
[ "def", "computeUniquePointsSensed", "(", "nCols", ",", "nPoints", ",", "s", ")", ":", "if", "nCols", "==", "1", ":", "return", "min", "(", "s", ",", "nPoints", ")", "elif", "nCols", "<", "nPoints", ":", "q", "=", "float", "(", "nCols", ")", "/", "n...
32.333333
0.012024
def real_to_complex(real_fid): """ Standard optimization routines as used in lmfit require real data. This function takes a real FID generated from the optimization routine and converts it back into a true complex form. :param real_fid: the real FID to be converted to complex. :return: the comp...
[ "def", "real_to_complex", "(", "real_fid", ")", ":", "np", "=", "int", "(", "real_fid", ".", "shape", "[", "0", "]", "/", "2", ")", "complex_fid", "=", "numpy", ".", "zeros", "(", "np", ",", "'complex'", ")", "complex_fid", "[", ":", "]", "=", "rea...
36.352941
0.001577
def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, permanent=False): ''' Set multiple salt process environment variables from a dict. Returns a dict. environ Must be a dict. The top-level keys of the dict are the names of the environment variables to set. Each...
[ "def", "setenv", "(", "environ", ",", "false_unsets", "=", "False", ",", "clear_all", "=", "False", ",", "update_minion", "=", "False", ",", "permanent", "=", "False", ")", ":", "ret", "=", "{", "}", "if", "not", "isinstance", "(", "environ", ",", "dic...
39.012658
0.000633
def bin_data(data, dim = 40, num_bins = 10): """ Fully bins the data generated by generate_data, using generate_RF_bins and bin_number. """ intervals = generate_RF_bins(data, dim, num_bins) binned_data = [numpy.concatenate([bin_number(data[x][i], intervals[i]) for i in range(len(data[x]))]) for x in r...
[ "def", "bin_data", "(", "data", ",", "dim", "=", "40", ",", "num_bins", "=", "10", ")", ":", "intervals", "=", "generate_RF_bins", "(", "data", ",", "dim", ",", "num_bins", ")", "binned_data", "=", "[", "numpy", ".", "concatenate", "(", "[", "bin_numbe...
38.777778
0.028011
def css(self): """Returns ------- str The CSS. """ css_list = [DEFAULT_MARK_CSS] for aes in self.aesthetics: css_list.extend(get_mark_css(aes, self.values[aes])) #print('\n'.join(css_list)) return '\n'.join(css_list)
[ "def", "css", "(", "self", ")", ":", "css_list", "=", "[", "DEFAULT_MARK_CSS", "]", "for", "aes", "in", "self", ".", "aesthetics", ":", "css_list", ".", "extend", "(", "get_mark_css", "(", "aes", ",", "self", ".", "values", "[", "aes", "]", ")", ")",...
26.727273
0.009868
def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node)
[ "def", "visit_NameConstant", "(", "self", ",", "node", ")", ":", "nnode", "=", "self", ".", "dnode", "(", "node", ")", "copy_from_lineno_col_offset", "(", "nnode", ",", "str", "(", "node", ".", "value", ")", ",", "self", ".", "bytes_pos_to_utf8", ",", "t...
39
0.01005
def get_task_db(self, source_path): '''从数据库中查询source_path的信息. 如果存在的话, 就返回这条记录; 如果没有的话, 就返回None ''' sql = 'SELECT * FROM upload WHERE source_path=?' req = self.cursor.execute(sql, [source_path, ]) if req: return req.fetchone() else: ...
[ "def", "get_task_db", "(", "self", ",", "source_path", ")", ":", "sql", "=", "'SELECT * FROM upload WHERE source_path=?'", "req", "=", "self", ".", "cursor", ".", "execute", "(", "sql", ",", "[", "source_path", ",", "]", ")", "if", "req", ":", "return", "r...
26.833333
0.009009
def _get(self, action, show, proxy, timeout): """ make HTTP request and cache response """ silent = self.flags['silent'] if action in self.cache: if action != 'imageinfo' and action != 'labels': utils.stderr("+ %s results in cache" % action, silent) ...
[ "def", "_get", "(", "self", ",", "action", ",", "show", ",", "proxy", ",", "timeout", ")", ":", "silent", "=", "self", ".", "flags", "[", "'silent'", "]", "if", "action", "in", "self", ".", "cache", ":", "if", "action", "!=", "'imageinfo'", "and", ...
34.382979
0.001203
def get_resampler_for_grouping(groupby, rule, how=None, fill_method=None, limit=None, kind=None, **kwargs): """ Return our appropriate resampler when grouping as well. """ # .resample uses 'on' similar to how .groupby uses 'key' kwargs['key'] = kwargs.pop('on', None) ...
[ "def", "get_resampler_for_grouping", "(", "groupby", ",", "rule", ",", "how", "=", "None", ",", "fill_method", "=", "None", ",", "limit", "=", "None", ",", "kind", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# .resample uses 'on' similar to how .groupby u...
42.125
0.001451
def post(self, uri, body=None, **kwargs): """make a POST request""" return self.fetch('post', uri, kwargs.pop("query", {}), body, **kwargs)
[ "def", "post", "(", "self", ",", "uri", ",", "body", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "fetch", "(", "'post'", ",", "uri", ",", "kwargs", ".", "pop", "(", "\"query\"", ",", "{", "}", ")", ",", "body", ",", ...
51
0.012903