text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def is_present(self, host=None): """ Returns true if the given host exists on the network. Returns false otherwise. """ r = self.local_renderer r.env.host = host or self.genv.host_string ret = r._local("getent hosts {host} | awk '{{ print $1 }}'", capture=True) or...
[ "def", "is_present", "(", "self", ",", "host", "=", "None", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "env", ".", "host", "=", "host", "or", "self", ".", "genv", ".", "host_string", "ret", "=", "r", ".", "_local", "(", "\"getent ...
37.185185
17.333333
def groupedby(collection, fn): """ same like itertools.groupby :note: This function does not needs initial sorting like itertools.groupby :attention: Order of pairs is not deterministic. """ d = {} for item in collection: k = fn(item) try: arr = d[k] exc...
[ "def", "groupedby", "(", "collection", ",", "fn", ")", ":", "d", "=", "{", "}", "for", "item", "in", "collection", ":", "k", "=", "fn", "(", "item", ")", "try", ":", "arr", "=", "d", "[", "k", "]", "except", "KeyError", ":", "arr", "=", "[", ...
21.578947
20.210526
def subtract_days(self, days: int) -> datetime: """ Subtracts dates from the given value """ self.value = self.value - relativedelta(days=days) return self.value
[ "def", "subtract_days", "(", "self", ",", "days", ":", "int", ")", "->", "datetime", ":", "self", ".", "value", "=", "self", ".", "value", "-", "relativedelta", "(", "days", "=", "days", ")", "return", "self", ".", "value" ]
45.5
10
def updated_by(self): """ | Comment: The id of the user who last updated the translation """ if self.api and self.updated_by_id: return self.api._get_user(self.updated_by_id)
[ "def", "updated_by", "(", "self", ")", ":", "if", "self", ".", "api", "and", "self", ".", "updated_by_id", ":", "return", "self", ".", "api", ".", "_get_user", "(", "self", ".", "updated_by_id", ")" ]
35.666667
11.666667
def queue_callback(self, session, block_id, data): """ Queues up a callback event to occur for a session with the given payload data. Will block if the queue is full. :param session: the session with a defined callback function to call. :param block_id: the block_id of the mess...
[ "def", "queue_callback", "(", "self", ",", "session", ",", "block_id", ",", "data", ")", ":", "self", ".", "_queue", ".", "put", "(", "(", "session", ",", "block_id", ",", "data", ")", ")" ]
45
18.8
def get_variant_id(variant): """Get a variant id on the format chrom_pos_ref_alt""" variant_id = '_'.join([ str(variant.CHROM), str(variant.POS), str(variant.REF), str(variant.ALT[0]) ] ) return variant_id
[ "def", "get_variant_id", "(", "variant", ")", ":", "variant_id", "=", "'_'", ".", "join", "(", "[", "str", "(", "variant", ".", "CHROM", ")", ",", "str", "(", "variant", ".", "POS", ")", ",", "str", "(", "variant", ".", "REF", ")", ",", "str", "(...
26.8
15
def extract_ace (archive, compression, cmd, verbosity, interactive, outdir): """Extract an ACE archive.""" cmdlist = [cmd, 'x'] if not outdir.endswith('/'): outdir += '/' cmdlist.extend([archive, outdir]) return cmdlist
[ "def", "extract_ace", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "cmdlist", "=", "[", "cmd", ",", "'x'", "]", "if", "not", "outdir", ".", "endswith", "(", "'/'", ")", ":", "outdir", ...
34.428571
14.857143
def namedb_get_version(con): """ Get the db version """ sql = 'SELECT version FROM db_version;' args = () try: rowdata = namedb_query_execute(con, sql, args, abort=False) row = rowdata.fetchone() return row['version'] except: # no version defined retu...
[ "def", "namedb_get_version", "(", "con", ")", ":", "sql", "=", "'SELECT version FROM db_version;'", "args", "=", "(", ")", "try", ":", "rowdata", "=", "namedb_query_execute", "(", "con", ",", "sql", ",", "args", ",", "abort", "=", "False", ")", "row", "=",...
22.785714
16.785714
def new_scansock (self): """Return a connected socket for sending scan data to it.""" port = None try: self.sock.sendall("STREAM") port = None for dummy in range(60): data = self.sock.recv(self.sock_rcvbuf) i = data.find("PORT")...
[ "def", "new_scansock", "(", "self", ")", ":", "port", "=", "None", "try", ":", "self", ".", "sock", ".", "sendall", "(", "\"STREAM\"", ")", "port", "=", "None", "for", "dummy", "in", "range", "(", "60", ")", ":", "data", "=", "self", ".", "sock", ...
33.56
14.76
def href_for(self, operation, qs=None, **kwargs): """ Construct an full href for an operation against a resource. :parm qs: the query string dictionary, if any :param kwargs: additional arguments for path expansion """ url = urljoin(request.url_root, self.url_for(operat...
[ "def", "href_for", "(", "self", ",", "operation", ",", "qs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url", "=", "urljoin", "(", "request", ".", "url_root", ",", "self", ".", "url_for", "(", "operation", ",", "*", "*", "kwargs", ")", ")", ...
33.866667
22.533333
def _ParseCachedEntry8(self, value_data, cached_entry_offset): """Parses a Windows 8.0 or 8.1 cached entry. Args: value_data (bytes): value data. cached_entry_offset (int): offset of the first cached entry data relative to the start of the value data. Returns: AppCompatCacheCac...
[ "def", "_ParseCachedEntry8", "(", "self", ",", "value_data", ",", "cached_entry_offset", ")", ":", "try", ":", "cached_entry", "=", "self", ".", "_ReadStructureFromByteStream", "(", "value_data", "[", "cached_entry_offset", ":", "]", ",", "cached_entry_offset", ",",...
37.920635
21.206349
def lazyload(reference: str, *args, **kw): """Lazily load and cache an object reference upon dereferencing. Assign the result of calling this function with either an object reference passed in positionally: class MyClass: debug = lazyload('logging:debug') Or the attribute path to traverse (using `marrow.p...
[ "def", "lazyload", "(", "reference", ":", "str", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "assert", "check_argument_types", "(", ")", "def", "lazily_load_reference", "(", "self", ")", ":", "ref", "=", "reference", "if", "ref", ".", "startswith", ...
25.535714
24.357143
async def get_reviews(self, **params): """Receives all reviews by cid Accepts: - cid - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = params.get("cid", 0) coinid = params.get("...
[ "async", "def", "get_reviews", "(", "self", ",", "*", "*", "params", ")", ":", "if", "params", ".", "get", "(", "\"message\"", ")", ":", "params", "=", "json", ".", "loads", "(", "params", ".", "get", "(", "\"message\"", ",", "\"{}\"", ")", ")", "i...
26.416667
20.375
def GetParserObjectByName(cls, parser_name): """Retrieves a specific parser object by its name. Args: parser_name (str): name of the parser. Returns: BaseParser: parser object or None. """ parser_class = cls._parser_classes.get(parser_name, None) if parser_class: return parse...
[ "def", "GetParserObjectByName", "(", "cls", ",", "parser_name", ")", ":", "parser_class", "=", "cls", ".", "_parser_classes", ".", "get", "(", "parser_name", ",", "None", ")", "if", "parser_class", ":", "return", "parser_class", "(", ")", "return", "None" ]
25.615385
17.384615
def filter(self, fn, skip_na=True, seed=None): """ Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element to true, this element is copied to the new SArray. If not, it isn't. Throws an exception if the return type of `fn` is...
[ "def", "filter", "(", "self", ",", "fn", ",", "skip_na", "=", "True", ",", "seed", "=", "None", ")", ":", "assert", "callable", "(", "fn", ")", ",", "\"Input must be callable\"", "if", "seed", "is", "None", ":", "seed", "=", "abs", "(", "hash", "(", ...
30.317073
23.634146
def sortByNamespacePrefix(urisList, nsList): """ Given an ordered list of namespaces prefixes, order a list of uris based on that. Eg In [7]: ll Out[7]: [rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.URIRef(u'printGenericTreeorg...
[ "def", "sortByNamespacePrefix", "(", "urisList", ",", "nsList", ")", ":", "exit", "=", "[", "]", "urisList", "=", "sort_uri_list_by_name", "(", "urisList", ")", "for", "ns", "in", "nsList", ":", "innerexit", "=", "[", "]", "for", "uri", "in", "urisList", ...
35.542857
24.571429
def free_symbols(self): """Set of free SymPy symbols contained within the equation.""" try: lhs_syms = self.lhs.free_symbols except AttributeError: lhs_syms = set() try: rhs_syms = self.rhs.free_symbols except AttributeError: rhs_sy...
[ "def", "free_symbols", "(", "self", ")", ":", "try", ":", "lhs_syms", "=", "self", ".", "lhs", ".", "free_symbols", "except", "AttributeError", ":", "lhs_syms", "=", "set", "(", ")", "try", ":", "rhs_syms", "=", "self", ".", "rhs", ".", "free_symbols", ...
32.272727
11.909091
def get(self, name): """Get a device model property. Args: name (str): The name of the property to get """ name = str(name) if name not in self._properties: raise ArgumentError("Unknown property in DeviceModel", name=name) return self._propertie...
[ "def", "get", "(", "self", ",", "name", ")", ":", "name", "=", "str", "(", "name", ")", "if", "name", "not", "in", "self", ".", "_properties", ":", "raise", "ArgumentError", "(", "\"Unknown property in DeviceModel\"", ",", "name", "=", "name", ")", "retu...
26.333333
19.833333
def ConsultarCTG(self, numero_carta_de_porte=None, numero_ctg=None, patente=None, cuit_solicitante=None, cuit_destino=None, fecha_emision_desde=None, fecha_emision_hasta=None): "Operación que realiza consulta de CTGs según el criterio ingresado." ret = self.cli...
[ "def", "ConsultarCTG", "(", "self", ",", "numero_carta_de_porte", "=", "None", ",", "numero_ctg", "=", "None", ",", "patente", "=", "None", ",", "cuit_solicitante", "=", "None", ",", "cuit_destino", "=", "None", ",", "fecha_emision_desde", "=", "None", ",", ...
47.961538
17.269231
def init(self): """Extract some info from chunks""" for type_, data in self.chunks: if type_ == "IHDR": self.hdr = data elif type_ == "IEND": self.end = data if self.hdr: # grab w, h info self.width, self.height = struct.unpack("!II", self.hdr[8:16])
[ "def", "init", "(", "self", ")", ":", "for", "type_", ",", "data", "in", "self", ".", "chunks", ":", "if", "type_", "==", "\"IHDR\"", ":", "self", ".", "hdr", "=", "data", "elif", "type_", "==", "\"IEND\"", ":", "self", ".", "end", "=", "data", "...
24.636364
19.636364
def execute_pool_txns(self, three_pc_batch) -> List: """ Execute a transaction that involves consensus pool management, like adding a node, client or a steward. :param ppTime: PrePrepare request time :param reqs_keys: requests keys to be committed """ committed_t...
[ "def", "execute_pool_txns", "(", "self", ",", "three_pc_batch", ")", "->", "List", ":", "committed_txns", "=", "self", ".", "default_executer", "(", "three_pc_batch", ")", "for", "txn", "in", "committed_txns", ":", "self", ".", "poolManager", ".", "onPoolMembers...
39.5
13.833333
async def get_form(self, request): """Base point load resource.""" if not self.form: return None formdata = await request.post() return self.form(formdata, obj=self.resource)
[ "async", "def", "get_form", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "form", ":", "return", "None", "formdata", "=", "await", "request", ".", "post", "(", ")", "return", "self", ".", "form", "(", "formdata", ",", "obj", "=", ...
35.5
8.666667
def parse(self, data, extent, desc_tag): # type: (bytes, int, UDFTag) -> None ''' Parse the passed in data into a UDF Anchor Volume Structure. Parameters: data - The data to parse. extent - The extent that this descriptor currently lives at. desc_tag - A UDFTa...
[ "def", "parse", "(", "self", ",", "data", ",", "extent", ",", "desc_tag", ")", ":", "# type: (bytes, int, UDFTag) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'Anchor Volume Structure already initializ...
33.25
24.083333
def add_flags(self, *flags): """Adds one or more flags to the query. For example: current-patch-set -> --current-patch-set """ if not isinstance(flags, (list, tuple)): flags = [str(flags)] self.extend(["--%s" % f for f in flags]) return self
[ "def", "add_flags", "(", "self", ",", "*", "flags", ")", ":", "if", "not", "isinstance", "(", "flags", ",", "(", "list", ",", "tuple", ")", ")", ":", "flags", "=", "[", "str", "(", "flags", ")", "]", "self", ".", "extend", "(", "[", "\"--%s\"", ...
27.727273
15.363636
def try_read(self, address, size): """Try to read memory content at specified address. If any location was not written before, it returns a tuple (False, None). Otherwise, it returns (True, memory content). """ value = 0x0 for i in range(0, size): addr = ad...
[ "def", "try_read", "(", "self", ",", "address", ",", "size", ")", ":", "value", "=", "0x0", "for", "i", "in", "range", "(", "0", ",", "size", ")", ":", "addr", "=", "address", "+", "i", "if", "addr", "in", "self", ".", "_memory", ":", "value", ...
27.166667
20.166667
def _update_version_data(self, result, info): """ Update a result dictionary (the final result from _get_project) with a dictionary for a specific version, whih typically holds information gleaned from a filename or URL for an archive for the distribution. """ name = info...
[ "def", "_update_version_data", "(", "self", ",", "result", ",", "info", ")", ":", "name", "=", "info", ".", "pop", "(", "'name'", ")", "version", "=", "info", ".", "pop", "(", "'version'", ")", "if", "version", "in", "result", ":", "dist", "=", "resu...
40.736842
14.526316
def runner(parallel, config): """Run functions, provided by string name, on multiple cores on the current machine. """ def run_parallel(fn_name, items): items = [x for x in items if x is not None] if len(items) == 0: return [] items = diagnostics.track_parallel(items, fn_...
[ "def", "runner", "(", "parallel", ",", "config", ")", ":", "def", "run_parallel", "(", "fn_name", ",", "items", ")", ":", "items", "=", "[", "x", "for", "x", "in", "items", "if", "x", "is", "not", "None", "]", "if", "len", "(", "items", ")", "=="...
54.666667
23
def __surname_triplet(input_string): """__surname_triplet(input_string) -> string""" consonants, vowels = __consonants_and_vowels(input_string) return __common_triplet(input_string, consonants, vowels)
[ "def", "__surname_triplet", "(", "input_string", ")", ":", "consonants", ",", "vowels", "=", "__consonants_and_vowels", "(", "input_string", ")", "return", "__common_triplet", "(", "input_string", ",", "consonants", ",", "vowels", ")" ]
42
17.4
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.port: conninfo.port = self.default_port credentials = pika.PlainCredentials(conninfo.userid, conninfo.password...
[ "def", "establish_connection", "(", "self", ")", ":", "conninfo", "=", "self", ".", "connection", "if", "not", "conninfo", ".", "port", ":", "conninfo", ".", "port", "=", "self", ".", "default_port", "credentials", "=", "pika", ".", "PlainCredentials", "(", ...
53.833333
17
def arrays2wcxf(C): """Convert a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format.""" d = {} ...
[ "def", "arrays2wcxf", "(", "C", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "C", ".", "items", "(", ")", ":", "if", "np", ".", "shape", "(", "v", ")", "==", "(", ")", "or", "np", ".", "shape", "(", "v", ")", "==", "(", "1"...
41.933333
19.733333
def iter_genotypes(self): """Iterates on available markers. Returns: Genotypes instances. """ for v in self.get_vcf(): alleles = {v.REF} | set(v.ALT) if self.quality_field: variant = ImputedVariant(v.ID, v.CHROM, v.POS, alleles, ...
[ "def", "iter_genotypes", "(", "self", ")", ":", "for", "v", "in", "self", ".", "get_vcf", "(", ")", ":", "alleles", "=", "{", "v", ".", "REF", "}", "|", "set", "(", "v", ".", "ALT", ")", "if", "self", ".", "quality_field", ":", "variant", "=", ...
34.578947
21.736842
def dac(self, expanded=False, return_res=64, inplace=False): """ Performs the digital to analogue conversion of the signal stored in `d_signal` if expanded is False, or `e_d_signal` if expanded is True. The d_signal/e_d_signal, fmt, gain, and baseline fields must all be ...
[ "def", "dac", "(", "self", ",", "expanded", "=", "False", ",", "return_res", "=", "64", ",", "inplace", "=", "False", ")", ":", "# The digital nan values for each channel", "d_nans", "=", "_digi_nan", "(", "self", ".", "fmt", ")", "# Get the appropriate float dt...
41.052632
20.926316
def send_transaction(self, fn_name, fn_args, transact=None): """Calls a smart contract function using either `personal_sendTransaction` (if passphrase is available) or `ether_sendTransaction`. :param fn_name: str the smart contract function name :param fn_args: tuple arguments to pass t...
[ "def", "send_transaction", "(", "self", ",", "fn_name", ",", "fn_args", ",", "transact", "=", "None", ")", ":", "contract_fn", "=", "getattr", "(", "self", ".", "contract", ".", "functions", ",", "fn_name", ")", "(", "*", "fn_args", ")", "contract_function...
46.214286
21
def diff(full, dataset_uri, reference_dataset_uri): """Report the difference between two datasets. 1. Checks that the identifiers are identicial 2. Checks that the sizes are identical 3. Checks that the hashes are identical, if the '--full' option is used If a differences is detected in step 1, st...
[ "def", "diff", "(", "full", ",", "dataset_uri", ",", "reference_dataset_uri", ")", ":", "def", "echo_header", "(", "desc", ",", "ds_name", ",", "ref_ds_name", ",", "prop", ")", ":", "click", ".", "secho", "(", "\"Different {}\"", ".", "format", "(", "desc"...
36.45283
21.339623
def normalize_uri(cls, uri): """ Normalize the given URI (removes extra slashes) :param uri: uri to normalize :return: str """ uri = WWebRoute.multiple_slashes_re.sub("/", uri) # remove last slash if len(uri) > 1: if uri[-1] == '/': uri = uri[:-1] return uri
[ "def", "normalize_uri", "(", "cls", ",", "uri", ")", ":", "uri", "=", "WWebRoute", ".", "multiple_slashes_re", ".", "sub", "(", "\"/\"", ",", "uri", ")", "# remove last slash", "if", "len", "(", "uri", ")", ">", "1", ":", "if", "uri", "[", "-", "1", ...
19.357143
20.642857
def _try_instantiate(self, ipopo, factory, component): # type: (Any, str, str) -> None """ Tries to instantiate a component from the queue. Hides all exceptions. :param ipopo: The iPOPO service :param factory: Component factory :param component: Component name ""...
[ "def", "_try_instantiate", "(", "self", ",", "ipopo", ",", "factory", ",", "component", ")", ":", "# type: (Any, str, str) -> None", "try", ":", "# Get component properties", "with", "self", ".", "__lock", ":", "properties", "=", "self", ".", "__queue", "[", "fa...
35.655172
13.655172
async def wait_stream(aiterable): """Wait for an asynchronous iterable to finish and return the last item. The iterable is executed within a safe stream context. A StreamEmpty exception is raised if the sequence is empty. """ async with streamcontext(aiterable) as streamer: async for item i...
[ "async", "def", "wait_stream", "(", "aiterable", ")", ":", "async", "with", "streamcontext", "(", "aiterable", ")", "as", "streamer", ":", "async", "for", "item", "in", "streamer", ":", "item", "try", ":", "return", "item", "except", "NameError", ":", "rai...
33.153846
15.230769
def _convert_agg_to_wx_image(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Image. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgb -> image image = wx.EmptyIma...
[ "def", "_convert_agg_to_wx_image", "(", "agg", ",", "bbox", ")", ":", "if", "bbox", "is", "None", ":", "# agg => rgb -> image", "image", "=", "wx", ".", "EmptyImage", "(", "int", "(", "agg", ".", "width", ")", ",", "int", "(", "agg", ".", "height", ")"...
36.933333
17.6
def save(self, trial, storage=Checkpoint.DISK): """Saves the trial's state to a checkpoint.""" trial._checkpoint.storage = storage trial._checkpoint.last_result = trial.last_result if storage == Checkpoint.MEMORY: trial._checkpoint.value = trial.runner.save_to_object.remote()...
[ "def", "save", "(", "self", ",", "trial", ",", "storage", "=", "Checkpoint", ".", "DISK", ")", ":", "trial", ".", "_checkpoint", ".", "storage", "=", "storage", "trial", ".", "_checkpoint", ".", "last_result", "=", "trial", ".", "last_result", "if", "sto...
47.37037
16.111111
def to_dict(self): """Returns a dict with the representation of this task configuration object.""" properties = find_class_properties(self.__class__) config = { name: self.__getattribute__(name) for name, _ in properties } return config
[ "def", "to_dict", "(", "self", ")", ":", "properties", "=", "find_class_properties", "(", "self", ".", "__class__", ")", "config", "=", "{", "name", ":", "self", ".", "__getattribute__", "(", "name", ")", "for", "name", ",", "_", "in", "properties", "}",...
35.25
22.875
def jumpTo(self, bytes): """Look for the next sequence of bytes matching a given sequence. If a match is found advance the position to the last byte of the match""" newPosition = self[self.position:].find(bytes) if newPosition > -1: # XXX: This is ugly, but I can't see a nice...
[ "def", "jumpTo", "(", "self", ",", "bytes", ")", ":", "newPosition", "=", "self", "[", "self", ".", "position", ":", "]", ".", "find", "(", "bytes", ")", "if", "newPosition", ">", "-", "1", ":", "# XXX: This is ugly, but I can't see a nicer way to fix this.", ...
44.166667
13.166667
def plot_line_loading( network, timesteps=range(1,2), filename=None, boundaries=[], arrows=False): """ Plots line loading as a colored heatmap. Line loading is displayed as relative to nominal capacity in %. Parameters ---------- network : PyPSA netw...
[ "def", "plot_line_loading", "(", "network", ",", "timesteps", "=", "range", "(", "1", ",", "2", ")", ",", "filename", "=", "None", ",", "boundaries", "=", "[", "]", ",", "arrows", "=", "False", ")", ":", "# TODO: replace p0 by max(p0,p1) and analogously for q0...
37.243056
21.215278
def beta(C, HIGHSCALE, newphys=True): """Return the beta functions of all SM parameters and SMEFT Wilson coefficients.""" g = C["g"] gp = C["gp"] gs = C["gs"] m2 = C["m2"] Lambda = C["Lambda"] Gu = C["Gu"] Gd = C["Gd"] Ge = C["Ge"] Eta1 = (3*np.trace(C["uphi"] @ Gu.conj()....
[ "def", "beta", "(", "C", ",", "HIGHSCALE", ",", "newphys", "=", "True", ")", ":", "g", "=", "C", "[", "\"g\"", "]", "gp", "=", "C", "[", "\"gp\"", "]", "gs", "=", "C", "[", "\"gs\"", "]", "m2", "=", "C", "[", "\"m2\"", "]", "Lambda", "=", "...
43.926092
14.986002
def djfrontend_normalize(version=None): """ Returns Normalize CSS file. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, 'DJFRONTEND_NORMALIZE', DJFRONTEND_NORMALIZE_DEFAULT) return format_html( '<link rel="stylesheet" href="{0}djfrontend/css/no...
[ "def", "djfrontend_normalize", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "getattr", "(", "settings", ",", "'DJFRONTEND_NORMALIZE'", ",", "DJFRONTEND_NORMALIZE_DEFAULT", ")", "return", "format_html", "(", "'<link rel...
33.545455
17.909091
def add_quantity_modifier(self, quantity, modifier, overwrite=False): """ Add a quantify modifier. Consider useing the high-level function `add_derived_quantity` instead! Parameters ---------- quantity : str name of the derived quantity to add modifi...
[ "def", "add_quantity_modifier", "(", "self", ",", "quantity", ",", "modifier", ",", "overwrite", "=", "False", ")", ":", "if", "quantity", "in", "self", ".", "_quantity_modifiers", "and", "not", "overwrite", ":", "raise", "ValueError", "(", "'quantity `{}` alrea...
50.875
29.708333
def map_to(self, attrname, tablename=None, selectable=None, schema=None, base=None, mapper_args=util.immutabledict()): """Configure a mapping to the given attrname. This is the "master" method that can be used to create any configuration. :param attrname: String a...
[ "def", "map_to", "(", "self", ",", "attrname", ",", "tablename", "=", "None", ",", "selectable", "=", "None", ",", "schema", "=", "None", ",", "base", "=", "None", ",", "mapper_args", "=", "util", ".", "immutabledict", "(", ")", ")", ":", "if", "attr...
43.195122
20.170732
def modified_lines(filename, extra_data, commit=None): """Returns the lines that have been modifed for this file. Args: filename: the file to check. extra_data: is the extra_data returned by modified_files. Additionally, a value of None means that the file was not modified. commit: th...
[ "def", "modified_lines", "(", "filename", ",", "extra_data", ",", "commit", "=", "None", ")", ":", "if", "extra_data", "is", "None", ":", "return", "[", "]", "if", "extra_data", "!=", "'M'", ":", "return", "None", "command", "=", "[", "'hg'", ",", "'di...
36.692308
20.717949
def _RunAndWaitForVFSFileUpdate(self, path): """Runs a flow on the client, and waits for it to finish.""" client_id = rdf_client.GetClientURNFromPath(path) # If we're not actually in a directory on a client, no need to run a flow. if client_id is None: return flow_utils.UpdateVFSFileAndWait...
[ "def", "_RunAndWaitForVFSFileUpdate", "(", "self", ",", "path", ")", ":", "client_id", "=", "rdf_client", ".", "GetClientURNFromPath", "(", "path", ")", "# If we're not actually in a directory on a client, no need to run a flow.", "if", "client_id", "is", "None", ":", "re...
30.357143
19.357143
def on_path(self, new): """ Handle the file path changing. """ self.name = basename(new) self.graph = self.editor_input.load()
[ "def", "on_path", "(", "self", ",", "new", ")", ":", "self", ".", "name", "=", "basename", "(", "new", ")", "self", ".", "graph", "=", "self", ".", "editor_input", ".", "load", "(", ")" ]
30.8
5.8
def query_job_status(self, submissionid): """ Queries vmray to check id a job was :param submissionid: ID of the job/submission :type submissionid: int :returns: True if job finished, false if not :rtype: bool """ apiurl = '/rest/submission/' ...
[ "def", "query_job_status", "(", "self", ",", "submissionid", ")", ":", "apiurl", "=", "'/rest/submission/'", "result", "=", "self", ".", "session", ".", "get", "(", "'{}{}{}'", ".", "format", "(", "self", ".", "url", ",", "apiurl", ",", "submissionid", ")"...
39.315789
20.052632
def T(a, half=False, cuda=True): """ Convert numpy array into a pytorch tensor. if Cuda is available and USE_GPU=True, store resulting tensor in GPU. """ if not torch.is_tensor(a): a = np.array(np.ascontiguousarray(a)) if a.dtype in (np.int8, np.int16, np.int32, np.int64): ...
[ "def", "T", "(", "a", ",", "half", "=", "False", ",", "cuda", "=", "True", ")", ":", "if", "not", "torch", ".", "is_tensor", "(", "a", ")", ":", "a", "=", "np", ".", "array", "(", "np", ".", "ascontiguousarray", "(", "a", ")", ")", "if", "a",...
39.285714
12.571429
def _wait_for_files(path): """ Retry with backoff up to 1 second to delete files from a directory. :param str path: The path to crawl to delete files from :return: A list of remaining paths or None :rtype: Optional[List[str]] """ timeout = 0.001 remaining = [] while timeout < 1.0: ...
[ "def", "_wait_for_files", "(", "path", ")", ":", "timeout", "=", "0.001", "remaining", "=", "[", "]", "while", "timeout", "<", "1.0", ":", "remaining", "=", "[", "]", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "L", "=", "os", "...
29.032258
14.451613
def parse(text): """Try to parse into a number. Return: the number (int or float) if successful; otherwise None. """ try: return int(text) except ValueError: try: amount = float(text) assert not isnan(amount) an...
[ "def", "parse", "(", "text", ")", ":", "try", ":", "return", "int", "(", "text", ")", "except", "ValueError", ":", "try", ":", "amount", "=", "float", "(", "text", ")", "assert", "not", "isnan", "(", "amount", ")", "and", "not", "isinf", "(", "amou...
28.8
16.866667
def to_xdr_object(self): """Creates an XDR Operation object that represents this :class:`AllowTrust`. """ trustor = account_xdr_object(self.trustor) length = len(self.asset_code) assert length <= 12 pad_length = 4 - length if length <= 4 else 12 - length ...
[ "def", "to_xdr_object", "(", "self", ")", ":", "trustor", "=", "account_xdr_object", "(", "self", ".", "trustor", ")", "length", "=", "len", "(", "self", ".", "asset_code", ")", "assert", "length", "<=", "12", "pad_length", "=", "4", "-", "length", "if",...
42.25
16.5
def openflow_controller_connection_address_connection_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow") controller_name_key = ET.SubEleme...
[ "def", "openflow_controller_connection_address_connection_port", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "openflow_controller", "=", "ET", ".", "SubElement", "(", "config", ",", "\"openflow-contr...
56.307692
27.307692
def checkout_deploy_branch(deploy_branch, canpush=True): """ Checkout the deploy branch, creating it if it doesn't exist. """ # Create an empty branch with .nojekyll if it doesn't already exist create_deploy_branch(deploy_branch, push=canpush) remote_branch = "doctr_remote/{}".format(deploy_bran...
[ "def", "checkout_deploy_branch", "(", "deploy_branch", ",", "canpush", "=", "True", ")", ":", "# Create an empty branch with .nojekyll if it doesn't already exist", "create_deploy_branch", "(", "deploy_branch", ",", "push", "=", "canpush", ")", "remote_branch", "=", "\"doct...
43.368421
22.315789
def add_beads_stats(beads_table, beads_samples, mef_outputs=None): """ Add stats fields to beads table. The following information is added to each row: - Notes (warnings, errors) resulting from the analysis - Number of Events - Acquisition Time (s) The following information is...
[ "def", "add_beads_stats", "(", "beads_table", ",", "beads_samples", ",", "mef_outputs", "=", "None", ")", ":", "# The index name is not preserved if beads_table is empty.", "# Save the index name for later", "beads_table_index_name", "=", "beads_table", ".", "index", ".", "na...
44.455056
19.713483
def push(self): """Binds the app context to the current context.""" self._refcnt += 1 _app_ctx_stack.push(self) appcontext_pushed.send(self.app)
[ "def", "push", "(", "self", ")", ":", "self", ".", "_refcnt", "+=", "1", "_app_ctx_stack", ".", "push", "(", "self", ")", "appcontext_pushed", ".", "send", "(", "self", ".", "app", ")" ]
34.4
9.4
def save(self): """ Update the SouceReading information for the currently recorded observations and then flush those to a file. @return: mpc_filename of the resulting save. """ self.get_writer().flush() mpc_filename = self.get_writer().get_filename() self.get_writ...
[ "def", "save", "(", "self", ")", ":", "self", ".", "get_writer", "(", ")", ".", "flush", "(", ")", "mpc_filename", "=", "self", ".", "get_writer", "(", ")", ".", "get_filename", "(", ")", "self", ".", "get_writer", "(", ")", ".", "close", "(", ")",...
37.9
16.7
def run_file(self, debug=False): """Run script inside current interpreter or in a new one""" editorstack = self.get_current_editorstack() if editorstack.save(): editor = self.get_current_editor() fname = osp.abspath(self.get_current_filename()) # Get f...
[ "def", "run_file", "(", "self", ",", "debug", "=", "False", ")", ":", "editorstack", "=", "self", ".", "get_current_editorstack", "(", ")", "if", "editorstack", ".", "save", "(", ")", ":", "editor", "=", "self", ".", "get_current_editor", "(", ")", "fnam...
46.477612
18.029851
def format_message(self, message): """ Formats a message with :class:Look """ look = Look(message) return look.pretty(display=False)
[ "def", "format_message", "(", "self", ",", "message", ")", ":", "look", "=", "Look", "(", "message", ")", "return", "look", ".", "pretty", "(", "display", "=", "False", ")" ]
38.25
4.75
def simple_cmd(): """ ``Deprecated``: Not better than ``fire`` -> pip install fire """ parser = argparse.ArgumentParser( prog="Simple command-line function toolkit.", description="""Input function name and args and kwargs. python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""", ) ...
[ "def", "simple_cmd", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"Simple command-line function toolkit.\"", ",", "description", "=", "\"\"\"Input function name and args and kwargs.\n python xxx.py main -a 1 2 3 -k a=1,b=2,c=3\"\"\"", ...
32.775
17.85
def ls(sess_id_or_alias, path): """ List files in a path of a running container. \b SESSID: Session ID or its alias given when creating the session. PATH: Path inside container. """ with Session() as session: try: print_wait('Retrieving list of files in "{}"...'.format(p...
[ "def", "ls", "(", "sess_id_or_alias", ",", "path", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "print_wait", "(", "'Retrieving list of files in \"{}\"...'", ".", "format", "(", "path", ")", ")", "kernel", "=", "session", ".", "...
36.09375
17.09375
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """ Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid) # create verified email address...
[ "def", "load_extra_data", "(", "backend", ",", "details", ",", "response", ",", "uid", ",", "user", ",", "social_user", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "social_user", "=", "social_user", "or", "UserSocialAuth", ".", "get...
50
21.95
def get_version(): """ Read version from __init__.py """ version_regex = re.compile( '__version__\\s*=\\s*(?P<q>[\'"])(?P<version>\\d+(\\.\\d+)*(-(alpha|beta|rc)(\\.\\d+)?)?)(?P=q)' ) here = path.abspath(path.dirname(__file__)) init_location = path.join(here, "CHAID/__init__.py") ...
[ "def", "get_version", "(", ")", ":", "version_regex", "=", "re", ".", "compile", "(", "'__version__\\\\s*=\\\\s*(?P<q>[\\'\"])(?P<version>\\\\d+(\\\\.\\\\d+)*(-(alpha|beta|rc)(\\\\.\\\\d+)?)?)(?P=q)'", ")", "here", "=", "path", ".", "abspath", "(", "path", ".", "dirname", ...
29.45
20.75
def _broadcast_indexes(self, key): """Prepare an indexing key for an indexing operation. Parameters ----------- key: int, slice, array, dict or tuple of integer, slices and arrays Any valid input for indexing. Returns ------- dims: tuple ...
[ "def", "_broadcast_indexes", "(", "self", ",", "key", ")", ":", "key", "=", "self", ".", "_item_key_to_tuple", "(", "key", ")", "# key is a tuple", "# key is a tuple of full size", "key", "=", "indexing", ".", "expanded_indexer", "(", "key", ",", "self", ".", ...
39.982456
17.666667
def encode_varint(v, f): """Encode integer `v` to file `f`. Parameters ---------- v: int Integer v >= 0. f: file Object containing a write method. Returns ------- int Number of bytes written. """ assert v >= 0 num_bytes = 0 while True: b...
[ "def", "encode_varint", "(", "v", ",", "f", ")", ":", "assert", "v", ">=", "0", "num_bytes", "=", "0", "while", "True", ":", "b", "=", "v", "%", "0x80", "v", "=", "v", "//", "0x80", "if", "v", ">", "0", ":", "b", "=", "b", "|", "0x80", "f",...
15.125
23.84375
def update(self, statement): """ Modifies an entry in the database. Creates an entry if one does not exist. """ Statement = self.get_model('statement') Tag = self.get_model('tag') if statement is not None: session = self.Session() record =...
[ "def", "update", "(", "self", ",", "statement", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "if", "statement", "is", "not", "None", ":", "session", "=", "self",...
34.3
20.1
def canberra_distance_numpy(object1, object2): """! @brief Calculate Canberra distance between two objects using numpy. @param[in] object1 (array_like): The first vector. @param[in] object2 (array_like): The second vector. @return (float) Canberra distance between two objects. """ ...
[ "def", "canberra_distance_numpy", "(", "object1", ",", "object2", ")", ":", "with", "numpy", ".", "errstate", "(", "divide", "=", "'ignore'", ",", "invalid", "=", "'ignore'", ")", ":", "result", "=", "numpy", ".", "divide", "(", "numpy", ".", "abs", "(",...
36.588235
23.352941
def global_include(self, pattern): """ Include all files anywhere in the current directory that match the pattern. This is very inefficient on large file trees. """ if self.allfiles is None: self.findall() match = translate_pattern(os.path.join('**', pattern))...
[ "def", "global_include", "(", "self", ",", "pattern", ")", ":", "if", "self", ".", "allfiles", "is", "None", ":", "self", ".", "findall", "(", ")", "match", "=", "translate_pattern", "(", "os", ".", "path", ".", "join", "(", "'**'", ",", "pattern", "...
38.636364
13.909091
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1,extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional ""...
[ "def", "parse", "(", "cls", ",", "src", ",", "dist", "=", "None", ")", ":", "try", ":", "attrs", "=", "extras", "=", "(", ")", "name", ",", "value", "=", "src", ".", "split", "(", "'='", ",", "1", ")", "if", "'['", "in", "value", ":", "value"...
35.366667
15.833333
def func_args(func): '''Basic function which returns a tuple of arguments of a function or method. ''' try: return tuple(inspect.signature(func).parameters) except: return tuple(inspect.getargspec(func).args)
[ "def", "func_args", "(", "func", ")", ":", "try", ":", "return", "tuple", "(", "inspect", ".", "signature", "(", "func", ")", ".", "parameters", ")", "except", ":", "return", "tuple", "(", "inspect", ".", "getargspec", "(", "func", ")", ".", "args", ...
29.625
25.375
def _create_application_version_request(app_metadata, application_id, template): """ Construct the request body to create application version. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param application_id: The Amazon Resource Name (ARN) of the app...
[ "def", "_create_application_version_request", "(", "app_metadata", ",", "application_id", ",", "template", ")", ":", "app_metadata", ".", "validate", "(", "[", "'semantic_version'", "]", ")", "request", "=", "{", "'ApplicationId'", ":", "application_id", ",", "'Sema...
38.47619
16.857143
def list_files(self, id=None, path="/"): """ List files in an allocation directory. https://www.nomadproject.io/docs/http/client-fs-ls.html arguments: - id - path returns: list raises: - nomad.api.exceptions.Bas...
[ "def", "list_files", "(", "self", ",", "id", "=", "None", ",", "path", "=", "\"/\"", ")", ":", "if", "id", ":", "return", "self", ".", "request", "(", "id", ",", "params", "=", "{", "\"path\"", ":", "path", "}", ",", "method", "=", "\"get\"", ")"...
34.058824
20.941176
def _from_stream(cls, stream, blob, filename=None): """ Return an instance of the |Image| subclass corresponding to the format of the image in *stream*. """ image_header = _ImageHeaderFactory(stream) if filename is None: filename = 'image.%s' % image_header.de...
[ "def", "_from_stream", "(", "cls", ",", "stream", ",", "blob", ",", "filename", "=", "None", ")", ":", "image_header", "=", "_ImageHeaderFactory", "(", "stream", ")", "if", "filename", "is", "None", ":", "filename", "=", "'image.%s'", "%", "image_header", ...
41.111111
10.222222
def select_by_ids(selname, idlist, selection_exists=False, chunksize=20, restrict=None): """Selection with a large number of ids concatenated into a selection list can cause buffer overflow in PyMOL. This function takes a selection name and and list of IDs (list of integers) as input and makes a careful ...
[ "def", "select_by_ids", "(", "selname", ",", "idlist", ",", "selection_exists", "=", "False", ",", "chunksize", "=", "20", ",", "restrict", "=", "None", ")", ":", "idlist", "=", "list", "(", "set", "(", "idlist", ")", ")", "# Remove duplicates", "if", "n...
60.923077
22.615385
def calcPosition(self,parent_circle): ''' Position the circle tangent to the parent circle with the line connecting the centers of the two circles meeting the x axis at angle theta. ''' if r not in self: raise AttributeError("radius must be calculated before position.") if theta not ...
[ "def", "calcPosition", "(", "self", ",", "parent_circle", ")", ":", "if", "r", "not", "in", "self", ":", "raise", "AttributeError", "(", "\"radius must be calculated before position.\"", ")", "if", "theta", "not", "in", "self", ":", "raise", "AttributeError", "(...
63.2
29
def read(self): """We have been called to read! As a consumer, continue to read for the length of the packet and then pass to the callback. """ data = self.dev.read() if len(data) == 0: self.log.warning("READ : Nothing received") return if data ...
[ "def", "read", "(", "self", ")", ":", "data", "=", "self", ".", "dev", ".", "read", "(", ")", "if", "len", "(", "data", ")", "==", "0", ":", "self", ".", "log", ".", "warning", "(", "\"READ : Nothing received\"", ")", "return", "if", "data", "==", ...
27.636364
20
def _control_transfer(self, data): """ Send device a control request with standard parameters and <data> as payload. """ LOGGER.debug('Ctrl transfer: %r', data) self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09, wValue=0x0200, wIndex=0x01, data_or_w...
[ "def", "_control_transfer", "(", "self", ",", "data", ")", ":", "LOGGER", ".", "debug", "(", "'Ctrl transfer: %r'", ",", "data", ")", "self", ".", "_device", ".", "ctrl_transfer", "(", "bmRequestType", "=", "0x21", ",", "bRequest", "=", "0x09", ",", "wValu...
42.75
17.5
def _count_values(self): """Return dict mapping relevance level to sample index""" indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]} return indices
[ "def", "_count_values", "(", "self", ")", ":", "indices", "=", "{", "yi", ":", "[", "i", "]", "for", "i", ",", "yi", "in", "enumerate", "(", "self", ".", "y", ")", "if", "self", ".", "status", "[", "i", "]", "}", "return", "indices" ]
37.4
22
def as_coeff_unit(self): """Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import u...
[ "def", "as_coeff_unit", "(", "self", ")", ":", "coeff", ",", "mul", "=", "self", ".", "expr", ".", "as_coeff_Mul", "(", ")", "coeff", "=", "float", "(", "coeff", ")", "ret", "=", "Unit", "(", "mul", ",", "self", ".", "base_value", "/", "coeff", ","...
26.37037
18.333333
def _file_size(self, field): """ Returns the file size for given file field. Args: field (str): File field Returns: int. File size """ size = 0 try: handle = open(self._files[field], "r") size = os.fstat(handle.fileno()).s...
[ "def", "_file_size", "(", "self", ",", "field", ")", ":", "size", "=", "0", "try", ":", "handle", "=", "open", "(", "self", ".", "_files", "[", "field", "]", ",", "\"r\"", ")", "size", "=", "os", ".", "fstat", "(", "handle", ".", "fileno", "(", ...
25.277778
16.388889
def add_ref(self, ref): """ Add a reference to a memory data object. :param CodeReference ref: The reference. :return: None """ self.refs[ref.insn_addr].append(ref) self.data_addr_to_ref[ref.memory_data.addr].append(ref)
[ "def", "add_ref", "(", "self", ",", "ref", ")", ":", "self", ".", "refs", "[", "ref", ".", "insn_addr", "]", ".", "append", "(", "ref", ")", "self", ".", "data_addr_to_ref", "[", "ref", ".", "memory_data", ".", "addr", "]", ".", "append", "(", "ref...
29
14.2
def delete_floating_ip(kwargs=None, call=None): ''' Delete a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( 'The ...
[ "def", "delete_floating_ip", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "log", ".", "error", "(", "'The delete_floating_ip function must be called with -f or --function.'", ")", "return", "False", "if", "...
23.424242
24.090909
def dict(self): """A dict that holds key/values for all of the properties in the object. :return: """ SKIP_KEYS = ('_source_table', '_dest_table', 'd_vid', 't_vid', 'st_id', 'dataset', 'hash', 'process_records') return OrderedDict([(k, getattr(self,...
[ "def", "dict", "(", "self", ")", ":", "SKIP_KEYS", "=", "(", "'_source_table'", ",", "'_dest_table'", ",", "'d_vid'", ",", "'t_vid'", ",", "'st_id'", ",", "'dataset'", ",", "'hash'", ",", "'process_records'", ")", "return", "OrderedDict", "(", "[", "(", "k...
36.4
26.9
def maxlen(max_length, strict=False # type: bool ): """ 'Maximum length' validation_function generator. Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True) :param max_length: maximum length for x :param...
[ "def", "maxlen", "(", "max_length", ",", "strict", "=", "False", "# type: bool", ")", ":", "if", "strict", ":", "def", "maxlen_", "(", "x", ")", ":", "if", "len", "(", "x", ")", "<", "max_length", ":", "return", "True", "else", ":", "# raise Failure('m...
40.103448
28.103448
def next(self): """Get the next row in the page.""" self._parse_block() if self._remaining > 0: self._remaining -= 1 return six.next(self._iter_rows)
[ "def", "next", "(", "self", ")", ":", "self", ".", "_parse_block", "(", ")", "if", "self", ".", "_remaining", ">", "0", ":", "self", ".", "_remaining", "-=", "1", "return", "six", ".", "next", "(", "self", ".", "_iter_rows", ")" ]
31.333333
9.166667
def copy2(src, dst, metadata=None, retry_params=None): """Copy the file content from src to dst. Args: src: /bucket/filename dst: /bucket/filename metadata: a dict of metadata for this copy. If None, old metadata is copied. For example, {'x-goog-meta-foo': 'bar'}. retry_params: An api_utils.R...
[ "def", "copy2", "(", "src", ",", "dst", ",", "metadata", "=", "None", ",", "retry_params", "=", "None", ")", ":", "common", ".", "validate_file_path", "(", "src", ")", "common", ".", "validate_file_path", "(", "dst", ")", "if", "metadata", "is", "None", ...
34.366667
21.233333
def run_batch(args: dict) -> int: """Runs a batch operation for the given arguments""" batcher.run_project( project_directory=args.get('project_directory'), log_path=args.get('logging_path'), output_directory=args.get('output_directory'), shared_data=load_shared_data(args.get('s...
[ "def", "run_batch", "(", "args", ":", "dict", ")", "->", "int", ":", "batcher", ".", "run_project", "(", "project_directory", "=", "args", ".", "get", "(", "'project_directory'", ")", ",", "log_path", "=", "args", ".", "get", "(", "'logging_path'", ")", ...
34.8
18.4
def make_logging_handlers_and_tools(self, multiproc=False): """Creates logging handlers and redirects stdout.""" log_stdout = self.log_stdout if sys.stdout is self._stdout_to_logger: # If we already redirected stdout we don't neet to redo it again log_stdout = False ...
[ "def", "make_logging_handlers_and_tools", "(", "self", ",", "multiproc", "=", "False", ")", ":", "log_stdout", "=", "self", ".", "log_stdout", "if", "sys", ".", "stdout", "is", "self", ".", "_stdout_to_logger", ":", "# If we already redirected stdout we don't neet to ...
38.533333
19.666667
def unsubscribe(self, request, *args, **kwargs): """ Performs the unsubscribe action. """ self.object = self.get_object() self.object.subscribers.remove(request.user) messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url())
[ "def", "unsubscribe", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "self", ".", "object", ".", "subscribers", ".", "remove", "(", "request", ".", ...
51
10
def records( self ): """ Returns the record set for the current settings of this browser. :return <orb.RecordSet> """ if ( self.isGroupingActive() ): self._records.setGroupBy(self.currentGrouping()) else: self._records.setGrou...
[ "def", "records", "(", "self", ")", ":", "if", "(", "self", ".", "isGroupingActive", "(", ")", ")", ":", "self", ".", "_records", ".", "setGroupBy", "(", "self", ".", "currentGrouping", "(", ")", ")", "else", ":", "self", ".", "_records", ".", "setGr...
31.727273
13.545455
def to_ufos( font, include_instances=False, family_name=None, propagate_anchors=True, ufo_module=defcon, minimize_glyphs_diffs=False, generate_GDEF=True, store_editor_state=True, ): """Take a GSFont object and convert it into one UFO per master. Takes in data as Glyphs.app-compa...
[ "def", "to_ufos", "(", "font", ",", "include_instances", "=", "False", ",", "family_name", "=", "None", ",", "propagate_anchors", "=", "True", ",", "ufo_module", "=", "defcon", ",", "minimize_glyphs_diffs", "=", "False", ",", "generate_GDEF", "=", "True", ",",...
29.552632
20.657895
def pretty_memory_info(): ''' Pretty format memory info. Returns ------- str Memory info. Examples -------- >>> pretty_memory_info() '5MB memory usage' ''' process = psutil.Process(os.getpid()) return '{}MB memory usage'.format(int(process.memory_info().rss / 2*...
[ "def", "pretty_memory_info", "(", ")", ":", "process", "=", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", "return", "'{}MB memory usage'", ".", "format", "(", "int", "(", "process", ".", "memory_info", "(", ")", ".", "rss", "/", "2...
19.375
25.375
def hashify_targets(targets: list, build_context) -> list: """Return sorted hashes of `targets`.""" return sorted(build_context.targets[target_name].hash(build_context) for target_name in listify(targets))
[ "def", "hashify_targets", "(", "targets", ":", "list", ",", "build_context", ")", "->", "list", ":", "return", "sorted", "(", "build_context", ".", "targets", "[", "target_name", "]", ".", "hash", "(", "build_context", ")", "for", "target_name", "in", "listi...
57
16
def build_variables(self, variable_placeholders): """ :param variables: The list of vertices/edges to return :return: a dict where the keys are the names of the variables to return, the values are the JSON of the properties of these variables """ variables = self...
[ "def", "build_variables", "(", "self", ",", "variable_placeholders", ")", ":", "variables", "=", "self", ".", "__substitute_names_in_list", "(", "variable_placeholders", ")", "attributes", "=", "{", "}", "for", "i", ",", "variable", "in", "enumerate", "(", "vari...
41.833333
18.9
def read_from_list_with_ids(self, lines): """ Read text fragments from a given list of tuples:: [(id_1, text_1), (id_2, text_2), ..., (id_n, text_n)]. :param list lines: the list of ``[id, text]`` fragments (see above) """ self.log(u"Reading text fragments from list...
[ "def", "read_from_list_with_ids", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Reading text fragments from list with ids\"", ")", "self", ".", "_create_text_fragments", "(", "[", "(", "line", "[", "0", "]", ",", "[", "line", "[", "1", "]...
40
21.8
def _update_example(self, request): """Updates the specified example. Args: request: A request that should contain 'index' and 'example'. Returns: An empty response. """ if request.method != 'POST': return http_util.Respond(request, {'error': 'invalid non-POST request'}, ...
[ "def", "_update_example", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "!=", "'POST'", ":", "return", "http_util", ".", "Respond", "(", "request", ",", "{", "'error'", ":", "'invalid non-POST request'", "}", ",", "'application/json'",...
39.73913
16.869565
def _validate(self): """ Ensure that our percentile bounds are well-formed. """ if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0: raise BadPercentileBounds( min_percentile=self._min_percentile, max_percentile=self._max_percent...
[ "def", "_validate", "(", "self", ")", ":", "if", "not", "0.0", "<=", "self", ".", "_min_percentile", "<", "self", ".", "_max_percentile", "<=", "100.0", ":", "raise", "BadPercentileBounds", "(", "min_percentile", "=", "self", ".", "_min_percentile", ",", "ma...
38.090909
13.545455
def atlas_node_add_callback(atlas_state, callback_name, callback): """ Add a callback to the initialized atlas state """ if callback_name == 'store_zonefile': atlas_state['zonefile_crawler'].set_store_zonefile_callback(callback) else: raise ValueError("Unrecognized callback {}".form...
[ "def", "atlas_node_add_callback", "(", "atlas_state", ",", "callback_name", ",", "callback", ")", ":", "if", "callback_name", "==", "'store_zonefile'", ":", "atlas_state", "[", "'zonefile_crawler'", "]", ".", "set_store_zonefile_callback", "(", "callback", ")", "else"...
36.666667
19.777778