text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _validated_locations(self, locations): """Ensure that the given locations argument is valid. :raises: ValueError if a given locations includes an invalid location. """ # The set difference between the given locations and the available locations # will be the set of invalid l...
[ "def", "_validated_locations", "(", "self", ",", "locations", ")", ":", "# The set difference between the given locations and the available locations", "# will be the set of invalid locations", "valid_locations", "=", "set", "(", "self", ".", "__location_map__", ".", "keys", "(...
45.5
17.357143
def remove_layer(svg_source, layer_name): ''' Remove layer(s) from SVG document. Arguments --------- svg_source : str or file-like A file path, URI, or file-like object. layer_name : str or list Layer name or list of layer names to remove from SVG document. Returns ----...
[ "def", "remove_layer", "(", "svg_source", ",", "layer_name", ")", ":", "# Parse input file.", "xml_root", "=", "lxml", ".", "etree", ".", "parse", "(", "svg_source", ")", "svg_root", "=", "xml_root", ".", "xpath", "(", "'/svg:svg'", ",", "namespaces", "=", "...
29.447368
21.394737
def query(options, collection_name, num_to_skip, num_to_return, query, field_selector=None): """Get a **query** message. """ data = struct.pack("<I", options) data += bson._make_c_string(collection_name) data += struct.pack("<i", num_to_skip) data += struct.pack("<i", num_to_return) ...
[ "def", "query", "(", "options", ",", "collection_name", ",", "num_to_skip", ",", "num_to_return", ",", "query", ",", "field_selector", "=", "None", ")", ":", "data", "=", "struct", ".", "pack", "(", "\"<I\"", ",", "options", ")", "data", "+=", "bson", "....
38.666667
5.833333
def saturating_sigmoid(x): """Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1].""" with tf.name_scope("saturating_sigmoid", values=[x]): y = tf.sigmoid(x) return tf.minimum(1.0, tf.maximum(0.0, 1.2 * y - 0.1))
[ "def", "saturating_sigmoid", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"saturating_sigmoid\"", ",", "values", "=", "[", "x", "]", ")", ":", "y", "=", "tf", ".", "sigmoid", "(", "x", ")", "return", "tf", ".", "minimum", "(", "1.0", ...
45
13.2
def assemble_caption(begin_line, begin_index, end_line, end_index, lines): """ Take the caption of a picture and put it all together in a nice way. If it spans multiple lines, put it on one line. If it contains controlled characters, strip them out. If it has tags we don't want to worry about, ge...
[ "def", "assemble_caption", "(", "begin_line", ",", "begin_index", ",", "end_line", ",", "end_index", ",", "lines", ")", ":", "# stuff we don't like", "label_head", "=", "'\\\\label{'", "# reassemble that sucker", "if", "end_line", ">", "begin_line", ":", "# our captio...
39.62
24.06
def macho_dependencies_list(target_path, header_magic=None): """ Generates a list of libraries the given Mach-O file depends on. In that list a single library is represented by its "install path": for some libraries it would be a full file path, and for others it would be a relative path (sometimes with dyld templ...
[ "def", "macho_dependencies_list", "(", "target_path", ",", "header_magic", "=", "None", ")", ":", "MachODeprendencies", "=", "namedtuple", "(", "\"MachODeprendecies\"", ",", "\"weak strong\"", ")", "# Convert the magic value into macholib representation if needed", "if", "isi...
46.040816
26.530612
def getChanges(self): """Get all :class:`rtcclient.models.Change` objects in this changeset :return: a :class:`list` contains all the :class:`rtcclient.models.Change` objects :rtype: list """ identifier = self.url.split("/")[-1] resource_url = "/".join(["%s"...
[ "def", "getChanges", "(", "self", ")", ":", "identifier", "=", "self", ".", "url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "resource_url", "=", "\"/\"", ".", "join", "(", "[", "\"%s\"", "%", "self", ".", "rtc_obj", ".", "url", ",", "...
41.423077
13.653846
def weighted_sampler(seq, weights): "Return a random-sample function that picks from seq weighted by weights." totals = [] for w in weights: totals.append(w + totals[-1] if totals else w) return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]
[ "def", "weighted_sampler", "(", "seq", ",", "weights", ")", ":", "totals", "=", "[", "]", "for", "w", "in", "weights", ":", "totals", ".", "append", "(", "w", "+", "totals", "[", "-", "1", "]", "if", "totals", "else", "w", ")", "return", "lambda", ...
46.5
22.833333
def parse_fixed(self, node): """ Parses <Fixed> @param node: Node containing the <Fixed> element @type node: xml.etree.Element """ try: parameter = node.lattrib['parameter'] except: self.raise_error('<Fixed> must specify a parameter to be...
[ "def", "parse_fixed", "(", "self", ",", "node", ")", ":", "try", ":", "parameter", "=", "node", ".", "lattrib", "[", "'parameter'", "]", "except", ":", "self", ".", "raise_error", "(", "'<Fixed> must specify a parameter to be fixed.'", ")", "try", ":", "value"...
29.666667
23.952381
def run(command, timeout=None, cwd=None, env=None, debug=None): """ Runs a given command on the system within a set time period, providing an easy way to access command output as it happens without waiting for the command to finish running. :type list :param command: Should be a list that contains ...
[ "def", "run", "(", "command", ",", "timeout", "=", "None", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "debug", "=", "None", ")", ":", "return", "Command", ".", "run", "(", "command", ",", "timeout", "=", "timeout", ",", "cwd", "=", "c...
57.342857
40.085714
def update_where(self, res, depth=0, since=None, **kwargs): "Like update() but uses WHERE-style args" fetch = lambda: self._fetcher.fetch_all_latest(res, 0, kwargs, since=since) self._update(res, fetch, depth)
[ "def", "update_where", "(", "self", ",", "res", ",", "depth", "=", "0", ",", "since", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fetch", "=", "lambda", ":", "self", ".", "_fetcher", ".", "fetch_all_latest", "(", "res", ",", "0", ",", "kwargs"...
57.5
18
def move_arc(x, y, r, speed = 1, orientation = True): # WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions """ Moves the cursor in an arc of radius r to (x, y) at a certain speed :param x: target x-ordinate :param y: target y-ordinate :par...
[ "def", "move_arc", "(", "x", ",", "y", ",", "r", ",", "speed", "=", "1", ",", "orientation", "=", "True", ")", ":", "# WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions", "_x", ",", "_y", "=", "win32api", ".", ...
41.444444
20.851852
def start(self, driver=None, device=None, midi_driver=None): """Start audio output driver in separate background thread Call this function any time after creating the Synth object. If you don't call this function, use get_samples() to generate samples. Optional keyword argument...
[ "def", "start", "(", "self", ",", "driver", "=", "None", ",", "device", "=", "None", ",", "midi_driver", "=", "None", ")", ":", "if", "driver", "is", "not", "None", ":", "assert", "(", "driver", "in", "[", "'alsa'", ",", "'oss'", ",", "'jack'", ","...
53.645161
29.483871
def build_verify_command(self, packages): """build_verify_command(self, packages) -> str Generate a command to verify the list of packages given in ``packages`` using the native package manager's verification tool. The command to be executed is returned as a stri...
[ "def", "build_verify_command", "(", "self", ",", "packages", ")", ":", "if", "not", "self", ".", "verify_command", ":", "return", "None", "# The re.match(pkg) used by all_pkgs_by_name_regex() may return", "# an empty list (`[[]]`) when no package matches: avoid building", "# an r...
41.1
16.825
def publish(self, user, provider, obj, comment, **kwargs): ''' user - django User or UserSocialAuth instance provider - name of publisher provider obj - sharing object comment - string ''' social_user = self._get_social_user(user, provider) ...
[ "def", "publish", "(", "self", ",", "user", ",", "provider", ",", "obj", ",", "comment", ",", "*", "*", "kwargs", ")", ":", "social_user", "=", "self", ".", "_get_social_user", "(", "user", ",", "provider", ")", "backend", "=", "self", ".", "get_backen...
42.2
17.8
def get_redis_info(): """Check Redis connection.""" from kombu.utils.url import _parse_url as parse_redis_url from redis import ( StrictRedis, ConnectionError as RedisConnectionError, ResponseError as RedisResponseError, ) for conf_name in ('REDIS_URL', 'BROKER_URL', 'CELERY_...
[ "def", "get_redis_info", "(", ")", ":", "from", "kombu", ".", "utils", ".", "url", "import", "_parse_url", "as", "parse_redis_url", "from", "redis", "import", "(", "StrictRedis", ",", "ConnectionError", "as", "RedisConnectionError", ",", "ResponseError", "as", "...
37.128205
17.512821
def release(self) -> None: """Increment the counter and wake one waiter.""" self._value += 1 while self._waiters: waiter = self._waiters.popleft() if not waiter.done(): self._value -= 1 # If the waiter is a coroutine paused at ...
[ "def", "release", "(", "self", ")", "->", "None", ":", "self", ".", "_value", "+=", "1", "while", "self", ".", "_waiters", ":", "waiter", "=", "self", ".", "_waiters", ".", "popleft", "(", ")", "if", "not", "waiter", ".", "done", "(", ")", ":", "...
37
16.5
def install(runas=None, path=None): ''' Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _install_pyenv(path, runas)
[ "def", "install", "(", "runas", "=", "None", ",", "path", "=", "None", ")", ":", "path", "=", "path", "or", "_pyenv_path", "(", "runas", ")", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "return", "_install_pyenv", "(", "path"...
19.769231
20.230769
def add_grid(self, row=None, col=None, row_span=1, col_span=1, **kwargs): """ Create a new Grid and add it as a child widget. Parameters ---------- row : int The row in which to add the widget (0 is the topmost row) col : int The ...
[ "def", "add_grid", "(", "self", ",", "row", "=", "None", ",", "col", "=", "None", ",", "row_span", "=", "1", ",", "col_span", "=", "1", ",", "*", "*", "kwargs", ")", ":", "from", ".", "grid", "import", "Grid", "grid", "=", "Grid", "(", "*", "*"...
37.238095
20.666667
def hostinterface_delete(interfaceids, **kwargs): ''' Delete host interface .. versionadded:: 2016.3.0 :param interfaceids: IDs of the host interfaces to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_passwo...
[ "def", "hostinterface_delete", "(", "interfaceids", ",", "*", "*", "kwargs", ")", ":", "conn_args", "=", "_login", "(", "*", "*", "kwargs", ")", "ret", "=", "{", "}", "try", ":", "if", "conn_args", ":", "method", "=", "'hostinterface.delete'", "if", "isi...
34.333333
26.333333
def _show_status_for_work(self, work): """Shows status for given work pieces. Args: work: instance of either AttackWorkPieces or DefenseWorkPieces """ work_count = len(work.work) work_completed = {} work_completed_count = 0 for v in itervalues(work.work): if v['is_completed']: ...
[ "def", "_show_status_for_work", "(", "self", ",", "work", ")", ":", "work_count", "=", "len", "(", "work", ".", "work", ")", "work_completed", "=", "{", "}", "work_completed_count", "=", "0", "for", "v", "in", "itervalues", "(", "work", ".", "work", ")",...
39.533333
13.166667
def get_sub_dept_ids(self): """Method to get the department list""" self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return self.json_response.get("sub_dept_id_list", None)
[ "def", "get_sub_dept_ids", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"%s\\t%s\"", "%", "(", "self", ".", "request_method", ",", "self", ".", "request_url", ")", ")", "return", "self", ".", "json_response", ".", "get", "(", "\"sub_...
54
18
def update_list_positions_obj(self, positions_obj_id, revision, values): ''' Updates the ordering of lists to have the given value. The given ID and revision should match the singleton object defining how lists are laid out. See https://developer.wunderlist.com/documentation/endpoints/positions...
[ "def", "update_list_positions_obj", "(", "self", ",", "positions_obj_id", ",", "revision", ",", "values", ")", ":", "return", "positions_endpoints", ".", "update_list_positions_obj", "(", "self", ",", "positions_obj_id", ",", "revision", ",", "values", ")" ]
54.2
46.8
def readFromProto(cls, proto): """ Read state from proto object. :param proto: SDRClassifierRegionProto capnproto object """ instance = cls() instance.implementation = proto.implementation instance.steps = proto.steps instance.stepsList = [int(i) for i in proto.steps.split(",")] in...
[ "def", "readFromProto", "(", "cls", ",", "proto", ")", ":", "instance", "=", "cls", "(", ")", "instance", ".", "implementation", "=", "proto", ".", "implementation", "instance", ".", "steps", "=", "proto", ".", "steps", "instance", ".", "stepsList", "=", ...
29.272727
17.181818
def hashable(val): """Test if `val` is hashable and if not, get it's string representation Parameters ---------- val: object Any (possibly not hashable) python object Returns ------- val or string The given `val` if it is hashable or it's string representation""" if val...
[ "def", "hashable", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "val", "try", ":", "hash", "(", "val", ")", "except", "TypeError", ":", "return", "repr", "(", "val", ")", "else", ":", "return", "val" ]
21.6
22.75
def git_ls_remote(self, uri, ref): """Determine the latest commit id for a given ref. Args: uri (string): git URI ref (string): git ref Returns: str: A commit id """ logger.debug("Invoking git to retrieve commit id for repo %s...", uri) ...
[ "def", "git_ls_remote", "(", "self", ",", "uri", ",", "ref", ")", ":", "logger", ".", "debug", "(", "\"Invoking git to retrieve commit id for repo %s...\"", ",", "uri", ")", "lsremote_output", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'ls-...
36.909091
19.772727
def numberOfTilesAtZoom(self, zoom): "Returns the total number of tile at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return (maxCol - minCol + 1) * (maxRow - minRow + 1)
[ "def", "numberOfTilesAtZoom", "(", "self", ",", "zoom", ")", ":", "[", "minRow", ",", "minCol", ",", "maxRow", ",", "maxCol", "]", "=", "self", ".", "getExtentAddress", "(", "zoom", ")", "return", "(", "maxCol", "-", "minCol", "+", "1", ")", "*", "("...
57.5
19.5
def plotShape (includePost = ['all'], includePre = ['all'], showSyns = False, showElectrodes = False, synStyle = '.', synSiz=3, dist=0.6, cvar=None, cvals=None, iv=False, ivprops=None, includeAxon=True, bkgColor = None, fontSize = 12, figSize = (10,8), saveData = None, dpi = 300, saveFig = None, showFig = True): ...
[ "def", "plotShape", "(", "includePost", "=", "[", "'all'", "]", ",", "includePre", "=", "[", "'all'", "]", ",", "showSyns", "=", "False", ",", "showElectrodes", "=", "False", ",", "synStyle", "=", "'.'", ",", "synSiz", "=", "3", ",", "dist", "=", "0....
48.417582
28.164835
def do_size(self, w, h): """Record size.""" if (w is None): self.sw = self.rw self.sh = self.rh else: self.sw = w self.sh = h # Now we have region and size, generate the image image = Image.new("RGB", (self.sw, self.sh), self.gen.ba...
[ "def", "do_size", "(", "self", ",", "w", ",", "h", ")", ":", "if", "(", "w", "is", "None", ")", ":", "self", ".", "sw", "=", "self", ".", "rw", "self", ".", "sh", "=", "self", ".", "rh", "else", ":", "self", ".", "sw", "=", "w", "self", "...
37.777778
13.777778
def submit(self, password=''): """Submits the participation to the web site. The passwords is sent as plain text. :return: the evaluation results. """ url = '{}/api/submit'.format(BASE_URL) try: r = requests.post(url, data=self...
[ "def", "submit", "(", "self", ",", "password", "=", "''", ")", ":", "url", "=", "'{}/api/submit'", ".", "format", "(", "BASE_URL", ")", "try", ":", "r", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "self", ".", "dumps", "(", ")", "...
32.153846
22.461538
def setDefaultIREncoding(encoding): ''' setDefaultIREncoding - Sets the default encoding used by IndexedRedis. This will be the default encoding used for field data. You can override this on a per-field basis by using an IRField (such as IRUnicodeField or IRRawField) @param encoding - An encoding (like ut...
[ "def", "setDefaultIREncoding", "(", "encoding", ")", ":", "try", ":", "b''", ".", "decode", "(", "encoding", ")", "except", ":", "raise", "ValueError", "(", "'setDefaultIREncoding was provided an invalid codec. Got (encoding=\"%s\")'", "%", "(", "str", "(", "encoding"...
34.866667
30.6
def get_args(obj): """Get a list of argument names for a callable.""" if inspect.isfunction(obj): return inspect.getargspec(obj).args elif inspect.ismethod(obj): return inspect.getargspec(obj).args[1:] elif inspect.isclass(obj): return inspect.getargspec(obj.__init__).args[1:] ...
[ "def", "get_args", "(", "obj", ")", ":", "if", "inspect", ".", "isfunction", "(", "obj", ")", ":", "return", "inspect", ".", "getargspec", "(", "obj", ")", ".", "args", "elif", "inspect", ".", "ismethod", "(", "obj", ")", ":", "return", "inspect", "....
40.083333
13.416667
def _check_min_max_range(self, var, test_ctx): """ Checks that either both valid_min and valid_max exist, or valid_range exists. """ if 'valid_range' in var.ncattrs(): test_ctx.assert_true(var.valid_range.dtype == var.dtype and len(var...
[ "def", "_check_min_max_range", "(", "self", ",", "var", ",", "test_ctx", ")", ":", "if", "'valid_range'", "in", "var", ".", "ncattrs", "(", ")", ":", "test_ctx", ".", "assert_true", "(", "var", ".", "valid_range", ".", "dtype", "==", "var", ".", "dtype",...
56.291667
26.541667
def is_bool_indexer(key: Any) -> bool: """ Check whether `key` is a valid boolean indexer. Parameters ---------- key : Any Only list-likes may be considered boolean indexers. All other types are not considered a boolean indexer. For array-like input, boolean ndarrays or Exte...
[ "def", "is_bool_indexer", "(", "key", ":", "Any", ")", "->", "bool", ":", "na_msg", "=", "'cannot index with vector containing NA / NaN values'", "if", "(", "isinstance", "(", "key", ",", "(", "ABCSeries", ",", "np", ".", "ndarray", ",", "ABCIndex", ")", ")", ...
33
19.583333
def get_all(self, references, field_paths=None, transaction=None): """Retrieve a batch of documents. .. note:: Documents returned by this method are not guaranteed to be returned in the same order that they are given in ``references``. .. note:: If multiple `...
[ "def", "get_all", "(", "self", ",", "references", ",", "field_paths", "=", "None", ",", "transaction", "=", "None", ")", ":", "document_paths", ",", "reference_map", "=", "_reference_info", "(", "references", ")", "mask", "=", "_get_doc_mask", "(", "field_path...
41.12766
25.340426
def install_frontend(instance='default', forcereload=False, forcerebuild=False, forcecopy=True, install=True, development=False, build_type='dist'): """Builds and installs the frontend""" hfoslog("Updating frontend components", emitter='BUILDER') components = {} loadable_components...
[ "def", "install_frontend", "(", "instance", "=", "'default'", ",", "forcereload", "=", "False", ",", "forcerebuild", "=", "False", ",", "forcecopy", "=", "True", ",", "install", "=", "True", ",", "development", "=", "False", ",", "build_type", "=", "'dist'",...
39.904523
22.417085
def reference(self, t, i): """Handle references.""" octal = self.get_octal(t, i) if t in _OCTAL and octal: self.parse_octal(octal, i) elif (t in _DIGIT or t == 'g') and not self.use_format: group = self.get_group(t, i) if not group: gro...
[ "def", "reference", "(", "self", ",", "t", ",", "i", ")", ":", "octal", "=", "self", ".", "get_octal", "(", "t", ",", "i", ")", "if", "t", "in", "_OCTAL", "and", "octal", ":", "self", ".", "parse_octal", "(", "octal", ",", "i", ")", "elif", "("...
35.860465
8.27907
def alpha_gen(x): """ Create a mappable function alpha to apply to each xmin in a list of xmins. This is essentially the slow version of fplfit/cplfit, though I bet it could be speeded up with a clever use of parellel_map. Not intended to be used by users. Docstring for the generated alpha function:: ...
[ "def", "alpha_gen", "(", "x", ")", ":", "def", "alpha_", "(", "xmin", ",", "x", "=", "x", ")", ":", "\"\"\"\n Given a sorted data set and a minimum, returns power law MLE fit\n data is passed as a keyword parameter so that it can be vectorized\n\n If there is onl...
35.481481
21.518519
def processTPED(uniqueSNPs, mapF, fileName, tfam, prefix): """Process the TPED file. :param uniqueSNPs: the unique markers. :param mapF: a representation of the ``map`` file. :param fileName: the name of the ``tped`` file. :param tfam: the name of the ``tfam`` file. :param prefix: the prefix of...
[ "def", "processTPED", "(", "uniqueSNPs", ",", "mapF", ",", "fileName", ",", "tfam", ",", "prefix", ")", ":", "# Copying the tfam file", "try", ":", "shutil", ".", "copy", "(", "tfam", ",", "prefix", "+", "\".unique_snps.tfam\"", ")", "except", "IOError", ":"...
32.942029
20.188406
def prepare_data(self): ''' Method returning data passed to template. Subclasses can override it. ''' value = self.get_raw_value() return dict(widget=self, field=self.field, value=value, readonly=not self.field.w...
[ "def", "prepare_data", "(", "self", ")", ":", "value", "=", "self", ".", "get_raw_value", "(", ")", "return", "dict", "(", "widget", "=", "self", ",", "field", "=", "self", ".", "field", ",", "value", "=", "value", ",", "readonly", "=", "not", "self"...
31.9
12.5
def next(self): """ Returns the next element from the array. :return: the next array element object, wrapped as JavaObject if not null :rtype: JavaObject or None """ if self.index < self.length: index = self.index self.index += 1 retur...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "index", "<", "self", ".", "length", ":", "index", "=", "self", ".", "index", "self", ".", "index", "+=", "1", "return", "self", ".", "data", "[", "index", "]", "else", ":", "raise", "StopI...
28.769231
14.307692
def find_transported_elements(rxn): """ Return a dictionary showing the amount of transported elements of a rxn. Collects the elements for each metabolite participating in a reaction, multiplies the amount by the metabolite's stoichiometry in the reaction and bins the result according to the compar...
[ "def", "find_transported_elements", "(", "rxn", ")", ":", "element_dist", "=", "defaultdict", "(", ")", "# Collecting elements for each metabolite.", "for", "met", "in", "rxn", ".", "metabolites", ":", "if", "met", ".", "compartment", "not", "in", "element_dist", ...
43.425
18.925
def inside(self, other): """ Return true if this rectangle is inside the given shape. """ return ( self.left >= other.left and self.right <= other.right and self.top <= other.top and self.bottom >= other.bottom)
[ "def", "inside", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "left", ">=", "other", ".", "left", "and", "self", ".", "right", "<=", "other", ".", "right", "and", "self", ".", "top", "<=", "other", ".", "top", "and", "self", "...
45.5
5.5
def css(src, dest=False, shift=4): """Beautify CSS Args: src: css string or path-to-file with text to beautify (mandatory) dest: path-to-file to save beautified css string; if file doesn't exist it is created automatically; (optional) if this arg is skept function re...
[ "def", "css", "(", "src", ",", "dest", "=", "False", ",", "shift", "=", "4", ")", ":", "if", "not", "dest", ":", "# all default", "return", "_css", "(", "_text", "(", "src", ")", ")", "else", ":", "if", "type", "(", "dest", ")", "is", "int", ":...
36.777778
19.055556
def execute(self): """ params = { "ApexCode" : "None", "ApexProfiling" : "01pd0000001yXtYAAU", "Callout" : True, "Database" : 1, "ExpirationDate" : 3, "ScopeId" ...
[ "def", "execute", "(", "self", ")", ":", "if", "'type'", "not", "in", "self", ".", "params", ":", "raise", "MMException", "(", "\"Please include the type of log, 'user' or 'apex'\"", ")", "if", "'debug_categories'", "not", "in", "self", ".", "params", ":", "rais...
40.320755
18.207547
def check_absolute_refs(self, construction_table): """Checks first three rows of ``construction_table`` for linear references Checks for each index from first to third row of the ``construction_table``, if the references are colinear. This case has to be specially treated, because the r...
[ "def", "check_absolute_refs", "(", "self", ",", "construction_table", ")", ":", "c_table", "=", "construction_table", "problem_index", "=", "[", "i", "for", "i", "in", "c_table", ".", "index", "[", ":", "3", "]", "if", "not", "self", ".", "_has_valid_abs_ref...
42
20.05
def deploy(self, *lambdas): """Deploys lambdas to AWS""" if not self.role: logger.error('Missing AWS Role') raise ArgumentsError('Role required') logger.debug('Deploying lambda {}'.format(self.lambda_name)) zfh = self.package() if self.lambda_name in se...
[ "def", "deploy", "(", "self", ",", "*", "lambdas", ")", ":", "if", "not", "self", ".", "role", ":", "logger", ".", "error", "(", "'Missing AWS Role'", ")", "raise", "ArgumentsError", "(", "'Role required'", ")", "logger", ".", "debug", "(", "'Deploying lam...
31.941176
15.794118
def RelaxNGValidateCtxt(self, reader, options): """Use RelaxNG schema context to validate the document as it is processed. Activation is only possible before the first Read(). If @ctxt is None, then RelaxNG schema validation is deactivated. """ if reader is None: reader__o...
[ "def", "RelaxNGValidateCtxt", "(", "self", ",", "reader", ",", "options", ")", ":", "if", "reader", "is", "None", ":", "reader__o", "=", "None", "else", ":", "reader__o", "=", "reader", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlTextReaderRelaxNGValidateC...
51.222222
15.555556
def retrieve_diaspora_hcard(handle): """ Retrieve a remote Diaspora hCard document. :arg handle: Remote handle to retrieve :return: str (HTML document) """ webfinger = retrieve_and_parse_diaspora_webfinger(handle) document, code, exception = fetch_document(webfinger.get("hcard_url")) if...
[ "def", "retrieve_diaspora_hcard", "(", "handle", ")", ":", "webfinger", "=", "retrieve_and_parse_diaspora_webfinger", "(", "handle", ")", "document", ",", "code", ",", "exception", "=", "fetch_document", "(", "webfinger", ".", "get", "(", "\"hcard_url\"", ")", ")"...
30
15
def get_exchange_rates(self, base, targets=None): """Return the ::base:: to ::targets:: exchange rate (as a dictionary).""" if targets is None: targets = get_available_currencies() return {t: self.get_exchange_rate(base, t, raise_errors=False) for t in targets}
[ "def", "get_exchange_rates", "(", "self", ",", "base", ",", "targets", "=", "None", ")", ":", "if", "targets", "is", "None", ":", "targets", "=", "get_available_currencies", "(", ")", "return", "{", "t", ":", "self", ".", "get_exchange_rate", "(", "base", ...
48.833333
19.666667
def print_tokens(output, tokens, style): """ Print a list of (Token, text) tuples in the given style to the output. """ assert isinstance(output, Output) assert isinstance(style, Style) # Reset first. output.reset_attributes() output.enable_autowrap() # Print all (token, text) tupl...
[ "def", "print_tokens", "(", "output", ",", "tokens", ",", "style", ")", ":", "assert", "isinstance", "(", "output", ",", "Output", ")", "assert", "isinstance", "(", "style", ",", "Style", ")", "# Reset first.", "output", ".", "reset_attributes", "(", ")", ...
23.888889
18.185185
def get_predicate_text(sent_tokens: List[Token], tags: List[str]) -> str: """ Get the predicate in this prediction. """ return " ".join([sent_tokens[pred_id].text for pred_id in get_predicate_indices(tags)])
[ "def", "get_predicate_text", "(", "sent_tokens", ":", "List", "[", "Token", "]", ",", "tags", ":", "List", "[", "str", "]", ")", "->", "str", ":", "return", "\" \"", ".", "join", "(", "[", "sent_tokens", "[", "pred_id", "]", ".", "text", "for", "pred...
39.833333
10.833333
def _clear_inspect(self): """Clears inspect attributes when re-executing a pipeline""" self.trace_info = defaultdict(list) self.process_tags = {} self.process_stats = {} self.samples = [] self.stored_ids = [] self.stored_log_ids = [] self.time_start = Non...
[ "def", "_clear_inspect", "(", "self", ")", ":", "self", ".", "trace_info", "=", "defaultdict", "(", "list", ")", "self", ".", "process_tags", "=", "{", "}", "self", ".", "process_stats", "=", "{", "}", "self", ".", "samples", "=", "[", "]", "self", "...
33.45
10.95
def get_statements_noprior(self): """Return a list of all non-prior Statements in a single list. Returns ------- stmts : list[indra.statements.Statement] A list of all the INDRA Statements in the model (excluding the prior). """ stmt_lists = [v fo...
[ "def", "get_statements_noprior", "(", "self", ")", ":", "stmt_lists", "=", "[", "v", "for", "k", ",", "v", "in", "self", ".", "stmts", ".", "items", "(", ")", "if", "k", "!=", "'prior'", "]", "stmts", "=", "[", "]", "for", "s", "in", "stmt_lists", ...
31.714286
18.214286
def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity): """ Create the DynamoDB table for async task return values """ try: dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name) return False, dynamodb_table #...
[ "def", "create_async_dynamodb_table", "(", "self", ",", "table_name", ",", "read_capacity", ",", "write_capacity", ")", ":", "try", ":", "dynamodb_table", "=", "self", ".", "dynamodb_client", ".", "describe_table", "(", "TableName", "=", "table_name", ")", "return...
37.973684
17.184211
def get(self, file_id, **queryparams): """ Get information about a specific file in the File Manager. :param file_id: The unique id for the File Manager file. :type file_id: :py:class:`str` :param queryparams: The query string parameters queryparams['fields'] = [] ...
[ "def", "get", "(", "self", ",", "file_id", ",", "*", "*", "queryparams", ")", ":", "self", ".", "file_id", "=", "file_id", "return", "self", ".", "_mc_client", ".", "_get", "(", "url", "=", "self", ".", "_build_path", "(", "file_id", ")", ",", "*", ...
39.166667
14
def ReadSerializedDict(cls, json_dict): """Reads an attribute container from serialized dictionary form. Args: json_dict (dict[str, object]): JSON serialized objects. Returns: AttributeContainer: attribute container or None. Raises: TypeError: if the serialized dictionary does not c...
[ "def", "ReadSerializedDict", "(", "cls", ",", "json_dict", ")", ":", "if", "json_dict", ":", "json_object", "=", "cls", ".", "_ConvertDictToObject", "(", "json_dict", ")", "if", "not", "isinstance", "(", "json_object", ",", "containers_interface", ".", "Attribut...
30.952381
22.904762
def close(self): """ Closes pipe :return: """ resource = ResourceLocator(CommandShell.ShellResource) resource.add_selector('ShellId', self.__shell_id) self.session.delete(resource)
[ "def", "close", "(", "self", ")", ":", "resource", "=", "ResourceLocator", "(", "CommandShell", ".", "ShellResource", ")", "resource", ".", "add_selector", "(", "'ShellId'", ",", "self", ".", "__shell_id", ")", "self", ".", "session", ".", "delete", "(", "...
28.625
13.875
def replaceChild(self, new_child: AbstractNode, old_child: AbstractNode) -> AbstractNode: """Replace an old child with new child.""" return self._replace_child(new_child, old_child)
[ "def", "replaceChild", "(", "self", ",", "new_child", ":", "AbstractNode", ",", "old_child", ":", "AbstractNode", ")", "->", "AbstractNode", ":", "return", "self", ".", "_replace_child", "(", "new_child", ",", "old_child", ")" ]
53.75
11.25
def backing_type_for(value): """Returns the DynamoDB backing type for a given python value's type :: 4 -> 'N' ['x', 3] -> 'L' {2, 4} -> 'SS' """ if isinstance(value, str): vtype = "S" elif isinstance(value, bytes): vty...
[ "def", "backing_type_for", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "vtype", "=", "\"S\"", "elif", "isinstance", "(", "value", ",", "bytes", ")", ":", "vtype", "=", "\"B\"", "# NOTE: numbers.Number check must come **AFTER...
35.868421
17.631579
def clone(self, **kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provi...
[ "def", "clone", "(", "self", ",", "*", "*", "kw", ")", ":", "names", "=", "'project_name version py_version platform location precedence'", "for", "attr", "in", "names", ".", "split", "(", ")", ":", "kw", ".", "setdefault", "(", "attr", ",", "getattr", "(", ...
50.571429
13.428571
def capture_objects(self): """! @brief Returns indexes of captured objects by each neuron. @details For example, network with size 2x2 has been trained on 5 sample, we neuron #1 has won one object with index '1', neuron #2 - objects with indexes '0', '3', '4', neuron #3 - n...
[ "def", "capture_objects", "(", "self", ")", ":", "if", "self", ".", "__ccore_som_pointer", "is", "not", "None", ":", "self", ".", "_capture_objects", "=", "wrapper", ".", "som_get_capture_objects", "(", "self", ".", "__ccore_som_pointer", ")", "return", "self", ...
47.2
30.733333
def update(self, friendly_name=values.unset, unique_name=values.unset, email=values.unset, cc_emails=values.unset, status=values.unset, verification_code=values.unset, verification_type=values.unset, verification_document_sid=values.unset, extension=values.unset, ...
[ "def", "update", "(", "self", ",", "friendly_name", "=", "values", ".", "unset", ",", "unique_name", "=", "values", ".", "unset", ",", "email", "=", "values", ".", "unset", ",", "cc_emails", "=", "values", ".", "unset", ",", "status", "=", "values", "....
48.5
25.690476
def subscribe_to_candles(self, pair, timeframe=None, **kwargs): """Subscribe to the passed pair's OHLC data channel. :param pair: str, Symbol pair to request data for :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwarg...
[ "def", "subscribe_to_candles", "(", "self", ",", "pair", ",", "timeframe", "=", "None", ",", "*", "*", "kwargs", ")", ":", "valid_tfs", "=", "[", "'1m'", ",", "'5m'", ",", "'15m'", ",", "'30m'", ",", "'1h'", ",", "'3h'", ",", "'6h'", ",", "'12h'", ...
41.047619
18.714286
def extend(self, schema): """ Extend a structured schema by another. For example extending ``tuple<rstring id, timestamp ts, float64 value>`` with ``tuple<float32 score>`` results in ``tuple<rstring id, timestamp ts, float64 value, float32 score>``. Args: schema(Str...
[ "def", "extend", "(", "self", ",", "schema", ")", ":", "if", "self", ".", "_spl_type", ":", "raise", "TypeError", "(", "\"Not supported for declared SPL types\"", ")", "base", "=", "self", ".", "schema", "(", ")", "extends", "=", "schema", ".", "schema", "...
36.736842
22.947368
async def dump_varint_t(writer, type_or, pv): """ Binary dump of the integer of given type :param writer: :param type_or: :param pv: :return: """ width = int_mark_to_size(type_or) n = (pv << 2) | type_or buffer = _UINT_BUFFER for _ in range(width): buffer[0] = n & 0...
[ "async", "def", "dump_varint_t", "(", "writer", ",", "type_or", ",", "pv", ")", ":", "width", "=", "int_mark_to_size", "(", "type_or", ")", "n", "=", "(", "pv", "<<", "2", ")", "|", "type_or", "buffer", "=", "_UINT_BUFFER", "for", "_", "in", "range", ...
19.736842
17.736842
def sum(self, axis=None, dtype=None, out=None, keepdims=False): """Return the sum of ``self``. See Also -------- numpy.sum prod """ return self.elem.__array_ufunc__( np.add, 'reduce', self.elem, axis=axis, dtype=dtype, out=(out,), keepdims...
[ "def", "sum", "(", "self", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "keepdims", "=", "False", ")", ":", "return", "self", ".", "elem", ".", "__array_ufunc__", "(", "np", ".", "add", ",", "'reduce'", ",", ...
29.090909
17.181818
def __inner_eval(self, data_name, data_idx, feval=None): """Evaluate training or validation data.""" if data_idx >= self.__num_dataset: raise ValueError("Data_idx should be smaller than number of dataset") self.__get_eval_info() ret = [] if self.__num_inner_eval > 0: ...
[ "def", "__inner_eval", "(", "self", ",", "data_name", ",", "data_idx", ",", "feval", "=", "None", ")", ":", "if", "data_idx", ">=", "self", ".", "__num_dataset", ":", "raise", "ValueError", "(", "\"Data_idx should be smaller than number of dataset\"", ")", "self",...
48.84375
17.25
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._label_user_creator is not None: ...
[ "def", "is_all_field_none", "(", "self", ")", ":", "if", "self", ".", "_id_", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_created", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_updated", "is", "not", "None", ...
19.095238
18.904762
def imgAverage(images, copy=True): ''' returns an image average works on many, also unloaded images minimises RAM usage ''' i0 = images[0] out = imread(i0, dtype='float') if copy and id(i0) == id(out): out = out.copy() for i in images[1:]: out += imread...
[ "def", "imgAverage", "(", "images", ",", "copy", "=", "True", ")", ":", "i0", "=", "images", "[", "0", "]", "out", "=", "imread", "(", "i0", ",", "dtype", "=", "'float'", ")", "if", "copy", "and", "id", "(", "i0", ")", "==", "id", "(", "out", ...
22.6875
17.3125
def export_compound(infile, outfile, format, outcsv, max_rs_peakgroup_qvalue): """ Export Compound TSV/CSV tables """ if format == "score_plots": export_score_plots(infile) else: if outfile is None: if outcsv: outfile = infile.split(".osw")[0] + ".csv" ...
[ "def", "export_compound", "(", "infile", ",", "outfile", ",", "format", ",", "outcsv", ",", "max_rs_peakgroup_qvalue", ")", ":", "if", "format", "==", "\"score_plots\"", ":", "export_score_plots", "(", "infile", ")", "else", ":", "if", "outfile", "is", "None",...
31.8125
18.9375
def merge_dict(dict_1, *other, **kw): """Merge two or more dict including kw into result dict.""" tmp = dict_1.copy() for x in other: tmp.update(x) tmp.update(kw) return tmp
[ "def", "merge_dict", "(", "dict_1", ",", "*", "other", ",", "*", "*", "kw", ")", ":", "tmp", "=", "dict_1", ".", "copy", "(", ")", "for", "x", "in", "other", ":", "tmp", ".", "update", "(", "x", ")", "tmp", ".", "update", "(", "kw", ")", "ret...
27.857143
15.428571
def bottom_sections(self): """ The number of cells that touch the bottom side. Returns ------- sections : int The number of sections on the top """ bottom_line = self.text.split('\n')[-1] sections = len(bottom_line.split('+')) - 2 ret...
[ "def", "bottom_sections", "(", "self", ")", ":", "bottom_line", "=", "self", ".", "text", ".", "split", "(", "'\\n'", ")", "[", "-", "1", "]", "sections", "=", "len", "(", "bottom_line", ".", "split", "(", "'+'", ")", ")", "-", "2", "return", "sect...
24.615385
16.615385
def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srl...
[ "def", "search", "(", "query", ",", "results", "=", "10", ",", "suggestion", "=", "False", ")", ":", "search_params", "=", "{", "'list'", ":", "'search'", ",", "'srprop'", ":", "''", ",", "'srlimit'", ":", "results", ",", "'limit'", ":", "results", ","...
26.567568
24.837838
def get_intel_compiler_top(version, abi): """ Return the main path to the top-level dir of the Intel compiler, using the given version. The compiler will be in <top>/bin/icl.exe (icc on linux), the include dir is <top>/include, etc. """ if is_windows: if not SCons.Util.can_read_reg:...
[ "def", "get_intel_compiler_top", "(", "version", ",", "abi", ")", ":", "if", "is_windows", ":", "if", "not", "SCons", ".", "Util", ".", "can_read_reg", ":", "raise", "NoRegistryModuleError", "(", "\"No Windows registry module was found\"", ")", "top", "=", "get_in...
49.797753
23.168539
def var(self, tensor_type, last_dim=0, test_shape=None): """ An alias of deepy.tensor.var. """ from deepy.tensor import var return var(tensor_type, last_dim=last_dim, test_shape=test_shape)
[ "def", "var", "(", "self", ",", "tensor_type", ",", "last_dim", "=", "0", ",", "test_shape", "=", "None", ")", ":", "from", "deepy", ".", "tensor", "import", "var", "return", "var", "(", "tensor_type", ",", "last_dim", "=", "last_dim", ",", "test_shape",...
37.333333
9.333333
def auth_config(self, stage=None): """Create auth config based on stage.""" if stage: section = 'stages.{}'.format(stage) else: section = 'stages.live' try: username = self.lookup(section, 'username') password = self.lookup(section, 'passw...
[ "def", "auth_config", "(", "self", ",", "stage", "=", "None", ")", ":", "if", "stage", ":", "section", "=", "'stages.{}'", ".", "format", "(", "stage", ")", "else", ":", "section", "=", "'stages.live'", "try", ":", "username", "=", "self", ".", "lookup...
35.972222
19.75
def set(self, key, value, **kwargs): """ Set the value of a Parameter in the ParameterSet. If :func:`get` would retrieve a Parameter, this will set the value of that parameter. Or you can provide 'value@...' or 'default_unit@...', etc to specify what attribute to set. ...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "twig", "=", "key", "method", "=", "None", "twigsplit", "=", "re", ".", "findall", "(", "r\"[\\w']+\"", ",", "twig", ")", "if", "twigsplit", "[", "0", "]", "=...
42.163265
20.857143
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers: self._transformers.append(transformer) self.sort_transformers()
[ "def", "register_transformer", "(", "self", ",", "transformer", ")", ":", "if", "transformer", "not", "in", "self", ".", "_transformers", ":", "self", ".", "_transformers", ".", "append", "(", "transformer", ")", "self", ".", "sort_transformers", "(", ")" ]
45
5.4
def apply_string_substitutions( inputs, substitutions, inverse=False, case_insensitive=False, unused_substitutions="ignore", ): """Apply a number of substitutions to a string(s). The substitutions are applied effectively all at once. This means that conflicting substitutions don't inter...
[ "def", "apply_string_substitutions", "(", "inputs", ",", "substitutions", ",", "inverse", "=", "False", ",", "case_insensitive", "=", "False", ",", "unused_substitutions", "=", "\"ignore\"", ",", ")", ":", "if", "inverse", ":", "substitutions", "=", "{", "v", ...
36.495327
30.149533
def album(self): """ album as :class:`Album` object """ if not self._album: self._album = Album(self._album_id, self._album_name, self._artist_id, self._artist_name, self._cover_url, self._connection) ret...
[ "def", "album", "(", "self", ")", ":", "if", "not", "self", ".", "_album", ":", "self", ".", "_album", "=", "Album", "(", "self", ".", "_album_id", ",", "self", ".", "_album_name", ",", "self", ".", "_artist_id", ",", "self", ".", "_artist_name", ","...
36.333333
14.555556
def register_default_action(self, file_pattern, action_function): """ Default action used if no compatible action is found. Args: file_pattern: A :program:`fnmatch` pattern for the files concerned by this action. action_function: Warning: Be careful...
[ "def", "register_default_action", "(", "self", ",", "file_pattern", ",", "action_function", ")", ":", "if", "self", ".", "__default_action", "is", "not", "None", ":", "self", ".", "log_error", "(", "'Default action function already exist.'", ")", "if", "not", "sel...
52.333333
36.333333
def path_dispatch1(mname, returns_model): """ Decorator for methods that accept path as a first argument. """ def _wrapper(self, *args, **kwargs): path, args = _get_arg('path', args, kwargs) prefix, mgr, mgr_path = _resolve_path(path, self.managers) result = getattr(mgr, mname)(m...
[ "def", "path_dispatch1", "(", "mname", ",", "returns_model", ")", ":", "def", "_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "path", ",", "args", "=", "_get_arg", "(", "'path'", ",", "args", ",", "kwargs", ")", "prefix"...
34.214286
14.214286
def log_interp(x, xp, *args, **kwargs): """Wrap log_interpolate_1d for deprecated log_interp.""" return log_interpolate_1d(x, xp, *args, **kwargs)
[ "def", "log_interp", "(", "x", ",", "xp", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "log_interpolate_1d", "(", "x", ",", "xp", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
50.666667
4.666667
def _get_parts_of_format_string(resolved_string, literal_texts, format_specs): """ Inner function of reverse_format, returns the resolved value for each field in pattern. """ _text = resolved_string bits = [] if literal_texts[-1] != '' and _text.endswith(literal_texts[-1]): _text = ...
[ "def", "_get_parts_of_format_string", "(", "resolved_string", ",", "literal_texts", ",", "format_specs", ")", ":", "_text", "=", "resolved_string", "bits", "=", "[", "]", "if", "literal_texts", "[", "-", "1", "]", "!=", "''", "and", "_text", ".", "endswith", ...
37.292683
18.512195
def update_share_image(liststore, tree_iters, col, large_col, pcs_files, dir_name, icon_size, large_icon_size): '''下载文件缩略图, 并将它显示到liststore里. 需要同时更新两列里的图片, 用不同的缩放尺寸. pcs_files - 里面包含了几个必要的字段. dir_name - 缓存目录, 下载到的图片会保存这个目录里. ''' def update_image(filepath, tree_iter): ...
[ "def", "update_share_image", "(", "liststore", ",", "tree_iters", ",", "col", ",", "large_col", ",", "pcs_files", ",", "dir_name", ",", "icon_size", ",", "large_icon_size", ")", ":", "def", "update_image", "(", "filepath", ",", "tree_iter", ")", ":", "try", ...
37.763636
16.127273
def urlread(url, encoding='utf8'): """ Read the content of an URL. Parameters ---------- url : str Returns ------- content : str """ try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen response = urlopen(url) conte...
[ "def", "urlread", "(", "url", ",", "encoding", "=", "'utf8'", ")", ":", "try", ":", "from", "urllib", ".", "request", "import", "urlopen", "except", "ImportError", ":", "from", "urllib2", "import", "urlopen", "response", "=", "urlopen", "(", "url", ")", ...
18.95
17.95
def add_densities(density1, density2): """ Method to sum two densities. Args: density1: First density. density2: Second density. Returns: Dict of {spin: density}. """ return {spin: np.array(density1[spin]) + np.array(density2[spin]) for spin in density1.keys...
[ "def", "add_densities", "(", "density1", ",", "density2", ")", ":", "return", "{", "spin", ":", "np", ".", "array", "(", "density1", "[", "spin", "]", ")", "+", "np", ".", "array", "(", "density2", "[", "spin", "]", ")", "for", "spin", "in", "densi...
23.923077
15.461538
def get_word(value): """word = atom / quoted-string Either atom or quoted-string may start with CFWS. We have to peel off this CFWS first to determine which type of word to parse. Afterward we splice the leading CFWS, if any, into the parsed sub-token. If neither an atom or a quoted-string is fo...
[ "def", "get_word", "(", "value", ")", ":", "if", "value", "[", "0", "]", "in", "CFWS_LEADER", ":", "leader", ",", "value", "=", "get_cfws", "(", "value", ")", "else", ":", "leader", "=", "None", "if", "value", "[", "0", "]", "==", "'\"'", ":", "t...
37.666667
22.566667
def bottleneck_block(cnn, depth, depth_bottleneck, stride, pre_activation): """Bottleneck block with identity short-cut. Args: cnn: the network to append bottleneck blocks. depth: the number of output filters for this bottleneck block. depth_bottleneck: the number of bottleneck filters for this block...
[ "def", "bottleneck_block", "(", "cnn", ",", "depth", ",", "depth_bottleneck", ",", "stride", ",", "pre_activation", ")", ":", "if", "pre_activation", ":", "bottleneck_block_v2", "(", "cnn", ",", "depth", ",", "depth_bottleneck", ",", "stride", ")", "else", ":"...
43.928571
23.285714
def update_translations(condition=None): """ Updates FieldTranslations table """ if condition is None: condition = {} # Number of updated translations num_translations = 0 # Module caching FieldTranslation._init_module_cache() # Current languages dict LANGUAGES = dict(lang for lang in MODELT...
[ "def", "update_translations", "(", "condition", "=", "None", ")", ":", "if", "condition", "is", "None", ":", "condition", "=", "{", "}", "# Number of updated translations", "num_translations", "=", "0", "# Module caching", "FieldTranslation", ".", "_init_module_cache"...
33.105263
20.315789
def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): ...
[ "def", "netbsd_interfaces", "(", ")", ":", "# NetBSD versions prior to 8.0 can still use linux_interfaces()", "if", "LooseVersion", "(", "os", ".", "uname", "(", ")", "[", "2", "]", ")", "<", "LooseVersion", "(", "'8.0'", ")", ":", "return", "linux_interfaces", "(...
37.529412
21.176471
def not_(self, *query_expressions): ''' Add a $not expression to the query, negating the query expressions given. **Examples**: ``query.not_(SomeDocClass.age <= 18)`` becomes ``{'age' : { '$not' : { '$gt' : 18 } }}`` :param query_expressions: Instances of :class:`ommongo.qu...
[ "def", "not_", "(", "self", ",", "*", "query_expressions", ")", ":", "for", "qe", "in", "query_expressions", ":", "self", ".", "filter", "(", "qe", ".", "not_", "(", ")", ")", "return", "self" ]
40.818182
30.454545
def encrypt(key, message): '''encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html ''' try: ret = kms.encrypt(KeyId=key, Plaintext=message) encrypted_data = base64.en...
[ "def", "encrypt", "(", "key", ",", "message", ")", ":", "try", ":", "ret", "=", "kms", ".", "encrypt", "(", "KeyId", "=", "key", ",", "Plaintext", "=", "message", ")", "encrypted_data", "=", "base64", ".", "encodestring", "(", "ret", ".", "get", "(",...
38.785714
24.785714
def http_exception(channel, title): """ Creates an embed UI containing the 'too long' error message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed Returns: ui (ui_embed.UI): The embed UI object """ # Create...
[ "def", "http_exception", "(", "channel", ",", "title", ")", ":", "# Create embed UI object", "gui", "=", "ui_embed", ".", "UI", "(", "channel", ",", "\"Too much help\"", ",", "\"{} is too helpful! Try trimming some of the help messages.\"", ".", "format", "(", "title", ...
24.619048
22.619048
def ndarray_fs(shape, dtype, location, lock, readonly=False, order='F', **kwargs): """Emulate shared memory using the filesystem.""" dbytes = np.dtype(dtype).itemsize nbytes = Vec(*shape).rectVolume() * dbytes directory = mkdir(EMULATED_SHM_DIRECTORY) filename = os.path.join(directory, location) if lock: ...
[ "def", "ndarray_fs", "(", "shape", ",", "dtype", ",", "location", ",", "lock", ",", "readonly", "=", "False", ",", "order", "=", "'F'", ",", "*", "*", "kwargs", ")", ":", "dbytes", "=", "np", ".", "dtype", "(", "dtype", ")", ".", "itemsize", "nbyte...
32.647059
20.705882
def fqname_to_id(self, fq_name, type): """ Return uuid for fq_name :param fq_name: resource fq name :type fq_name: FQName :param type: resource type :type type: str :rtype: UUIDv4 str :raises HttpError: fq_name not found """ data = { ...
[ "def", "fqname_to_id", "(", "self", ",", "fq_name", ",", "type", ")", ":", "data", "=", "{", "\"type\"", ":", "type", ",", "\"fq_name\"", ":", "list", "(", "fq_name", ")", "}", "return", "self", ".", "post_json", "(", "self", ".", "make_url", "(", "\...
26.352941
14.823529
def get_user(self, login=github.GithubObject.NotSet): """ :calls: `GET /users/:user <http://developer.github.com/v3/users>`_ or `GET /user <http://developer.github.com/v3/users>`_ :param login: string :rtype: :class:`github.NamedUser.NamedUser` """ assert login is github....
[ "def", "get_user", "(", "self", ",", "login", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", "assert", "login", "is", "github", ".", "GithubObject", ".", "NotSet", "or", "isinstance", "(", "login", ",", "(", "str", ",", "unicode", ")", ")...
51.666667
27.666667
def _create_ret_object(self, status=SUCCESS, data=None, error=False, error_message=None, error_cause=None): """ Create generic reponse objects. :param str status: The SUCCESS or FAILURE of the request :param obj data: The data to return :param bool err...
[ "def", "_create_ret_object", "(", "self", ",", "status", "=", "SUCCESS", ",", "data", "=", "None", ",", "error", "=", "False", ",", "error_message", "=", "None", ",", "error_cause", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "status", "==", "...
34.892857
14.464286
def list_namespaced_job(self, namespace, **kwargs): # noqa: E501 """list_namespaced_job # noqa: E501 list or watch objects of kind Job # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> th...
[ "def", "list_namespaced_job", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "l...
161
132.566667