text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def dusk_utc(self, date, latitude, longitude, depression=0, observer_elevation=0): """Calculate dusk time in the UTC timezone. :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northern latitudes should be positive ...
[ "def", "dusk_utc", "(", "self", ",", "date", ",", "latitude", ",", "longitude", ",", "depression", "=", "0", ",", "observer_elevation", "=", "0", ")", ":", "if", "depression", "==", "0", ":", "depression", "=", "self", ".", "_depression", "depression", "...
38.4
19.371429
def filter_with_english_letters(buf): """ Returns a copy of ``buf`` that retains only the sequences of English alphabet and high byte characters that are not between <> characters. Also retains English alphabet and high byte characters immediately before occurrences of >. ...
[ "def", "filter_with_english_letters", "(", "buf", ")", ":", "filtered", "=", "bytearray", "(", ")", "in_tag", "=", "False", "prev", "=", "0", "for", "curr", "in", "range", "(", "len", "(", "buf", ")", ")", ":", "# Slice here to get bytes instead of an int with...
39.214286
18.928571
def addClassToGraph( self, class_id, label=None, class_type=None, description=None ): """ Any node added to the graph will get at least 3 triples: *(node, type, owl:Class) and *(node, label, literal(label)) *if a type is added, then the node will be an...
[ "def", "addClassToGraph", "(", "self", ",", "class_id", ",", "label", "=", "None", ",", "class_type", "=", "None", ",", "description", "=", "None", ")", ":", "assert", "class_id", "is", "not", "None", "self", ".", "graph", ".", "addTriple", "(", "class_i...
35.15625
17.78125
def connection_made(self, transport): """ Called by the underlying transport when a connection is made. :param transport: The transport representing the connection. """ # Save the underlying transport self._transport = transport # Call connection_made() on the ...
[ "def", "connection_made", "(", "self", ",", "transport", ")", ":", "# Save the underlying transport", "self", ".", "_transport", "=", "transport", "# Call connection_made() on the client protocol, passing", "# ourself as the transport", "self", ".", "_client", ".", "connectio...
31.538462
16.769231
def get_sanitize_files(self): """ Return list of all sanitize files provided by the user on the command line. N.B.: We only support one sanitize file at the moment, but this is likely to change in the future """ if self.parent.config.option.sanitize_with is not No...
[ "def", "get_sanitize_files", "(", "self", ")", ":", "if", "self", ".", "parent", ".", "config", ".", "option", ".", "sanitize_with", "is", "not", "None", ":", "return", "[", "self", ".", "parent", ".", "config", ".", "option", ".", "sanitize_with", "]", ...
34.083333
21.75
def make_day_night_masks(solarZenithAngle, good_mask, highAngleCutoff, lowAngleCutoff, stepsDegrees=None): """ given information on the solarZenithAngle for each point, generate masks defining where the day, ...
[ "def", "make_day_night_masks", "(", "solarZenithAngle", ",", "good_mask", ",", "highAngleCutoff", ",", "lowAngleCutoff", ",", "stepsDegrees", "=", "None", ")", ":", "# if the caller passes None, we're only doing one step", "stepsDegrees", "=", "highAngleCutoff", "-", "lowAn...
43.837838
20.216216
def enable_directory_service(self, check_peer=False): """Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional ...
[ "def", "enable_directory_service", "(", "self", ",", "check_peer", "=", "False", ")", ":", "if", "check_peer", ":", "return", "self", ".", "set_directory_service", "(", "check_peer", "=", "True", ")", "return", "self", ".", "set_directory_service", "(", "enabled...
37.733333
19.666667
def update_compliance(self, timeout=-1): """ Returns logical interconnects to a consistent state. The current logical interconnect state is compared to the associated logical interconnect group. Any differences identified are corrected, bringing the logical interconnect back to a consis...
[ "def", "update_compliance", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "\"{}/compliance\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ")", "return", "self", ".", "_helper", ".", "update", "(", "None", ",", "...
57.4
37.5
def getBehavior(name, id=None): """ Return a matching behavior if it exists, or None. If id is None, return the default for name. """ name = name.upper() if name in __behaviorRegistry: if id: for n, behavior in __behaviorRegistry[name]: if n == id: ...
[ "def", "getBehavior", "(", "name", ",", "id", "=", "None", ")", ":", "name", "=", "name", ".", "upper", "(", ")", "if", "name", "in", "__behaviorRegistry", ":", "if", "id", ":", "for", "n", ",", "behavior", "in", "__behaviorRegistry", "[", "name", "]...
26.266667
14.8
def link(self, mu, dist): """ glm link function this is useful for going from mu to the linear prediction Parameters ---------- mu : array-like of legth n dist : Distribution instance Returns ------- lp : np.array of length n """ ...
[ "def", "link", "(", "self", ",", "mu", ",", "dist", ")", ":", "return", "np", ".", "log", "(", "mu", ")", "-", "np", ".", "log", "(", "dist", ".", "levels", "-", "mu", ")" ]
23.866667
17.2
def _completed_cb(self, data): """ Extract info from data and emit completed. """ try: info = json.loads(data) except ValueError: info = self._hook_data(data) except Exception, e: info = None logging.error('%s: _completed_cb crashed with %s...
[ "def", "_completed_cb", "(", "self", ",", "data", ")", ":", "try", ":", "info", "=", "json", ".", "loads", "(", "data", ")", "except", "ValueError", ":", "info", "=", "self", ".", "_hook_data", "(", "data", ")", "except", "Exception", ",", "e", ":", ...
35.307692
12.230769
def thermostat(self, temperature): """A temperature to set the thermostat to. Requires a float. :param temperature: A float of the desired temperature to change to. """ target = int(temperature * 100) data = copy.copy(self._parameters) data.update({'value': target}) ...
[ "def", "thermostat", "(", "self", ",", "temperature", ")", ":", "target", "=", "int", "(", "temperature", "*", "100", ")", "data", "=", "copy", ".", "copy", "(", "self", ".", "_parameters", ")", "data", ".", "update", "(", "{", "'value'", ":", "targe...
42.363636
13.727273
def _writtable(self, watcher, events): """Called by the pyev watcher (self.write_watcher) whenever the socket is writtable. Calls send using the userspace buffer (self.write_buffer) and checks for errors. If there are no errors then continue on as before. Otherwise closes the so...
[ "def", "_writtable", "(", "self", ",", "watcher", ",", "events", ")", ":", "try", ":", "sent", "=", "self", ".", "sock", ".", "send", "(", "bytes", "(", "self", ".", "write_buffer", ")", ")", "self", ".", "write_buffer", "=", "self", ".", "write_buff...
40.470588
17.117647
def fetch(self): """ Fetch a DocumentPermissionInstance :returns: Fetched DocumentPermissionInstance :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance """ params = values.of({}) payload = self._version.fetch( ...
[ "def", "fetch", "(", "self", ")", ":", "params", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "fetch", "(", "'GET'", ",", "self", ".", "_uri", ",", "params", "=", "params", ",", ")", "return", "Docum...
28.590909
19.045455
def interpolate_single(start, end, coefficient, how='linear'): """ Interpolate single value between start and end in given number of steps """ return INTERP_SINGLE_DICT[how](start, end, coefficient)
[ "def", "interpolate_single", "(", "start", ",", "end", ",", "coefficient", ",", "how", "=", "'linear'", ")", ":", "return", "INTERP_SINGLE_DICT", "[", "how", "]", "(", "start", ",", "end", ",", "coefficient", ")" ]
68
13.666667
def get_servers_list(self): """Return the current server list (list of dict). Merge of static + autodiscover servers list. """ ret = [] if self.args.browser: ret = self.static_server.get_servers_list() if self.autodiscover_server is not None: ...
[ "def", "get_servers_list", "(", "self", ")", ":", "ret", "=", "[", "]", "if", "self", ".", "args", ".", "browser", ":", "ret", "=", "self", ".", "static_server", ".", "get_servers_list", "(", ")", "if", "self", ".", "autodiscover_server", "is", "not", ...
32.461538
22.615385
def space_exists(args): """ Determine if the named space exists in the given project (namespace)""" # The return value is the INVERSE of UNIX exit status semantics, (where # 0 = good/true, 1 = bad/false), so to check existence in UNIX one would do # if ! fissfc space_exists blah ; then # ... ...
[ "def", "space_exists", "(", "args", ")", ":", "# The return value is the INVERSE of UNIX exit status semantics, (where", "# 0 = good/true, 1 = bad/false), so to check existence in UNIX one would do", "# if ! fissfc space_exists blah ; then", "# ...", "# fi", "try", ":", "r", "="...
37.761905
19.047619
def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=0, viewer=None): ''' Simulated annealing. schedule is the scheduling function that decides the chance to choose worst nodes depending on the time. If iterations_limit is specified, the algorithm will end after that number...
[ "def", "simulated_annealing", "(", "problem", ",", "schedule", "=", "_exp_schedule", ",", "iterations_limit", "=", "0", ",", "viewer", "=", "None", ")", ":", "return", "_local_search", "(", "problem", ",", "_create_simulated_annealing_expander", "(", "schedule", "...
45
22.555556
def raw(self) -> str: """ Return a raw document of the certification """ if not isinstance(self.identity, Identity): raise MalformedDocumentError("Can not return full certification document created from inline") return """Version: {version} Type: Certification Curren...
[ "def", "raw", "(", "self", ")", "->", "str", ":", "if", "not", "isinstance", "(", "self", ".", "identity", ",", "Identity", ")", ":", "raise", "MalformedDocumentError", "(", "\"Can not return full certification document created from inline\"", ")", "return", "\"\"\"...
34.458333
13.125
def add_taxes(self, taxes): """Appends the data to the 'taxes' key in the request object 'taxes' should be in format: [("tax_name", "tax_amount")] For example: [("Other TAX", 700), ("VAT", 5000)] """ # fixme: how to resolve duplicate tax names _idx = len(self.tax...
[ "def", "add_taxes", "(", "self", ",", "taxes", ")", ":", "# fixme: how to resolve duplicate tax names", "_idx", "=", "len", "(", "self", ".", "taxes", ")", "# current index to prevent overwriting", "for", "idx", ",", "tax", "in", "enumerate", "(", "taxes", ")", ...
42.5
14.75
def xcorr_plot(template, image, shift=None, cc=None, cc_vec=None, **kwargs): """ Plot a template overlying an image aligned by correlation. :type template: numpy.ndarray :param template: Short template image :type image: numpy.ndarray :param image: Long master image :type shift: int :pa...
[ "def", "xcorr_plot", "(", "template", ",", "image", ",", "shift", "=", "None", ",", "cc", "=", "None", ",", "cc_vec", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "cc", "is", "None", "or"...
38.16
17.08
def estimator_status_send(self, time_usec, flags, vel_ratio, pos_horiz_ratio, pos_vert_ratio, mag_ratio, hagl_ratio, tas_ratio, pos_horiz_accuracy, pos_vert_accuracy, force_mavlink1=False): ''' Estimator status message including flags, innovation test ratios and estimated...
[ "def", "estimator_status_send", "(", "self", ",", "time_usec", ",", "flags", ",", "vel_ratio", ",", "pos_horiz_ratio", ",", "pos_vert_ratio", ",", "mag_ratio", ",", "hagl_ratio", ",", "tas_ratio", ",", "pos_horiz_accuracy", ",", "pos_vert_accuracy", ",", "force_mavl...
80.709677
48.580645
def _check_flow_operator(string): """ Checks the flow operator ('>') to make sure that it: 1) Is non empty 2) There is only one of them """ greater_than_count = string.count('>') if greater_than_count > 1: raise ValueError(MULTIPLE_FLOW_OPERATORS) elif (string[0] == '>') or (stri...
[ "def", "_check_flow_operator", "(", "string", ")", ":", "greater_than_count", "=", "string", ".", "count", "(", "'>'", ")", "if", "greater_than_count", ">", "1", ":", "raise", "ValueError", "(", "MULTIPLE_FLOW_OPERATORS", ")", "elif", "(", "string", "[", "0", ...
28.764706
12.647059
def encode_to_py3bytes_or_py2str(s): """ takes anything and attempts to return a py2 string or py3 bytes. this is typically used when creating command + arguments to be executed via os.exec* """ fallback_encoding = "utf8" if IS_PY3: # if we're already bytes, do nothing if isinstan...
[ "def", "encode_to_py3bytes_or_py2str", "(", "s", ")", ":", "fallback_encoding", "=", "\"utf8\"", "if", "IS_PY3", ":", "# if we're already bytes, do nothing", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "pass", "else", ":", "s", "=", "str", "(", "s", ...
35.294118
20.294118
def construct_listener(outfile=None): """Create the listener that prints tweets""" if outfile is not None: if os.path.exists(outfile): raise IOError("File %s already exists" % outfile) outfile = open(outfile, 'wb') return PrintingListener(out=outfile)
[ "def", "construct_listener", "(", "outfile", "=", "None", ")", ":", "if", "outfile", "is", "not", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "raise", "IOError", "(", "\"File %s already exists\"", "%", "outfile", ")", "...
32.555556
13
def send(self, stream_to_file=None): """ This will perform the http request. stream_to_file: str of the file name to stream the data too :return: str of status """ try: self._stage = STAGE_REQUEST self.prepared_request.prepare(method=self.method, ...
[ "def", "send", "(", "self", ",", "stream_to_file", "=", "None", ")", ":", "try", ":", "self", ".", "_stage", "=", "STAGE_REQUEST", "self", ".", "prepared_request", ".", "prepare", "(", "method", "=", "self", ".", "method", ",", "url", "=", "self", ".",...
43.522727
17.068182
def mdot(*args): """ Multiply all the arguments using matrix product rules. The output is equivalent to multiplying the arguments one by one from left to right using dot(). Precedence can be controlled by creating tuples of arguments, for instance mdot(a,((b,c),d)) multiplies a (a*((b*c)*d)). ...
[ "def", "mdot", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "args", "[", "0", "]", "elif", "len", "(", "args", ")", "==", "2", ":", "return", "_mdot_r", "(", "args", "[", "0", "]", ",", "args", "[", "...
34.823529
16.823529
def make_assignment(instr, queue, stack): """ Make an ast.Assign node. """ value = make_expr(stack) # Make assignment targets. # If there are multiple assignments (e.g. 'a = b = c'), # each LHS expression except the last is preceded by a DUP_TOP instruction. # Thus, we make targets unti...
[ "def", "make_assignment", "(", "instr", ",", "queue", ",", "stack", ")", ":", "value", "=", "make_expr", "(", "stack", ")", "# Make assignment targets.", "# If there are multiple assignments (e.g. 'a = b = c'),", "# each LHS expression except the last is preceded by a DUP_TOP ins...
33.631579
19.842105
def number_of_subkeys(self): """int: number of subkeys within the key.""" if not self._registry_key and self._registry: self._GetKeyFromRegistry() return len(self._subkeys)
[ "def", "number_of_subkeys", "(", "self", ")", ":", "if", "not", "self", ".", "_registry_key", "and", "self", ".", "_registry", ":", "self", ".", "_GetKeyFromRegistry", "(", ")", "return", "len", "(", "self", ".", "_subkeys", ")" ]
31
13.333333
def superpose(ras, rbs, weights=None): """Compute the transformation that minimizes the RMSD between the points ras and rbs Arguments: | ``ras`` -- a ``np.array`` with 3D coordinates of geometry A, shape=(N,3) | ``rbs`` -- a ``np.array`` with 3D coordinates of geom...
[ "def", "superpose", "(", "ras", ",", "rbs", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "ma", "=", "ras", ".", "mean", "(", "axis", "=", "0", ")", "mb", "=", "rbs", ".", "mean", "(", "axis", "=", "0", ")", "else...
34.613636
20.363636
def _runCombProcesses(self) -> None: """ Delta step for combinational processes """ for proc in self._combProcsToRun: cont = self._outputContainers[proc] proc(self, cont) for sigName, sig in cont._all_signals: newVal = getattr(cont, sig...
[ "def", "_runCombProcesses", "(", "self", ")", "->", "None", ":", "for", "proc", "in", "self", ".", "_combProcsToRun", ":", "cont", "=", "self", ".", "_outputContainers", "[", "proc", "]", "proc", "(", "self", ",", "cont", ")", "for", "sigName", ",", "s...
39
8.578947
def add_subtask(self, task, params={}, **options): """Creates a new subtask and adds it to the parent task. Returns the full record for the newly created subtask. Parameters ---------- task : {Id} The task to add a subtask to. [data] : {Object} Data for the request ...
[ "def", "add_subtask", "(", "self", ",", "task", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/tasks/%s/subtasks\"", "%", "(", "task", ")", "return", "self", ".", "client", ".", "post", "(", "path", ",", "params", ...
38.090909
12
def _parse_names(self): """ parse sample names from the sequence file""" self.samples = [] with iter(open(self.files.data, 'r')) as infile: infile.next().strip().split() while 1: try: self.samples.append(infile.next().split()[0]) ...
[ "def", "_parse_names", "(", "self", ")", ":", "self", ".", "samples", "=", "[", "]", "with", "iter", "(", "open", "(", "self", ".", "files", ".", "data", ",", "'r'", ")", ")", "as", "infile", ":", "infile", ".", "next", "(", ")", ".", "strip", ...
36.8
13.2
def _ixs(self, i, axis=0): """ Return the i-th value or values in the SparseSeries by location Parameters ---------- i : int, slice, or sequence of integers Returns ------- value : scalar (int) or Series (slice, sequence) """ label = self...
[ "def", "_ixs", "(", "self", ",", "i", ",", "axis", "=", "0", ")", ":", "label", "=", "self", ".", "index", "[", "i", "]", "if", "isinstance", "(", "label", ",", "Index", ")", ":", "return", "self", ".", "take", "(", "i", ",", "axis", "=", "ax...
26.235294
16.941176
def identify_marker_genes_corr(self, labels=None, n_genes=4000): """ Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster-specific reference expression profiles. Parameters ---------- labels - numpy.array or str...
[ "def", "identify_marker_genes_corr", "(", "self", ",", "labels", "=", "None", ",", "n_genes", "=", "4000", ")", ":", "if", "(", "labels", "is", "None", ")", ":", "try", ":", "keys", "=", "np", ".", "array", "(", "list", "(", "self", ".", "adata", "...
37.709091
22.472727
def copy(self): """ Return copy :return: WHTTPCookie """ copy_cookie = WHTTPCookie(self.__name, self.__value) copy_cookie.__attrs = self.__attrs.copy() return copy_cookie
[ "def", "copy", "(", "self", ")", ":", "copy_cookie", "=", "WHTTPCookie", "(", "self", ".", "__name", ",", "self", ".", "__value", ")", "copy_cookie", ".", "__attrs", "=", "self", ".", "__attrs", ".", "copy", "(", ")", "return", "copy_cookie" ]
22
15
def sendVX(self, vx): ''' Sends VX velocity. @param vx: VX velocity @type vx: float ''' self.lock.acquire() self.data.vx = vx self.lock.release()
[ "def", "sendVX", "(", "self", ",", "vx", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "self", ".", "data", ".", "vx", "=", "vx", "self", ".", "lock", ".", "release", "(", ")" ]
17.416667
22.583333
def to_dict(self): """Transforms the object to a Python dictionary. Note: If an Input hasn't been signed yet, this method returns a dictionary representation. Returns: dict: The Input as an alternative serialization format. """ ...
[ "def", "to_dict", "(", "self", ")", ":", "try", ":", "fulfillment", "=", "self", ".", "fulfillment", ".", "serialize_uri", "(", ")", "except", "(", "TypeError", ",", "AttributeError", ",", "ASN1EncodeError", ",", "ASN1DecodeError", ")", ":", "fulfillment", "...
32.222222
21.148148
def _inbound(self, From, to, protocol, udp_source=None): """ Implementation of L{Inbound}. """ # Verify stuff! self.verifyCertificateAllowed(to, From) return self.service.verifyHook(From, to, protocol ).addCallback(self._inboundimpl...
[ "def", "_inbound", "(", "self", ",", "From", ",", "to", ",", "protocol", ",", "udp_source", "=", "None", ")", ":", "# Verify stuff!", "self", ".", "verifyCertificateAllowed", "(", "to", ",", "From", ")", "return", "self", ".", "service", ".", "verifyHook",...
44.785714
17.5
def create(self, asns): """ Method to create asns :param asns: List containing asns desired to be created on database :return: None """ data = {'asns': asns} return super(ApiV4As, self).post('api/v4/as/', data)
[ "def", "create", "(", "self", ",", "asns", ")", ":", "data", "=", "{", "'asns'", ":", "asns", "}", "return", "super", "(", "ApiV4As", ",", "self", ")", ".", "post", "(", "'api/v4/as/'", ",", "data", ")" ]
25.9
19.3
def setFixedWidth(self, width): """ Sets the maximum width value to the inputed width and emits the \ sizeConstraintChanged signal. :param width | <int> """ super(XView, self).setFixedWidth(width) if ( not self.signalsBlocked() ): ...
[ "def", "setFixedWidth", "(", "self", ",", "width", ")", ":", "super", "(", "XView", ",", "self", ")", ".", "setFixedWidth", "(", "width", ")", "if", "(", "not", "self", ".", "signalsBlocked", "(", ")", ")", ":", "self", ".", "sizeConstraintChanged", "....
31.363636
11.727273
def _create_import_log(items): """ Used to create log with successfully imported data. """ log = [] for item in items: if isinstance(item, MetadataFile): log.append( "Metadata file '%s' successfully imported." % item.filename ) elif isinstance...
[ "def", "_create_import_log", "(", "items", ")", ":", "log", "=", "[", "]", "for", "item", "in", "items", ":", "if", "isinstance", "(", "item", ",", "MetadataFile", ")", ":", "log", ".", "append", "(", "\"Metadata file '%s' successfully imported.\"", "%", "it...
32.96
18.96
def threaded_quit(self, arg): """ quit command when several threads are involved. """ threading_list = threading.enumerate() mythread = threading.currentThread() for t in threading_list: if t != mythread: ctype_async_raise(t, Mexcept.DebuggerQuit) ...
[ "def", "threaded_quit", "(", "self", ",", "arg", ")", ":", "threading_list", "=", "threading", ".", "enumerate", "(", ")", "mythread", "=", "threading", ".", "currentThread", "(", ")", "for", "t", "in", "threading_list", ":", "if", "t", "!=", "mythread", ...
37.2
10.9
def restart(self, name): """Restart a service """ init = self._get_implementation(name) self._assert_service_installed(init, name) logger.info('Restarting service: %s...', name) init.stop() # Here we would use status to verify that the service stopped # be...
[ "def", "restart", "(", "self", ",", "name", ")", ":", "init", "=", "self", ".", "_get_implementation", "(", "name", ")", "self", ".", "_assert_service_installed", "(", "init", ",", "name", ")", "logger", ".", "info", "(", "'Restarting service: %s...'", ",", ...
38.833333
14.916667
def add_entry(self, entry): """Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already prese...
[ "def", "add_entry", "(", "self", ",", "entry", ")", ":", "self", ".", "entry_keys", ".", "setdefault", "(", "entry", ",", "[", "]", ")", "self", ".", "entries", ".", "append", "(", "entry", ")", "for", "dist", "in", "find_distributions", "(", "entry", ...
48.642857
18.357143
def best_model(seq2hmm): """ determine the best model: archaea, bacteria, eukarya (best score) """ for seq in seq2hmm: best = [] for model in seq2hmm[seq]: best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]]) best_model = sorted(best, ...
[ "def", "best_model", "(", "seq2hmm", ")", ":", "for", "seq", "in", "seq2hmm", ":", "best", "=", "[", "]", "for", "model", "in", "seq2hmm", "[", "seq", "]", ":", "best", ".", "append", "(", "[", "model", ",", "sorted", "(", "[", "i", "[", "-", "...
39.636364
20.909091
def _validate(self): """Validate the class entries. """ checker = (self._check0, self._check1, self._check2, self._check3, self._check4, self._check5) if not 0 <= self.field_type <= 5: raise NotImplementedError("unsupported widget type") if type(sel...
[ "def", "_validate", "(", "self", ")", ":", "checker", "=", "(", "self", ".", "_check0", ",", "self", ".", "_check1", ",", "self", ".", "_check2", ",", "self", ".", "_check3", ",", "self", ".", "_check4", ",", "self", ".", "_check5", ")", "if", "not...
38.162162
17.162162
def utilization(self): """Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written ...
[ "def", "utilization", "(", "self", ")", ":", "class", "GpuUtilizationInfo", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "'gpu'", ",", "c_uint", ")", ",", "(", "'memory'", ",", "c_uint", ")", ",", "]", "c_util", "=", "GpuUtilizationInfo", "(", ...
32.625
23.625
def describe(self): """ describes a Symbol, returns a string """ lines = [] lines.append("Symbol = {}".format(self.name)) if len(self.tags): tgs = ", ".join(x.tag for x in self.tags) lines.append(" tagged = {}".format(tgs)) if len(self.aliases): ...
[ "def", "describe", "(", "self", ")", ":", "lines", "=", "[", "]", "lines", ".", "append", "(", "\"Symbol = {}\"", ".", "format", "(", "self", ".", "name", ")", ")", "if", "len", "(", "self", ".", "tags", ")", ":", "tgs", "=", "\", \"", ".", "join...
40.176471
14.941176
def getBucketValues(self): """ See the function description in base.py """ # Need to re-create? if self._bucketValues is None: scaledValues = self.encoder.getBucketValues() self._bucketValues = [] for scaledValue in scaledValues: value = math.pow(10, scaledValue) s...
[ "def", "getBucketValues", "(", "self", ")", ":", "# Need to re-create?", "if", "self", ".", "_bucketValues", "is", "None", ":", "scaledValues", "=", "self", ".", "encoder", ".", "getBucketValues", "(", ")", "self", ".", "_bucketValues", "=", "[", "]", "for",...
26.357143
11.071429
def update_dataset(self, dataset_key, **kwargs): """Update an existing dataset :param description: Dataset description :type description: str, optional :param summary: Dataset summary markdown :type summary: str, optional :param tags: Dataset tags :type tags: lis...
[ "def", "update_dataset", "(", "self", ",", "dataset_key", ",", "*", "*", "kwargs", ")", ":", "request", "=", "self", ".", "__build_dataset_obj", "(", "lambda", ":", "_swagger", ".", "DatasetPatchRequest", "(", ")", ",", "lambda", "name", ",", "url", ",", ...
41.577778
13.488889
def _get_peers(self, child_self, parent_other): '''_get_peers Low-level api: Given a config node, find peers under a parent node. Parameters ---------- child_self : `Element` An Element node on this side. parent_other : `Element` An Element nod...
[ "def", "_get_peers", "(", "self", ",", "child_self", ",", "parent_other", ")", ":", "peers", "=", "parent_other", ".", "findall", "(", "child_self", ".", "tag", ")", "s_node", "=", "self", ".", "device", ".", "get_schema_node", "(", "child_self", ")", "if"...
29.794118
20.088235
def extract_content(image_path, member_name, return_hash=False): '''extract_content will extract content from an image using cat. If hash=True, a hash sum is returned instead ''' if member_name.startswith('./'): member_name = member_name.replace('.','',1) if return_hash: hashy = hash...
[ "def", "extract_content", "(", "image_path", ",", "member_name", ",", "return_hash", "=", "False", ")", ":", "if", "member_name", ".", "startswith", "(", "'./'", ")", ":", "member_name", "=", "member_name", ".", "replace", "(", "'.'", ",", "''", ",", "1", ...
29.2
19.6
def _add_match(self, match_key, match_value, match): """Adds a match key/value""" if match_key is None: raise NullArgument() if match is None: match = True if match: inin = '$in' else: inin = '$nin' if match_key in self._que...
[ "def", "_add_match", "(", "self", ",", "match_key", ",", "match_value", ",", "match", ")", ":", "if", "match_key", "is", "None", ":", "raise", "NullArgument", "(", ")", "if", "match", "is", "None", ":", "match", "=", "True", "if", "match", ":", "inin",...
35.352941
16.882353
def get_stp_mst_detail_output_msti_port_port_hello_time(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
[ "def", "get_stp_mst_detail_output_msti_port_port_hello_time", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_stp_mst_detail", "=", "ET", ".", "Element", "(", "\"get_stp_mst_detail\"", ")", "config"...
45
14.5625
def files(self): """files that will be add to tar file later should be tuple, list or generator that returns strings """ ios_names = [info.name for info in self._ios_to_add.keys()] return set(self.files_to_add + ios_names)
[ "def", "files", "(", "self", ")", ":", "ios_names", "=", "[", "info", ".", "name", "for", "info", "in", "self", ".", "_ios_to_add", ".", "keys", "(", ")", "]", "return", "set", "(", "self", ".", "files_to_add", "+", "ios_names", ")" ]
42.833333
13.833333
def addFactory(self, identifier, factory): """Adds a factory. After calling this method, remote clients will be able to connect to it. This will call ``factory.doStart``. """ factory.doStart() self._factories[identifier] = factory
[ "def", "addFactory", "(", "self", ",", "identifier", ",", "factory", ")", ":", "factory", ".", "doStart", "(", ")", "self", ".", "_factories", "[", "identifier", "]", "=", "factory" ]
25.363636
17.090909
def config(name, value): ''' Set Traffic Server configuration variable values. .. code-block:: yaml proxy.config.proxy_name: trafficserver.config: - value: cdn.site.domain.tld OR traffic_server_setting: trafficserver.config: - name: pro...
[ "def", "config", "(", "name", ",", "value", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "__opts__", "[", "'test'", "]", ":", "ret", "[", ...
22.028571
21.971429
def get_cached_value(self, *args, **kwargs): """ :returns: The cached value or ``Ellipsis`` """ key = self.get_cache_key(*args, **kwargs) logger.debug(key) return self.cache.get(key, default=Ellipsis)
[ "def", "get_cached_value", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "self", ".", "get_cache_key", "(", "*", "args", ",", "*", "*", "kwargs", ")", "logger", ".", "debug", "(", "key", ")", "return", "self", ".", ...
34.571429
7.142857
def get_attribute(self, attrkey, as_string=False, as_list=False): """ Get the value of an attribute. By default, returns a string for ID and attributes with a single value, and a list of strings for attributes with multiple values. The `as_string` and `as_list` options can be us...
[ "def", "get_attribute", "(", "self", ",", "attrkey", ",", "as_string", "=", "False", ",", "as_list", "=", "False", ")", ":", "assert", "not", "as_string", "or", "not", "as_list", "if", "attrkey", "not", "in", "self", ".", "_attrs", ":", "return", "None",...
38.954545
15.5
def _recurse_config(parent_config, modules, f, prefix=''): '''Walk through the module tree. This is a helper function for :func:`create_config_tree` and :func:`_walk_config`. It calls `f` once for each module in the configuration tree with parameters `parent_config`, `config_name`, `prefix`, and `...
[ "def", "_recurse_config", "(", "parent_config", ",", "modules", ",", "f", ",", "prefix", "=", "''", ")", ":", "for", "module", "in", "modules", ":", "config_name", "=", "getattr", "(", "module", ",", "'config_name'", ",", "None", ")", "if", "config_name", ...
42.230769
22.128205
def save(self): """ Write the textual content (self._txt) to .spec file (self.fn). """ if not self.txt: # no changes return if not self.fn: raise exception.InvalidAction( "Can't save .spec file without its file name specified.") f = cod...
[ "def", "save", "(", "self", ")", ":", "if", "not", "self", ".", "txt", ":", "# no changes", "return", "if", "not", "self", ".", "fn", ":", "raise", "exception", ".", "InvalidAction", "(", "\"Can't save .spec file without its file name specified.\"", ")", "f", ...
35.166667
16.333333
def createRecurringPaymentsProfile(self, params, direct=False): """ Set direct to True to indicate that this is being called as a directPayment. Returns True PayPal successfully creates the profile otherwise False. """ defaults = {"method": "CreateRecurringPaymentsProfile"} ...
[ "def", "createRecurringPaymentsProfile", "(", "self", ",", "params", ",", "direct", "=", "False", ")", ":", "defaults", "=", "{", "\"method\"", ":", "\"CreateRecurringPaymentsProfile\"", "}", "required", "=", "[", "\"profilestartdate\"", ",", "\"billingperiod\"", ",...
40.25
23.45
def ping(self): """Ping Redis Server and return Round-Trip-Time in seconds. @return: Round-trip-time in seconds as float. """ start = time.time() self._conn.ping() return (time.time() - start)
[ "def", "ping", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "self", ".", "_conn", ".", "ping", "(", ")", "return", "(", "time", ".", "time", "(", ")", "-", "start", ")" ]
27.777778
14.888889
def _load_model(self): """ Loads robot and optionally add grippers. """ super()._load_model() self.mujoco_robot = Sawyer() if self.has_gripper: self.gripper = gripper_factory(self.gripper_type) if not self.gripper_visualization: sel...
[ "def", "_load_model", "(", "self", ")", ":", "super", "(", ")", ".", "_load_model", "(", ")", "self", ".", "mujoco_robot", "=", "Sawyer", "(", ")", "if", "self", ".", "has_gripper", ":", "self", ".", "gripper", "=", "gripper_factory", "(", "self", ".",...
37.272727
10.727273
def _wrap_response(request, data=None, metadata=None, status=200): """Creates the JSON response envelope to be sent back to the client. """ envelope = metadata or {} if data is not None: envelope['data'] = data return web.Response( status=status, ...
[ "def", "_wrap_response", "(", "request", ",", "data", "=", "None", ",", "metadata", "=", "None", ",", "status", "=", "200", ")", ":", "envelope", "=", "metadata", "or", "{", "}", "if", "data", "is", "not", "None", ":", "envelope", "[", "'data'", "]",...
31
13.1875
def run_command(local_root, command, env_var=True, pipeto=None, retry=0, environ=None): """Run a command and return the output. :raise CalledProcessError: Command exits non-zero. :param str local_root: Local path to git root directory. :param iter command: Command to run. :param dict environ: Envi...
[ "def", "run_command", "(", "local_root", ",", "command", ",", "env_var", "=", "True", ",", "pipeto", "=", "None", ",", "retry", "=", "0", ",", "environ", "=", "None", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "# Setup env...
38.386364
27.022727
def update_item(self, table_name, key, attribute_updates, expected=None, return_values=None, object_hook=None): """ Edits an existing item's attributes. You can perform a conditional update (insert a new attribute name-value pair if it doesn't exist, ...
[ "def", "update_item", "(", "self", ",", "table_name", ",", "key", ",", "attribute_updates", ",", "expected", "=", "None", ",", "return_values", "=", "None", ",", "object_hook", "=", "None", ")", ":", "data", "=", "{", "'TableName'", ":", "table_name", ",",...
40.707317
17.634146
def execute(self, progress_fn, print_verbose_info=None): """ Start the progress bar, and return only when the progress reaches 100%. :param progress_fn: the executor function (or a generator). This function should take no arguments and return either a single number -- the current pr...
[ "def", "execute", "(", "self", ",", "progress_fn", ",", "print_verbose_info", "=", "None", ")", ":", "assert_is_type", "(", "progress_fn", ",", "FunctionType", ",", "GeneratorType", ",", "MethodType", ")", "if", "isinstance", "(", "progress_fn", ",", "GeneratorT...
53.194805
27.532468
def p_class_variable_declaration_no_initial(p): '''class_variable_declaration : class_variable_declaration COMMA VARIABLE | VARIABLE''' if len(p) == 4: p[0] = p[1] + [ast.ClassVariable(p[3], None, lineno=p.lineno(2))] else: p[0] = [ast.ClassVariable(p[1], No...
[ "def", "p_class_variable_declaration_no_initial", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "ast", ".", "ClassVariable", "(", "p", "[", "3", "]", ",", "None", ",", "li...
48.285714
23.142857
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
[ "def", "nb_to_python", "(", "nb_path", ")", ":", "exporter", "=", "python", ".", "PythonExporter", "(", ")", "output", ",", "resources", "=", "exporter", ".", "from_filename", "(", "nb_path", ")", "return", "output" ]
35.8
10.8
def check_meta(pfeed, *, as_df=False, include_warnings=False): """ Analog of :func:`check_frequencies` for ``pfeed.meta`` """ table = 'meta' problems = [] # Preliminary checks if pfeed.meta is None: problems.append(['error', 'Missing table', table, []]) else: f = pfeed.m...
[ "def", "check_meta", "(", "pfeed", ",", "*", ",", "as_df", "=", "False", ",", "include_warnings", "=", "False", ")", ":", "table", "=", "'meta'", "problems", "=", "[", "]", "# Preliminary checks", "if", "pfeed", ".", "meta", "is", "None", ":", "problems"...
31.47619
23.285714
def levenberg_marquardt(self, start_x=None, damping=1.0e-3, tolerance=1.0e-6): """ Optimise value of x using levenberg marquardt """ if start_x is None: start_x = self._analytical_fitter.fit(self._c) return optimise_levenberg_marquardt(start_x, self._a, self._c, toler...
[ "def", "levenberg_marquardt", "(", "self", ",", "start_x", "=", "None", ",", "damping", "=", "1.0e-3", ",", "tolerance", "=", "1.0e-6", ")", ":", "if", "start_x", "is", "None", ":", "start_x", "=", "self", ".", "_analytical_fitter", ".", "fit", "(", "sel...
45.571429
17.571429
def add_data(self, data): """Add data to our stream, emitting reports as each new one is seen Args: data (bytearray): A chunk of new data to add """ if self.state == self.ErrorState: return self.raw_data += bytearray(data) still_processing = Tr...
[ "def", "add_data", "(", "self", ",", "data", ")", ":", "if", "self", ".", "state", "==", "self", ".", "ErrorState", ":", "return", "self", ".", "raw_data", "+=", "bytearray", "(", "data", ")", "still_processing", "=", "True", "while", "still_processing", ...
26.066667
17.933333
def prior_prediction(self): """get a dict of prior prediction variances Returns ------- prior_prediction : dict dictionary of prediction name, prior variance pairs """ if self.__prior_prediction is not None: return self.__prior_prediction ...
[ "def", "prior_prediction", "(", "self", ")", ":", "if", "self", ".", "__prior_prediction", "is", "not", "None", ":", "return", "self", ".", "__prior_prediction", "else", ":", "if", "self", ".", "predictions", "is", "not", "None", ":", "self", ".", "log", ...
38.434783
16.782609
def to_etree(self): """ creates an etree element of a ``SaltLayer`` that mimicks a SaltXMI <layers> element """ nodes_attrib_val = ' '.join('//@nodes.{}'.format(node_id) for node_id in self.nodes) edges_attrib_val = ' '.join('//@edges.{...
[ "def", "to_etree", "(", "self", ")", ":", "nodes_attrib_val", "=", "' '", ".", "join", "(", "'//@nodes.{}'", ".", "format", "(", "node_id", ")", "for", "node_id", "in", "self", ".", "nodes", ")", "edges_attrib_val", "=", "' '", ".", "join", "(", "'//@edg...
42.181818
20.818182
def parse_quantitationesultsline(self, line): """ Parses quantitation result lines Quantitation results example: Quantitation Results,,,,,,,,,,,,,,,,, Target Compound,25-OH D3+PTAD+MA,,,,,,,,,,,,,,,, Data File,Compound,ISTD,Resp,ISTD Resp,Resp Ratio, Final Conc,E...
[ "def", "parse_quantitationesultsline", "(", "self", ",", "line", ")", ":", "# Quantitation Results,,,,,,,,,,,,,,,,,", "# prerunrespchk.d,25-OH D3+PTAD+MA,25-OH D3d3+PTAD+MA,5816,274638,0.0212,0.9145,,,,,,,,,,,", "# mid_respchk.d,25-OH D3+PTAD+MA,25-OH D3d3+PTAD+MA,4699,242798,0.0194,0.8514,,,,,,...
57.72
29.328
def write( frame, writer: Callable[[bytes], Any], *, mask: bool, extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None, ) -> None: """ Write a WebSocket frame. ``frame`` is the :class:`Frame` object to write. ``writer`...
[ "def", "write", "(", "frame", ",", "writer", ":", "Callable", "[", "[", "bytes", "]", ",", "Any", "]", ",", "*", ",", "mask", ":", "bool", ",", "extensions", ":", "Optional", "[", "Sequence", "[", "\"websockets.extensions.base.Extension\"", "]", "]", "="...
31.445946
23.094595
def axes(self, axes): '''Set the angular axis of rotation for this joint. Parameters ---------- axes : list containing one 3-tuple of floats A list of the axes for this joint. For a hinge joint, which has one degree of freedom, this must contain one 3-tuple speci...
[ "def", "axes", "(", "self", ",", "axes", ")", ":", "self", ".", "amotor", ".", "axes", "=", "[", "axes", "[", "0", "]", "]", "self", ".", "ode_obj", ".", "setAxis", "(", "tuple", "(", "axes", "[", "0", "]", ")", ")" ]
38
20.666667
def point_is_valid( generator, x, y ): """Is (x,y) a valid public key based on the specified generator?""" # These are the tests specified in X9.62. n = generator.order() curve = generator.curve() if x < 0 or n <= x or y < 0 or n <= y: return False if not curve.contains_point( x, y ): return False...
[ "def", "point_is_valid", "(", "generator", ",", "x", ",", "y", ")", ":", "# These are the tests specified in X9.62.", "n", "=", "generator", ".", "order", "(", ")", "curve", "=", "generator", ".", "curve", "(", ")", "if", "x", "<", "0", "or", "n", "<=", ...
27.8
15.866667
def split_line(self): """ Split line into coordinates and meta string """ # coordinate of the # symbol or end of the line (-1) if not found hash_or_end = self.line.find("#") temp = self.line[self.region_end:hash_or_end].strip(" |") self.coord_str = regex_paren.sub...
[ "def", "split_line", "(", "self", ")", ":", "# coordinate of the # symbol or end of the line (-1) if not found", "hash_or_end", "=", "self", ".", "line", ".", "find", "(", "\"#\"", ")", "temp", "=", "self", ".", "line", "[", "self", ".", "region_end", ":", "hash...
36.285714
15.857143
def mpi_weighted_mean(comm, local_name2valcount): """ Perform a weighted average over dicts that are each on a different node Input: local_name2valcount: dict mapping key -> (value, count) Returns: key -> mean """ all_name2valcount = comm.gather(local_name2valcount) if comm.rank == 0: ...
[ "def", "mpi_weighted_mean", "(", "comm", ",", "local_name2valcount", ")", ":", "all_name2valcount", "=", "comm", ".", "gather", "(", "local_name2valcount", ")", "if", "comm", ".", "rank", "==", "0", ":", "name2sum", "=", "defaultdict", "(", "float", ")", "na...
40.347826
15.826087
def validate_setup(transactions): """ First two transactions must set rate & days. """ if not transactions: return True try: first, second = transactions[:2] except ValueError: print('Error: vacationrc file must have both initial days and rates entries') return False ...
[ "def", "validate_setup", "(", "transactions", ")", ":", "if", "not", "transactions", ":", "return", "True", "try", ":", "first", ",", "second", "=", "transactions", "[", ":", "2", "]", "except", "ValueError", ":", "print", "(", "'Error: vacationrc file must ha...
33.47619
24.047619
def get(self, indexes, as_list=False): """ Given indexes will return a sub-set of the Series. This method will direct to the specific methods based on what types are passed in for the indexes. The type of the return is determined by the types of the parameters. :param indexes: i...
[ "def", "get", "(", "self", ",", "indexes", ",", "as_list", "=", "False", ")", ":", "if", "isinstance", "(", "indexes", ",", "(", "list", ",", "blist", ")", ")", ":", "return", "self", ".", "get_rows", "(", "indexes", ",", "as_list", ")", "else", ":...
50.357143
25.5
def main(): """function to """ # parse arg to find file(s) parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="convert the markdown file to HTML") parser.add_argument("-d", "--directory", help="convert the markdown files in the...
[ "def", "main", "(", ")", ":", "# parse arg to find file(s)", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"-f\"", ",", "\"--file\"", ",", "help", "=", "\"convert the markdown file to HTML\"", ")", "parser", ".",...
35.5
20.5
async def send_upstream(self, message, stream_name=None): """ Send a message upstream to a de-multiplexed application. If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream steams. """ if stream_name is None: ...
[ "async", "def", "send_upstream", "(", "self", ",", "message", ",", "stream_name", "=", "None", ")", ":", "if", "stream_name", "is", "None", ":", "for", "steam_queue", "in", "self", ".", "application_streams", ".", "values", "(", ")", ":", "await", "steam_q...
43.4
21.533333
def _getWorkerCommandList(self): """Generate the workerCommand as list""" c = [] c.extend(self._WorkerCommand_environment()) c.extend(self._WorkerCommand_launcher()) c.extend(self._WorkerCommand_options()) c.extend(self._WorkerCommand_executable()) return c
[ "def", "_getWorkerCommandList", "(", "self", ")", ":", "c", "=", "[", "]", "c", ".", "extend", "(", "self", ".", "_WorkerCommand_environment", "(", ")", ")", "c", ".", "extend", "(", "self", ".", "_WorkerCommand_launcher", "(", ")", ")", "c", ".", "ext...
34
14.888889
def execute_cmd(cmd, cwd=None, timeout=5): """Excecute command on thread :param cmd: Command to execute :param cwd: current working directory :return: None """ p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: p.wait(timeout=timeout) except ...
[ "def", "execute_cmd", "(", "cmd", ",", "cwd", "=", "None", ",", "timeout", "=", "5", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "cwd", "=", "cwd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess"...
36.818182
20.909091
def json_default(obj): """ 对一些数据类型的 json 序列化, 默认情况下 json 没有对 datetime 和 Decimal 进行序列化 如果不指定的话,会抛异常 :param obj: :return: """ if isinstance(obj, datetime): return obj.strftime("%Y-%m-%d %H:%M:%S") elif isinstance(obj, Decimal): return float(obj) elif isinstance(obj,...
[ "def", "json_default", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ")", ":", "return", "obj", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", "elif", "isinstance", "(", "obj", ",", "Decimal", ")", ":", "return", "float", "(...
23.333333
16.095238
async def _auth_handler_post_check_retry(self, response_obj): ''' The other half of _auth_handler_post_check_retry (what a mouthful). If auth has not yet been attempted and the most recent response object is a 401, we store that response object and retry the request in exactly th...
[ "async", "def", "_auth_handler_post_check_retry", "(", "self", ",", "response_obj", ")", ":", "if", "isinstance", "(", "self", ".", "auth", ",", "PostResponseAuth", ")", ":", "if", "response_obj", ".", "status_code", "==", "401", ":", "if", "not", "self", "....
47
21.3
def new_random_state(seed=None, fully_random=False): """ Returns a new random state. Parameters ---------- seed : None or int, optional Optional seed value to use. The same datatypes are allowed as for ``numpy.random.RandomState(seed)``. fully_random : bool, optional Wh...
[ "def", "new_random_state", "(", "seed", "=", "None", ",", "fully_random", "=", "False", ")", ":", "if", "seed", "is", "None", ":", "if", "not", "fully_random", ":", "# sample manually a seed instead of just RandomState(),", "# because the latter one", "# is way slower."...
32.107143
21.035714
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
[ "def", "convert", "(", "self", ",", "vroot", ",", "entry_variables", ")", ":", "self", ".", "graph_info", "=", "GraphInfo", "(", "vroot", ")", "self", ".", "entry_variables", "=", "entry_variables", "cnt", "=", "0", "with", "nn", ".", "parameter_scope", "(...
37.925926
16.074074
def dict_to_querystring(dictionary): """Converts a dict to a querystring suitable to be appended to a URL.""" s = u"" for d in dictionary.keys(): s = unicode.format(u"{0}{1}={2}&", s, d, dictionary[d]) return s[:-1]
[ "def", "dict_to_querystring", "(", "dictionary", ")", ":", "s", "=", "u\"\"", "for", "d", "in", "dictionary", ".", "keys", "(", ")", ":", "s", "=", "unicode", ".", "format", "(", "u\"{0}{1}={2}&\"", ",", "s", ",", "d", ",", "dictionary", "[", "d", "]...
39
14.666667
def sub_notes(docs): """ Substitutes the special controls for notes, warnings, todos, and bugs with the corresponding div. """ def substitute(match): ret = "</p><div class=\"alert alert-{}\" role=\"alert\"><h4>{}</h4>" \ "<p>{}</p></div>".format(NOTE_TYPE[match.group(1).lower()...
[ "def", "sub_notes", "(", "docs", ")", ":", "def", "substitute", "(", "match", ")", ":", "ret", "=", "\"</p><div class=\\\"alert alert-{}\\\" role=\\\"alert\\\"><h4>{}</h4>\"", "\"<p>{}</p></div>\"", ".", "format", "(", "NOTE_TYPE", "[", "match", ".", "group", "(", "...
40.785714
21.214286
def prep_itasser_modeling(self, itasser_installation, itlib_folder, runtype, create_in_dir=None, execute_from_dir=None, all_genes=False, print_exec=False, **kwargs): """Prepare to run I-TASSER homology modeling for genes without structures, or all genes. Args: it...
[ "def", "prep_itasser_modeling", "(", "self", ",", "itasser_installation", ",", "itlib_folder", ",", "runtype", ",", "create_in_dir", "=", "None", ",", "execute_from_dir", "=", "None", ",", "all_genes", "=", "False", ",", "print_exec", "=", "False", ",", "*", "...
55.583333
35.104167
def parse_requirements(filename): """ Load requirements from a pip requirements file. :param filename: file name with requirements to parse """ try: with open(filename) as fh_req: return [line.strip() for line in fh_req if line.strip() and not line.startswith('#')] except F...
[ "def", "parse_requirements", "(", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ")", "as", "fh_req", ":", "return", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "fh_req", "if", "line", ".", "strip", "(", ")", "and", ...
31.923077
21.461538
def git_branch(repo_dir, branch_name, start_point='HEAD', force=True, verbose=True, checkout=False): """Create a new branch like `git branch <branch_name> <start_point>`.""" command = ['git', 'branch'] if verbose: command.append('--verbose') if force: command.append('--for...
[ "def", "git_branch", "(", "repo_dir", ",", "branch_name", ",", "start_point", "=", "'HEAD'", ",", "force", "=", "True", ",", "verbose", "=", "True", ",", "checkout", "=", "False", ")", ":", "command", "=", "[", "'git'", ",", "'branch'", "]", "if", "ver...
38.071429
15.5
def to_dict(self): """Transform to dictionary Returns: dict: dictionary with same content """ return {key: self.__getitem__(key).value for key in self.options()}
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "key", ":", "self", ".", "__getitem__", "(", "key", ")", ".", "value", "for", "key", "in", "self", ".", "options", "(", ")", "}" ]
28.571429
18.142857
def data(self, data): """Use a length prefixed protocol to give the length of a pickled message. """ self._buffer = self._buffer + data while self._data_handler(): pass
[ "def", "data", "(", "self", ",", "data", ")", ":", "self", ".", "_buffer", "=", "self", ".", "_buffer", "+", "data", "while", "self", ".", "_data_handler", "(", ")", ":", "pass" ]
23.777778
17.111111
def list_cache_nodes_full(opts=None, provider=None, base=None): ''' Return a list of minion data from the cloud cache, rather from the cloud providers themselves. This is the cloud cache version of list_nodes_full(). ''' if opts is None: opts = __opts__ if opts.get('update_cachedir', Fal...
[ "def", "list_cache_nodes_full", "(", "opts", "=", "None", ",", "provider", "=", "None", ",", "base", "=", "None", ")", ":", "if", "opts", "is", "None", ":", "opts", "=", "__opts__", "if", "opts", ".", "get", "(", "'update_cachedir'", ",", "False", ")",...
41.194444
20.638889