Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
75
104k
code_tokens
sequence
avg_line_len
float64
7.91
980
score
float64
0
0.18
def from_fortran_file(cls, fortran_file: str, tmpdir: str = "."): """Builds GrFN object from a Fortran program.""" stem = Path(fortran_file).stem if tmpdir == "." and "/" in fortran_file: tmpdir = Path(fortran_file).parent preprocessed_fortran_file = f"{tmpdir}/{stem}_preproc...
[ "def", "from_fortran_file", "(", "cls", ",", "fortran_file", ":", "str", ",", "tmpdir", ":", "str", "=", "\".\"", ")", ":", "stem", "=", "Path", "(", "fortran_file", ")", ".", "stem", "if", "tmpdir", "==", "\".\"", "and", "\"/\"", "in", "fortran_file", ...
38.055556
0.001423
def get_serializer(context): """Returns a serializer for a given context""" cluster_config = context.get_cluster_config() serializer_clsname = cluster_config.get(constants.TOPOLOGY_SERIALIZER_CLASSNAME, None) if serializer_clsname is None: return PythonSerializer() else: try: top...
[ "def", "get_serializer", "(", "context", ")", ":", "cluster_config", "=", "context", ".", "get_cluster_config", "(", ")", "serializer_clsname", "=", "cluster_config", ".", "get", "(", "constants", ".", "TOPOLOGY_SERIALIZER_CLASSNAME", ",", "None", ")", "if", "seri...
46
0.009321
def reset_parameter(**kwargs): """Create a callback that resets the parameter after the first iteration. Note ---- The initial parameter will still take in-effect on first iteration. Parameters ---------- **kwargs : value should be list or function List of parameters for each boost...
[ "def", "reset_parameter", "(", "*", "*", "kwargs", ")", ":", "def", "_callback", "(", "env", ")", ":", "new_parameters", "=", "{", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "key", "in", "[", "'num_class'", ...
41.023256
0.001661
def _filter(self, filename): """ return 'true' if filename doesn't match name_filter regex and should be filtered out of the list. @param filename: @return: """ return self.name_filter is not None and re.search(self.name_filter, filename) is None
[ "def", "_filter", "(", "self", ",", "filename", ")", ":", "return", "self", ".", "name_filter", "is", "not", "None", "and", "re", ".", "search", "(", "self", ".", "name_filter", ",", "filename", ")", "is", "None" ]
41.142857
0.013605
def load_source(source): """ Common entry point for loading some form of raw swagger schema. Supports: - python object (dictionary-like) - path to yaml file - path to json file - file object (json or yaml). - json string. - yaml string. """ if isinsta...
[ "def", "load_source", "(", "source", ")", ":", "if", "isinstance", "(", "source", ",", "collections", ".", "Mapping", ")", ":", "return", "deepcopy", "(", "source", ")", "elif", "hasattr", "(", "source", ",", "'read'", ")", "and", "callable", "(", "sourc...
30.978261
0.00068
def metric(self, slug, num=1, category=None, expire=None, date=None): """Records a metric, creating it if it doesn't exist or incrementing it if it does. All metrics are prefixed with 'm', and automatically aggregate for Seconds, Minutes, Hours, Day, Week, Month, and Year. Parameters: ...
[ "def", "metric", "(", "self", ",", "slug", ",", "num", "=", "1", ",", "category", "=", "None", ",", "expire", "=", "None", ",", "date", "=", "None", ")", ":", "# Add the slug to the set of metric slugs", "self", ".", "r", ".", "sadd", "(", "self", ".",...
42.886364
0.001036
def weather_from_dictionary(d): """ Builds a *Weather* object out of a data dictionary. Only certain properties of the dictionary are used: if these properties are not found or cannot be read, an error is issued. :param d: a data dictionary :type d: dict :returns: a *Weather* instance :...
[ "def", "weather_from_dictionary", "(", "d", ")", ":", "# -- times", "if", "'dt'", "in", "d", ":", "reference_time", "=", "d", "[", "'dt'", "]", "elif", "'dt'", "in", "d", "[", "'last'", "]", ":", "reference_time", "=", "d", "[", "'last'", "]", "[", "...
31.874346
0.000796
def run(self, agent_host): """run the agent on the world""" total_reward = 0 current_r = 0 tol = 0.01 self.prev_s = None self.prev_a = None # wait for a valid observation world_state = agent_host.peekWorldState() while world_stat...
[ "def", "run", "(", "self", ",", "agent_host", ")", ":", "total_reward", "=", "0", "current_r", "=", "0", "tol", "=", "0.01", "self", ".", "prev_s", "=", "None", "self", ".", "prev_a", "=", "None", "# wait for a valid observation", "world_state", "=", "agen...
47.090909
0.014337
def autodiscover(module_name=None): """ Autodiscover INSTALLED_APPS perms.py modules and fail silently when not present. This forces an import on them to register any permissions bits they may want. """ from django.utils.module_loading import module_has_submodule from permission.compat impor...
[ "def", "autodiscover", "(", "module_name", "=", "None", ")", ":", "from", "django", ".", "utils", ".", "module_loading", "import", "module_has_submodule", "from", "permission", ".", "compat", "import", "import_module", "from", "permission", ".", "conf", "import", ...
41
0.001907
def json2py(json_obj): """ Converts the inputted JSON object to a python value. :param json_obj | <variant> """ for key, value in json_obj.items(): if type(value) not in (str, unicode): continue # restore a datetime if re.match('^\d{4}-\d{2}-\d{2} \d{2}...
[ "def", "json2py", "(", "json_obj", ")", ":", "for", "key", ",", "value", "in", "json_obj", ".", "items", "(", ")", ":", "if", "type", "(", "value", ")", "not", "in", "(", "str", ",", "unicode", ")", ":", "continue", "# restore a datetime", "if", "re"...
33.424242
0.014097
def join_multiline_pairs(source, pair="()"): """ Finds and removes newlines in multiline matching pairs of characters in *source*. By default it joins parens () but it will join any two characters given via the *pair* variable. .. note:: Doesn't remove extraneous whitespace that ends ...
[ "def", "join_multiline_pairs", "(", "source", ",", "pair", "=", "\"()\"", ")", ":", "opener", "=", "pair", "[", "0", "]", "closer", "=", "pair", "[", "1", "]", "io_obj", "=", "io", ".", "StringIO", "(", "source", ")", "out_tokens", "=", "[", "]", "...
28.613636
0.001536
def do_watch(self, params): """ \x1b[1mNAME\x1b[0m watch - Recursively watch for all changes under a path. \x1b[1mSYNOPSIS\x1b[0m watch <start|stop|stats> <path> [options] \x1b[1mDESCRIPTION\x1b[0m watch start <path> [debug] [depth] with debug=true, print watches as they fire....
[ "def", "do_watch", "(", "self", ",", "params", ")", ":", "wm", "=", "get_watch_manager", "(", "self", ".", "_zk", ")", "if", "params", ".", "command", "==", "\"start\"", ":", "debug", "=", "to_bool", "(", "params", ".", "debug", ")", "children", "=", ...
31.254902
0.001217
def from_archive(cls, archive: Archive, predictor_name: str = None) -> 'Predictor': """ Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`; that is, from the result of training a model. Optionally specify which `Predictor` subclass; otherwise, the default...
[ "def", "from_archive", "(", "cls", ",", "archive", ":", "Archive", ",", "predictor_name", ":", "str", "=", "None", ")", "->", "'Predictor'", ":", "# Duplicate the config so that the config inside the archive doesn't get consumed", "config", "=", "archive", ".", "config"...
48.521739
0.008787
def block(context_name, parent_block_func, view_func=None): """A decorator that is used for inserting the decorated block function in the block template hierarchy. The :func:`block` decorator accepts the following arguments: :param context_name: key in the `g.blocks` dictionary in which the result ...
[ "def", "block", "(", "context_name", ",", "parent_block_func", ",", "view_func", "=", "None", ")", ":", "def", "decorator", "(", "block_func", ")", ":", "block", "=", "Block", "(", "block_func", ",", "view_func", ")", "parent_block", "=", "Block", ".", "bl...
53.307692
0.000709
def keys(self): """Create an ordered dict of the names and values of key fields.""" keys = OrderedDict() def order_key(_): (k, v) = _ cache_key = getattr(type(self), k) return cache_key.order items = [(k, getattr(type(self), k)) for k in...
[ "def", "keys", "(", "self", ")", ":", "keys", "=", "OrderedDict", "(", ")", "def", "order_key", "(", "_", ")", ":", "(", "k", ",", "v", ")", "=", "_", "cache_key", "=", "getattr", "(", "type", "(", "self", ")", ",", "k", ")", "return", "cache_k...
25.52381
0.01259
def update(self, points, pointvol=0., vol_dec=0.5, vol_check=2., rstate=None, bootstrap=0, pool=None, mc_integrate=False): """ Update the set of ellipsoids to bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim...
[ "def", "update", "(", "self", ",", "points", ",", "pointvol", "=", "0.", ",", "vol_dec", "=", "0.5", ",", "vol_check", "=", "2.", ",", "rstate", "=", "None", ",", "bootstrap", "=", "0", ",", "pool", "=", "None", ",", "mc_integrate", "=", "False", "...
39.07619
0.000713
def get(self, name, return_json=False, quiet=False): '''get is a list for a single instance. It is assumed to be running, and we need to look up the PID, etc. ''' from spython.utils import check_install check_install() # Ensure compatible for singularity prior to 3.0, and after 3.0 subgr...
[ "def", "get", "(", "self", ",", "name", ",", "return_json", "=", "False", ",", "quiet", "=", "False", ")", ":", "from", "spython", ".", "utils", "import", "check_install", "check_install", "(", ")", "# Ensure compatible for singularity prior to 3.0, and after 3.0", ...
28.473684
0.002382
def removed(name, updates=None): ''' Ensure Microsoft Updates are uninstalled. Args: name (str): The identifier of a single update to uninstall. updates (list): A list of identifiers for updates to be removed. Overrides ``name``. Default is None. ....
[ "def", "removed", "(", "name", ",", "updates", "=", "None", ")", ":", "if", "isinstance", "(", "updates", ",", "six", ".", "string_types", ")", ":", "updates", "=", "[", "updates", "]", "if", "not", "updates", ":", "updates", "=", "name", "ret", "=",...
28.52459
0.000833
def alter_edge(self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None): """ Alters either the weight or the edge_properties of an edge in the StructureGraph. :param from_index: int :param to_index: int :param to_jimage: t...
[ "def", "alter_edge", "(", "self", ",", "from_index", ",", "to_index", ",", "to_jimage", "=", "None", ",", "new_weight", "=", "None", ",", "new_edge_properties", "=", "None", ")", ":", "existing_edges", "=", "self", ".", "graph", ".", "get_edge_data", "(", ...
40.5
0.002296
def render_registration(self): ''' Render pinned points on video frame as red rectangle. ''' surface = self.get_surface() if self.canvas is None or self.df_canvas_corners.shape[0] == 0: return surface corners = self.df_canvas_corners.copy() corners['w...
[ "def", "render_registration", "(", "self", ")", ":", "surface", "=", "self", ".", "get_surface", "(", ")", "if", "self", ".", "canvas", "is", "None", "or", "self", ".", "df_canvas_corners", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "surfac...
34.24
0.002273
def completed_number(prefix, length): """ 'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number to generate. Typically 13 or 16 """ ccnumber = prefix # generate digits while len(ccnumber) < (length - 1): digit = random.choic...
[ "def", "completed_number", "(", "prefix", ",", "length", ")", ":", "ccnumber", "=", "prefix", "# generate digits", "while", "len", "(", "ccnumber", ")", "<", "(", "length", "-", "1", ")", ":", "digit", "=", "random", ".", "choice", "(", "[", "'0'", ","...
32.25
0.009677
def get_field_info(wrapper,entity_type): 'type: wrapper :atws.Wrapper' fields = wrapper.new('GetFieldInfo') fields.psObjectType = entity_type return wrapper.GetFieldInfo(fields)
[ "def", "get_field_info", "(", "wrapper", ",", "entity_type", ")", ":", "fields", "=", "wrapper", ".", "new", "(", "'GetFieldInfo'", ")", "fields", ".", "psObjectType", "=", "entity_type", "return", "wrapper", ".", "GetFieldInfo", "(", "fields", ")" ]
37.8
0.010363
def graph_from_seeds(seeds, cell_source): """ This creates/updates a networkx graph from a list of cells. The graph is created when the cell_source is an instance of ExcelCompiler The graph is updated when the cell_source is an instance of Spreadsheet """ # when called from Spreadsheet instanc...
[ "def", "graph_from_seeds", "(", "seeds", ",", "cell_source", ")", ":", "# when called from Spreadsheet instance, use the Spreadsheet cellmap and graph", "if", "hasattr", "(", "cell_source", ",", "'G'", ")", ":", "# ~ cell_source is a Spreadsheet", "cellmap", "=", "cell_source...
43.918552
0.008966
def port(alias_name, default=None, allow_none=False): """Get the port from the docker link alias or return the default. Args: alias_name: The docker link alias default: The default value if the link isn't available allow_none: If the return value can be `None` (i.e. optional) Examp...
[ "def", "port", "(", "alias_name", ",", "default", "=", "None", ",", "allow_none", "=", "False", ")", ":", "warnings", ".", "warn", "(", "'Will be removed in v1.0'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "try", ":", "return", "int", "...
34.478261
0.002454
def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, six.integer_types) return str(value).encode("utf_8")
[ "def", "value_to_db", "(", "self", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "six", ".", "integer_types", ")", "return", "str", "(", "value", ")", ".", "encode", "(", "\"utf_8\"", ")" ]
50.5
0.014634
def get(self, sid): """ Constructs a OriginationUrlContext :param sid: The unique string that identifies the resource :returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext :rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlContext ...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "OriginationUrlContext", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "'trunk_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
41.8
0.01171
def from_header(self, header): """Generate a SpanContext object using the trace context header. The value of enabled parsed from header is int. Need to convert to bool. :type header: str :param header: Trace context header which was extracted from the HTTP ...
[ "def", "from_header", "(", "self", ",", "header", ")", ":", "if", "header", "is", "None", ":", "return", "SpanContext", "(", ")", "try", ":", "match", "=", "re", ".", "search", "(", "_TRACE_CONTEXT_HEADER_RE", ",", "header", ")", "except", "TypeError", "...
33.690476
0.001374
def apply_multicolor_transit(self,band,depth): """ Applies constraint corresponding to measuring transit in different band This is not implemented yet. """ if '{} band transit'.format(band) not in self.constraints: self.constraints.append('{} band transit'.format(ban...
[ "def", "apply_multicolor_transit", "(", "self", ",", "band", ",", "depth", ")", ":", "if", "'{} band transit'", ".", "format", "(", "band", ")", "not", "in", "self", ".", "constraints", ":", "self", ".", "constraints", ".", "append", "(", "'{} band transit'"...
40
0.012225
def add_view( self, baseview, name, href="", icon="", label="", category="", category_icon="", category_label="", ): """ Add your views associated with menus using this method. :param baseview: A BaseView ty...
[ "def", "add_view", "(", "self", ",", "baseview", ",", "name", ",", "href", "=", "\"\"", ",", "icon", "=", "\"\"", ",", "label", "=", "\"\"", ",", "category", "=", "\"\"", ",", "category_icon", "=", "\"\"", ",", "category_label", "=", "\"\"", ",", ")"...
34.858824
0.001969
def do_some_work( self, work_dict): """do_some_work :param work_dict: dictionary for key/values """ label = "do_some_work" log.info(("task - {} - start " "work_dict={}") .format(label, work_dict)) ret_data = { "job_resul...
[ "def", "do_some_work", "(", "self", ",", "work_dict", ")", ":", "label", "=", "\"do_some_work\"", "log", ".", "info", "(", "(", "\"task - {} - start \"", "\"work_dict={}\"", ")", ".", "format", "(", "label", ",", "work_dict", ")", ")", "ret_data", "=", "{", ...
20.192308
0.001818
def active_vectors_info(self): """Return the active scalar's field and name: [field, name]""" if not hasattr(self, '_active_vectors_info'): self._active_vectors_info = [POINT_DATA_FIELD, None] # field and name _, name = self._active_vectors_info # rare error where scalar nam...
[ "def", "active_vectors_info", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_active_vectors_info'", ")", ":", "self", ".", "_active_vectors_info", "=", "[", "POINT_DATA_FIELD", ",", "None", "]", "# field and name", "_", ",", "name", "=", ...
40.666667
0.008016
def prepare_lineage(func): """ Prepares the lineage inlets and outlets. Inlets can be: * "auto" -> picks up any outlets from direct upstream tasks that have outlets defined, as such that if A -> B -> C and B does not have outlets but A does, these are provided as inlets. * "list of task_ids" -> p...
[ "def", "prepare_lineage", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "context", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Preparing lineage inlets and ...
39.75
0.002192
def pixel_scale_angle_at_skycoord(skycoord, wcs, offset=1. * u.arcsec): """ Calculate the pixel scale and WCS rotation angle at the position of a SkyCoord coordinate. Parameters ---------- skycoord : `~astropy.coordinates.SkyCoord` The SkyCoord coordinate. wcs : `~astropy.wcs.WCS` ...
[ "def", "pixel_scale_angle_at_skycoord", "(", "skycoord", ",", "wcs", ",", "offset", "=", "1.", "*", "u", ".", "arcsec", ")", ":", "# We take a point directly \"above\" (in latitude) the input position", "# and convert it to pixel coordinates, then we use the pixel deltas", "# bet...
35.981481
0.000501
def som_simulate(som_pointer, pattern): """! @brief Processes input pattern (no learining) and returns index of neuron-winner. @details Using index of neuron winner catched object can be obtained using property capture_objects. @param[in] som_pointer (c_pointer): pointer to object of self-orga...
[ "def", "som_simulate", "(", "som_pointer", ",", "pattern", ")", ":", "pointer_data", "=", "package_builder", "(", "pattern", ",", "c_double", ")", ".", "create", "(", ")", "ccore", "=", "ccore_library", ".", "get", "(", ")", "ccore", ".", "som_simulate", "...
37.470588
0.013783
def bb_pad_collate(samples:BatchSamples, pad_idx:int=0) -> Tuple[FloatTensor, Tuple[LongTensor, LongTensor]]: "Function that collect `samples` of labelled bboxes and adds padding with `pad_idx`." if isinstance(samples[0][1], int): return data_collate(samples) max_len = max([len(s[1].data[1]) for s in sample...
[ "def", "bb_pad_collate", "(", "samples", ":", "BatchSamples", ",", "pad_idx", ":", "int", "=", "0", ")", "->", "Tuple", "[", "FloatTensor", ",", "Tuple", "[", "LongTensor", ",", "LongTensor", "]", "]", ":", "if", "isinstance", "(", "samples", "[", "0", ...
51.071429
0.017857
def gen_search_article_url(keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None): """拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 ...
[ "def", "gen_search_article_url", "(", "keyword", ",", "page", "=", "1", ",", "timesn", "=", "WechatSogouConst", ".", "search_article_time", ".", "anytime", ",", "article_type", "=", "WechatSogouConst", ".", "search_article_type", ".", "all", ",", "ft", "=", "Non...
39.128571
0.002493
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: di...
[ "def", "querypath", "(", "self", ",", "block", ",", "path", ")", ":", "class", "BadPath", "(", "Exception", ")", ":", "\"\"\"Bad path exception thrown when path cannot be found.\"\"\"", "pass", "results", "=", "self", ".", "query", "(", "block", ")", "ROOT", ","...
35.612903
0.001322
def to_string(self, style=None, utcoffset=None): """Return a |str| object representing the actual date in accordance with the given style and the eventually given UTC offset (in minutes). Without any input arguments, the actual |Date.style| is used to return a date string in you...
[ "def", "to_string", "(", "self", ",", "style", "=", "None", ",", "utcoffset", "=", "None", ")", ":", "if", "not", "style", ":", "style", "=", "self", ".", "style", "if", "utcoffset", "is", "None", ":", "string", "=", "''", "date", "=", "self", ".",...
34.44898
0.001152
def convert_double_to_two_registers(doubleValue): """ Convert 32 Bit Value to two 16 Bit Value to send as Modbus Registers doubleValue: Value to be converted return: 16 Bit Register values int[] """ myList = list() myList.append(int(doubleValue & 0x0000FFFF)) #Append Least Signific...
[ "def", "convert_double_to_two_registers", "(", "doubleValue", ")", ":", "myList", "=", "list", "(", ")", "myList", ".", "append", "(", "int", "(", "doubleValue", "&", "0x0000FFFF", ")", ")", "#Append Least Significant Word ", "myList", ".", "append", "(", "...
43.6
0.020225
def delete_group_dampening(self, group_id, dampening_id): """ Delete an existing group dampening :param group_id: Group Trigger id to be retrieved :param dampening_id: id of the Dampening to be deleted """ self._delete(self._service_url(['triggers', 'groups', group_id, '...
[ "def", "delete_group_dampening", "(", "self", ",", "group_id", ",", "dampening_id", ")", ":", "self", ".", "_delete", "(", "self", ".", "_service_url", "(", "[", "'triggers'", ",", "'groups'", ",", "group_id", ",", "'dampenings'", ",", "dampening_id", "]", "...
42.625
0.008621
def find_matching(cls, message, channel): """ Yield ``cls`` subclasses that match message and channel """ return ( handler for handler in cls._registry if isinstance(handler, cls) and handler.match(message, channel) )
[ "def", "find_matching", "(", "cls", ",", "message", ",", "channel", ")", ":", "return", "(", "handler", "for", "handler", "in", "cls", ".", "_registry", "if", "isinstance", "(", "handler", ",", "cls", ")", "and", "handler", ".", "match", "(", "message", ...
23
0.046025
def create_event_hub(self, hub_name, hub=None, fail_on_exist=False): ''' Creates a new Event Hub. hub_name: Name of event hub. hub: Optional. Event hub properties. Instance of EventHub class. hub.message_retention_in_days: Number of days to re...
[ "def", "create_event_hub", "(", "self", ",", "hub_name", ",", "hub", "=", "None", ",", "fail_on_exist", "=", "False", ")", ":", "_validate_not_none", "(", "'hub_name'", ",", "hub_name", ")", "request", "=", "HTTPRequest", "(", ")", "request", ".", "method", ...
38.918919
0.002033
def get_url_file_name(url): """Get the file name from an url Parameters ---------- url : str Returns ------- str The file name """ assert isinstance(url, (str, _oldstr)) return urlparse.urlparse(url).path.split('/')[-1]
[ "def", "get_url_file_name", "(", "url", ")", ":", "assert", "isinstance", "(", "url", ",", "(", "str", ",", "_oldstr", ")", ")", "return", "urlparse", ".", "urlparse", "(", "url", ")", ".", "path", ".", "split", "(", "'/'", ")", "[", "-", "1", "]" ...
17.4
0.010909
async def api_call(self, verb, action, params=None, add_authorization_token=True, retry=False): """Send api call.""" if add_authorization_token and not self.token: await self.refresh_token() try: return await self._api_call_impl(verb, action, params, add_authorization_to...
[ "async", "def", "api_call", "(", "self", ",", "verb", ",", "action", ",", "params", "=", "None", ",", "add_authorization_token", "=", "True", ",", "retry", "=", "False", ")", ":", "if", "add_authorization_token", "and", "not", "self", ".", "token", ":", ...
45.923077
0.00821
def georadius(self, key, longitude, latitude, radius, unit='m', *, with_dist=False, with_hash=False, with_coord=False, count=None, sort=None, encoding=_NOTSET): """Query a sorted set representing a geospatial index to fetch members matching a given maximum distance fr...
[ "def", "georadius", "(", "self", ",", "key", ",", "longitude", ",", "latitude", ",", "radius", ",", "unit", "=", "'m'", ",", "*", ",", "with_dist", "=", "False", ",", "with_hash", "=", "False", ",", "with_coord", "=", "False", ",", "count", "=", "Non...
41.97561
0.002271
def bz2_compress_stream(src, level=9): """Compress data from `src`. Args: src (iterable): iterable that yields blocks of data to compress level (int): compression level (1-9) default is 9 Yields: blocks of compressed data """ compressor = bz2.BZ2Compressor(level) for b...
[ "def", "bz2_compress_stream", "(", "src", ",", "level", "=", "9", ")", ":", "compressor", "=", "bz2", ".", "BZ2Compressor", "(", "level", ")", "for", "block", "in", "src", ":", "encoded", "=", "compressor", ".", "compress", "(", "block", ")", "if", "en...
25.647059
0.002212
def on(self, *args): """ If no arguments are specified, turn all the LEDs on. If arguments are specified, they must be the indexes of the LEDs you wish to turn on. For example:: from gpiozero import LEDBoard leds = LEDBoard(2, 3, 4, 5) leds.on(0) ...
[ "def", "on", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_stop_blink", "(", ")", "if", "args", ":", "for", "index", "in", "args", ":", "self", "[", "index", "]", ".", "on", "(", ")", "else", ":", "super", "(", "LEDBoard", ",", "self"...
34.148148
0.00211
def get_querydict(self): """ 这个函数跟 self.method有关 self.method 暂时没用, querydict都是POST的 """ if self.method: querydict = getattr(self.request, self.method.upper()) else: querydict = getattr(self.request, 'POST'.upper()) # copy make querydict ...
[ "def", "get_querydict", "(", "self", ")", ":", "if", "self", ".", "method", ":", "querydict", "=", "getattr", "(", "self", ".", "request", ",", "self", ".", "method", ".", "upper", "(", ")", ")", "else", ":", "querydict", "=", "getattr", "(", "self",...
29.846154
0.015
def makevFunc(self,solution): ''' Creates the value function for this period, defined over market resources m and persistent income p. self must have the attribute EndOfPrdvFunc in order to execute. Parameters ---------- solution : ConsumerSolution T...
[ "def", "makevFunc", "(", "self", ",", "solution", ")", ":", "mSize", "=", "self", ".", "aXtraGrid", ".", "size", "pSize", "=", "self", ".", "pLvlGrid", ".", "size", "# Compute expected value and marginal value on a grid of market resources", "pLvl_temp", "=", "np", ...
49.946429
0.028401
def get_deploy_data(self): ''' Gets any default data attached to the current deploy, if any. ''' if self.state and self.state.deploy_data: return self.state.deploy_data return {}
[ "def", "get_deploy_data", "(", "self", ")", ":", "if", "self", ".", "state", "and", "self", ".", "state", ".", "deploy_data", ":", "return", "self", ".", "state", ".", "deploy_data", "return", "{", "}" ]
24.888889
0.008621
def _seconds_as_string(seconds): """ Returns seconds as a human-friendly string, e.g. '1d 4h 47m 41s' """ TIME_UNITS = [('s', 60), ('m', 60), ('h', 24), ('d', None)] unit_strings = [] cur = max(int(seconds), 1) for suffix, size in TIME_UNITS: if size is not None: cur, res...
[ "def", "_seconds_as_string", "(", "seconds", ")", ":", "TIME_UNITS", "=", "[", "(", "'s'", ",", "60", ")", ",", "(", "'m'", ",", "60", ")", ",", "(", "'h'", ",", "24", ")", ",", "(", "'d'", ",", "None", ")", "]", "unit_strings", "=", "[", "]", ...
31.933333
0.002028
def _get_branches(self): """Get branches from org/repo.""" if self.offline: local_path = Path(LOCAL_PATH).expanduser() / self.org / self.repo get_refs = f"git -C {shlex.quote(str(local_path))} show-ref --heads" else: get_refs = f"git ls-remote --heads https://...
[ "def", "_get_branches", "(", "self", ")", ":", "if", "self", ".", "offline", ":", "local_path", "=", "Path", "(", "LOCAL_PATH", ")", ".", "expanduser", "(", ")", "/", "self", ".", "org", "/", "self", ".", "repo", "get_refs", "=", "f\"git -C {shlex.quote(...
48.166667
0.008489
def partitions(collection): """Generate all set partitions of a collection. Example: >>> list(partitions(range(3))) # doctest: +NORMALIZE_WHITESPACE [[[0, 1, 2]], [[0], [1, 2]], [[0, 1], [2]], [[1], [0, 2]], [[0], [1], [2]]] """ collection = list(col...
[ "def", "partitions", "(", "collection", ")", ":", "collection", "=", "list", "(", "collection", ")", "# Special cases", "if", "not", "collection", ":", "return", "if", "len", "(", "collection", ")", "==", "1", ":", "yield", "[", "collection", "]", "return"...
25.153846
0.001473
def write(self, filehandle, file_format): """Write :class:`~ctfile.ctfile.CTfile` data into file. :param filehandle: File-like object. :param str file_format: Format to use to write data: ``ctfile`` or ``json``. :return: None. :rtype: :py:obj:`None`. """ try: ...
[ "def", "write", "(", "self", ",", "filehandle", ",", "file_format", ")", ":", "try", ":", "filehandle", ".", "write", "(", "self", ".", "writestr", "(", "file_format", "=", "file_format", ")", ")", "except", "IOError", ":", "raise", "IOError", "(", "'\"f...
39.083333
0.008333
def find_vlans( self, number, name, iexact, environment, net_type, network, ip_version, subnet, acl, pagination): """ Find vlans by all search parameters :param nu...
[ "def", "find_vlans", "(", "self", ",", "number", ",", "name", ",", "iexact", ",", "environment", ",", "net_type", ",", "network", ",", "ip_version", ",", "subnet", ",", "acl", ",", "pagination", ")", ":", "if", "not", "isinstance", "(", "pagination", ","...
34.765432
0.001036
def _finite_well_energy(P, n=1, atol=1e-6): ''' Returns the nth bound-state energy for a finite-potential quantum well with the given well-strength parameter, `P`. ''' assert n > 0 and n <= _finite_well_states(P) pi_2 = pi / 2. r = (1 / (P + pi_2)) * (n * pi_2) eta = n * pi_2 - arcsin(r)...
[ "def", "_finite_well_energy", "(", "P", ",", "n", "=", "1", ",", "atol", "=", "1e-6", ")", ":", "assert", "n", ">", "0", "and", "n", "<=", "_finite_well_states", "(", "P", ")", "pi_2", "=", "pi", "/", "2.", "r", "=", "(", "1", "/", "(", "P", ...
32.882353
0.000869
def sample(problem, N, seed=None): """Generate model inputs using Latin hypercube sampling (LHS). Returns a NumPy matrix containing the model inputs generated by Latin hypercube sampling. The resulting matrix contains N rows and D columns, where D is the number of parameters. Parameters ...
[ "def", "sample", "(", "problem", ",", "N", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "D", "=", "problem", "[", "'num_vars'", "]", "result", "=", "np", ".", "zeros", "(", "[", "N",...
25.371429
0.001085
def sumMerge(dict1, dict2): """ Adds two dictionaries together, and merges into the first, dict1. Returns first dict. """ for key in dict2: dict1[key] = list(map(lambda a,b: a + b, dict1.get(key, [0,0,0,0]), dict2[key])) return dict1
[ "def", "sumMerge", "(", "dict1", ",", "dict2", ")", ":", "for", "key", "in", "dict2", ":", "dict1", "[", "key", "]", "=", "list", "(", "map", "(", "lambda", "a", ",", "b", ":", "a", "+", "b", ",", "dict1", ".", "get", "(", "key", ",", "[", ...
32.25
0.022642
def get_kapur_threshold(image, mask=None): """The Kapur, Sahoo, & Wong method of thresholding, adapted to log-space.""" cropped_image = np.array(image.flat) if mask is None else image[mask] if np.product(cropped_image.shape)<3: return 0 if np.min(cropped_image) == np.max(cropped_image): ...
[ "def", "get_kapur_threshold", "(", "image", ",", "mask", "=", "None", ")", ":", "cropped_image", "=", "np", ".", "array", "(", "image", ".", "flat", ")", "if", "mask", "is", "None", "else", "image", "[", "mask", "]", "if", "np", ".", "product", "(", ...
42.923077
0.008762
def describe(self, pid, vendorSpecific=None): """Note: If the server returns a status code other than 200 OK, a ServiceFailure will be raised, as this method is based on a HEAD request, which cannot carry exception information.""" response = self.describeResponse(pid, vendorSpecific=vend...
[ "def", "describe", "(", "self", ",", "pid", ",", "vendorSpecific", "=", "None", ")", ":", "response", "=", "self", ".", "describeResponse", "(", "pid", ",", "vendorSpecific", "=", "vendorSpecific", ")", "return", "self", ".", "_read_header_response", "(", "r...
63
0.010444
def is_valid_program(self,p): """checks whether program p makes a syntactically valid tree. checks that the accumulated program length is always greater than the accumulated arities, indicating that the appropriate number of arguments is alway present for functions. It then checks that ...
[ "def", "is_valid_program", "(", "self", ",", "p", ")", ":", "# print(\"p:\",p)", "arities", "=", "list", "(", "a", ".", "arity", "[", "a", ".", "in_type", "]", "for", "a", "in", "p", ")", "accu_arities", "=", "list", "(", "accumulate", "(", "arities", ...
51
0.009626
def send(self, command): """send function sends the command to the oxd server and recieves the response. Parameters: * **command (dict):** Dict representation of the JSON command string Returns: **response (dict):** The JSON response from the oxd Server as a dic...
[ "def", "send", "(", "self", ",", "command", ")", ":", "cmd", "=", "json", ".", "dumps", "(", "command", ")", "cmd", "=", "\"{:04d}\"", ".", "format", "(", "len", "(", "cmd", ")", ")", "+", "cmd", "msg_length", "=", "len", "(", "cmd", ")", "# make...
32.762712
0.002009
def is_active(self): """Determines whether this plugin is active. This plugin is active if any health pills information is present for any run. Returns: A boolean. Whether this plugin is active. """ return bool( self._grpc_port is not None and self._event_multiplexer and ...
[ "def", "is_active", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "_grpc_port", "is", "not", "None", "and", "self", ".", "_event_multiplexer", "and", "self", ".", "_event_multiplexer", ".", "PluginRunToTagToContent", "(", "constants", ".", "DEBUGG...
29.142857
0.002375
def present(name, ip, clean=False): # pylint: disable=C0103 ''' Ensures that the named host is present with the given ip name The host to assign an ip to ip The ip addr(s) to apply to the host. Can be a single IP or a list of IP addresses. clean : False Remove any...
[ "def", "present", "(", "name", ",", "ip", ",", "clean", "=", "False", ")", ":", "# pylint: disable=C0103", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", "if", "__opts__", "[", "'test'", "]", "e...
36.135417
0.001403
def set_training(model, mode): """ A context manager to temporarily set the training mode of 'model' to 'mode', resetting it when we exit the with-block. A no-op if mode is None. """ if mode is None: yield return old_mode = model.training if old_mode != mode: mod...
[ "def", "set_training", "(", "model", ",", "mode", ")", ":", "if", "mode", "is", "None", ":", "yield", "return", "old_mode", "=", "model", ".", "training", "if", "old_mode", "!=", "mode", ":", "model", ".", "train", "(", "mode", ")", "try", ":", "yiel...
24.529412
0.002309
def find_path(target, from_path=None, direction='both', depth_first=False): """ Finds a file or subdirectory from the given path, defaulting to a breadth-first search. :param target: str of file or subdirectory to be found :param from_path: str of path from which to search (defaults to relati...
[ "def", "find_path", "(", "target", ",", "from_path", "=", "None", ",", "direction", "=", "'both'", ",", "depth_first", "=", "False", ")", ":", "from_path", "=", "from_path", "if", "from_path", "else", "relative_path", "(", "''", ",", "2", ")", "if", "dir...
39.673913
0.000535
def run(self): """Run command.""" command = ['npm', 'install'] self.announce( 'Running command: %s' % str(command), level=INFO) subprocess.check_call(command)
[ "def", "run", "(", "self", ")", ":", "command", "=", "[", "'npm'", ",", "'install'", "]", "self", ".", "announce", "(", "'Running command: %s'", "%", "str", "(", "command", ")", ",", "level", "=", "INFO", ")", "subprocess", ".", "check_call", "(", "com...
29.714286
0.009346
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
8