text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def encode_int(self, n): """ Encodes an integer into a short Base64 string. Example: ``encode_int(123)`` returns ``'B7'``. """ str = [] while True: n, r = divmod(n, self.BASE) str.append(self.ALPHABET[r]) if n == 0: break r...
[ "def", "encode_int", "(", "self", ",", "n", ")", ":", "str", "=", "[", "]", "while", "True", ":", "n", ",", "r", "=", "divmod", "(", "n", ",", "self", ".", "BASE", ")", "str", ".", "append", "(", "self", ".", "ALPHABET", "[", "r", "]", ")", ...
28.083333
0.008621
def _skip_whitespace(self): """Increment over whitespace, counting characters.""" i = 0 while self._cur_token['type'] is TT.ws and not self._finished: self._increment() i += 1 return i
[ "def", "_skip_whitespace", "(", "self", ")", ":", "i", "=", "0", "while", "self", ".", "_cur_token", "[", "'type'", "]", "is", "TT", ".", "ws", "and", "not", "self", ".", "_finished", ":", "self", ".", "_increment", "(", ")", "i", "+=", "1", "retur...
29.25
0.008299
def _set_error_response_without_body(self, bucket_name=None): """ Sets all the error response fields from response headers. """ if self._response.status == 404: if bucket_name: if self.object_name: self.code = 'NoSuchKey' ...
[ "def", "_set_error_response_without_body", "(", "self", ",", "bucket_name", "=", "None", ")", ":", "if", "self", ".", "_response", ".", "status", "==", "404", ":", "if", "bucket_name", ":", "if", "self", ".", "object_name", ":", "self", ".", "code", "=", ...
41.157895
0.001249
def _GetDateValuesWithEpoch(self, number_of_days, date_time_epoch): """Determines date values. Args: number_of_days (int): number of days since epoch. date_time_epoch (DateTimeEpoch): date and time of the epoch. Returns: tuple[int, int, int]: year, month, day of month. """ retur...
[ "def", "_GetDateValuesWithEpoch", "(", "self", ",", "number_of_days", ",", "date_time_epoch", ")", ":", "return", "self", ".", "_GetDateValues", "(", "number_of_days", ",", "date_time_epoch", ".", "year", ",", "date_time_epoch", ".", "month", ",", "date_time_epoch",...
33.615385
0.002227
def get_id_parts(self): """ Return the three pieces of the int_8s-style sngl_inspiral event_id. """ int_event_id = int(self.event_id) a = int_event_id // 1000000000 slidenum = (int_event_id % 1000000000) // 100000 b = int_event_id % 100000 return int(a), int(slidenum), int(b)
[ "def", "get_id_parts", "(", "self", ")", ":", "int_event_id", "=", "int", "(", "self", ".", "event_id", ")", "a", "=", "int_event_id", "//", "1000000000", "slidenum", "=", "(", "int_event_id", "%", "1000000000", ")", "//", "100000", "b", "=", "int_event_id...
28.5
0.037415
def get(self, request, response): """Processes a `GET` request.""" # Ensure we're allowed to read the resource. self.assert_operations('read') # Delegate to `read` to retrieve the items. items = self.read() # if self.slug is not None and not items: # # Reque...
[ "def", "get", "(", "self", ",", "request", ",", "response", ")", ":", "# Ensure we're allowed to read the resource.", "self", ".", "assert_operations", "(", "'read'", ")", "# Delegate to `read` to retrieve the items.", "items", "=", "self", ".", "read", "(", ")", "#...
36.096774
0.001741
def process(self, sched, coro): """If there aren't enough coroutines waiting for the signal as the recipicient param add the calling coro in another queue to be activated later, otherwise activate the waiting coroutines.""" super(Signal, self).process(sched, coro) self.resul...
[ "def", "process", "(", "self", ",", "sched", ",", "coro", ")", ":", "super", "(", "Signal", ",", "self", ")", ".", "process", "(", "sched", ",", "coro", ")", "self", ".", "result", "=", "len", "(", "sched", ".", "sigwait", "[", "self", ".", "name...
39.041667
0.002083
def trace_filter(mode): ''' Set the trace filter mode. mode: Whether to enable the trace hook. True: Trace filtering on (skipping methods tagged @DontTrace) False: Trace filtering off (trace methods tagged @DontTrace) None/default: Toggle trace filtering. ''' global should_trace_h...
[ "def", "trace_filter", "(", "mode", ")", ":", "global", "should_trace_hook", "if", "mode", "is", "None", ":", "mode", "=", "should_trace_hook", "is", "None", "if", "mode", ":", "should_trace_hook", "=", "default_should_trace_hook", "else", ":", "should_trace_hook"...
26.052632
0.001949
def remove_user(self, user): """ Deletes a user from an organization. """ org_user = self._org_user_model.objects.get(user=user, organization=self) org_user.delete() # User removed signal user_removed.send(sender=self, user=user)
[ "def", "remove_user", "(", "self", ",", "user", ")", ":", "org_user", "=", "self", ".", "_org_user_model", ".", "objects", ".", "get", "(", "user", "=", "user", ",", "organization", "=", "self", ")", "org_user", ".", "delete", "(", ")", "# User removed s...
30.888889
0.01049
def get_format(n): """Gets a list of the formats a credit card number fits.""" formats = [] if is_visa(n): formats.append('visa') if is_visa_electron(n): formats.append('visa electron') if is_mastercard(n): formats.append('mastercard') if is_amex(n): formats.appe...
[ "def", "get_format", "(", "n", ")", ":", "formats", "=", "[", "]", "if", "is_visa", "(", "n", ")", ":", "formats", ".", "append", "(", "'visa'", ")", "if", "is_visa_electron", "(", "n", ")", ":", "formats", ".", "append", "(", "'visa electron'", ")",...
24.833333
0.002155
def _get_a1(bbar, dbar, slip_moment, mmax): """ Returns the A1 term (I.4 of Table 2 in Anderson & Luco) """ return ((dbar - bbar) / dbar) * (slip_moment / _scale_moment(mmax))
[ "def", "_get_a1", "(", "bbar", ",", "dbar", ",", "slip_moment", ",", "mmax", ")", ":", "return", "(", "(", "dbar", "-", "bbar", ")", "/", "dbar", ")", "*", "(", "slip_moment", "/", "_scale_moment", "(", "mmax", ")", ")" ]
40.6
0.009662
def CreateServer(frontend=None): """Start frontend http server.""" max_port = config.CONFIG.Get("Frontend.port_max", config.CONFIG["Frontend.bind_port"]) for port in range(config.CONFIG["Frontend.bind_port"], max_port + 1): server_address = (config.CONFIG["Frontend.bind_addres...
[ "def", "CreateServer", "(", "frontend", "=", "None", ")", ":", "max_port", "=", "config", ".", "CONFIG", ".", "Get", "(", "\"Frontend.port_max\"", ",", "config", ".", "CONFIG", "[", "\"Frontend.bind_port\"", "]", ")", "for", "port", "in", "range", "(", "co...
34.619048
0.014726
def apply_to_event(self, event, hint=None): # type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]] """Applies the information contained on the scope to the given event.""" def _drop(event, cause, ty): # type: (Dict[str, Any], Callable, str) -> Optional[Any] ...
[ "def", "apply_to_event", "(", "self", ",", "event", ",", "hint", "=", "None", ")", ":", "# type: (Dict[str, Any], Dict[str, Any]) -> Optional[Dict[str, Any]]", "def", "_drop", "(", "event", ",", "cause", ",", "ty", ")", ":", "# type: (Dict[str, Any], Callable, str) -> O...
38.444444
0.002349
def _safe_getmodule(o): """Attempts to return the module in which `o` is defined. """ from inspect import getmodule try: return getmodule(o) except: # pragma: no cover #There is nothing we can do about this for now. msg.err("_safe_getmodule: {}".format(o), 2) pass
[ "def", "_safe_getmodule", "(", "o", ")", ":", "from", "inspect", "import", "getmodule", "try", ":", "return", "getmodule", "(", "o", ")", "except", ":", "# pragma: no cover", "#There is nothing we can do about this for now.", "msg", ".", "err", "(", "\"_safe_getmodu...
30.7
0.012658
def factor_for_trace(ls: HilbertSpace, op: Operator) -> Operator: r'''Given a :class:`.LocalSpace` `ls` to take the partial trace over and an operator `op`, factor the trace such that operators acting on disjoint degrees of freedom are pulled out of the trace. If the operator acts trivially on ls the tr...
[ "def", "factor_for_trace", "(", "ls", ":", "HilbertSpace", ",", "op", ":", "Operator", ")", "->", "Operator", ":", "if", "op", ".", "space", "==", "ls", ":", "if", "isinstance", "(", "op", ",", "OperatorTimes", ")", ":", "pull_out", "=", "[", "o", "f...
43.176471
0.000888
def export_ply(mesh, encoding='binary', vertex_normal=None): """ Export a mesh in the PLY format. Parameters ---------- mesh : Trimesh object encoding : ['ascii'|'binary_little_endian'] vertex_normal : include vertex normals Returns ---------- expo...
[ "def", "export_ply", "(", "mesh", ",", "encoding", "=", "'binary'", ",", "vertex_normal", "=", "None", ")", ":", "# evaluate input args", "# allow a shortcut for binary", "if", "encoding", "==", "'binary'", ":", "encoding", "=", "'binary_little_endian'", "elif", "en...
34.385321
0.000259
def Almedeij(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left[\frac{1}{(\phi_1 + \phi_2)^{-1} + (\phi_3)^{-1}} + \phi_4\right]^{0.1} \phi_1 = (24Re^{-1})^{10} + (21Re^{-0.67})^{10} + (4Re^{-0.33})^{10} + 0.4^{10} ...
[ "def", "Almedeij", "(", "Re", ")", ":", "phi4", "=", "(", "(", "6E-17", "*", "Re", "**", "2.63", ")", "**", "-", "10", "+", "0.2", "**", "-", "10", ")", "**", "-", "1", "phi3", "=", "(", "1.57E8", "*", "Re", "**", "-", "1.625", ")", "**", ...
31.884615
0.002341
def fan_watts(fan_tot_eff, pascal, m3s): """return the fan power in watts given fan efficiency, Pressure rise (Pa) and flow (m3/s)""" # got this from a google search bhp = fan_bhp(fan_tot_eff, pascal, m3s) return bhp2watts(bhp)
[ "def", "fan_watts", "(", "fan_tot_eff", ",", "pascal", ",", "m3s", ")", ":", "# got this from a google search", "bhp", "=", "fan_bhp", "(", "fan_tot_eff", ",", "pascal", ",", "m3s", ")", "return", "bhp2watts", "(", "bhp", ")" ]
47.8
0.00823
def simple_swap(ins: Instruction) -> Instruction: """Replaces one instruction with another based on the transform rules in the bytecode definitions. This can help simplify your code as it reduces the overall number of instructions. For example, `aload_0` will become `aload 0`. :param ins: Instructi...
[ "def", "simple_swap", "(", "ins", ":", "Instruction", ")", "->", "Instruction", ":", "try", ":", "rule", "=", "ins", ".", "details", "[", "'transform'", "]", "[", "'simple_swap'", "]", "except", "KeyError", ":", "return", "ins", "replacement_ins", "=", "op...
30.96
0.001253
def get_state_shape_invariants(tensor): """Returns the shape of the tensor but sets middle dims to None.""" shape = tensor.shape.as_list() for i in range(1, len(shape) - 1): shape[i] = None return tf.TensorShape(shape)
[ "def", "get_state_shape_invariants", "(", "tensor", ")", ":", "shape", "=", "tensor", ".", "shape", ".", "as_list", "(", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "shape", ")", "-", "1", ")", ":", "shape", "[", "i", "]", "=", "No...
37.5
0.021739
def write_post_script(self,fh): """ Write the post script for the job, if there is one @param fh: descriptor of open DAG file. """ if self.__post_script: fh.write( 'SCRIPT POST ' + str(self) + ' ' + self.__post_script + ' ' + ' '.join(self.__post_script_args) + '\n' )
[ "def", "write_post_script", "(", "self", ",", "fh", ")", ":", "if", "self", ".", "__post_script", ":", "fh", ".", "write", "(", "'SCRIPT POST '", "+", "str", "(", "self", ")", "+", "' '", "+", "self", ".", "__post_script", "+", "' '", "+", "' '", "."...
36.875
0.019868
def discard(self, value): """Remove element *value* from the set if it is present.""" # Raise TypeError if value is not hashable hash(value) self.redis.srem(self.key, self._pickle(value))
[ "def", "discard", "(", "self", ",", "value", ")", ":", "# Raise TypeError if value is not hashable", "hash", "(", "value", ")", "self", ".", "redis", ".", "srem", "(", "self", ".", "key", ",", "self", ".", "_pickle", "(", "value", ")", ")" ]
35.833333
0.009091
def filter(self, *args, **kwargs): """filter lets django managers use `objects.filter` on a hashable object.""" obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs['object_hash'] = self.model._compute_hash(obj) return super().filter(*args, **kwargs)
[ "def", "filter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "kwargs", ".", "pop", "(", "self", ".", "object_property_name", ",", "None", ")", "if", "obj", "is", "not", "None", ":", "kwargs", "[", "'object_hash'", ...
52.166667
0.009434
def get_process(self): """Returns :class:`subprocess.Popen` instance with args from :meth:`get_args` result and piped stdin, stdout and stderr. """ return Popen(self.get_args(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
[ "def", "get_process", "(", "self", ")", ":", "return", "Popen", "(", "self", ".", "get_args", "(", ")", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")" ]
48.6
0.008097
def effective_value(self): """ Read/write |float| representing normalized adjustment value for this adjustment. Actual values are a large-ish integer expressed in shape coordinates, nominally between 0 and 100,000. The effective value is normalized to a corresponding value nomina...
[ "def", "effective_value", "(", "self", ")", ":", "raw_value", "=", "self", ".", "actual", "if", "raw_value", "is", "None", ":", "raw_value", "=", "self", ".", "def_val", "return", "self", ".", "_normalize", "(", "raw_value", ")" ]
53.941176
0.002144
def overlap(self, other): """Determine whether this range overlaps with another.""" if self._start < other.end and self._end > other.start: return True return False
[ "def", "overlap", "(", "self", ",", "other", ")", ":", "if", "self", ".", "_start", "<", "other", ".", "end", "and", "self", ".", "_end", ">", "other", ".", "start", ":", "return", "True", "return", "False" ]
39.2
0.01
def _u0Eq(logu,delta,pot,E,Lz22): """The equation that needs to be minimized to find u0""" u= numpy.exp(logu) sinh2u= numpy.sinh(u)**2. cosh2u= numpy.cosh(u)**2. dU= cosh2u*actionAngleStaeckel.potentialStaeckel(u,numpy.pi/2.,pot,delta) return -(E*sinh2u-dU-Lz22/delta**2./sinh2u)
[ "def", "_u0Eq", "(", "logu", ",", "delta", ",", "pot", ",", "E", ",", "Lz22", ")", ":", "u", "=", "numpy", ".", "exp", "(", "logu", ")", "sinh2u", "=", "numpy", ".", "sinh", "(", "u", ")", "**", "2.", "cosh2u", "=", "numpy", ".", "cosh", "(",...
42.428571
0.039604
def update(self): """Updates an instance within a project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_update_instance] :end-before: [END bigtable_update_instance] .. note:: Updates any or all of the following values:...
[ "def", "update", "(", "self", ")", ":", "update_mask_pb", "=", "field_mask_pb2", ".", "FieldMask", "(", ")", "if", "self", ".", "display_name", "is", "not", "None", ":", "update_mask_pb", ".", "paths", ".", "append", "(", "\"display_name\"", ")", "if", "se...
31.066667
0.001387
def from_traceback(cls, tb): """Initializes a StackTrace from a python traceback instance""" stack_trace = cls( stack_trace_hash_id=generate_hash_id_from_traceback(tb) ) # use the add_stack_frame so that json formatting is applied for tb_frame_info in traceback.extrac...
[ "def", "from_traceback", "(", "cls", ",", "tb", ")", ":", "stack_trace", "=", "cls", "(", "stack_trace_hash_id", "=", "generate_hash_id_from_traceback", "(", "tb", ")", ")", "# use the add_stack_frame so that json formatting is applied", "for", "tb_frame_info", "in", "t...
41.380952
0.00225
def add_string(self, s): """ Add a string to the stream. :param str s: string to add """ s = asbytes(s) self.add_size(len(s)) self.packet.write(s) return self
[ "def", "add_string", "(", "self", ",", "s", ")", ":", "s", "=", "asbytes", "(", "s", ")", "self", ".", "add_size", "(", "len", "(", "s", ")", ")", "self", ".", "packet", ".", "write", "(", "s", ")", "return", "self" ]
22.2
0.012987
def symbolic_heisenberg_eom( self, X=None, noises=None, expand_simplify=True): """Compute the symbolic Heisenberg equations of motion of a system operator X. If no X is given, an OperatorSymbol is created in its place. If no noises are given, this correspnds to the ensemble...
[ "def", "symbolic_heisenberg_eom", "(", "self", ",", "X", "=", "None", ",", "noises", "=", "None", ",", "expand_simplify", "=", "True", ")", ":", "L", ",", "H", "=", "self", ".", "L", ",", "self", ".", "H", "if", "X", "is", "None", ":", "X", "=", ...
39.581395
0.00172
def load(cls, path): """ load the keys from a path :param path: the filename (path) in which we find the keys :return: """ auth = cls() with open(path) as fd: for pubkey in itertools.imap(str.strip, fd): # skip empty lines ...
[ "def", "load", "(", "cls", ",", "path", ")", ":", "auth", "=", "cls", "(", ")", "with", "open", "(", "path", ")", "as", "fd", ":", "for", "pubkey", "in", "itertools", ".", "imap", "(", "str", ".", "strip", ",", "fd", ")", ":", "# skip empty lines...
27.666667
0.009324
def complex_el_from_dict(parent, data, key): """Create element from a dict definition and add it to ``parent``. :param parent: parent element :type parent: Element :param data: dictionary with elements definitions, it can be a simple \ {element_name: 'element_value'} or complex \ {element_name:...
[ "def", "complex_el_from_dict", "(", "parent", ",", "data", ",", "key", ")", ":", "el", "=", "ET", ".", "SubElement", "(", "parent", ",", "key", ")", "value", "=", "data", "[", "key", "]", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "if...
29.769231
0.001252
def publish(**kwargs): """ Runs the version task before pushing to git and uploading to pypi. """ current_version = get_current_version() click.echo('Current version: {0}'.format(current_version)) retry = kwargs.get("retry") debug('publish: retry=', retry) if retry: # The "new" ...
[ "def", "publish", "(", "*", "*", "kwargs", ")", ":", "current_version", "=", "get_current_version", "(", ")", "click", ".", "echo", "(", "'Current version: {0}'", ".", "format", "(", "current_version", ")", ")", "retry", "=", "kwargs", ".", "get", "(", "\"...
35.45614
0.002407
def flip_video(self, is_flip, callback=None): ''' Flip video ``is_flip``: 0 Not flip, 1 Flip ''' params = {'isFlip': is_flip } return self.execute_command('flipVideo', params, callback=callback)
[ "def", "flip_video", "(", "self", ",", "is_flip", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'isFlip'", ":", "is_flip", "}", "return", "self", ".", "execute_command", "(", "'flipVideo'", ",", "params", ",", "callback", "=", "callback", ...
33.714286
0.012397
def _get_xlsx_kws(self, **kws_usr): """Return keyword arguments relevant to writing an xlsx.""" kws_xlsx = {'fld2col_widths':self._get_fld2col_widths(**kws_usr), 'items':'GO IDs'} remaining_keys = set(['title', 'hdrs', 'prt_flds', 'fld2fmt', 'ntval2wbfmtdict', 'ntfl...
[ "def", "_get_xlsx_kws", "(", "self", ",", "*", "*", "kws_usr", ")", ":", "kws_xlsx", "=", "{", "'fld2col_widths'", ":", "self", ".", "_get_fld2col_widths", "(", "*", "*", "kws_usr", ")", ",", "'items'", ":", "'GO IDs'", "}", "remaining_keys", "=", "set", ...
53.444444
0.010225
def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. ...
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "__initialized", ":", "raise", "RuntimeError", "(", "\"thread.__init__() not called\"", ")", "if", "self", ".", "__started", ".", "is_set", "(", ")", ":", "raise", "RuntimeError", "(", "\"threa...
34.6
0.00225
def cast_column(self, keys, func): """ like map column but applies values inplace """ import utool as ut for key in ut.ensure_iterable(keys): self[key] = [func(v) for v in self[key]]
[ "def", "cast_column", "(", "self", ",", "keys", ",", "func", ")", ":", "import", "utool", "as", "ut", "for", "key", "in", "ut", ".", "ensure_iterable", "(", "keys", ")", ":", "self", "[", "key", "]", "=", "[", "func", "(", "v", ")", "for", "v", ...
42.8
0.009174
def init_app(self, app): """ Initialize the application once the configuration has been loaded there. """ self.app = app self.log = app.logger.getChild('compass') self.log.debug("Initializing compass integration") self.compass_path = self.app.config.get('C...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "app", "=", "app", "self", ".", "log", "=", "app", ".", "logger", ".", "getChild", "(", "'compass'", ")", "self", ".", "log", ".", "debug", "(", "\"Initializing compass integration\"", ...
43.608696
0.001951
def choices(self, cl): """ Take choices from field's 'choices' attribute for 'ChoicesField' and use 'flatchoices' as usual for other fields. """ #: Just tidy up standard implementation for the sake of DRY principle. def _choice_item(is_selected, query_string, title): ...
[ "def", "choices", "(", "self", ",", "cl", ")", ":", "#: Just tidy up standard implementation for the sake of DRY principle.", "def", "_choice_item", "(", "is_selected", ",", "query_string", ",", "title", ")", ":", "return", "{", "'selected'", ":", "is_selected", ",", ...
36
0.002004
def purview(self): """tuple[int]: The nodes of the purview in the partition.""" return tuple(sorted( chain.from_iterable(part.purview for part in self)))
[ "def", "purview", "(", "self", ")", ":", "return", "tuple", "(", "sorted", "(", "chain", ".", "from_iterable", "(", "part", ".", "purview", "for", "part", "in", "self", ")", ")", ")" ]
44.5
0.01105
def mendelian_errors(args): """ %prog mendelian_errors STR-Mendelian-errors.csv Plot Mendelian errors as calculated by mendelian(). File `STR-Mendelian-errors.csv` looks like: ,Duos - Mendelian errors,Trios - Mendelian errors SCA36,1.40%,0.60% ULD,0.30%,1.50% BPES,0.00%,1.80% One...
[ "def", "mendelian_errors", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mendelian_errors", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"6x6\"", ")", "if", "len"...
32.241935
0.000971
def _to_date(t): ''' Internal function that tries whatever to convert ``t`` into a :class:`datetime.date` object. >>> _to_date('2013-12-11') datetime.date(2013, 12, 11) >>> _to_date('Wed, 11 Dec 2013') datetime.date(2013, 12, 11) >>> _to_date('Wed, 11 Dec 13') datetime.date(2013, 12...
[ "def", "_to_date", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "six", ".", "integer_types", "+", "(", "float", ",", ")", ")", ":", "return", "datetime", ".", "date", ".", "fromtimestamp", "(", "t", ")", "elif", "isinstance", "(", "t", ",...
25.484848
0.001145
def hierarchy_name(self, adjust_for_printing=True): """ return the name for this object with the parents names attached by dots. :param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()` on the names, recursively ...
[ "def", "hierarchy_name", "(", "self", ",", "adjust_for_printing", "=", "True", ")", ":", "if", "adjust_for_printing", ":", "adjust", "=", "lambda", "x", ":", "adjust_name_for_printing", "(", "x", ")", "else", ":", "adjust", "=", "lambda", "x", ":", "x", "i...
45.769231
0.011532
def encode(self, value): """Encode value.""" value = self.serialize(value) if self.encoding: value = value.encode(self.encoding) return value
[ "def", "encode", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "serialize", "(", "value", ")", "if", "self", ".", "encoding", ":", "value", "=", "value", ".", "encode", "(", "self", ".", "encoding", ")", "return", "value" ]
30
0.010811
def value(self): """Value of property.""" if self._prop.fget is None: raise AttributeError('Unable to read attribute') return self._prop.fget(self._obj)
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "_prop", ".", "fget", "is", "None", ":", "raise", "AttributeError", "(", "'Unable to read attribute'", ")", "return", "self", ".", "_prop", ".", "fget", "(", "self", ".", "_obj", ")" ]
36.8
0.010638
def _create_update_tracking_related_event(instance): """ Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model. """ events = {} # Create a dict mapping related model field to modified fields for field, related_fields in instance._tracked_related_field...
[ "def", "_create_update_tracking_related_event", "(", "instance", ")", ":", "events", "=", "{", "}", "# Create a dict mapping related model field to modified fields", "for", "field", ",", "related_fields", "in", "instance", ".", "_tracked_related_fields", ".", "items", "(", ...
42.945946
0.000615
def __valid_on_demand_ext_pillar(self, opts): ''' Check to see if the on demand external pillar is allowed ''' if not isinstance(self.ext, dict): log.error( 'On-demand pillar %s is not formatted as a dictionary', self.ext ) ...
[ "def", "__valid_on_demand_ext_pillar", "(", "self", ",", "opts", ")", ":", "if", "not", "isinstance", "(", "self", ".", "ext", ",", "dict", ")", ":", "log", ".", "error", "(", "'On-demand pillar %s is not formatted as a dictionary'", ",", "self", ".", "ext", "...
38.30303
0.002315
def connect(self): """Connect to the Docker server.""" try: ret = docker.from_env() except Exception as e: logger.error("docker plugin - Can not connect to Docker ({})".format(e)) ret = None return ret
[ "def", "connect", "(", "self", ")", ":", "try", ":", "ret", "=", "docker", ".", "from_env", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"docker plugin - Can not connect to Docker ({})\"", ".", "format", "(", "e", ")", ")...
29.111111
0.011111
def derivative(self, rate): """Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate` Params: rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively. Returns: A unit ...
[ "def", "derivative", "(", "self", ",", "rate", ")", ":", "rate", "=", "self", ".", "_validate_number_sequence", "(", "rate", ",", "3", ")", "return", "0.5", "*", "self", "*", "Quaternion", "(", "vector", "=", "rate", ")" ]
42.545455
0.008368
def check_clang_apply_replacements_binary(args): """Checks if invoking supplied clang-apply-replacements binary works.""" try: subprocess.check_call([args.clang_apply_replacements_binary, '--version']) except: print('Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary c...
[ "def", "check_clang_apply_replacements_binary", "(", "args", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "args", ".", "clang_apply_replacements_binary", ",", "'--version'", "]", ")", "except", ":", "print", "(", "'Unable to run clang-apply-replace...
43.555556
0.015
def recursive_glob(base_directory, regex=''): """ Uses glob to find all files or folders that match the regex starting from the base_directory. Parameters ---------- base_directory: str regex: str Returns ------- files: list """ files = glob(op.join(base_directory, re...
[ "def", "recursive_glob", "(", "base_directory", ",", "regex", "=", "''", ")", ":", "files", "=", "glob", "(", "op", ".", "join", "(", "base_directory", ",", "regex", ")", ")", "for", "path", ",", "dirlist", ",", "filelist", "in", "os", ".", "walk", "...
21.727273
0.002004
def phaser(self, gain_in=0.9, gain_out=0.8, delay=1, decay=0.25, speed=2, triangular=False): """phaser takes 6 parameters: input gain (max 1.0), output gain (max 1.0), delay, decay, speed and LFO shape=trianglar (w...
[ "def", "phaser", "(", "self", ",", "gain_in", "=", "0.9", ",", "gain_out", "=", "0.8", ",", "delay", "=", "1", ",", "decay", "=", "0.25", ",", "speed", "=", "2", ",", "triangular", "=", "False", ")", ":", "self", ".", "command", ".", "append", "(...
33.142857
0.011173
def shared_s3_app_bucket(self, include_region=False): """Generate shared s3 application bucket name. Args: include_region (bool): Include region in the name generation. """ if include_region: shared_s3_app_bucket = self.format['shared_s3_app_region_bucket'].forma...
[ "def", "shared_s3_app_bucket", "(", "self", ",", "include_region", "=", "False", ")", ":", "if", "include_region", ":", "shared_s3_app_bucket", "=", "self", ".", "format", "[", "'shared_s3_app_region_bucket'", "]", ".", "format", "(", "*", "*", "self", ".", "d...
42.272727
0.008421
def axpy(x, y, a=1.0): """Quick level-1 call to BLAS y = a*x+y. Parameters ---------- x : array_like nx1 real or complex vector y : array_like nx1 real or complex vector a : float real or complex scalar Returns ------- y : array_like Input variable y...
[ "def", "axpy", "(", "x", ",", "y", ",", "a", "=", "1.0", ")", ":", "from", "scipy", ".", "linalg", "import", "get_blas_funcs", "fn", "=", "get_blas_funcs", "(", "[", "'axpy'", "]", ",", "[", "x", ",", "y", "]", ")", "[", "0", "]", "fn", "(", ...
19.740741
0.001789
def steepest_descent(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None, residuals=None): """Steepest descent algorithm. Solves the linear system Ax = b. Left preconditioning is supported. Parameters ---------- A : array, matrix, sparse matrix, LinearOper...
[ "def", "steepest_descent", "(", "A", ",", "b", ",", "x0", "=", "None", ",", "tol", "=", "1e-5", ",", "maxiter", "=", "None", ",", "xtype", "=", "None", ",", "M", "=", "None", ",", "callback", "=", "None", ",", "residuals", "=", "None", ")", ":", ...
30.886792
0.000592
def flightmode_colour(self, flightmode): '''return colour to be used for rendering a flight mode background''' if flightmode not in self.flightmode_colourmap: self.flightmode_colourmap[flightmode] = self.next_flightmode_colour() return self.flightmode_colourmap[flightmode]
[ "def", "flightmode_colour", "(", "self", ",", "flightmode", ")", ":", "if", "flightmode", "not", "in", "self", ".", "flightmode_colourmap", ":", "self", ".", "flightmode_colourmap", "[", "flightmode", "]", "=", "self", ".", "next_flightmode_colour", "(", ")", ...
61
0.009709
def check_result(state): """High level function which wraps other SCTs for checking results. ``check_result()`` * uses ``lowercase()``, then * runs ``check_all_columns()`` on the state produced by ``lowercase()``, then * runs ``has_equal_value`` on the state produced by ``check_all_columns()``...
[ "def", "check_result", "(", "state", ")", ":", "state1", "=", "lowercase", "(", "state", ")", "state2", "=", "check_all_columns", "(", "state1", ")", "has_equal_value", "(", "state2", ")", "return", "state2" ]
30.857143
0.008989
def t_HEXCONSTANT(self, t): r'0x[0-9A-Fa-f]+' t.value = int(t.value, 16) t.type = 'INTCONSTANT' return t
[ "def", "t_HEXCONSTANT", "(", "self", ",", "t", ")", ":", "t", ".", "value", "=", "int", "(", "t", ".", "value", ",", "16", ")", "t", ".", "type", "=", "'INTCONSTANT'", "return", "t" ]
26.4
0.014706
def pcolor_helper(xi, yi, zi=None): """Prepare a set of arrays for plotting using `pcolor`. The return values are suitable for feeding directly into ``matplotlib.pcolor`` such that the pixels are properly centered. Parameters ---------- xi : 1D or 2D array-like Array of X-coordinates. ...
[ "def", "pcolor_helper", "(", "xi", ",", "yi", ",", "zi", "=", "None", ")", ":", "xi", "=", "xi", ".", "copy", "(", ")", "yi", "=", "yi", ".", "copy", "(", ")", "if", "xi", ".", "ndim", "==", "1", ":", "xi", ".", "shape", "=", "(", "xi", "...
28.794118
0.000988
def add_text(self, text, label=None): """stub""" if label is None: label = self._label_metadata['default_string_values'][0] else: if not self.my_osid_object_form._is_valid_string( label, self.get_label_metadata()) or '.' in label: raise...
[ "def", "add_text", "(", "self", ",", "text", ",", "label", "=", "None", ")", ":", "if", "label", "is", "None", ":", "label", "=", "self", ".", "_label_metadata", "[", "'default_string_values'", "]", "[", "0", "]", "else", ":", "if", "not", "self", "....
44.518519
0.002443
def pitch(self, shift, use_tree=False, segment=82, search=14.68, overlap=12): """pitch takes 4 parameters: user_tree (True or False), segment, search and overlap.""" self.command.append("pitch") if use_tree: self.command...
[ "def", "pitch", "(", "self", ",", "shift", ",", "use_tree", "=", "False", ",", "segment", "=", "82", ",", "search", "=", "14.68", ",", "overlap", "=", "12", ")", ":", "self", ".", "command", ".", "append", "(", "\"pitch\"", ")", "if", "use_tree", "...
32.266667
0.012048
def unsigned_input(outpoint, redeem_script=None, sequence=None): ''' Outpoint, byte-like, int -> TxIn ''' if redeem_script is not None and sequence is None: sequence = guess_sequence(redeem_script) if sequence is None: sequence = 0xFFFFFFFE return tb.make_legacy_input( ou...
[ "def", "unsigned_input", "(", "outpoint", ",", "redeem_script", "=", "None", ",", "sequence", "=", "None", ")", ":", "if", "redeem_script", "is", "not", "None", "and", "sequence", "is", "None", ":", "sequence", "=", "guess_sequence", "(", "redeem_script", ")...
31.076923
0.002404
def iseq(start=0, stop=None, inc=1): """ Generate integers from start to (and including!) stop, with increment of inc. Alternative to range/xrange. """ if stop is None: # allow isequence(3) to be 0, 1, 2, 3 # take 1st arg as stop, start as 0, and inc=1 stop = start; start = 0; inc = ...
[ "def", "iseq", "(", "start", "=", "0", ",", "stop", "=", "None", ",", "inc", "=", "1", ")", ":", "if", "stop", "is", "None", ":", "# allow isequence(3) to be 0, 1, 2, 3", "# take 1st arg as stop, start as 0, and inc=1", "stop", "=", "start", "start", "=", "0",...
39.222222
0.01108
def _radial_distance(shape): """ Return an array where each value is the Euclidean distance from the array center. Parameters ---------- shape : tuple of int The size of the output array along each axis. Returns ------- result : `~numpy.ndarray` An array containing ...
[ "def", "_radial_distance", "(", "shape", ")", ":", "if", "len", "(", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'shape must have only 2 elements'", ")", "position", "=", "(", "np", ".", "asarray", "(", "shape", ")", "-", "1", ")", "/", ...
26.833333
0.001499
def multivariate_gaussian_samples(matrix, N, mean=None): """ Generate samples from a multidimensional Gaussian with a given covariance. :param matrix: ``(k, k)`` The covariance matrix. :param N: The number of samples to generate. :param mean: ``(k,)`` (optional) The mean o...
[ "def", "multivariate_gaussian_samples", "(", "matrix", ",", "N", ",", "mean", "=", "None", ")", ":", "if", "mean", "is", "None", ":", "mean", "=", "np", ".", "zeros", "(", "len", "(", "matrix", ")", ")", "samples", "=", "np", ".", "random", ".", "m...
27.478261
0.001529
def _disable(self): """ Overload this method when subclassing. Called after actually disabling trace. """ self.total_time += time() - self.enabled_start self.enabled_start = None del self.stack
[ "def", "_disable", "(", "self", ")", ":", "self", ".", "total_time", "+=", "time", "(", ")", "-", "self", ".", "enabled_start", "self", ".", "enabled_start", "=", "None", "del", "self", ".", "stack" ]
30.25
0.008032
def update(self, task, params={}, **options): """A specific, existing task can be updated by making a PUT request on the URL for that task. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is ...
[ "def", "update", "(", "self", ",", "task", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/tasks/%s\"", "%", "(", "task", ")", "return", "self", ".", "client", ".", "put", "(", "path", ",", "params", ",", "*", ...
41.722222
0.009115
def block_to_graphviz_string(block=None, namer=_graphviz_default_namer): """ Return a graphviz string for the block. """ graph = net_graph(block, split_state=True) node_index_map = {} # map node -> index rstring = """\ digraph g {\n graph [splines="spline"]; n...
[ "def", "block_to_graphviz_string", "(", "block", "=", "None", ",", "namer", "=", "_graphviz_default_namer", ")", ":", "graph", "=", "net_graph", "(", "block", ",", "split_state", "=", "True", ")", "node_index_map", "=", "{", "}", "# map node -> index", "rstring"...
38.8125
0.002357
def DAVIDenrich(database, categories, user, ids, ids_bg = None, name = '', name_bg = '', verbose = False, p = 0.1, n = 2): # Modified from https://david.ncifcrf.gov/content.jsp?file=WS.html # by courtesy of HuangYi @ 20110424 """ Queries the DAVID database for an enrichment analysis Check https://d...
[ "def", "DAVIDenrich", "(", "database", ",", "categories", ",", "user", ",", "ids", ",", "ids_bg", "=", "None", ",", "name", "=", "''", ",", "name_bg", "=", "''", ",", "verbose", "=", "False", ",", "p", "=", "0.1", ",", "n", "=", "2", ")", ":", ...
40.591549
0.012195
def list_datacenters(kwargs=None, call=None): ''' List all the data centers for this VMware environment CLI Example: .. code-block:: bash salt-cloud -f list_datacenters my-vmware-config ''' if call != 'function': raise SaltCloudSystemExit( 'The list_datacenters fun...
[ "def", "list_datacenters", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_datacenters function must be called with '", "'-f or --function.'", ")", "return", "{", ...
26.352941
0.002155
def nfa_intersection(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the intersection of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. There is a NFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math...
[ "def", "nfa_intersection", "(", "nfa_1", ":", "dict", ",", "nfa_2", ":", "dict", ")", "->", "dict", ":", "intersection", "=", "{", "'alphabet'", ":", "nfa_1", "[", "'alphabet'", "]", ".", "intersection", "(", "nfa_2", "[", "'alphabet'", "]", ")", ",", ...
38.969231
0.000385
def get_ticket(self, service): """Return an existing AuthTicket for a given service.""" return self.auth_tickets \ .filter(expires__gt=datetime.now(timezone.utc), service=service) \ .last()
[ "def", "get_ticket", "(", "self", ",", "service", ")", ":", "return", "self", ".", "auth_tickets", ".", "filter", "(", "expires__gt", "=", "datetime", ".", "now", "(", "timezone", ".", "utc", ")", ",", "service", "=", "service", ")", ".", "last", "(", ...
45
0.008734
def get_core(self): """ Get an unsatisfiable core if the formula was previously unsatisfied. """ if self.minicard and self.status == False: return pysolvers.minicard_core(self.minicard)
[ "def", "get_core", "(", "self", ")", ":", "if", "self", ".", "minicard", "and", "self", ".", "status", "==", "False", ":", "return", "pysolvers", ".", "minicard_core", "(", "self", ".", "minicard", ")" ]
29.875
0.012195
def _can_be_double(x): """ Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrower, or when is an integer that can be safely converted to double (if the roundtrip conversion works). """ return ((np.issubdtype(...
[ "def", "_can_be_double", "(", "x", ")", ":", "return", "(", "(", "np", ".", "issubdtype", "(", "x", ".", "dtype", ",", "np", ".", "floating", ")", "and", "x", ".", "dtype", ".", "itemsize", "<=", "np", ".", "dtype", "(", "float", ")", ".", "items...
37.538462
0.002
def receive(self): """ Receive instructions from Guacamole guacd server. """ start = 0 while True: idx = self._buffer.find(INST_TERM.encode(), start) if idx != -1: # instruction was fully received! line = self._buffer[:idx ...
[ "def", "receive", "(", "self", ")", ":", "start", "=", "0", "while", "True", ":", "idx", "=", "self", ".", "_buffer", ".", "find", "(", "INST_TERM", ".", "encode", "(", ")", ",", "start", ")", "if", "idx", "!=", "-", "1", ":", "# instruction was fu...
37.32
0.00209
def read_object_array(f, data, options): """ Reads an array of objects recursively. Read the elements of the given HDF5 Reference array recursively in the and constructs a ``numpy.object_`` array from its elements, which is returned. Parameters ---------- f : h5py.File The HDF5 fil...
[ "def", "read_object_array", "(", "f", ",", "data", ",", "options", ")", ":", "# Go through all the elements of data and read them using their", "# references, and the putting the output in new object array.", "data_derefed", "=", "np", ".", "zeros", "(", "shape", "=", "data",...
30.604651
0.001473
def q_limited(self): """ Is the machine at it's limit of reactive power? """ if (self.q >= self.q_max) or (self.q <= self.q_min): return True else: return False
[ "def", "q_limited", "(", "self", ")", ":", "if", "(", "self", ".", "q", ">=", "self", ".", "q_max", ")", "or", "(", "self", ".", "q", "<=", "self", ".", "q_min", ")", ":", "return", "True", "else", ":", "return", "False" ]
30
0.009259
def set_bind(self): """ Sets key bindings -- we need this more than once """ IntegerEntry.set_bind(self) self.bind('<Next>', lambda e: self.set(0))
[ "def", "set_bind", "(", "self", ")", ":", "IntegerEntry", ".", "set_bind", "(", "self", ")", "self", ".", "bind", "(", "'<Next>'", ",", "lambda", "e", ":", "self", ".", "set", "(", "0", ")", ")" ]
30.333333
0.010695
def merge_dicts(dict1, dict2, append_lists=False): """ Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list. """ for key in dict2: ...
[ "def", "merge_dicts", "(", "dict1", ",", "dict2", ",", "append_lists", "=", "False", ")", ":", "for", "key", "in", "dict2", ":", "if", "isinstance", "(", "dict2", "[", "key", "]", ",", "dict", ")", ":", "if", "key", "in", "dict1", "and", "key", "in...
41.653846
0.000903
def parse_inline_styles(self, data=None, import_type ='string'): """ Function for parsing styles defined in the body of the document. This only includes data inside of HTML <style> tags, a URL, or file to open. """ if data is None: raise parser = cssutils.CSS...
[ "def", "parse_inline_styles", "(", "self", ",", "data", "=", "None", ",", "import_type", "=", "'string'", ")", ":", "if", "data", "is", "None", ":", "raise", "parser", "=", "cssutils", ".", "CSSParser", "(", ")", "if", "import_type", "==", "'string'", ":...
44.659574
0.008858
def parse_wrap_facets(facets): """ Return list of facetting variables """ valid_forms = ['~ var1', '~ var1 + var2'] error_msg = ("Valid formula for 'facet_wrap' look like" " {}".format(valid_forms)) if isinstance(facets, (list, tuple)): return facets if not isinsta...
[ "def", "parse_wrap_facets", "(", "facets", ")", ":", "valid_forms", "=", "[", "'~ var1'", ",", "'~ var1 + var2'", "]", "error_msg", "=", "(", "\"Valid formula for 'facet_wrap' look like\"", "\" {}\"", ".", "format", "(", "valid_forms", ")", ")", "if", "isinstance", ...
29.068966
0.001148
def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return ...
[ "def", "get_size", "(", "vm_", ")", ":", "sizes", "=", "avail_sizes", "(", ")", "vm_size", "=", "six", ".", "text_type", "(", "config", ".", "get_cloud_config_value", "(", "'size'", ",", "vm_", ",", "__opts__", ",", "search_global", "=", "False", ")", ")...
31.142857
0.002227
def node(self, node): """ Return the other node """ if node == self.node1: return self.node2 elif node == self.node2: return self.node1 else: return None
[ "def", "node", "(", "self", ",", "node", ")", ":", "if", "node", "==", "self", ".", "node1", ":", "return", "self", ".", "node2", "elif", "node", "==", "self", ".", "node2", ":", "return", "self", ".", "node1", "else", ":", "return", "None" ]
20.727273
0.008403
def generate(env): """Add Builders and construction variables for qt to an Environment.""" CLVar = SCons.Util.CLVar Action = SCons.Action.Action Builder = SCons.Builder.Builder env.SetDefault(QTDIR = _detect(env), QT_BINPATH = os.path.join('$QTDIR', 'bin'), QT...
[ "def", "generate", "(", "env", ")", ":", "CLVar", "=", "SCons", ".", "Util", ".", "CLVar", "Action", "=", "SCons", ".", "Action", ".", "Action", "Builder", "=", "SCons", ".", "Builder", ".", "Builder", "env", ".", "SetDefault", "(", "QTDIR", "=", "_d...
46.67033
0.014296
def derivative_fit(xdata, ydata, neighbors=1): """ loops over the data points, performing a least-squares linear fit of the nearest neighbors at each point. Returns an array of x-values and slopes. xdata should probably be well-ordered. neighbors How many data point on the left and right to incl...
[ "def", "derivative_fit", "(", "xdata", ",", "ydata", ",", "neighbors", "=", "1", ")", ":", "x", "=", "[", "]", "dydx", "=", "[", "]", "nmax", "=", "len", "(", "xdata", ")", "-", "1", "for", "n", "in", "range", "(", "nmax", "+", "1", ")", ":",...
27.533333
0.002339
def cluster_over_time(stat, time, window, argmax=numpy.argmax): """Cluster generalized transient events over time via maximum stat over a symmetric sliding window Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time: numpy.ndarray time to use for c...
[ "def", "cluster_over_time", "(", "stat", ",", "time", ",", "window", ",", "argmax", "=", "numpy", ".", "argmax", ")", ":", "logging", ".", "info", "(", "'Clustering events over %s s window'", ",", "window", ")", "indices", "=", "[", "]", "time_sorting", "=",...
26.861538
0.001105
def find_thumbnail(self, width=None, height=None): """Finds the thumbnail of the image with the given ``width`` and/or ``height``. :param width: the thumbnail width :type width: :class:`numbers.Integral` :param height: the thumbnail height :type height: :class:`numbers.I...
[ "def", "find_thumbnail", "(", "self", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "if", "width", "is", "None", "and", "height", "is", "None", ":", "raise", "TypeError", "(", "'required width and/or height'", ")", "q", "=", "self", "i...
36.83871
0.001706
def _create_model(self, X, Y): """ Creates the model given some input data X and Y. """ # --- define kernel self.input_dim = X.shape[1] if self.kernel is None: kern = GPy.kern.Matern52(self.input_dim, variance=1., ARD=self.ARD) #+ GPy.kern.Bias(self.input_dim...
[ "def", "_create_model", "(", "self", ",", "X", ",", "Y", ")", ":", "# --- define kernel", "self", ".", "input_dim", "=", "X", ".", "shape", "[", "1", "]", "if", "self", ".", "kernel", "is", "None", ":", "kern", "=", "GPy", ".", "kern", ".", "Matern...
39.814815
0.008174
def imagetransformer_base_8l_8h_big_cond_dr03_dan(): """big 1d model for conditional image generation.2.99 on cifar10.""" hparams = imagetransformer_sep_channels_8l() hparams.block_width = 256 hparams.block_length = 256 hparams.hidden_size = 512 hparams.num_heads = 8 hparams.filter_size = 2048 hparams.b...
[ "def", "imagetransformer_base_8l_8h_big_cond_dr03_dan", "(", ")", ":", "hparams", "=", "imagetransformer_sep_channels_8l", "(", ")", "hparams", ".", "block_width", "=", "256", "hparams", ".", "block_length", "=", "256", "hparams", ".", "hidden_size", "=", "512", "hp...
35.466667
0.027473
def request_parking(self, endpoint, url_args={}, **kwargs): """Make a request to the given endpoint of the ``parking`` server. This returns the plain JSON (dict) response which can then be parsed using one of the implemented types. Args: endpoint (str): Endpoint to send the...
[ "def", "request_parking", "(", "self", ",", "endpoint", ",", "url_args", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "if", "endpoint", "not", "in", "ENDPOINTS_PARKING", ":", "# Unknown endpoint", "return", "None", "url", "=", "URL_OPENBUS", "+", "END...
33.294118
0.001717
def receive_message( sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" header = _receive_data_on_socket(sock, 16) length = _UNPACK_INT(header[:4])[0] actual_op = _UNPACK_INT(header[12:])[0] if operation != actual_op: ...
[ "def", "receive_message", "(", "sock", ",", "operation", ",", "request_id", ",", "max_message_size", "=", "MAX_MESSAGE_SIZE", ")", ":", "header", "=", "_receive_data_on_socket", "(", "sock", ",", "16", ")", "length", "=", "_UNPACK_INT", "(", "header", "[", ":"...
46.75
0.000873
def convert(files, **kwargs): """ Wrap directory to pif as a dice extension :param files: a list of files, which must be non-empty :param kwargs: any additional keyword arguments :return: the created pif """ if len(files) < 1: raise ValueError("Files needs to be a non-empty list") ...
[ "def", "convert", "(", "files", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "files", ")", "<", "1", ":", "raise", "ValueError", "(", "\"Files needs to be a non-empty list\"", ")", "if", "len", "(", "files", ")", "==", "1", ":", "if", "os", "...
31.722222
0.001701
def load_fitsbuf(self, imname, fitsbuf, num_hdu): """Display a FITS file buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. chname : str Name of a channel in which to load th...
[ "def", "load_fitsbuf", "(", "self", ",", "imname", ",", "fitsbuf", ",", "num_hdu", ")", ":", "load_fits_buffer", "=", "self", ".", "_client_", ".", "lookup_attr", "(", "'load_fits_buffer'", ")", "return", "load_fits_buffer", "(", "imname", ",", "self", ".", ...
29.2
0.00221
def build_synchronize_decorator(): """Returns a decorator which prevents concurrent calls to functions. Usage: synchronized = build_synchronize_decorator() @synchronized def read_value(): ... @synchronized def write_value(x): ... Returns: make_threadsafe (fct): The decorato...
[ "def", "build_synchronize_decorator", "(", ")", ":", "lock", "=", "threading", ".", "Lock", "(", ")", "def", "lock_decorator", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "lock_decorated", "(", "*", "args", ",", "*", "*"...
19.8
0.009631
def broadcast(data, root): """Broadcast object from one node to all other nodes. Parameters ---------- data : any type that can be pickled Input data, if current rank does not equal root, this can be None root : int Rank of the node to broadcast data from. Returns ------- ...
[ "def", "broadcast", "(", "data", ",", "root", ")", ":", "rank", "=", "get_rank", "(", ")", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "if", "root", "==", "rank", ":", "assert", "data", "is", "not", "None", ",", "'need to pass in data when broadca...
31.638889
0.000852
def error_page( participant=None, error_text=None, compensate=True, error_type="default", request_data="", ): """Render HTML for error page.""" config = _config() if error_text is None: error_text = """There has been an error and so you are unable to continue, sorry!""" ...
[ "def", "error_page", "(", "participant", "=", "None", ",", "error_text", "=", "None", ",", "compensate", "=", "True", ",", "error_type", "=", "\"default\"", ",", "request_data", "=", "\"\"", ",", ")", ":", "config", "=", "_config", "(", ")", "if", "error...
29.195652
0.00072
def _check_rules(browser, rules_js, config): """ Run an accessibility audit on the page using the axe-core ruleset. Args: browser: a browser instance. rules_js: the ruleset JavaScript as a string. config: an AxsAuditConfig instance. Returns: ...
[ "def", "_check_rules", "(", "browser", ",", "rules_js", ",", "config", ")", ":", "audit_run_script", "=", "dedent", "(", "u\"\"\"\n {rules_js}\n {custom_rules}\n axe.configure(customRules);\n var callback = function(err, results) {{\n ...
31.567568
0.00083
def merge_neighbours(self, strict=True): """ Makes a new striplog in which matching neighbours (for which the components are the same) are unioned. That is, they are replaced by a new Interval with the same top as the uppermost and the same bottom as the lowermost. Args ...
[ "def", "merge_neighbours", "(", "self", ",", "strict", "=", "True", ")", ":", "new_strip", "=", "[", "self", "[", "0", "]", ".", "copy", "(", ")", "]", "for", "lower", "in", "self", "[", "1", ":", "]", ":", "# Determine if touching.", "touching", "="...
32.473684
0.001574
def parse(self, file=None, string=None): """ SAX parse XML text. @param file: Parse a python I{file-like} object. @type file: I{file-like} object. @param string: Parse string XML. @type string: str """ timer = metrics.Timer() timer.start() ...
[ "def", "parse", "(", "self", ",", "file", "=", "None", ",", "string", "=", "None", ")", ":", "timer", "=", "metrics", ".", "Timer", "(", ")", "timer", ".", "start", "(", ")", "sax", ",", "handler", "=", "self", ".", "saxparser", "(", ")", "if", ...
34.695652
0.002439