text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def reduce_by_device(parallelism, data, reduce_fn): """Reduces data per device. This can be useful, for example, if we want to all-reduce n tensors on k<n devices (like during eval when we have only one device). We call reduce_by_device() to first sum the tensors per device, then call our usual all-reduce o...
[ "def", "reduce_by_device", "(", "parallelism", ",", "data", ",", "reduce_fn", ")", ":", "unique_devices", "=", "[", "]", "device_to_data", "=", "{", "}", "for", "dev", ",", "datum", "in", "zip", "(", "parallelism", ".", "devices", ",", "data", ")", ":", ...
42.033333
21.766667
def _patch_stats_request(request): '''If the request has no filter config, add one that should do what is expected (include all items) see: PE-11813 ''' filt = request.get('filter', {}) if not filt.get('config', None): request['filter'] = filters.date_range('acquired', ...
[ "def", "_patch_stats_request", "(", "request", ")", ":", "filt", "=", "request", ".", "get", "(", "'filter'", ",", "{", "}", ")", "if", "not", "filt", ".", "get", "(", "'config'", ",", "None", ")", ":", "request", "[", "'filter'", "]", "=", "filters"...
38.5
18.5
def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ''' framed_msg = {} if header is ...
[ "def", "frame_msg_ipc", "(", "body", ",", "header", "=", "None", ",", "raw_body", "=", "False", ")", ":", "# pylint: disable=unused-argument", "framed_msg", "=", "{", "}", "if", "header", "is", "None", ":", "header", "=", "{", "}", "framed_msg", "[", "'hea...
31.823529
25
def clean(input_string, tag_dictionary=constants.SUPPORTED_TAGS): """ Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are removed, and child nodes are recursively moved to parent of removed node. Attributes not contained as arguments in tag_dictionary are removed. Do...
[ "def", "clean", "(", "input_string", ",", "tag_dictionary", "=", "constants", ".", "SUPPORTED_TAGS", ")", ":", "try", ":", "assert", "isinstance", "(", "input_string", ",", "basestring", ")", "except", "AssertionError", ":", "raise", "TypeError", "root", "=", ...
45.590164
20.770492
def simxGetObjectSelection(clientID, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' objectCount = ct.c_int() objectHandles = ct.POINTER(ct.c_int)() ret = c_GetObjectSelection(clientID, ct.byref(objectHandles), ct.byref(objectCount)...
[ "def", "simxGetObjectSelection", "(", "clientID", ",", "operationMode", ")", ":", "objectCount", "=", "ct", ".", "c_int", "(", ")", "objectHandles", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_int", ")", "(", ")", "ret", "=", "c_GetObjectSelection", "(",...
33.428571
25.285714
def validate_periods(periods): """ If a `periods` argument is passed to the Datetime/Timedelta Array/Index constructor, cast it to an integer. Parameters ---------- periods : None, float, int Returns ------- periods : None or int Raises ------ TypeError if peri...
[ "def", "validate_periods", "(", "periods", ")", ":", "if", "periods", "is", "not", "None", ":", "if", "lib", ".", "is_float", "(", "periods", ")", ":", "periods", "=", "int", "(", "periods", ")", "elif", "not", "lib", ".", "is_integer", "(", "periods",...
24.48
19.2
def create_variable(self, varname, vtype=None): """Create a tk variable. If the variable was created previously return that instance. """ var_types = ('string', 'int', 'boolean', 'double') vname = varname var = None type_from_name = 'string' # default type ...
[ "def", "create_variable", "(", "self", ",", "varname", ",", "vtype", "=", "None", ")", ":", "var_types", "=", "(", "'string'", ",", "'int'", ",", "'boolean'", ",", "'double'", ")", "vname", "=", "varname", "var", "=", "None", "type_from_name", "=", "'str...
36.305556
14.222222
def split(self, fragment_height): """ Split an image into multiple fragments after fragment_height pixels :param fragment_height: height of fragment :return: list of PIL objects """ passes = int(math.ceil(self.height/fragment_height)) fragments = [] for n...
[ "def", "split", "(", "self", ",", "fragment_height", ")", ":", "passes", "=", "int", "(", "math", ".", "ceil", "(", "self", ".", "height", "/", "fragment_height", ")", ")", "fragments", "=", "[", "]", "for", "n", "in", "range", "(", "0", ",", "pass...
35.882353
13.647059
def applications(self): """ Access the applications :returns: twilio.rest.api.v2010.account.application.ApplicationList :rtype: twilio.rest.api.v2010.account.application.ApplicationList """ if self._applications is None: self._applications = ApplicationList(s...
[ "def", "applications", "(", "self", ")", ":", "if", "self", ".", "_applications", "is", "None", ":", "self", ".", "_applications", "=", "ApplicationList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ...
39.5
20.3
def parse_ics(icsfile): """Takes an icsfilename, parses it, and returns Events.""" events = [] cal = Calendar.from_ical(open(icsfile, 'rb').read()) for component in cal.walk('vevent'): dtstart = component['dtstart'].dt rrule = component['rrule'] freq, args = convert_rrule(rrule...
[ "def", "parse_ics", "(", "icsfile", ")", ":", "events", "=", "[", "]", "cal", "=", "Calendar", ".", "from_ical", "(", "open", "(", "icsfile", ",", "'rb'", ")", ".", "read", "(", ")", ")", "for", "component", "in", "cal", ".", "walk", "(", "'vevent'...
36
21.583333
def blacken( c, line_length=79, folders=None, check=False, diff=False, find_opts=None ): r""" Run black on the current source tree (all ``.py`` files). .. warning:: ``black`` only runs on Python 3.6 or above. (However, it can be executed against Python 2 compatible code.) :param in...
[ "def", "blacken", "(", "c", ",", "line_length", "=", "79", ",", "folders", "=", "None", ",", "check", "=", "False", ",", "diff", "=", "False", ",", "find_opts", "=", "None", ")", ":", "config", "=", "c", ".", "config", ".", "get", "(", "\"blacken\"...
35.735849
21.264151
def fit(self, sequences, y=None): """Fit the kcenters clustering on the data Parameters ---------- sequences : list of array-like, each of shape [sequence_length, n_features] A list of multivariate timeseries, or ``md.Trajectory``. Each sequence may have a differ...
[ "def", "fit", "(", "self", ",", "sequences", ",", "y", "=", "None", ")", ":", "MultiSequenceClusterMixin", ".", "fit", "(", "self", ",", "sequences", ")", "self", ".", "cluster_center_indices_", "=", "self", ".", "_split_indices", "(", "self", ".", "cluste...
37.333333
24.944444
def is_repeated_suggestion(params, history): """ Parameters ---------- params : dict Trial param set history : list of 3-tuples History of past function evaluations. Each element in history should be a tuple `(params, score, status)`, where `pa...
[ "def", "is_repeated_suggestion", "(", "params", ",", "history", ")", ":", "if", "any", "(", "params", "==", "hparams", "and", "hstatus", "==", "'SUCCEEDED'", "for", "hparams", ",", "hscore", ",", "hstatus", "in", "history", ")", ":", "return", "True", "els...
31.25
17.65
def update(self, mini_batch, num_sequences): """ Performs update on model. :param mini_batch: Batch of experiences. :param num_sequences: Number of sequences to process. :return: Results of update. """ feed_dict = {self.model.dropout_rate: self.update_rate, ...
[ "def", "update", "(", "self", ",", "mini_batch", ",", "num_sequences", ")", ":", "feed_dict", "=", "{", "self", ".", "model", ".", "dropout_rate", ":", "self", ".", "update_rate", ",", "self", ".", "model", ".", "batch_size", ":", "num_sequences", ",", "...
50.354839
20.225806
def near(self, key, point): """ 增加查询条件,限制返回结果指定字段值的位置与给定地理位置临近。 :param key: 查询条件字段名 :param point: 需要查询的地理位置 :rtype: Query """ if point is None: raise ValueError('near query does not accept None') self._add_condition(key, '$nearSphere', point)...
[ "def", "near", "(", "self", ",", "key", ",", "point", ")", ":", "if", "point", "is", "None", ":", "raise", "ValueError", "(", "'near query does not accept None'", ")", "self", ".", "_add_condition", "(", "key", ",", "'$nearSphere'", ",", "point", ")", "ret...
25.230769
16
def _stroke_simplification(self, pointlist): """The Douglas-Peucker line simplification takes a list of points as an argument. It tries to simplifiy this list by removing as many points as possible while still maintaining the overall shape of the stroke. It does so by taking the...
[ "def", "_stroke_simplification", "(", "self", ",", "pointlist", ")", ":", "# Find the point with the biggest distance", "dmax", "=", "0", "index", "=", "0", "for", "i", "in", "range", "(", "1", ",", "len", "(", "pointlist", ")", ")", ":", "d", "=", "geomet...
46.258065
21.967742
def read_value(hive, key, vname=None, use_32bit_registry=False): r''' Reads a registry value entry or the default value for a key. To read the default value, don't pass ``vname`` Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM ...
[ "def", "read_value", "(", "hive", ",", "key", ",", "vname", "=", "None", ",", "use_32bit_registry", "=", "False", ")", ":", "return", "__utils__", "[", "'reg.read_value'", "]", "(", "hive", "=", "hive", ",", "key", "=", "key", ",", "vname", "=", "vname...
32.661017
26.084746
def icon(self): """ Returns the icon filepath for this plugin. :return <str> """ path = self._icon if not path: return '' path = os.path.expandvars(os.path.expanduser(path)) if path.startswith('.'): base_path = os.path...
[ "def", "icon", "(", "self", ")", ":", "path", "=", "self", ".", "_icon", "if", "not", "path", ":", "return", "''", "path", "=", "os", ".", "path", ".", "expandvars", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "if", "path", ...
26.0625
19.0625
def resolve_redirects_if_needed(self, uri): """ substitute with final uri after 303 redirects (if it's a www location!) :param uri: :return: """ if type(uri) == type("string") or type(uri) == type(u"unicode"): if uri.startswith("www."): # support for lazy pe...
[ "def", "resolve_redirects_if_needed", "(", "self", ",", "uri", ")", ":", "if", "type", "(", "uri", ")", "==", "type", "(", "\"string\"", ")", "or", "type", "(", "uri", ")", "==", "type", "(", "u\"unicode\"", ")", ":", "if", "uri", ".", "startswith", ...
36
19.714286
def from_file(filename, use_cores=True, thresh=1.e-4): """ Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). ...
[ "def", "from_file", "(", "filename", ",", "use_cores", "=", "True", ",", "thresh", "=", "1.e-4", ")", ":", "with", "zopen", "(", "filename", ",", "\"rt\"", ")", "as", "f", ":", "return", "Xr", ".", "from_string", "(", "f", ".", "read", "(", ")", ",...
41.142857
18.952381
def hash(obj, hash_name='md5', coerce_mmap=False): """ Quick calculation of a hash to identify uniquely Python objects containing numpy arrays. Parameters ----------- hash_name: 'md5' or 'sha1' Hashing algorithm used. sha1 is supposedly safer, but md5 is faste...
[ "def", "hash", "(", "obj", ",", "hash_name", "=", "'md5'", ",", "coerce_mmap", "=", "False", ")", ":", "if", "'numpy'", "in", "sys", ".", "modules", ":", "hasher", "=", "NumpyHasher", "(", "hash_name", "=", "hash_name", ",", "coerce_mmap", "=", "coerce_m...
37.3125
15.4375
def bezier_roots(coeffs): r"""Compute polynomial roots from a polynomial in the Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :math:`\...
[ "def", "bezier_roots", "(", "coeffs", ")", ":", "companion", ",", "degree", ",", "effective_degree", "=", "bernstein_companion", "(", "coeffs", ")", "if", "effective_degree", ":", "sigma_roots", "=", "np", ".", "linalg", ".", "eigvals", "(", "companion", ")", ...
27.941176
23.382353
def parse_add_loopback(): """ Validate params when adding a loopback adapter """ class Add(argparse.Action): def __call__(self, parser, args, values, option_string=None): try: ipaddress.IPv4Interface("{}/{}".format(values[1], values[2])) except ipaddress...
[ "def", "parse_add_loopback", "(", ")", ":", "class", "Add", "(", "argparse", ".", "Action", ")", ":", "def", "__call__", "(", "self", ",", "parser", ",", "args", ",", "values", ",", "option_string", "=", "None", ")", ":", "try", ":", "ipaddress", ".", ...
38.3125
21.6875
def update_token(self): """Request a new token and store it for future use""" logger.info('updating token') if None in self.credentials.values(): raise RuntimeError("You must provide an username and a password") credentials = dict(auth=self.credentials) url = self.tes...
[ "def", "update_token", "(", "self", ")", ":", "logger", ".", "info", "(", "'updating token'", ")", "if", "None", "in", "self", ".", "credentials", ".", "values", "(", ")", ":", "raise", "RuntimeError", "(", "\"You must provide an username and a password\"", ")",...
44.15
12.8
def data(self, index, role = QtCore.Qt.DisplayRole): """Reimplemented from QtCore.QAbstractItemModel The value gets validated and is red if validation fails and green if it passes. """ if not index.isValid(): return None if role == QtCore.Qt.DisplayRole or ro...
[ "def", "data", "(", "self", ",", "index", ",", "role", "=", "QtCore", ".", "Qt", ".", "DisplayRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "None", "if", "role", "==", "QtCore", ".", "Qt", ".", "DisplayRole", "or",...
41.28125
11.21875
def _get_envs_from_ref_paths(self, refs): ''' Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags. ''' def _check_ref(env_set, rname): ''' Add the appropriate saltenv(s) to the set ''' ...
[ "def", "_get_envs_from_ref_paths", "(", "self", ",", "refs", ")", ":", "def", "_check_ref", "(", "env_set", ",", "rname", ")", ":", "'''\n Add the appropriate saltenv(s) to the set\n '''", "if", "rname", "in", "self", ".", "saltenv_revmap", ":", ...
37.594595
15.378378
def xorc_constraint(v=0, sense="maximize"): """ XOR (r as variable) custom constraint""" assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__() model, x, y, z = _init() r = model.addVar("r", "B") n = model.addVar("n", "I") # auxiliary model.addCons(r+quicksum([x,y,z]) == 2*n) mod...
[ "def", "xorc_constraint", "(", "v", "=", "0", ",", "sense", "=", "\"maximize\"", ")", ":", "assert", "v", "in", "[", "0", ",", "1", "]", ",", "\"v must be 0 or 1 instead of %s\"", "%", "v", ".", "__repr__", "(", ")", "model", ",", "x", ",", "y", ",",...
41.5
8.9
def init(project_name): """ build a minimal flask project """ # the destination path dst_path = os.path.join(os.getcwd(), project_name) start_init_info(dst_path) # create dst path _mkdir_p(dst_path) os.chdir(dst_path) # create files init_code('manage.py', _manage_basic_cod...
[ "def", "init", "(", "project_name", ")", ":", "# the destination path", "dst_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "project_name", ")", "start_init_info", "(", "dst_path", ")", "# create dst path", "_mkdir_p", "...
22.633333
18.633333
def get_vm_config_file(name, datacenter, placement, datastore, service_instance=None): ''' Queries the virtual machine config file and returns vim.host.DatastoreBrowser.SearchResults object on success None on failure name Name of the virtual machine datacenter ...
[ "def", "get_vm_config_file", "(", "name", ",", "datacenter", ",", "placement", ",", "datastore", ",", "service_instance", "=", "None", ")", ":", "browser_spec", "=", "vim", ".", "host", ".", "DatastoreBrowser", ".", "SearchSpec", "(", ")", "directory", "=", ...
38.867925
21.698113
def create_md5(path): """Create the md5 hash of a file using the hashlib library.""" m = hashlib.md5() # rb necessary to run correctly in windows. with open(path, "rb") as f: while True: data = f.read(8192) if not data: break m.update(data) ...
[ "def", "create_md5", "(", "path", ")", ":", "m", "=", "hashlib", ".", "md5", "(", ")", "# rb necessary to run correctly in windows.", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":", "while", "True", ":", "data", "=", "f", ".", "read", ...
27.583333
15.75
def handler(self): """Handler on explicitly closing the GUI window.""" self.pauseMovie() if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"): self.exitClient() else: # When the user presses cancel, resume playing. #self.playMovie() print "Playing Movie" threadi...
[ "def", "handler", "(", "self", ")", ":", "self", ".", "pauseMovie", "(", ")", "if", "tkMessageBox", ".", "askokcancel", "(", "\"Quit?\"", ",", "\"Are you sure you want to quit?\"", ")", ":", "self", ".", "exitClient", "(", ")", "else", ":", "# When the user pr...
38.25
14
def read_first_available_value(filename, field_name): """Reads the first assigned value of the given field in the CSV table. """ if not os.path.exists(filename): return None with open(filename, 'rb') as csvfile: reader = csv.DictReader(csvfile) for row in reader: valu...
[ "def", "read_first_available_value", "(", "filename", ",", "field_name", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "None", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "csvfile", ":", "reade...
33.25
9.166667
def _binaryconfig(path, conf, dtype=None, shape=None, credentials=None): """ Collects parameters to use for binary series loading. """ import json from thunder.readers import get_file_reader, FileNotFoundError reader = get_file_reader(path)(credentials=credentials) try: buf = reader...
[ "def", "_binaryconfig", "(", "path", ",", "conf", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "credentials", "=", "None", ")", ":", "import", "json", "from", "thunder", ".", "readers", "import", "get_file_reader", ",", "FileNotFoundError", "...
29.814815
22.555556
def write_response( self, status_code: Union[int, constants.HttpStatusCode], *, headers: Optional[_HeaderType]=None ) -> "writers.HttpResponseWriter": """ Write a response to the client. """ self._writer = self.__delegate.write_response( constants....
[ "def", "write_response", "(", "self", ",", "status_code", ":", "Union", "[", "int", ",", "constants", ".", "HttpStatusCode", "]", ",", "*", ",", "headers", ":", "Optional", "[", "_HeaderType", "]", "=", "None", ")", "->", "\"writers.HttpResponseWriter\"", ":...
32.916667
12.25
def render(ont, query_ids, args): """ Writes or displays graph """ if args.slim.find('m') > -1: logging.info("SLIMMING") g = get_minimal_subgraph(g, query_ids) w = GraphRenderer.create(args.to) if args.showdefs: w.config.show_text_definition = True if args.render: ...
[ "def", "render", "(", "ont", ",", "query_ids", ",", "args", ")", ":", "if", "args", ".", "slim", ".", "find", "(", "'m'", ")", ">", "-", "1", ":", "logging", ".", "info", "(", "\"SLIMMING\"", ")", "g", "=", "get_minimal_subgraph", "(", "g", ",", ...
34
10.117647
def emit(self, what, *args): ''' what can be either name of the op, or node, or a list of statements.''' if isinstance(what, basestring): return self.exe.emit(what, *args) elif isinstance(what, list): self._emit_statement_list(what) else: return getatt...
[ "def", "emit", "(", "self", ",", "what", ",", "*", "args", ")", ":", "if", "isinstance", "(", "what", ",", "basestring", ")", ":", "return", "self", ".", "exe", ".", "emit", "(", "what", ",", "*", "args", ")", "elif", "isinstance", "(", "what", "...
42.75
13.5
def unsubscribe(self, transform="", downlink=False): """Unsubscribes from a previously subscribed stream. Note that the same values of transform and downlink must be passed in order to do the correct unsubscribe:: s.subscribe(callback,transform="if last") s.unsubscribe(transform...
[ "def", "unsubscribe", "(", "self", ",", "transform", "=", "\"\"", ",", "downlink", "=", "False", ")", ":", "streampath", "=", "self", ".", "path", "if", "downlink", ":", "streampath", "+=", "\"/downlink\"", "return", "self", ".", "db", ".", "unsubscribe", ...
40.083333
16.416667
def _confidence(matches, ext=None): """ Rough confidence based on string length and file extension""" results = [] for match in matches: con = (0.8 if len(match.extension) > 9 else float("0.{0}".format(len(match.extension)))) if ext == match.extension: con = 0.9 ...
[ "def", "_confidence", "(", "matches", ",", "ext", "=", "None", ")", ":", "results", "=", "[", "]", "for", "match", "in", "matches", ":", "con", "=", "(", "0.8", "if", "len", "(", "match", ".", "extension", ")", ">", "9", "else", "float", "(", "\"...
42.909091
15.909091
def healthy_services(self, role=None): ''' Look up healthy services in the registry. A service is considered healthy if its 'last_heartbeat' was less than 'ttl' seconds ago Args: role (str, optional): role name Returns: If `role` is supplied, re...
[ "def", "healthy_services", "(", "self", ",", "role", "=", "None", ")", ":", "try", ":", "query", "=", "self", ".", "rr", ".", "table", "(", "self", ".", "table", ")", "if", "role", ":", "query", "=", "query", ".", "get_all", "(", "role", ",", "in...
33.576923
21.346154
def get_db_state(working_dir): """ Callback to the virtual chain state engine. Get a *read-only* handle to our state engine implementation (i.e. our name database). Note that in this implementation, the database handle returned will only support read-only operations by default. Attempts to ...
[ "def", "get_db_state", "(", "working_dir", ")", ":", "impl", "=", "sys", ".", "modules", "[", "__name__", "]", "db_inst", "=", "BlockstackDB", ".", "get_readonly_instance", "(", "working_dir", ")", "assert", "db_inst", ",", "'Failed to instantiate database handle'",...
35
17.588235
def _call(self, x): """Sum all values if indices are given multiple times.""" y = np.bincount(self._indices_flat, weights=x, minlength=self.range.size) out = y.reshape(self.range.shape) if self.variant == 'dirac': weights = getattr(self.range, 'cell_...
[ "def", "_call", "(", "self", ",", "x", ")", ":", "y", "=", "np", ".", "bincount", "(", "self", ".", "_indices_flat", ",", "weights", "=", "x", ",", "minlength", "=", "self", ".", "range", ".", "size", ")", "out", "=", "y", ".", "reshape", "(", ...
31.578947
19.526316
def process(self, makeGlyphs=True, makeKerning=True, makeInfo=True): """ Process the input file and generate the instances. """ if self.logger: self.logger.info("Reading %s", self.path) self.readInstances(makeGlyphs=makeGlyphs, makeKerning=makeKerning, makeInfo=makeInfo) self...
[ "def", "process", "(", "self", ",", "makeGlyphs", "=", "True", ",", "makeKerning", "=", "True", ",", "makeInfo", "=", "True", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "\"Reading %s\"", ",", "self", ".", "pa...
57.666667
19
def is_correct(self): """ Check if the items list configuration is correct :: * check if duplicate items exist in the list and warn about this * set alias and display_name property for each item in the list if they do not exist * check each item in the list * log all pre...
[ "def", "is_correct", "(", "self", ")", ":", "# we are ok at the beginning. Hope we are still ok at the end...", "valid", "=", "True", "# Better check individual items before displaying the global items list errors and warnings", "for", "i", "in", "self", ":", "# Alias and display_nam...
40.395833
21.9375
def luminosities_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_luminosity='eps', exposure_time=None): """Compute the total luminosity of all galaxies in this plane within a circle of specified radius. See *galaxy.light_within_circle* and *light_profiles.light_within_circle* for de...
[ "def", "luminosities_of_galaxies_within_circles_in_units", "(", "self", ",", "radius", ":", "dim", ".", "Length", ",", "unit_luminosity", "=", "'eps'", ",", "exposure_time", "=", "None", ")", ":", "return", "list", "(", "map", "(", "lambda", "galaxy", ":", "ga...
52.789474
28.842105
def get_offset_range(self, row_offset, column_offset): """ Gets an object which represents a range that's offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an ...
[ "def", "get_offset_range", "(", "self", ",", "row_offset", ",", "column_offset", ")", ":", "return", "self", ".", "_get_range", "(", "'offset_range'", ",", "rowOffset", "=", "row_offset", ",", "columnOffset", "=", "column_offset", ")" ]
54.923077
22.461538
def token_approve(self, spender_address, price, from_account): """ Approve the passed address to spend the specified amount of tokens. :param spender_address: Account address, str :param price: Asset price, int :param from_account: Account address, str :return: bool ...
[ "def", "token_approve", "(", "self", ",", "spender_address", ",", "price", ",", "from_account", ")", ":", "if", "not", "Web3Provider", ".", "get_web3", "(", ")", ".", "isChecksumAddress", "(", "spender_address", ")", ":", "spender_address", "=", "Web3Provider", ...
38.25
19.25
def get_nameserver_detail_output_show_nameserver_nameserver_fabric_portname(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_nameserver_detail = ET.Element("get_nameserver_detail") config = get_nameserver_detail output = ET.SubElement(get_name...
[ "def", "get_nameserver_detail_output_show_nameserver_nameserver_fabric_portname", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_nameserver_detail", "=", "ET", ".", "Element", "(", "\"get_nameserver_de...
54.8
24.6
def submit_task(rel_path, cache_string, buffer): """Put an upload job on the queue, and start the thread if required""" global upload_queue global upload_thread upload_queue.put((rel_path, cache_string, buffer)) if upload_thread is None or not upload_thread.is_alive(): upload_thread = Uploa...
[ "def", "submit_task", "(", "rel_path", ",", "cache_string", ",", "buffer", ")", ":", "global", "upload_queue", "global", "upload_thread", "upload_queue", ".", "put", "(", "(", "rel_path", ",", "cache_string", ",", "buffer", ")", ")", "if", "upload_thread", "is...
39.222222
14.111111
def _tower_loss(images, labels, num_classes, scope, reuse_variables=None): """Calculate the total loss on a single tower running the ImageNet model. We perform 'batch splitting'. This means that we cut up a batch across multiple GPU's. For instance, if the batch size = 32 and num_gpus = 2, then each tower will...
[ "def", "_tower_loss", "(", "images", ",", "labels", ",", "num_classes", ",", "scope", ",", "reuse_variables", "=", "None", ")", ":", "# When fine-tuning a model, we do not restore the logits but instead we", "# randomly initialize the logits. The number of classes in the output of ...
46.508475
24.983051
def phi_a(mass1, mass2, spin1x, spin1y, spin2x, spin2y): """ Returns the angle between the in-plane perpendicular spins.""" phi1 = phi_from_spinx_spiny(primary_spin(mass1, mass2, spin1x, spin2x), primary_spin(mass1, mass2, spin1y, spin2y)) phi2 = phi_from_spinx_spiny(secondar...
[ "def", "phi_a", "(", "mass1", ",", "mass2", ",", "spin1x", ",", "spin1y", ",", "spin2x", ",", "spin2y", ")", ":", "phi1", "=", "phi_from_spinx_spiny", "(", "primary_spin", "(", "mass1", ",", "mass2", ",", "spin1x", ",", "spin2x", ")", ",", "primary_spin"...
67.285714
23
def update_db(self, giver, receiverkarma): """ Record a the giver of karma, the receiver of karma, and the karma amount. Typically the count will be 1, but it can be any positive or negative integer. """ for receiver in receiverkarma: if receiver != giver: ...
[ "def", "update_db", "(", "self", ",", "giver", ",", "receiverkarma", ")", ":", "for", "receiver", "in", "receiverkarma", ":", "if", "receiver", "!=", "giver", ":", "urow", "=", "KarmaStatsTable", "(", "ude", "(", "giver", ")", ",", "ude", "(", "receiver"...
37.846154
13.538462
def make_data(n,m): """make_data: prepare matrix of m times n random processing times""" p = {} for i in range(1,m+1): for j in range(1,n+1): p[i,j] = random.randint(1,10) return p
[ "def", "make_data", "(", "n", ",", "m", ")", ":", "p", "=", "{", "}", "for", "i", "in", "range", "(", "1", ",", "m", "+", "1", ")", ":", "for", "j", "in", "range", "(", "1", ",", "n", "+", "1", ")", ":", "p", "[", "i", ",", "j", "]", ...
30
14.857143
def isometric_build_atlased_mesh(script, BorderSize=0.1): """Isometric parameterization: Build Atlased Mesh This actually generates the UV mapping from the isometric parameterization """ filter_xml = ''.join([ ' <filter name="Iso Parametrization Build Atlased Mesh">\n', ' <Param na...
[ "def", "isometric_build_atlased_mesh", "(", "script", ",", "BorderSize", "=", "0.1", ")", ":", "filter_xml", "=", "''", ".", "join", "(", "[", "' <filter name=\"Iso Parametrization Build Atlased Mesh\">\\n'", ",", "' <Param name=\"BorderSize\"'", ",", "'value=\"%s\"'", ...
63.052632
46.315789
def get_parameter(value): """ attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF through some extra checks. We do it this way because it makes both error recov...
[ "def", "get_parameter", "(", "value", ")", ":", "# It is possible CFWS would also be implicitly allowed between the section", "# and the 'extended-attribute' marker (the '*') , but we've never seen that", "# in the wild and we will therefore ignore the possibility.", "param", "=", "Parameter",...
39.594203
16.471014
def copy_with(self, **kwargs): """Return a copy with (a few) changed attributes The keyword arguments are the attributes to be replaced by new values. All other attributes are copied (or referenced) from the original object. This only works if the constructor takes all ...
[ "def", "copy_with", "(", "self", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "{", "}", "for", "key", ",", "descriptor", "in", "self", ".", "__class__", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isinstance", "(", "descriptor", ",", "...
43.588235
17.058824
def product_status(request, form): ''' Summarises the inventory status of the given items, grouping by invoice status. ''' products = form.cleaned_data["product"] categories = form.cleaned_data["category"] items = commerce.ProductItem.objects.filter( Q(product__in=products) | Q(product__ca...
[ "def", "product_status", "(", "request", ",", "form", ")", ":", "products", "=", "form", ".", "cleaned_data", "[", "\"product\"", "]", "categories", "=", "form", ".", "cleaned_data", "[", "\"category\"", "]", "items", "=", "commerce", ".", "ProductItem", "."...
29.205882
21.441176
def createPerson(self, nickname, vip=_NO_VIP): """ Create a new L{Person} with the given name in this organizer. @type nickname: C{unicode} @param nickname: The value for the new person's C{name} attribute. @type vip: C{bool} @param vip: Value to set the created person'...
[ "def", "createPerson", "(", "self", ",", "nickname", ",", "vip", "=", "_NO_VIP", ")", ":", "for", "person", "in", "(", "self", ".", "store", ".", "query", "(", "Person", ",", "attributes", ".", "AND", "(", "Person", ".", "name", "==", "nickname", ","...
32.969697
17.818182
def translate_latex2unicode(text, kb_file=None): """Translate latex text to unicode. This function will take given text, presumably containing LaTeX symbols, and attempts to translate it to Unicode using the given or default KB translation table located under CFG_ETCDIR/bibconvert/KB/latex-to-unico...
[ "def", "translate_latex2unicode", "(", "text", ",", "kb_file", "=", "None", ")", ":", "if", "kb_file", "is", "None", ":", "kb_file", "=", "get_kb_filename", "(", ")", "# First decode input text to Unicode", "try", ":", "text", "=", "decode_to_unicode", "(", "tex...
40.348837
18.627907
def solve_full(z, Fval, DPhival, G, A): M, N=G.shape P, N=A.shape """Total number of inequality constraints""" m=M """Primal variable""" x=z[0:N] """Multiplier for equality constraints""" nu=z[N:N+P] """Multiplier for inequality constraints""" l=z[N+P:N+P+M] """S...
[ "def", "solve_full", "(", "z", ",", "Fval", ",", "DPhival", ",", "G", ",", "A", ")", ":", "M", ",", "N", "=", "G", ".", "shape", "P", ",", "N", "=", "A", ".", "shape", "m", "=", "M", "\"\"\"Primal variable\"\"\"", "x", "=", "z", "[", "0", ":"...
22.106667
18.733333
def queue(self, *args, **kwargs): """ A function to queue a RQ job, e.g.:: @rq.job(timeout=60) def add(x, y): return x + y add.queue(1, 2, timeout=30) :param \\*args: The positional arguments to pass to the queued job. :param \\*\\*...
[ "def", "queue", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queue_name", "=", "kwargs", ".", "pop", "(", "'queue'", ",", "self", ".", "queue_name", ")", "timeout", "=", "kwargs", ".", "pop", "(", "'timeout'", ",", "self", "."...
34.746667
20.293333
def schema(self): """ The DQL query that will construct this table's schema """ attrs = self.attrs.copy() parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema] del attrs[self.hash_key.name] if self.range_key: parts.append(self.range_key.schema + ",") ...
[ "def", "schema", "(", "self", ")", ":", "attrs", "=", "self", ".", "attrs", ".", "copy", "(", ")", "parts", "=", "[", "\"CREATE\"", ",", "\"TABLE\"", ",", "self", ".", "name", ",", "\"(%s,\"", "%", "self", ".", "hash_key", ".", "schema", "]", "del"...
41.705882
19.294118
def start(self, *args, **kwargs): r"""Starts the internal task in the event loop. Parameters ------------ \*args The arguments to to use. \*\*kwargs The keyword arguments to use. Raises -------- RuntimeError A task has...
[ "def", "start", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_task", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'Task is already launched.'", ")", "if", "self", ".", "_injected", "is", "not", "None...
24.62069
19.103448
def namespace_to_taxon() -> Dict[str, Node]: """ namespace to taxon mapping """ human_taxon = Node( id='NCBITaxon:9606', label='Homo sapiens' ) return { 'MGI': Node( id='NCBITaxon:10090', label='Mus musculus' ), 'MONDO': human_tax...
[ "def", "namespace_to_taxon", "(", ")", "->", "Dict", "[", "str", ",", "Node", "]", ":", "human_taxon", "=", "Node", "(", "id", "=", "'NCBITaxon:9606'", ",", "label", "=", "'Homo sapiens'", ")", "return", "{", "'MGI'", ":", "Node", "(", "id", "=", "'NCB...
23.966667
14.433333
def maximum_distance(value): """ :param value: input string corresponding to a valid maximum distance :returns: a IntegrationDistance mapping """ dic = floatdict(value) for trt, magdists in dic.items(): if isinstance(magdists, list): # could be a scalar otherwise ...
[ "def", "maximum_distance", "(", "value", ")", ":", "dic", "=", "floatdict", "(", "value", ")", "for", "trt", ",", "magdists", "in", "dic", ".", "items", "(", ")", ":", "if", "isinstance", "(", "magdists", ",", "list", ")", ":", "# could be a scalar other...
36.071429
14.642857
def autoprefixCSS(sassPath): ''' Take CSS file and automatically add browser prefixes with postCSS autoprefixer ''' print("Autoprefixing CSS") cssPath = os.path.splitext(sassPath)[0] + ".css" command = "postcss --use autoprefixer --autoprefixer.browsers '> 5%' -o" + cssPath + " " + cssPath ...
[ "def", "autoprefixCSS", "(", "sassPath", ")", ":", "print", "(", "\"Autoprefixing CSS\"", ")", "cssPath", "=", "os", ".", "path", ".", "splitext", "(", "sassPath", ")", "[", "0", "]", "+", "\".css\"", "command", "=", "\"postcss --use autoprefixer --autoprefixer....
38.666667
27.111111
def apply_noise(self, noise_weights=None, uniform_amount=0.1): """ Add noise to every link in the network. Can use either a ``uniform_amount`` or a ``noise_weight`` weight profile. If ``noise_weight`` is set, ``uniform_amount`` will be ignored. Args: noise_w...
[ "def", "apply_noise", "(", "self", ",", "noise_weights", "=", "None", ",", "uniform_amount", "=", "0.1", ")", ":", "# Main node loop", "for", "node", "in", "self", ".", "node_list", ":", "for", "link", "in", "node", ".", "link_list", ":", "if", "noise_weig...
39.26087
17.565217
def mkdir_p(path_to_dir): """Make directory(ies). This function behaves like mkdir -p. Args: path_to_dir (:obj:`str`): Path to the directory to make. """ try: os.makedirs(path_to_dir) except OSError as e: # Python >2.5 if e.errno == EEXIST and os.path.isdir(path_to_dir...
[ "def", "mkdir_p", "(", "path_to_dir", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path_to_dir", ")", "except", "OSError", "as", "e", ":", "# Python >2.5", "if", "e", ".", "errno", "==", "EEXIST", "and", "os", ".", "path", ".", "isdir", "(", "p...
27.4375
19.0625
def safe_filepath(file_path_name, dir_sep=None): ''' Input the full path and filename, splits on directory separator and calls safe_filename_leaf for each part of the path. dir_sep allows coder to force a directory separate to a particular character .. versionadded:: 2017.7.2 :codeauthor: Damon At...
[ "def", "safe_filepath", "(", "file_path_name", ",", "dir_sep", "=", "None", ")", ":", "if", "not", "dir_sep", ":", "dir_sep", "=", "os", ".", "sep", "# Normally if file_path_name or dir_sep is Unicode then the output will be Unicode", "# This code ensure the output type is th...
47.809524
31.142857
def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): """Trains the model and predicts on the test data set.""" net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds =...
[ "def", "learn", "(", "epochs", ",", "verbose_epoch", ",", "X_train", ",", "y_train", ",", "test", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "net", "=", "get_net", "(", ")", "_", "=", "train", "(", "net", ",", "X_train", ",...
51.3
15.6
def load_snps( self, raw_data, discrepant_snp_positions_threshold=100, discrepant_genotypes_threshold=500, save_output=False, ): """ Load raw genotype data. Parameters ---------- raw_data : list or str path(s) to file(s) with raw g...
[ "def", "load_snps", "(", "self", ",", "raw_data", ",", "discrepant_snp_positions_threshold", "=", "100", ",", "discrepant_genotypes_threshold", "=", "500", ",", "save_output", "=", "False", ",", ")", ":", "if", "type", "(", "raw_data", ")", "is", "list", ":", ...
37.128205
17.641026
def feeling_lucky(cls, obj): """Tries to convert given object to an UTC timestamp is ms, based on its type. """ if isinstance(obj, six.string_types): return cls.from_str(obj) elif isinstance(obj, six.integer_types) and obj <= MAX_POSIX_TIMESTAMP: return cl...
[ "def", "feeling_lucky", "(", "cls", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")", ":", "return", "cls", ".", "from_str", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "six", ".", "integer_types", ...
39.071429
13.357143
def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None, callback=None): """ Returns the direct descendants of a piece of Content, limited to a single descendant type. The {@link ContentType}(s) of the descend...
[ "def", "get_content_descendants_by_type", "(", "self", ",", "content_id", ",", "child_type", ",", "expand", "=", "None", ",", "start", "=", "None", ",", "limit", "=", "None", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "}", "if", "expand"...
63.966667
35.833333
def update(self, process_list): """Update the AMP""" # Get the systemctl status logger.debug('{}: Update stats using service {}'.format(self.NAME, self.get('service_cmd'))) try: res = check_output(self.get('service_cmd').split(), stderr=STDOUT).decode('utf-8') except ...
[ "def", "update", "(", "self", ",", "process_list", ")", ":", "# Get the systemctl status", "logger", ".", "debug", "(", "'{}: Update stats using service {}'", ".", "format", "(", "self", ".", "NAME", ",", "self", ".", "get", "(", "'service_cmd'", ")", ")", ")"...
39.62069
15
def pexpire(self, name, time): """ Set an expire flag on key ``name`` for ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object. """ if isinstance(time, datetime.timedelta): time = int(time.total_seconds() * 1000) ...
[ "def", "pexpire", "(", "self", ",", "name", ",", "time", ")", ":", "if", "isinstance", "(", "time", ",", "datetime", ".", "timedelta", ")", ":", "time", "=", "int", "(", "time", ".", "total_seconds", "(", ")", "*", "1000", ")", "return", "self", "....
40.444444
14.666667
def make_fileitem_peinfo_exports_dllname(dll_name, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/Exports/DllName :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/Exports/DllName' conte...
[ "def", "make_fileitem_peinfo_exports_dllname", "(", "dll_name", ",", "condition", "=", "'is'", ",", "negate", "=", "False", ",", "preserve_case", "=", "False", ")", ":", "document", "=", "'FileItem'", "search", "=", "'FileItem/PEInfo/Exports/DllName'", "content_type",...
42.769231
23.846154
def _init_file(self, ti): """ Create log directory and give it correct permissions. :param ti: task instance object :return: relative log path of the given task instance """ # To handle log writing when tasks are impersonated, the log files need to # be writable b...
[ "def", "_init_file", "(", "self", ",", "ti", ")", ":", "# To handle log writing when tasks are impersonated, the log files need to", "# be writable by the user that runs the Airflow command and the user", "# that is impersonated. This is mainly to handle corner cases with the", "# SubDagOperat...
56.105263
24.842105
async def _dump_message_field(self, writer, msg, field, fvalue=None): """ Dumps a message field to the writer. Field is defined by the message field specification. :param writer: :param msg: :param field: :param fvalue: :return: """ fname, ftype, ...
[ "async", "def", "_dump_message_field", "(", "self", ",", "writer", ",", "msg", ",", "field", ",", "fvalue", "=", "None", ")", ":", "fname", ",", "ftype", ",", "params", "=", "field", "[", "0", "]", ",", "field", "[", "1", "]", ",", "field", "[", ...
36.923077
22.923077
def convert_to_merged_ids(self, id_run): """ Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases :param id_run: a run of token ids :param dictionary: a dictionary of acceptable phrases described as there component token ids ...
[ "def", "convert_to_merged_ids", "(", "self", ",", "id_run", ")", ":", "i", "=", "0", "rv", "=", "[", "]", "while", "i", "<", "len", "(", "id_run", ")", ":", "phrase_id", ",", "offset", "=", "self", ".", "max_phrase", "(", "id_run", ",", "i", ")", ...
36.666667
18
def clean(text, cls=None, **kwargs): """Public facing function to clean ``text`` using the scrubber ``cls`` by replacing all personal information with ``{{PLACEHOLDERS}}``. """ cls = cls or Scrubber scrubber = cls() return scrubber.clean(text, **kwargs)
[ "def", "clean", "(", "text", ",", "cls", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cls", "=", "cls", "or", "Scrubber", "scrubber", "=", "cls", "(", ")", "return", "scrubber", ".", "clean", "(", "text", ",", "*", "*", "kwargs", ")" ]
38.714286
9.285714
def secondary_mass(mass1, mass2): """Returns the smaller of mass1 and mass2 (s = secondary).""" mass1, mass2, input_is_array = ensurearray(mass1, mass2) if mass1.shape != mass2.shape: raise ValueError("mass1 and mass2 must have same shape") ms = copy.copy(mass2) mask = mass1 < mass2 ms[m...
[ "def", "secondary_mass", "(", "mass1", ",", "mass2", ")", ":", "mass1", ",", "mass2", ",", "input_is_array", "=", "ensurearray", "(", "mass1", ",", "mass2", ")", "if", "mass1", ".", "shape", "!=", "mass2", ".", "shape", ":", "raise", "ValueError", "(", ...
41.555556
11.666667
def element(element, name, default=None): """ Returns the value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to retur...
[ "def", "element", "(", "element", ",", "name", ",", "default", "=", "None", ")", ":", "element_value", "=", "element", ".", "find", "(", "name", ")", "return", "element_value", ".", "text", "if", "element_value", "is", "not", "None", "else", "default" ]
32.714286
18.571429
def _transform(self, inp): """Basic MD5 step transforming the digest based on the input. Note that if the Mysterious Constants are arranged backwards in little-endian order and decrypted with the DES they produce OCCULT MESSAGES! """ a, b, c, d = A, B, C, D = se...
[ "def", "_transform", "(", "self", ",", "inp", ")", ":", "a", ",", "b", ",", "c", ",", "d", "=", "A", ",", "B", ",", "C", ",", "D", "=", "self", ".", "A", ",", "self", ".", "B", ",", "self", ".", "C", ",", "self", ".", "D", "# Round 1.\r",...
48.12
23.3
def to_native_units(self, motor): """ Return the native speed measurement required to achieve desired degrees-per-minute """ assert abs(self.degrees_per_minute) <= motor.max_dpm,\ "invalid degrees-per-minute: {} max DPM is {}, {} was requested".format( motor, moto...
[ "def", "to_native_units", "(", "self", ",", "motor", ")", ":", "assert", "abs", "(", "self", ".", "degrees_per_minute", ")", "<=", "motor", ".", "max_dpm", ",", "\"invalid degrees-per-minute: {} max DPM is {}, {} was requested\"", ".", "format", "(", "motor", ",", ...
52.375
21.375
def vnic_attach_to_network_distributed(nicspec, port_group, logger): """ Attach vNIC to a Distributed Port Group network :param nicspec: <vim.vm.device.VirtualDeviceSpec> :param port_group: <vim.dvs.DistributedVirtualPortgroup> :param logger: :return: updated 'nicspec' ...
[ "def", "vnic_attach_to_network_distributed", "(", "nicspec", ",", "port_group", ",", "logger", ")", ":", "if", "nicspec", "and", "network_is_portgroup", "(", "port_group", ")", ":", "network_name", "=", "port_group", ".", "name", "dvs_port_connection", "=", "vim", ...
44.5
24.318182
def log_p_blanket(self, beta): """ Creates complete Markov blanket for latent variables Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- Markov blanket for latent variables "...
[ "def", "log_p_blanket", "(", "self", ",", "beta", ")", ":", "states", "=", "np", ".", "zeros", "(", "[", "self", ".", "state_no", ",", "self", ".", "data", ".", "shape", "[", "0", "]", "]", ")", "for", "state_i", "in", "range", "(", "self", ".", ...
38.705882
25.294118
def transform(self, data, test=False): '''Transform image data to latent space. Parameters ---------- data : array-like shape (n_images, image_width, image_height, n_colors) Input numpy array of images. test [optional] : bool ...
[ "def", "transform", "(", "self", ",", "data", ",", "test", "=", "False", ")", ":", "#make sure that data has the right shape.", "if", "not", "type", "(", "data", ")", "==", "Variable", ":", "if", "len", "(", "data", ".", "shape", ")", "<", "4", ":", "d...
38.82
18.74
def get_index(binstr, end_index=160): """ Return the position of the first 1 bit from the left in the word until end_index :param binstr: :param end_index: :return: """ res = -1 try: res = binstr.index('1') + 1 except ValueError: res = end_index return res
[ "def", "get_index", "(", "binstr", ",", "end_index", "=", "160", ")", ":", "res", "=", "-", "1", "try", ":", "res", "=", "binstr", ".", "index", "(", "'1'", ")", "+", "1", "except", "ValueError", ":", "res", "=", "end_index", "return", "res" ]
20.2
16.333333
def _url_params(size:str='>400*300', format:str='jpg') -> str: "Build Google Images Search Url params and return them as a string." _fmts = {'jpg':'ift:jpg','gif':'ift:gif','png':'ift:png','bmp':'ift:bmp', 'svg':'ift:svg','webp':'webp','ico':'ift:ico'} if size not in _img_sizes: raise RuntimeError(...
[ "def", "_url_params", "(", "size", ":", "str", "=", "'>400*300'", ",", "format", ":", "str", "=", "'jpg'", ")", "->", "str", ":", "_fmts", "=", "{", "'jpg'", ":", "'ift:jpg'", ",", "'gif'", ":", "'ift:gif'", ",", "'png'", ":", "'ift:png'", ",", "'bmp...
71.777778
27.888889
def _get_record(self, ipnum): """ Populate location dict for converted IP. Returns dict with numerous location properties. :arg ipnum: Result of ip2long conversion """ seek_country = self._seek_country(ipnum) if seek_country == self._databaseSegments: ...
[ "def", "_get_record", "(", "self", ",", "ipnum", ")", ":", "seek_country", "=", "self", ".", "_seek_country", "(", "ipnum", ")", "if", "seek_country", "==", "self", ".", "_databaseSegments", ":", "return", "{", "}", "read_length", "=", "(", "2", "*", "se...
33.416667
21.416667
def obj(self): """ Returns passed object but if chain method is used returns the last processed result """ if self._wrapped is not self.Null: return self._wrapped else: return self.object
[ "def", "obj", "(", "self", ")", ":", "if", "self", ".", "_wrapped", "is", "not", "self", ".", "Null", ":", "return", "self", ".", "_wrapped", "else", ":", "return", "self", ".", "object" ]
27.888889
10.111111
def _extract_dir(self, dir_not_exists, output): """Extract the content of dvc tree file Args: self(object) - Repo class instance dir_not_exists(bool) - flag for directory existence output(object) - OutputLOCAL class instance Returns: dict - dictionary with keys - paths to fil...
[ "def", "_extract_dir", "(", "self", ",", "dir_not_exists", ",", "output", ")", ":", "if", "not", "dir_not_exists", ":", "lst", "=", "output", ".", "dir_cache", "return", "{", "i", "[", "\"relpath\"", "]", ":", "i", "[", "\"md5\"", "]", "for", "i", "in"...
37.071429
14.928571
def replace_post_data_parameters(request, replacements): """ Replace post data in request--either form data or json--according to replacements. The replacements should be a list of (key, value) pairs where the value can be any of: 1. A simple replacement string value. 2. None to remove the g...
[ "def", "replace_post_data_parameters", "(", "request", ",", "replacements", ")", ":", "replacements", "=", "dict", "(", "replacements", ")", "if", "request", ".", "method", "==", "'POST'", "and", "not", "isinstance", "(", "request", ".", "body", ",", "BytesIO"...
46.795455
15.204545
def mod_watch(name, **kwargs): ''' Install/reinstall a package based on a watch requisite .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the stat...
[ "def", "mod_watch", "(", "name", ",", "*", "*", "kwargs", ")", ":", "sfun", "=", "kwargs", ".", "pop", "(", "'sfun'", ",", "None", ")", "mapfun", "=", "{", "'purged'", ":", "purged", ",", "'latest'", ":", "latest", ",", "'removed'", ":", "removed", ...
34.904762
21.095238
def remove_option(self, mask): """Unset arbitrary query flags using a bitmask. To unset the tailable flag: cursor.remove_option(2) """ if not isinstance(mask, int): raise TypeError("mask must be an int") self.__check_okay_to_chain() if mask & _QUERY_...
[ "def", "remove_option", "(", "self", ",", "mask", ")", ":", "if", "not", "isinstance", "(", "mask", ",", "int", ")", ":", "raise", "TypeError", "(", "\"mask must be an int\"", ")", "self", ".", "__check_okay_to_chain", "(", ")", "if", "mask", "&", "_QUERY_...
27.8
13.133333
def execute(self, statements, exc=IntegrityError, rasie_as=ValueError): """Execute ``statements`` in a session, and perform a rollback on error. ``exc`` is a single exception object or a tuple of objects to be used in the except clause. The error message is re-raised as the exception spe...
[ "def", "execute", "(", "self", ",", "statements", ",", "exc", "=", "IntegrityError", ",", "rasie_as", "=", "ValueError", ")", ":", "Session", "=", "sessionmaker", "(", "bind", "=", "self", ".", "engine", ")", "session", "=", "Session", "(", ")", "try", ...
33.095238
18.142857
def gather(self, *futures: Union[asyncio.Future, asyncio.coroutine]): """Gather list of futures/coros and return single Task ready to schedule. :Example: Prepare all futures to execution .. code-block:: python >>> async def do_something(): ... return 'some...
[ "def", "gather", "(", "self", ",", "*", "futures", ":", "Union", "[", "asyncio", ".", "Future", ",", "asyncio", ".", "coroutine", "]", ")", ":", "self", ".", "ft_count", "=", "len", "(", "futures", ")", "self", ".", "futures", "=", "asyncio", ".", ...
33.147059
19.441176
def weave_on(advices, pointcut=None, ctx=None, depth=1, ttl=None): """Decorator for weaving advices on a callable target. :param pointcut: condition for weaving advices on joinpointe. The condition depends on its type. :param ctx: target ctx (instance or class). :type pointcut: - NoneTy...
[ "def", "weave_on", "(", "advices", ",", "pointcut", "=", "None", ",", "ctx", "=", "None", ",", "depth", "=", "1", ",", "ttl", "=", "None", ")", ":", "def", "__weave", "(", "target", ")", ":", "\"\"\"Internal weave function.\"\"\"", "weave", "(", "target"...
30.586207
20.206897
def minute(self): """ Extract the "minute" part from a date column. :returns: a single-column H2OFrame containing the "minute" part from the source frame. """ fr = H2OFrame._expr(expr=ExprNode("minute", self), cache=self._ex._cache) if fr._ex._cache.types_valid(): ...
[ "def", "minute", "(", "self", ")", ":", "fr", "=", "H2OFrame", ".", "_expr", "(", "expr", "=", "ExprNode", "(", "\"minute\"", ",", "self", ")", ",", "cache", "=", "self", ".", "_ex", ".", "_cache", ")", "if", "fr", ".", "_ex", ".", "_cache", ".",...
40.5
23.7
def _join_keys_v1(left, right): """ Join two keys into a format separable by using _split_keys_v1. """ if left.endswith(':') or '::' in left: raise ValueError("Can't join a left string ending in ':' or containing '::'") return u"{}::{}".format(_encode_v1(left), _encode_v1(right))
[ "def", "_join_keys_v1", "(", "left", ",", "right", ")", ":", "if", "left", ".", "endswith", "(", "':'", ")", "or", "'::'", "in", "left", ":", "raise", "ValueError", "(", "\"Can't join a left string ending in ':' or containing '::'\"", ")", "return", "u\"{}::{}\"",...
43.142857
15.142857
def summarize_dataframe(self): """Summarize default dataframe for this cohort using a hash function. Useful for confirming the version of data used in various reports, e.g. ipynbs """ if self.dataframe_hash: return(self.dataframe_hash) else: df = self._as_...
[ "def", "summarize_dataframe", "(", "self", ")", ":", "if", "self", ".", "dataframe_hash", ":", "return", "(", "self", ".", "dataframe_hash", ")", "else", ":", "df", "=", "self", ".", "_as_dataframe_unmodified", "(", ")", "return", "(", "self", ".", "datafr...
41.555556
11.333333