text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def is_satisfied(self): """ Returns a boolean indicating whether or not the double has been satisfied. Stubs are always satisfied, but mocks are only satisfied if they've been called as was declared, or if call is expected not to happen. :return: Whether or not the double is sat...
[ "def", "is_satisfied", "(", "self", ")", ":", "return", "self", ".", "_call_counter", ".", "has_correct_call_count", "(", ")", "and", "(", "self", ".", "_call_counter", ".", "never", "(", ")", "or", "self", ".", "_is_satisfied", ")" ]
39.75
0.008197
def prioritize(): """ Yield the messages in the queue in the order they should be sent. """ while True: hp_qs = Message.objects.high_priority().using('default') mp_qs = Message.objects.medium_priority().using('default') lp_qs = Message.objects.low_priority().using('default') ...
[ "def", "prioritize", "(", ")", ":", "while", "True", ":", "hp_qs", "=", "Message", ".", "objects", ".", "high_priority", "(", ")", ".", "using", "(", "'default'", ")", "mp_qs", "=", "Message", ".", "objects", ".", "medium_priority", "(", ")", ".", "usi...
42
0.001225
def main(): """Used for development and testing.""" expr_list = [ "max(-_.千幸福的笑脸{घोड़ा=馬, " "dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 " "times 3 && " "(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and " "count(fizzle) lt 0or count(baz) > 1)".decode('utf8'), ...
[ "def", "main", "(", ")", ":", "expr_list", "=", "[", "\"max(-_.千幸福的笑脸{घोड़ा=馬, \"", "\"dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 \"", "\"times 3 && \"", "\"(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and \"", "\"count(fizzle) lt 0or count(baz) > 1)\"", ".", "decode", "(", "'utf...
31.781818
0.000555
def main_production(self): """Returns main rule""" for rule in self.productions: if rule.leftside[0] == self._initialsymbol: return rule raise IndexError
[ "def", "main_production", "(", "self", ")", ":", "for", "rule", "in", "self", ".", "productions", ":", "if", "rule", ".", "leftside", "[", "0", "]", "==", "self", ".", "_initialsymbol", ":", "return", "rule", "raise", "IndexError" ]
33.333333
0.009756
def delete(self, callback=None, errback=None): """ Delete the Network and all associated addresses """ return self._rest.delete(self.id, callback=callback, errback=errback)
[ "def", "delete", "(", "self", ",", "callback", "=", "None", ",", "errback", "=", "None", ")", ":", "return", "self", ".", "_rest", ".", "delete", "(", "self", ".", "id", ",", "callback", "=", "callback", ",", "errback", "=", "errback", ")" ]
40
0.009804
def get_order(self, order_id): '''Get an order''' resp = self.get('/orders/{}'.format(order_id)) return Order(resp)
[ "def", "get_order", "(", "self", ",", "order_id", ")", ":", "resp", "=", "self", ".", "get", "(", "'/orders/{}'", ".", "format", "(", "order_id", ")", ")", "return", "Order", "(", "resp", ")" ]
34
0.014388
def parse_userinfo(cls, userinfo): '''Parse the userinfo and return username and password.''' username, sep, password = userinfo.partition(':') return username, password
[ "def", "parse_userinfo", "(", "cls", ",", "userinfo", ")", ":", "username", ",", "sep", ",", "password", "=", "userinfo", ".", "partition", "(", "':'", ")", "return", "username", ",", "password" ]
38
0.010309
def _BuildEventData(self, record): """Builds an FseventsdData object from a parsed structure. Args: record (dls_record_v1|dls_record_v2): parsed record structure. Returns: FseventsdEventData: event data attribute container. """ event_data = FseventsdEventData() event_data.path = re...
[ "def", "_BuildEventData", "(", "self", ",", "record", ")", ":", "event_data", "=", "FseventsdEventData", "(", ")", "event_data", ".", "path", "=", "record", ".", "path", "event_data", ".", "flags", "=", "record", ".", "event_flags", "event_data", ".", "event...
33.117647
0.001727
def get_conf_files(filename): """ Return :class:`list` of the all configuration files. *filename* is a path of the main configuration file. :: >>> get_conf_files('exampleapp.conf') ['exampleapp.conf', 'exampleapp.conf.d/10-database.conf'] """ if not os.path.isfile(filename): ...
[ "def", "get_conf_files", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "ValueError", "(", "\"'%s' is not a file\"", "%", "filename", ")", "conf_d_path", "=", "\"%s.d\"", "%", "filename", "if", ...
32.25
0.001883
def entity_copy(args): """ Copy entities from one workspace to another. """ if not args.to_workspace: args.to_workspace = args.workspace if not args.to_project: args.to_project = args.project if (args.project == args.to_project and args.workspace == args.to_workspace): ep...
[ "def", "entity_copy", "(", "args", ")", ":", "if", "not", "args", ".", "to_workspace", ":", "args", ".", "to_workspace", "=", "args", ".", "workspace", "if", "not", "args", ".", "to_project", ":", "args", ".", "to_project", "=", "args", ".", "project", ...
42.580645
0.002222
def _tumor_normal_stats(rec, somatic_info, vcf_rec): """Retrieve depth and frequency of tumor and normal samples. """ out = {"normal": {"alt": None, "depth": None, "freq": None}, "tumor": {"alt": 0, "depth": 0, "freq": None}} if hasattr(vcf_rec, "samples"): samples = [(s, {}) for s in...
[ "def", "_tumor_normal_stats", "(", "rec", ",", "somatic_info", ",", "vcf_rec", ")", ":", "out", "=", "{", "\"normal\"", ":", "{", "\"alt\"", ":", "None", ",", "\"depth\"", ":", "None", ",", "\"freq\"", ":", "None", "}", ",", "\"tumor\"", ":", "{", "\"a...
38.586207
0.000872
def sg_summary_image(tensor, prefix=None, name=None): r"""Register `tensor` to summary report as `image` Args: tensor: A tensor to log as image prefix: A `string`. A prefix to display in the tensor board web UI. name: A `string`. A name to display in the tensor board web UI. Returns: ...
[ "def", "sg_summary_image", "(", "tensor", ",", "prefix", "=", "None", ",", "name", "=", "None", ")", ":", "# defaults", "prefix", "=", "''", "if", "prefix", "is", "None", "else", "prefix", "+", "'/'", "# summary name", "name", "=", "prefix", "+", "_prett...
33.111111
0.001631
def free_param_bounds(self): """Returns the bounds of the free hyperparameters. Returns ------- free_param_bounds : :py:class:`Array` Array of the bounds of the free parameters, in order. """ return scipy.concatenate((self.k1.free_param_bounds, self.k...
[ "def", "free_param_bounds", "(", "self", ")", ":", "return", "scipy", ".", "concatenate", "(", "(", "self", ".", "k1", ".", "free_param_bounds", ",", "self", ".", "k2", ".", "free_param_bounds", ")", ")" ]
37
0.01173
def _get_simple_dtype_and_shape(self, colnum, rows=None): """ When reading a single column, we want the basic data type and the shape of the array. for scalar columns, shape is just nrows, otherwise it is (nrows, dim1, dim2) Note if rows= is sent and only a single row i...
[ "def", "_get_simple_dtype_and_shape", "(", "self", ",", "colnum", ",", "rows", "=", "None", ")", ":", "# basic datatype", "npy_type", ",", "isvar", ",", "istbit", "=", "self", ".", "_get_tbl_numpy_dtype", "(", "colnum", ")", "info", "=", "self", ".", "_info"...
29.815789
0.001709
def find_font(face, bold, italic): """Find font""" bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN face = face.encode('utf8') fontconfig.FcInit() pattern = fontconfig.FcPatternCreate() fontconfig.FcPatternAddInteger(pattern, FC_WEIG...
[ "def", "find_font", "(", "face", ",", "bold", ",", "italic", ")", ":", "bold", "=", "FC_WEIGHT_BOLD", "if", "bold", "else", "FC_WEIGHT_REGULAR", "italic", "=", "FC_SLANT_ITALIC", "if", "italic", "else", "FC_SLANT_ROMAN", "face", "=", "face", ".", "encode", "...
43.814815
0.000827
def thumbUrl(self): """ Return url to for the thumbnail image. """ key = self.firstAttr('thumb', 'parentThumb', 'granparentThumb') return self._server.url(key, includeToken=True) if key else None
[ "def", "thumbUrl", "(", "self", ")", ":", "key", "=", "self", ".", "firstAttr", "(", "'thumb'", ",", "'parentThumb'", ",", "'granparentThumb'", ")", "return", "self", ".", "_server", ".", "url", "(", "key", ",", "includeToken", "=", "True", ")", "if", ...
54
0.009132
def kill(self): """ Kills the processes right now with a SIGKILL """ for process in list(self.processes): process["subprocess"].send_signal(signal.SIGKILL) self.stop_watch()
[ "def", "kill", "(", "self", ")", ":", "for", "process", "in", "list", "(", "self", ".", "processes", ")", ":", "process", "[", "\"subprocess\"", "]", ".", "send_signal", "(", "signal", ".", "SIGKILL", ")", "self", ".", "stop_watch", "(", ")" ]
29.285714
0.009479
def force_process_ordered(self): """ Take any messages from replica that have been ordered and process them, this should be done rarely, like before catchup starts so a more current LedgerStatus can be sent. can be called either 1. when node is participating, this happens...
[ "def", "force_process_ordered", "(", "self", ")", ":", "for", "instance_id", ",", "messages", "in", "self", ".", "replicas", ".", "take_ordereds_out_of_turn", "(", ")", ":", "num_processed", "=", "0", "for", "message", "in", "messages", ":", "self", ".", "tr...
50.136364
0.001779
def _compute_heating_rates(self): '''Compute energy flux convergences to get heating rates in :math:`W/m^2`.''' self.LW_to_atm = self._compute_emission() self.SW_to_atm = self._compute_reflected_flux() self.heating_rate['Ts'] = ( self.LW_from_atm - self.LW_to_atm ...
[ "def", "_compute_heating_rates", "(", "self", ")", ":", "self", ".", "LW_to_atm", "=", "self", ".", "_compute_emission", "(", ")", "self", ".", "SW_to_atm", "=", "self", ".", "_compute_reflected_flux", "(", ")", "self", ".", "heating_rate", "[", "'Ts'", "]",...
60.333333
0.016349
def diff_jid(jid, config='root'): ''' Returns the changes applied by a `jid` jid The job id to lookup config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.diff_jid jid=20160607130930720112 ''' pre_snapshot, post_snapshot = _get_jid_sn...
[ "def", "diff_jid", "(", "jid", ",", "config", "=", "'root'", ")", ":", "pre_snapshot", ",", "post_snapshot", "=", "_get_jid_snapshots", "(", "jid", ",", "config", "=", "config", ")", "return", "diff", "(", "config", ",", "num_pre", "=", "pre_snapshot", ","...
22.222222
0.002398
def signature_parser(func): """ Creates an argparse.ArgumentParser from the function's signature. Arguments with no default are compulsary positional arguments, Arguments with defaults are optional --flags. If the default is True or False, the action of the flag will toggle...
[ "def", "signature_parser", "(", "func", ")", ":", "args", ",", "trail", ",", "kwargs", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "func", ")", "if", "not", "args", ":", "args", "=", "[", "]", "if", "not", "defaults", ":", "defaults", "=...
31.929825
0.000178
def catch_warnings(action, category=Warning, lineno=0, append=False): """Wrap the function in a `warnings.catch_warnings` context. It can be used to silence some particular specific warnings, or instead to treat them as errors within the function body. Example: >>> import warnings >>> ...
[ "def", "catch_warnings", "(", "action", ",", "category", "=", "Warning", ",", "lineno", "=", "0", ",", "append", "=", "False", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "newfunc", "(...
29.892857
0.001157
def register_trainable(name, trainable): """Register a trainable function or class. Args: name (str): Name to register. trainable (obj): Function or tune.Trainable class. Functions must take (config, status_reporter) as arguments and will be automatically converted into ...
[ "def", "register_trainable", "(", "name", ",", "trainable", ")", ":", "from", "ray", ".", "tune", ".", "trainable", "import", "Trainable", "from", "ray", ".", "tune", ".", "function_runner", "import", "wrap_function", "if", "isinstance", "(", "trainable", ",",...
39.518519
0.000915
def __create_index(self, keys, index_options): """Internal create index helper. :Parameters: - `keys`: a list of tuples [(key, type), (key, type), ...] - `index_options`: a dict of index options. """ index_doc = helpers._index_document(keys) index = {"key": i...
[ "def", "__create_index", "(", "self", ",", "keys", ",", "index_options", ")", ":", "index_doc", "=", "helpers", ".", "_index_document", "(", "keys", ")", "index", "=", "{", "\"key\"", ":", "index_doc", "}", "collation", "=", "validate_collation_or_none", "(", ...
44.555556
0.00122
async def info(self, token): """Queries the policy of a given token. Parameters: token (ObjectID): Token ID Returns: ObjectMeta: where value is token Raises: NotFound: It returns a body like this:: { "CreateIndex"...
[ "async", "def", "info", "(", "self", ",", "token", ")", ":", "token_id", "=", "extract_attr", "(", "token", ",", "keys", "=", "[", "\"ID\"", "]", ")", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/acl/info\"", ",", "token_id", ...
29.973684
0.001701
def send_request(self, worker_class_or_function, args, on_receive=None): """ Requests some work to be done by the backend. You can get notified of the work results by passing a callback (on_receive). :param worker_class_or_function: Worker class or function :param args: worker a...
[ "def", "send_request", "(", "self", ",", "worker_class_or_function", ",", "args", ",", "on_receive", "=", "None", ")", ":", "if", "not", "self", ".", "running", ":", "try", ":", "# try to restart the backend if it crashed.", "self", ".", "start", "(", "self", ...
45.058824
0.001278
def set_config(new_config={}): """ Reset config options to defaults, and then update (optionally) with the provided dictionary of options. """ # The default base configuration. flask_app.base_config = dict(working_directory='.', template='collapse-input', ...
[ "def", "set_config", "(", "new_config", "=", "{", "}", ")", ":", "# The default base configuration.", "flask_app", ".", "base_config", "=", "dict", "(", "working_directory", "=", "'.'", ",", "template", "=", "'collapse-input'", ",", "debug", "=", "False", ",", ...
46.222222
0.002358
def show_clusters(data, observer, marker='.', markersize=None): """! @brief Shows allocated clusters by the genetic algorithm. @param[in] data (list): Input data that was used for clustering process by the algorithm. @param[in] observer (ga_observer): Observer that was used for ...
[ "def", "show_clusters", "(", "data", ",", "observer", ",", "marker", "=", "'.'", ",", "markersize", "=", "None", ")", ":", "figure", "=", "plt", ".", "figure", "(", ")", "ax1", "=", "figure", ".", "add_subplot", "(", "121", ")", "clusters", "=", "ga_...
47.36
0.013245
def create(doc=None, error_text=None, exception_handlers=empty.dict, extend=Type, chain=True, auto_instance=True, accept_context=False): """Creates a new type handler with the specified type-casting handler""" extend = extend if type(extend) == type else type(extend) def new_type_handler(functio...
[ "def", "create", "(", "doc", "=", "None", ",", "error_text", "=", "None", ",", "exception_handlers", "=", "empty", ".", "dict", ",", "extend", "=", "Type", ",", "chain", "=", "True", ",", "auto_instance", "=", "True", ",", "accept_context", "=", "False",...
54.762712
0.001824
def read(filename): """Reads H5M files, cf. https://trac.mcs.anl.gov/projects/ITAPS/wiki/MOAB/h5m. """ import h5py f = h5py.File(filename, "r") dset = f["tstt"] points = dset["nodes"]["coordinates"][()] # read point data point_data = {} if "tags" in dset["nodes"]: for n...
[ "def", "read", "(", "filename", ")", ":", "import", "h5py", "f", "=", "h5py", ".", "File", "(", "filename", ",", "\"r\"", ")", "dset", "=", "f", "[", "\"tstt\"", "]", "points", "=", "dset", "[", "\"nodes\"", "]", "[", "\"coordinates\"", "]", "[", "...
40.75
0.000545
def check_bam(bam, o): """ Check reads in BAM file for read type and lengths. :param str bam: BAM file path. :param int o: Number of reads to look at for estimation. """ try: p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE) # Count paired alignments paired = 0 ...
[ "def", "check_bam", "(", "bam", ",", "o", ")", ":", "try", ":", "p", "=", "sp", ".", "Popen", "(", "[", "'samtools'", ",", "'view'", ",", "bam", "]", ",", "stdout", "=", "sp", ".", "PIPE", ")", "# Count paired alignments", "paired", "=", "0", "read...
35.966667
0.000903
def gettrace(self, burn=0, thin=1, chain=-1, slicing=None): """Return the trace (last by default). :Parameters: burn : integer The number of transient steps to skip. thin : integer Keep one in thin. chain : integer The index of the chain to fetch. I...
[ "def", "gettrace", "(", "self", ",", "burn", "=", "0", ",", "thin", "=", "1", ",", "chain", "=", "-", "1", ",", "slicing", "=", "None", ")", ":", "if", "chain", "is", "not", "None", ":", "vlarrays", "=", "[", "self", ".", "_vlarrays", "[", "cha...
32.0625
0.001892
def index(count, page): """ Serves the page with a list of blog posts :param count: :param offset: :return: """ blogging_engine = _get_blogging_engine(current_app) storage = blogging_engine.storage config = blogging_engine.config count = count or config.get("BLOGGING_POSTS_PER_P...
[ "def", "index", "(", "count", ",", "page", ")", ":", "blogging_engine", "=", "_get_blogging_engine", "(", "current_app", ")", "storage", "=", "blogging_engine", ".", "storage", "config", "=", "blogging_engine", ".", "config", "count", "=", "count", "or", "conf...
38.533333
0.000844
def does_coord_increase_w_index(arr): """Determine if the array values increase with the index. Useful, e.g., for pressure, which sometimes is indexed surface to TOA and sometimes the opposite. """ diff = np.diff(arr) if not np.all(np.abs(np.sign(diff))): raise ValueError("Array is not ...
[ "def", "does_coord_increase_w_index", "(", "arr", ")", ":", "diff", "=", "np", ".", "diff", "(", "arr", ")", "if", "not", "np", ".", "all", "(", "np", ".", "abs", "(", "np", ".", "sign", "(", "diff", ")", ")", ")", ":", "raise", "ValueError", "("...
38.545455
0.002304
def socketBinaryStream(self, hostname, port, length): """Create a TCP socket server for binary input. .. warning:: This is not part of the PySpark API. :param string hostname: Hostname of TCP server. :param int port: Port of TCP server. :param length: Me...
[ "def", "socketBinaryStream", "(", "self", ",", "hostname", ",", "port", ",", "length", ")", ":", "deserializer", "=", "TCPDeserializer", "(", "self", ".", "_context", ")", "tcp_binary_stream", "=", "TCPBinaryStream", "(", "length", ")", "tcp_binary_stream", ".",...
42.166667
0.001932
def from_cli(opt, dyn_range_fac=1, precision='single', inj_filter_rejector=None): """Parses the CLI options related to strain data reading and conditioning. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attri...
[ "def", "from_cli", "(", "opt", ",", "dyn_range_fac", "=", "1", ",", "precision", "=", "'single'", ",", "inj_filter_rejector", "=", "None", ")", ":", "gating_info", "=", "{", "}", "if", "opt", ".", "frame_cache", "or", "opt", ".", "frame_files", "or", "op...
43.52766
0.002198
def argsize(self): """The total size in bytes of all the command arguments.""" argsize = sum(arg.nbytes for arg in self.argdefns) return argsize if len(self.argdefns) > 0 else 0
[ "def", "argsize", "(", "self", ")", ":", "argsize", "=", "sum", "(", "arg", ".", "nbytes", "for", "arg", "in", "self", ".", "argdefns", ")", "return", "argsize", "if", "len", "(", "self", ".", "argdefns", ")", ">", "0", "else", "0" ]
49.5
0.00995
def great_circle_distance(lon1, lat1, lon2, lat2): """Calculate the great circle distance between one or multiple pairs of points given in spherical coordinates. Spherical coordinates are expected in degrees. Angle definition follows standard longitude/latitude definition. This uses the arctan version o...
[ "def", "great_circle_distance", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ")", ":", "# Convert to radians:", "lat1", "=", "np", ".", "array", "(", "lat1", ")", "*", "np", ".", "pi", "/", "180.0", "lat2", "=", "np", ".", "array", "(", "lat2"...
37.309091
0.001425
def get_orbit(name, date): """Retrieve the orbit of a solar system object Args: name (str): The name of the body desired. For exact nomenclature, see :py:func:`available_planets` date (Date): Date at which the state vector will be extracted Return: Orbit: Orbit of the de...
[ "def", "get_orbit", "(", "name", ",", "date", ")", ":", "# On-demand Propagator and Frame generation", "if", "name", "not", "in", "[", "x", ".", "name", "for", "x", "in", "Bsp", "(", ")", ".", "top", ".", "list", "]", ":", "raise", "UnknownBodyError", "(...
34.076923
0.002195
def change_subscription(self, topics): """Change the topic subscription. Arguments: topics (list of str): topics for subscription Raises: IllegalStateErrror: if assign_from_user has been used already TypeError: if a topic is None or a non-str Val...
[ "def", "change_subscription", "(", "self", ",", "topics", ")", ":", "if", "self", ".", "_user_assignment", ":", "raise", "IllegalStateError", "(", "self", ".", "_SUBSCRIPTION_EXCEPTION_MESSAGE", ")", "if", "isinstance", "(", "topics", ",", "six", ".", "string_ty...
36.6
0.002281
def ensure_valid_nums_in_specification_cols(specification, dataframe): """ Checks whether each column in `specification` contains numeric data, excluding positive or negative infinity and excluding NaN. Raises ValueError if any of the columns do not meet these requirements. Parameters ---------...
[ "def", "ensure_valid_nums_in_specification_cols", "(", "specification", ",", "dataframe", ")", ":", "problem_cols", "=", "[", "]", "for", "col", "in", "specification", ":", "# The condition below checks for values that are not floats or integers", "# This will catch values that a...
37.864865
0.000696
def _get_execution_state_with_watch(self, topologyName, callback, isWatching): """ Helper function to get execution state with a callback. The future watch is placed only if isWatching is True. """ path = self.get_execution_state_path(topologyName) if isWatching: LOG.info("Adding data ...
[ "def", "_get_execution_state_with_watch", "(", "self", ",", "topologyName", ",", "callback", ",", "isWatching", ")", ":", "path", "=", "self", ".", "get_execution_state_path", "(", "topologyName", ")", "if", "isWatching", ":", "LOG", ".", "info", "(", "\"Adding ...
34.32
0.010204
def next(self): """Select the next cluster.""" if not self.selected: self.cluster_view.next() else: self.similarity_view.next()
[ "def", "next", "(", "self", ")", ":", "if", "not", "self", ".", "selected", ":", "self", ".", "cluster_view", ".", "next", "(", ")", "else", ":", "self", ".", "similarity_view", ".", "next", "(", ")" ]
28.333333
0.011429
def _create_topk_unique(inputs, k): """Creates the top k values in sorted order with indices. Args: inputs: A tensor with rank of 2. [batch_size, original_size]. k: An integer, number of top elements to select. Returns: topk_r2: A tensor, the k largest elements. [batch_size, k]. topk_indices_r2:...
[ "def", "_create_topk_unique", "(", "inputs", ",", "k", ")", ":", "height", "=", "inputs", ".", "shape", "[", "0", "]", "width", "=", "inputs", ".", "shape", "[", "1", "]", "neg_inf_r0", "=", "tf", ".", "constant", "(", "-", "np", ".", "inf", ",", ...
41.153846
0.01339
def open( config, mode="continue", zoom=None, bounds=None, single_input_file=None, with_cache=False, debug=False ): """ Open a Mapchete process. Parameters ---------- config : MapcheteConfig object, config dict or path to mapchete file Mapchete process configuration mode : strin...
[ "def", "open", "(", "config", ",", "mode", "=", "\"continue\"", ",", "zoom", "=", "None", ",", "bounds", "=", "None", ",", "single_input_file", "=", "None", ",", "with_cache", "=", "False", ",", "debug", "=", "False", ")", ":", "return", "Mapchete", "(...
33.472222
0.000806
def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an erro...
[ "def", "reset_catalog", "(", ")", ":", "# This command always returns an error code, though it completes", "# successfully. Success will be determined by making sure get_catalog", "# returns 'Default'", "cmd", "=", "[", "'softwareupdate'", ",", "'--clear-catalog'", "]", "try", ":", ...
24.153846
0.001531
def create_native(self): """ Create the native widget if not already done so. If the widget is already created, this function does nothing. """ if self._backend is not None: return # Make sure that the app is active assert self._app.native # Instantiat...
[ "def", "create_native", "(", "self", ")", ":", "if", "self", ".", "_backend", "is", "not", "None", ":", "return", "# Make sure that the app is active", "assert", "self", ".", "_app", ".", "native", "# Instantiate the backend with the right class", "self", ".", "_app...
44.631579
0.002309
def user_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" pdb.Pdb.user_exception(self, frame, exc_info)
[ "def", "user_exception", "(", "self", ",", "frame", ",", "exc_info", ")", ":", "pdb", ".", "Pdb", ".", "user_exception", "(", "self", ",", "frame", ",", "exc_info", ")" ]
54.75
0.009009
def _check_for_inception(self, root_dict): ''' Used to check if there is a dict in a dict ''' for key in root_dict: if isinstance(root_dict[key], dict): root_dict[key] = ResponseObject(root_dict[key]) return root_dict
[ "def", "_check_for_inception", "(", "self", ",", "root_dict", ")", ":", "for", "key", "in", "root_dict", ":", "if", "isinstance", "(", "root_dict", "[", "key", "]", ",", "dict", ")", ":", "root_dict", "[", "key", "]", "=", "ResponseObject", "(", "root_di...
24.8
0.011673
def initiate_tasks(self): """ Loads all tasks using `TaskLoader` from respective configuration option """ self.tasks_classes = TaskLoader().load_tasks( paths=self.configuration[Configuration.ALGORITHM][Configuration.TASKS][Configuration.PATHS])
[ "def", "initiate_tasks", "(", "self", ")", ":", "self", ".", "tasks_classes", "=", "TaskLoader", "(", ")", ".", "load_tasks", "(", "paths", "=", "self", ".", "configuration", "[", "Configuration", ".", "ALGORITHM", "]", "[", "Configuration", ".", "TASKS", ...
67.25
0.014706
def get_secret(secret_name, default=None): """ Gets contents of secret file :param secret_name: The name of the secret present in BANANAS_SECRETS_DIR :param default: Default value to return if no secret was found :return: The secret or default if not found """ secrets_dir = get_secrets_dir(...
[ "def", "get_secret", "(", "secret_name", ",", "default", "=", "None", ")", ":", "secrets_dir", "=", "get_secrets_dir", "(", ")", "secret_path", "=", "os", ".", "path", ".", "join", "(", "secrets_dir", ",", "secret_name", ")", "try", ":", "with", "open", ...
33.733333
0.001923
def remove_imath_operators(lines): """Remove mathematical expressions that require Pythons global interpreter locking mechanism. This is not a exhaustive test, but shows how the method works: >>> lines = [' x += 1*1'] >>> from hydpy.cythons.modelutils import FuncConverter ...
[ "def", "remove_imath_operators", "(", "lines", ")", ":", "for", "idx", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "for", "operator", "in", "(", "'+='", ",", "'-='", ",", "'**='", ",", "'*='", ",", "'//='", ",", "'/='", ",", "'%='", ")", ...
43.863636
0.002028
def prettyprint(self): """Return hypercat formatted prettily""" return json.dumps(self.asJSON(), sort_keys=True, indent=4, separators=(',', ': '))
[ "def", "prettyprint", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "asJSON", "(", ")", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
53.333333
0.018519
def select_spikes(cluster_ids=None, max_n_spikes_per_cluster=None, spikes_per_cluster=None, batch_size=None, subset=None, ): """Return a selection of spikes belonging to the specified clusters.""" subset = subset or 'regul...
[ "def", "select_spikes", "(", "cluster_ids", "=", "None", ",", "max_n_spikes_per_cluster", "=", "None", ",", "spikes_per_cluster", "=", "None", ",", "batch_size", "=", "None", ",", "subset", "=", "None", ",", ")", ":", "subset", "=", "subset", "or", "'regular...
44.763158
0.000575
def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi
[ "def", "window_boundaries", "(", "self", ",", "current_round", ")", ":", "lo", "=", "max", "(", "0", ",", "current_round", "-", "self", ".", "window_length", "+", "1", ")", "hi", "=", "current_round", "+", "1", "return", "lo", ",", "hi" ]
28.6
0.010169
def export_data(self, directory, filename, with_md5_hash=False): """ Save model data in a JSON file. Parameters ---------- :param directory : string The directory. :param filename : string The filename. :param with_md5_hash : bool, default...
[ "def", "export_data", "(", "self", ",", "directory", ",", "filename", ",", "with_md5_hash", "=", "False", ")", ":", "model_data", "=", "{", "'X'", ":", "self", ".", "estimator", ".", "_fit_X", ".", "tolist", "(", ")", ",", "# pylint: disable=W0212", "'y'",...
37.586207
0.001789
def mass_properties(triangles, crosses=None, density=1.0, center_mass=None, skip_inertia=False): """ Calculate the mass properties of a group of triangles. Implemented from: http://www.geometrictools.com/Documentation/Polyh...
[ "def", "mass_properties", "(", "triangles", ",", "crosses", "=", "None", ",", "density", "=", "1.0", ",", "center_mass", "=", "None", ",", "skip_inertia", "=", "False", ")", ":", "triangles", "=", "np", ".", "asanyarray", "(", "triangles", ",", "dtype", ...
33.564815
0.001072
def encode_multipart_formdata(self, fields, filename, file_values): ''' Encodes data to updload a file to Trello. Fields is a dictionary of api_key and token. Filename is the name of the file and file_values is the open(file).read() string. ''' boundary = '----------Trell...
[ "def", "encode_multipart_formdata", "(", "self", ",", "fields", ",", "filename", ",", "file_values", ")", ":", "boundary", "=", "'----------Trello_Boundary_$'", "crlf", "=", "'\\r\\n'", "data", "=", "[", "]", "for", "key", "in", "fields", ":", "data", ".", "...
32.571429
0.001704
def _init(init, X, N, rank, dtype): """ Initialization for CP models """ Uinit = [None for _ in range(N)] if isinstance(init, list): Uinit = init elif init == 'random': for n in range(1, N): Uinit[n] = array(rand(X.shape[n], rank), dtype=dtype) elif init == 'nvecs...
[ "def", "_init", "(", "init", ",", "X", ",", "N", ",", "rank", ",", "dtype", ")", ":", "Uinit", "=", "[", "None", "for", "_", "in", "range", "(", "N", ")", "]", "if", "isinstance", "(", "init", ",", "list", ")", ":", "Uinit", "=", "init", "eli...
29.875
0.002028
def fromTFExample(iter, binary_features=[]): """mapPartition function to convert an RDD of serialized tf.train.Example bytestring into an RDD of Row. Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to disambiguate these types for Spark DataFrames DTypes (StringType an...
[ "def", "fromTFExample", "(", "iter", ",", "binary_features", "=", "[", "]", ")", ":", "# convert from protobuf-like dict to DataFrame-friendly dict", "def", "_get_value", "(", "k", ",", "v", ")", ":", "if", "v", ".", "int64_list", ".", "value", ":", "result", ...
37.928571
0.011628
def readScriptRanges(scripts=None): """ Read script ranges from http://unicode.org/Public/UNIDATA/Scripts.txt file. """ scripts = scripts or LATIN_LIKE_SCRIPTS ranges = [] f = open('Scripts.txt', 'r') for line in f: line = line.strip('\n') matchObj = re.match( '^...
[ "def", "readScriptRanges", "(", "scripts", "=", "None", ")", ":", "scripts", "=", "scripts", "or", "LATIN_LIKE_SCRIPTS", "ranges", "=", "[", "]", "f", "=", "open", "(", "'Scripts.txt'", ",", "'r'", ")", "for", "line", "in", "f", ":", "line", "=", "line...
29.125
0.01108
def autofix_codeblock(codeblock, max_line_len=80, aggressive=False, very_aggressive=False, experimental=False): r""" Uses autopep8 to format a block of code Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> co...
[ "def", "autofix_codeblock", "(", "codeblock", ",", "max_line_len", "=", "80", ",", "aggressive", "=", "False", ",", "very_aggressive", "=", "False", ",", "experimental", "=", "False", ")", ":", "# FIXME idk how to remove the blank line following the function with", "# a...
33.5
0.000763
def insertInitialPeer(dataRepository, url, logger=None): """ Takes the datarepository, a url, and an optional logger and attempts to add the peer into the repository. """ insertPeer = dataRepository.insertPeer try: peer = datamodel.peers.Peer(url) insertPeer(peer) except exce...
[ "def", "insertInitialPeer", "(", "dataRepository", ",", "url", ",", "logger", "=", "None", ")", ":", "insertPeer", "=", "dataRepository", ".", "insertPeer", "try", ":", "peer", "=", "datamodel", ".", "peers", ".", "Peer", "(", "url", ")", "insertPeer", "("...
38.294118
0.001499
def has_next(self): """Return True if there are more values present""" if self._result_cache: return self._result_cache.has_next return self.all().has_next
[ "def", "has_next", "(", "self", ")", ":", "if", "self", ".", "_result_cache", ":", "return", "self", ".", "_result_cache", ".", "has_next", "return", "self", ".", "all", "(", ")", ".", "has_next" ]
31.166667
0.010417
def find_all(s, sub, start=0, end=0, limit=-1, reverse=False): """ Find all indexes of sub in s. :param s: the string to search :param sub: the string to search for :param start: the index in s at which to begin the search (same as in ''.find) :param end: the index in s at which to stop searchi...
[ "def", "find_all", "(", "s", ",", "sub", ",", "start", "=", "0", ",", "end", "=", "0", ",", "limit", "=", "-", "1", ",", "reverse", "=", "False", ")", ":", "indexes", "=", "[", "]", "if", "not", "bool", "(", "s", "and", "sub", ")", ":", "re...
24.804348
0.001686
def get_filters(component): """ Get the set of filters for the given datasource. Filters added to a ``RegistryPoint`` will be applied to all datasources that implement it. Filters added to a datasource implementation apply only to that implementation. For example, a filter added to ``Specs.ps_...
[ "def", "get_filters", "(", "component", ")", ":", "def", "inner", "(", "c", ",", "filters", "=", "None", ")", ":", "filters", "=", "filters", "or", "set", "(", ")", "if", "not", "ENABLED", ":", "return", "filters", "if", "not", "plugins", ".", "is_da...
30.710526
0.001661
def generateUnabridgedAPI(self): ''' Generates the unabridged (full) API listing into ``self.unabridged_api_file``. This is necessary as some items may not show up in either hierarchy view, depending on: 1. The item. For example, if a namespace has only one member which is a ...
[ "def", "generateUnabridgedAPI", "(", "self", ")", ":", "####flake8fail", "# TODO: I've reverted my decision, the full API should include everything,", "# including nested types. the code below invalidates certain portions of the", "# docs and probably gets rid of a need for the recursive find met...
43.618557
0.010169
def potential(self, value): """ Setter for 'potential' property Args: value (bool): True if a potential is required. False else """ if value: self._potential = True else: self._potential = False
[ "def", "potential", "(", "self", ",", "value", ")", ":", "if", "value", ":", "self", ".", "_potential", "=", "True", "else", ":", "self", ".", "_potential", "=", "False" ]
17.166667
0.050691
def save_settings(file_path, record_details, overwrite=False, secret_key=''): ''' a method to save dictionary typed data to a local file :param file_path: string with path to settings file :param record_details: dictionary with record details :param overwrite: [optional] boolean to overwrite exi...
[ "def", "save_settings", "(", "file_path", ",", "record_details", ",", "overwrite", "=", "False", ",", "secret_key", "=", "''", ")", ":", "# validate inputs\r", "title", "=", "'save_settings'", "try", ":", "_path_arg", "=", "'%s(file_path=%s)'", "%", "(", "title"...
34.06383
0.001517
def getsource(classorfunc): """ Return the source code for a class or function. Notes: Returned source will not include any decorators for the object. This will only return the explicit declaration of the object, not any dependencies Args: classorfunc (type or function): the object...
[ "def", "getsource", "(", "classorfunc", ")", ":", "if", "_isbuiltin", "(", "classorfunc", ")", ":", "return", "''", "try", ":", "source", "=", "inspect", ".", "getsource", "(", "classorfunc", ")", "except", "TypeError", ":", "# raised if defined in __main__ - us...
34.384615
0.002175
def node_to_edge(edges, directed=True): """ From list of edges, record per node, incoming and outgoing edges """ outgoing = defaultdict(set) incoming = defaultdict(set) if directed else outgoing nodes = set() for i, edge in enumerate(edges): a, b, = edge[:2] outgoing[a].add(i...
[ "def", "node_to_edge", "(", "edges", ",", "directed", "=", "True", ")", ":", "outgoing", "=", "defaultdict", "(", "set", ")", "incoming", "=", "defaultdict", "(", "set", ")", "if", "directed", "else", "outgoing", "nodes", "=", "set", "(", ")", "for", "...
28.529412
0.001996
def _getPaddingToSectionOffset(self): """ Returns the offset to last section header present in the PE file. @rtype: int @return: The offset where the end of the last section header resides in the PE file. """ return len(str(self.dosHeader) + str(self.dosStub) + s...
[ "def", "_getPaddingToSectionOffset", "(", "self", ")", ":", "return", "len", "(", "str", "(", "self", ".", "dosHeader", ")", "+", "str", "(", "self", ".", "dosStub", ")", "+", "str", "(", "self", ".", "ntHeaders", ")", "+", "str", "(", "self", ".", ...
44.875
0.013661
def GetSystemConfigurationArtifact(self, session_identifier=CURRENT_SESSION): """Retrieves the knowledge base as a system configuration artifact. Args: session_identifier (Optional[str])): session identifier, where CURRENT_SESSION represents the active session. Returns: SystemConfigu...
[ "def", "GetSystemConfigurationArtifact", "(", "self", ",", "session_identifier", "=", "CURRENT_SESSION", ")", ":", "system_configuration", "=", "artifacts", ".", "SystemConfigurationArtifact", "(", ")", "system_configuration", ".", "code_page", "=", "self", ".", "GetVal...
38.692308
0.001293
def connect_put_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501 """connect_put_namespaced_service_proxy_with_path # noqa: E501 connect PUT requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
[ "def", "connect_put_namespaced_service_proxy_with_path", "(", "self", ",", "name", ",", "namespace", ",", "path", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "...
67
0.001226
def _get_shard(self, shard): """Dynamically Builds methods to query shard with proper with arg and kwargs support""" @wraps(API_WRAPPER._get_shard) def get_shard(*arg, **kwargs): """Gets the shard '{}'""".format(shard) return self.get_shards(Shard(shard, *arg, **kwargs)) ...
[ "def", "_get_shard", "(", "self", ",", "shard", ")", ":", "@", "wraps", "(", "API_WRAPPER", ".", "_get_shard", ")", "def", "get_shard", "(", "*", "arg", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Gets the shard '{}'\"\"\"", ".", "format", "(", "shard", ")...
48.285714
0.008721
def get_node(self, node_id): """ Return the node or raise a 404 if the node is unknown """ try: return self._nodes[node_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Node ID {} doesn't exist".format(node_id))
[ "def", "get_node", "(", "self", ",", "node_id", ")", ":", "try", ":", "return", "self", ".", "_nodes", "[", "node_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Node ID {} doesn't exist\"", "....
34.625
0.010563
def multipublish(self, topic, messages, binary=False): """Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param binary: enable binary mode. defaults to False (requires ...
[ "def", "multipublish", "(", "self", ",", "topic", ",", "messages", ",", "binary", "=", "False", ")", ":", "nsq", ".", "assert_valid_topic_name", "(", "topic", ")", "fields", "=", "{", "'topic'", ":", "topic", "}", "if", "binary", ":", "fields", "[", "'...
36.958333
0.002198
async def open_interface(self, conn_id, interface): """Open an interface on an IOTile device. See :meth:`AbstractDeviceAdapter.open_interface`. """ resp = await self._execute(self._adapter.open_interface_sync, conn_id, interface) _raise_error(conn_id, 'open_interface', resp)
[ "async", "def", "open_interface", "(", "self", ",", "conn_id", ",", "interface", ")", ":", "resp", "=", "await", "self", ".", "_execute", "(", "self", ".", "_adapter", ".", "open_interface_sync", ",", "conn_id", ",", "interface", ")", "_raise_error", "(", ...
38.75
0.009464
def add(self, value): """Add element *value* to the set.""" # Raise TypeError if value is not hashable hash(value) self.redis.sadd(self.key, self._pickle(value))
[ "def", "add", "(", "self", ",", "value", ")", ":", "# Raise TypeError if value is not hashable", "hash", "(", "value", ")", "self", ".", "redis", ".", "sadd", "(", "self", ".", "key", ",", "self", ".", "_pickle", "(", "value", ")", ")" ]
31.5
0.010309
def open_remote_url(urls, **kwargs): """Open the url and check that it stores a file. Args: :urls: Endpoint to take the file """ if isinstance(urls, str): urls = [urls] for url in urls: try: web_file = requests.get(url, stream=True, **kwargs) if 'html'...
[ "def", "open_remote_url", "(", "urls", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "urls", ",", "str", ")", ":", "urls", "=", "[", "urls", "]", "for", "url", "in", "urls", ":", "try", ":", "web_file", "=", "requests", ".", "get", ...
34.6875
0.001754
def delete_issue(self, issue_id, params=None): """Deletes an individual issue. If the issue has sub-tasks you must set the deleteSubtasks=true parameter to delete the issue. You cannot delete an issue without deleting its sub-tasks. Args: issue_id: params: ...
[ "def", "delete_issue", "(", "self", ",", "issue_id", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_delete", "(", "self", ".", "API_URL", "+", "'issue/{}'", ".", "format", "(", "issue_id", ")", ",", "params", "=", "params", ")" ]
29.928571
0.009259
def datetime_period(base=None, hours=None, minutes=None, seconds=None): """Round a datetime object down to the start of a defined period. The `base` argument may be used to find the period start for an arbitrary datetime, defaults to `utcnow()`. """ if base is None: base = utcnow() base -= timedelta( ho...
[ "def", "datetime_period", "(", "base", "=", "None", ",", "hours", "=", "None", ",", "minutes", "=", "None", ",", "seconds", "=", "None", ")", ":", "if", "base", "is", "None", ":", "base", "=", "utcnow", "(", ")", "base", "-=", "timedelta", "(", "ho...
35.470588
0.051696
def mkCompoundFilter(parts): """Create a filter out of a list of filter-like things Used by mkFilter @param parts: list of filter, endpoint, callable or list of any of these """ # Separate into a list of callables and a list of filter objects transformers = [] filters = [] for subfilte...
[ "def", "mkCompoundFilter", "(", "parts", ")", ":", "# Separate into a list of callables and a list of filter objects", "transformers", "=", "[", "]", "filters", "=", "[", "]", "for", "subfilter", "in", "parts", ":", "try", ":", "subfilter", "=", "list", "(", "subf...
34.512821
0.000723
def from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord": """Get object back from dict.""" obj = cls() for key, item in obj_dict.items(): obj.__dict__[key] = item return obj
[ "def", "from_dict", "(", "cls", ",", "obj_dict", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "\"IterationRecord\"", ":", "obj", "=", "cls", "(", ")", "for", "key", ",", "item", "in", "obj_dict", ".", "items", "(", ")", ":", "obj", ".", "...
31.571429
0.008811
def api_key_from_file(url): """ Check bugzillarc for an API key for this Bugzilla URL. """ path = os.path.expanduser('~/.config/python-bugzilla/bugzillarc') cfg = SafeConfigParser() cfg.read(path) domain = urlparse(url)[1] if domain not in cfg.sections(): return None if not cfg.has_o...
[ "def", "api_key_from_file", "(", "url", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.config/python-bugzilla/bugzillarc'", ")", "cfg", "=", "SafeConfigParser", "(", ")", "cfg", ".", "read", "(", "path", ")", "domain", "=", "urlparse"...
35.727273
0.002481
def thermal_conductivity(self, temperature, volume): """ Eq(17) in 10.1103/PhysRevB.90.174107 Args: temperature (float): temperature in K volume (float): in Ang^3 Returns: float: thermal conductivity in W/K/m """ gamma = self.gruneise...
[ "def", "thermal_conductivity", "(", "self", ",", "temperature", ",", "volume", ")", ":", "gamma", "=", "self", ".", "gruneisen_parameter", "(", "temperature", ",", "volume", ")", "theta_d", "=", "self", ".", "debye_temperature", "(", "volume", ")", "# K", "t...
38.454545
0.002307
def rotate(self, angle, direction='z', axis=None): """ Returns a new Polyhedron which is the same but rotated about a given axis. If the axis given is ``None``, the rotation will be computed about the Polyhedron's centroid. :param angle: Rotatio...
[ "def", "rotate", "(", "self", ",", "angle", ",", "direction", "=", "'z'", ",", "axis", "=", "None", ")", ":", "polygon", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "1", "]", ",", "[", "1", ",", "1", "]...
40.947368
0.01005
def get_sortobj(self, goea_results, **kws): """Return a Grouper object, given a list of GOEnrichmentRecord.""" nts_goea = MgrNtGOEAs(goea_results).get_goea_nts_prt(**kws) goids = set(nt.GO for nt in nts_goea) go2nt = {nt.GO:nt for nt in nts_goea} grprobj = Grouper("GOEA", goids, ...
[ "def", "get_sortobj", "(", "self", ",", "goea_results", ",", "*", "*", "kws", ")", ":", "nts_goea", "=", "MgrNtGOEAs", "(", "goea_results", ")", ".", "get_goea_nts_prt", "(", "*", "*", "kws", ")", "goids", "=", "set", "(", "nt", ".", "GO", "for", "nt...
57.2
0.008606
def insert_rows(self, table, rows, target_fields=None, commit_every=1000, replace=False): """ A generic way to insert a set of tuples into a table, a new transaction is created every commit_every rows :param table: Name of the target table :type table: str ...
[ "def", "insert_rows", "(", "self", ",", "table", ",", "rows", ",", "target_fields", "=", "None", ",", "commit_every", "=", "1000", ",", "replace", "=", "False", ")", ":", "if", "target_fields", ":", "target_fields", "=", "\", \"", ".", "join", "(", "targ...
39.962963
0.001357
def remember_identity(self, subject, authc_token, account_id): """ Yosai consolidates rememberIdentity, an overloaded method in java, to a method that will use an identifier-else-account logic. Remembers a subject-unique identity for retrieval later. This implementation first r...
[ "def", "remember_identity", "(", "self", ",", "subject", ",", "authc_token", ",", "account_id", ")", ":", "try", ":", "identifiers", "=", "self", ".", "get_identity_to_remember", "(", "subject", ",", "account_id", ")", "except", "AttributeError", ":", "msg", "...
50.363636
0.001771
def send_static_message(sender, message): """Send a static message to the listeners. Static messages represents a whole new message. Usually it will replace the previous message. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich...
[ "def", "send_static_message", "(", "sender", ",", "message", ")", ":", "dispatcher", ".", "send", "(", "signal", "=", "STATIC_MESSAGE_SIGNAL", ",", "sender", "=", "sender", ",", "message", "=", "message", ")" ]
25
0.002028
def get_zone(server, token, domain, keyword='', raw_flag=False): """Retrieve zone records. Argument: server: TonicDNS API server token: TonicDNS API authentication token domain: Specify domain name keyword: Search keyword x-authentication-token: token """ metho...
[ "def", "get_zone", "(", "server", ",", "token", ",", "domain", ",", "keyword", "=", "''", ",", "raw_flag", "=", "False", ")", ":", "method", "=", "'GET'", "uri", "=", "'https://'", "+", "server", "+", "'/zone/'", "+", "domain", "data", "=", "connect", ...
30.411765
0.001876
def _store_work_results(self, results, collection, md5): """ Internal: Stores the work results of a worker.""" self.data_store.store_work_results(results, collection, md5)
[ "def", "_store_work_results", "(", "self", ",", "results", ",", "collection", ",", "md5", ")", ":", "self", ".", "data_store", ".", "store_work_results", "(", "results", ",", "collection", ",", "md5", ")" ]
61.666667
0.010695
def validate(name, re=None, convert=None, doc=None): """Decorator. Apply on a :class:`wsgiservice.Resource` or any of it's methods to validates a parameter on input. When a parameter does not validate, a :class:`wsgiservice.exceptions.ValidationException` exception will be thrown. :param name: Name...
[ "def", "validate", "(", "name", ",", "re", "=", "None", ",", "convert", "=", "None", ",", "doc", "=", "None", ")", ":", "def", "wrap", "(", "cls_or_func", ")", ":", "if", "not", "hasattr", "(", "cls_or_func", ",", "'_validations'", ")", ":", "cls_or_...
46.884615
0.001608
def precision(y, y_pred): """Precision score precision = true_positives / (true_positives + false_positives) Parameters: ----------- y : vector, shape (n_samples,) The target labels. y_pred : vector, shape (n_samples,) The predicted labels. Returns: -------- preci...
[ "def", "precision", "(", "y", ",", "y_pred", ")", ":", "tp", "=", "true_positives", "(", "y", ",", "y_pred", ")", "fp", "=", "false_positives", "(", "y", ",", "y_pred", ")", "return", "tp", "/", "(", "tp", "+", "fp", ")" ]
19.227273
0.011261
def db_connect(engine, schema=None, clobber=False): """Create a connection object to a database. Attempt to establish a schema. If there are existing tables, delete them if clobber is True and return otherwise. Returns a sqlalchemy engine object. """ if schema is None: base = declarative_b...
[ "def", "db_connect", "(", "engine", ",", "schema", "=", "None", ",", "clobber", "=", "False", ")", ":", "if", "schema", "is", "None", ":", "base", "=", "declarative_base", "(", ")", "else", ":", "try", ":", "engine", ".", "execute", "(", "sqlalchemy", ...
30.115385
0.001238
def get_art(cache_dir, size, client): """Get the album art.""" song = client.currentsong() if len(song) < 2: print("album: Nothing currently playing.") return file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "") file_name = cache_dir / file_name if file_...
[ "def", "get_art", "(", "cache_dir", ",", "size", ",", "client", ")", ":", "song", "=", "client", ".", "currentsong", "(", ")", "if", "len", "(", "song", ")", "<", "2", ":", "print", "(", "\"album: Nothing currently playing.\"", ")", "return", "file_name", ...
29.961538
0.001244
def groupby(df, *, group_cols: Union[str, List[str]], aggregations: Dict[str, Union[str, List[str]]]): """ Aggregate values by groups. --- ### Parameters *mandatory :* - `group_cols` (*list*): list of columns used to group data - `aggregations` (*dict*): dictionnary of values ...
[ "def", "groupby", "(", "df", ",", "*", ",", "group_cols", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "aggregations", ":", "Dict", "[", "str", ",", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "]", ")", ":", "...
30.532258
0.001024
def delims(self, delims): """Set the delimiters for line splitting.""" expr = '[' + ''.join('\\'+ c for c in delims) + ']' self._delim_re = re.compile(expr) self._delims = delims self._delim_expr = expr
[ "def", "delims", "(", "self", ",", "delims", ")", ":", "expr", "=", "'['", "+", "''", ".", "join", "(", "'\\\\'", "+", "c", "for", "c", "in", "delims", ")", "+", "']'", "self", ".", "_delim_re", "=", "re", ".", "compile", "(", "expr", ")", "sel...
39.5
0.012397
def geometry_from_json(obj): '''try to find a geometry in the provided JSON object''' obj_type = obj.get('type', None) if not obj_type: return None if obj_type == 'FeatureCollection': features = obj.get('features', []) if len(features): obj = obj['features'][0] ...
[ "def", "geometry_from_json", "(", "obj", ")", ":", "obj_type", "=", "obj", ".", "get", "(", "'type'", ",", "None", ")", "if", "not", "obj_type", ":", "return", "None", "if", "obj_type", "==", "'FeatureCollection'", ":", "features", "=", "obj", ".", "get"...
30.526316
0.001672