text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def dump(node, annotate_fields=True, include_attributes=False, indent=" "): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation...
[ "def", "dump", "(", "node", ",", "annotate_fields", "=", "True", ",", "include_attributes", "=", "False", ",", "indent", "=", "\" \"", ")", ":", "def", "_format", "(", "node", ",", "level", "=", "0", ")", ":", "if", "isinstance", "(", "node", ",", "...
37.18
18.62
def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = ...
[ "def", "diskusage", "(", "path", ")", ":", "total_size", "=", "0", "seen", "=", "set", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "stat_structure", "=", "os", ".", "stat", "(", "path", ")", "ret", "=", "stat_structure"...
21.27027
22.783784
def ckinv(self,oo): """ check the value is date or not 檢查是否為日期格式 """ pattern = re.compile(r"[0-9]{2}/[0-9]{2}/[0-9]{2}") b = re.search(pattern, oo[0]) try: b.group() return True except: return False
[ "def", "ckinv", "(", "self", ",", "oo", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r\"[0-9]{2}/[0-9]{2}/[0-9]{2}\"", ")", "b", "=", "re", ".", "search", "(", "pattern", ",", "oo", "[", "0", "]", ")", "try", ":", "b", ".", "group", "(", ...
21.636364
17.909091
def _evolve(self, state, qargs=None): """Evolve a quantum state by the QuantumChannel. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Retu...
[ "def", "_evolve", "(", "self", ",", "state", ",", "qargs", "=", "None", ")", ":", "# If subsystem evolution we use the SuperOp representation", "if", "qargs", "is", "not", "None", ":", "return", "SuperOp", "(", "self", ")", ".", "_evolve", "(", "state", ",", ...
42.075
19.2
def guess_base_branch(): # type: (str) -> Optional[str, None] """ Try to guess the base branch for the current branch. Do not trust this guess. git makes it pretty much impossible to guess the base branch reliably so this function implements few heuristics that will work on most common use cases bu...
[ "def", "guess_base_branch", "(", ")", ":", "# type: (str) -> Optional[str, None]", "my_branch", "=", "current_branch", "(", "refresh", "=", "True", ")", ".", "name", "curr", "=", "latest_commit", "(", ")", "if", "len", "(", "curr", ".", "branches", ")", ">", ...
33.092593
17.925926
def fetch_events_async(self, issues, tag_name): """ Fetch events for all issues and add them to self.events :param list issues: all issues :param str tag_name: name of the tag to fetch events for :returns: Nothing """ if not issues: return issues ...
[ "def", "fetch_events_async", "(", "self", ",", "issues", ",", "tag_name", ")", ":", "if", "not", "issues", ":", "return", "issues", "max_simultaneous_requests", "=", "self", ".", "options", ".", "max_simultaneous_requests", "verbose", "=", "self", ".", "options"...
33.290909
16.018182
def enable(app_id, enabled=True): ''' Enable or disable an existing assistive access application. app_id The bundle ID or command to set assistive access status. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' ...
[ "def", "enable", "(", "app_id", ",", "enabled", "=", "True", ")", ":", "enable_str", "=", "'1'", "if", "enabled", "else", "'0'", "for", "a", "in", "_get_assistive_access", "(", ")", ":", "if", "app_id", "==", "a", "[", "0", "]", ":", "cmd", "=", "'...
29.609756
24.097561
def load_extra_vi_page_navigation_bindings(): """ Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them. """ registry = ConditionalRegistry(Registry(), ViMode()) handle = registry.add_binding handle(Keys.ControlF)(scroll_fo...
[ "def", "load_extra_vi_page_navigation_bindings", "(", ")", ":", "registry", "=", "ConditionalRegistry", "(", "Registry", "(", ")", ",", "ViMode", "(", ")", ")", "handle", "=", "registry", ".", "add_binding", "handle", "(", "Keys", ".", "ControlF", ")", "(", ...
35.944444
11.722222
def describe(self, percentiles=None, include=None, exclude=None): """ Generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``Da...
[ "def", "describe", "(", "self", ",", "percentiles", "=", "None", ",", "include", "=", "None", ",", "exclude", "=", "None", ")", ":", "if", "self", ".", "ndim", ">=", "3", ":", "msg", "=", "\"describe is not implemented on Panel objects.\"", "raise", "NotImpl...
36.924699
19.28012
def instantiate(self, parallel_envs, seed=0, preset='default') -> VecEnv: """ Create vectorized environments """ envs = DummyVecEnv([self._creation_function(i, seed, preset) for i in range(parallel_envs)]) if self.frame_history is not None: envs = VecFrameStack(envs, self.frame_hist...
[ "def", "instantiate", "(", "self", ",", "parallel_envs", ",", "seed", "=", "0", ",", "preset", "=", "'default'", ")", "->", "VecEnv", ":", "envs", "=", "DummyVecEnv", "(", "[", "self", ".", "_creation_function", "(", "i", ",", "seed", ",", "preset", ")...
42.25
26.75
def _rollback_handle(cls, connection): """On snowflake, rolling back the handle of an aborted session raises an exception. """ try: connection.handle.rollback() except snowflake.connector.errors.ProgrammingError as e: msg = dbt.compat.to_string(e) ...
[ "def", "_rollback_handle", "(", "cls", ",", "connection", ")", ":", "try", ":", "connection", ".", "handle", ".", "rollback", "(", ")", "except", "snowflake", ".", "connector", ".", "errors", ".", "ProgrammingError", "as", "e", ":", "msg", "=", "dbt", "....
37.8
10.6
def _makedirs(path): """ Create a base directory of the provided path and return None. :param path: A string containing a path to be deconstructed and basedir created. :return: None """ dirname, _ = os.path.split(path) try: os.makedirs(dirname) except OSError as exc: ...
[ "def", "_makedirs", "(", "path", ")", ":", "dirname", ",", "_", "=", "os", ".", "path", ".", "split", "(", "path", ")", "try", ":", "os", ".", "makedirs", "(", "dirname", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "=="...
24.0625
19.3125
def hist2d(self, da, **kwargs): """Make the two dimensional histogram Parameters ---------- da: xarray.DataArray The data source""" if self.value is None or self.value == 'counts': normed = False else: normed = True y = da.valu...
[ "def", "hist2d", "(", "self", ",", "da", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "value", "is", "None", "or", "self", ".", "value", "==", "'counts'", ":", "normed", "=", "False", "else", ":", "normed", "=", "True", "y", "=", "da", ...
31.555556
12.833333
def remove_members_in_score_range(self, min_score, max_score): ''' Remove members from the leaderboard in a given score range. @param min_score [float] Minimum score. @param max_score [float] Maximum score. ''' self.remove_members_in_score_range_in( self.lead...
[ "def", "remove_members_in_score_range", "(", "self", ",", "min_score", ",", "max_score", ")", ":", "self", ".", "remove_members_in_score_range_in", "(", "self", ".", "leaderboard_name", ",", "min_score", ",", "max_score", ")" ]
33.545455
19
def get_buffer(self, *args): ''' all args-->_cffi_backend.CDataOwn Must be a pointer or an array Returns-->buffer (if a SINGLE argument was provided) LIST of buffer (if a args was a tuple or list) ''' res = tuple([ self.buffer(x) for x in arg...
[ "def", "get_buffer", "(", "self", ",", "*", "args", ")", ":", "res", "=", "tuple", "(", "[", "self", ".", "buffer", "(", "x", ")", "for", "x", "in", "args", "]", ")", "if", "len", "(", "res", ")", "==", "0", ":", "return", "None", "elif", "le...
26.941176
18.352941
def cov_error(self, comp_cov, score_metric="frobenius"): """Computes the covariance error vs. comp_cov. May require self.path_ Parameters ---------- comp_cov : array-like, shape = (n_features, n_features) The precision to compare with. This should normal...
[ "def", "cov_error", "(", "self", ",", "comp_cov", ",", "score_metric", "=", "\"frobenius\"", ")", ":", "if", "not", "isinstance", "(", "self", ".", "precision_", ",", "list", ")", ":", "return", "_compute_error", "(", "comp_cov", ",", "self", ".", "covaria...
34.418182
20.909091
def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is...
[ "def", "get_home", "(", "self", ",", "home_id", "=", "None", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "if", "self", ".", "home", "and", "now", "<", "self", ".", "home_refresh_at", ":", "return", "self", ".", "home",...
26.642857
19.261905
def generate_single_simulation(self, x): """ Generate a single SSA simulation :param x: an integer to reset the random seed. If None, the initial random number generator is used :return: a list of :class:`~means.simulation.Trajectory` one per species in the problem :rtype: list[:...
[ "def", "generate_single_simulation", "(", "self", ",", "x", ")", ":", "#reset random seed", "if", "x", ":", "self", ".", "__rng", "=", "np", ".", "random", ".", "RandomState", "(", "x", ")", "# perform one stochastic simulation", "time_points", ",", "species_ove...
41.269231
23.5
def _premium(fn): """Premium decorator for APIs that require premium access level.""" @_functools.wraps(fn) def _fn(self, *args, **kwargs): if self._lite: raise RuntimeError('Premium API not available in lite access.') return fn(self, *args, **kwargs) ...
[ "def", "_premium", "(", "fn", ")", ":", "@", "_functools", ".", "wraps", "(", "fn", ")", "def", "_fn", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_lite", ":", "raise", "RuntimeError", "(", "'Premium API no...
40.875
14.25
def _call_timeout_handlers(self): """Call the timeout handlers due. :Return: (next_event_timeout, sources_handled) tuple. next_event_timeout is number of seconds until the next timeout event, sources_handled is number of handlers called. """ sources_handled = 0 ...
[ "def", "_call_timeout_handlers", "(", "self", ")", ":", "sources_handled", "=", "0", "now", "=", "time", ".", "time", "(", ")", "schedule", "=", "None", "while", "self", ".", "_timeout_handlers", ":", "schedule", ",", "handler", "=", "self", ".", "_timeout...
46.365854
17.97561
def query(self): """ Returns the query instance for this widget. :return <orb.Query> || <orb.QueryCompound> """ queryWidget = self.queryWidget() # check to see if there is an active container for this widget container = queryWidget.c...
[ "def", "query", "(", "self", ")", ":", "queryWidget", "=", "self", ".", "queryWidget", "(", ")", "# check to see if there is an active container for this widget\r", "container", "=", "queryWidget", ".", "containerFor", "(", "self", ")", "if", "container", ":", "retu...
31.964286
14.678571
def _Ep(self): """ Proton energy array in GeV """ return np.logspace( np.log10(self.Epmin.to("GeV").value), np.log10(self.Epmax.to("GeV").value), int(self.nEpd * (np.log10(self.Epmax / self.Epmin))), )
[ "def", "_Ep", "(", "self", ")", ":", "return", "np", ".", "logspace", "(", "np", ".", "log10", "(", "self", ".", "Epmin", ".", "to", "(", "\"GeV\"", ")", ".", "value", ")", ",", "np", ".", "log10", "(", "self", ".", "Epmax", ".", "to", "(", "...
32.75
14.125
def convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if isinstance(argument, str): if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) i...
[ "def", "convert", "(", "self", ",", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "str", ")", ":", "if", "argument", ".", "lower", "(", ")", "in", "[", "'true'", ",", "'t'", ",", "'1'", "]", ":", "return", "True", "elif", "argumen...
38.933333
19
def get_system_name(self, oid_system_name): """Get the short os name from the OS name OID string.""" short_system_name = None if oid_system_name == '': return short_system_name # Find the short name in the oid_to_short_os_name dict for r, v in iteritems(oid_to_short...
[ "def", "get_system_name", "(", "self", ",", "oid_system_name", ")", ":", "short_system_name", "=", "None", "if", "oid_system_name", "==", "''", ":", "return", "short_system_name", "# Find the short name in the oid_to_short_os_name dict", "for", "r", ",", "v", "in", "i...
32.928571
15.357143
def maximum_syscall_number(self, abi): """ :param abi: The abi to evaluate :return: The largest syscall number known for the given abi """ if abi not in self.syscall_number_mapping or \ not self.syscall_number_mapping[abi]: return 0 return m...
[ "def", "maximum_syscall_number", "(", "self", ",", "abi", ")", ":", "if", "abi", "not", "in", "self", ".", "syscall_number_mapping", "or", "not", "self", ".", "syscall_number_mapping", "[", "abi", "]", ":", "return", "0", "return", "max", "(", "self", ".",...
38.666667
10.222222
def _topLevelObjectGenerator(self, request, numObjects, getByIndexMethod): """ Returns a generator over the results for the specified request, which is over a set of objects of the specified size. The objects are returned by call to the specified method, which must take a single ...
[ "def", "_topLevelObjectGenerator", "(", "self", ",", "request", ",", "numObjects", ",", "getByIndexMethod", ")", ":", "currentIndex", "=", "0", "if", "request", ".", "page_token", ":", "currentIndex", ",", "=", "paging", ".", "_parsePageToken", "(", "request", ...
47.1
16.3
def load_file(filename, out=sys.stdout): """ load a Python source file and compile it to byte-code _load_file(filename: string): code_object filename: name of file containing Python source code (normally a .py) code_object: code_object compiled from this source code This function...
[ "def", "load_file", "(", "filename", ",", "out", "=", "sys", ".", "stdout", ")", ":", "fp", "=", "open", "(", "filename", ",", "'rb'", ")", "try", ":", "source", "=", "fp", ".", "read", "(", ")", "try", ":", "if", "PYTHON_VERSION", "<", "2.6", ":...
31.521739
15.869565
async def get_cred_def_id(self): """ Get the ledger ID of the object Example: source_id = 'foobar123' schema_name = 'Schema Name' payment_handle = 0 credential_def1 = await CredentialDef.create(source_id, name, schema_id, payment_handle) assert await cred...
[ "async", "def", "get_cred_def_id", "(", "self", ")", ":", "cb", "=", "create_cb", "(", "CFUNCTYPE", "(", "None", ",", "c_uint32", ",", "c_uint32", ",", "c_char_p", ")", ")", "c_handle", "=", "c_uint32", "(", "self", ".", "handle", ")", "cred_def_id", "="...
40.3125
18.8125
def get_expiration_time(self, app: 'Quart', session: SessionMixin) -> Optional[datetime]: """Helper method to return the Session expiration time. If the session is not 'permanent' it will expire as and when the browser stops accessing the app. """ if session.permanent: ...
[ "def", "get_expiration_time", "(", "self", ",", "app", ":", "'Quart'", ",", "session", ":", "SessionMixin", ")", "->", "Optional", "[", "datetime", "]", ":", "if", "session", ".", "permanent", ":", "return", "datetime", ".", "utcnow", "(", ")", "+", "app...
40.9
20.5
def pixel_to_geo(pixel, level): """Transform from pixel to geo coordinates""" pixel_x = pixel[0] pixel_y = pixel[1] map_size = float(TileSystem.map_size(level)) x = (TileSystem.clip(pixel_x, (0, map_size - 1)) / map_size) - 0.5 y = 0.5 - (TileSystem.clip(pixel_y, (0, map_...
[ "def", "pixel_to_geo", "(", "pixel", ",", "level", ")", ":", "pixel_x", "=", "pixel", "[", "0", "]", "pixel_y", "=", "pixel", "[", "1", "]", "map_size", "=", "float", "(", "TileSystem", ".", "map_size", "(", "level", ")", ")", "x", "=", "(", "TileS...
45.2
15.1
def _keep_analyses( analyses, keep_forms, target_forms ): ''' Filters the given list of *analyses* by morphological forms: deletes analyses that are listed in *target_forms*, but not in *keep_forms*. ''' to_delete = [] for aid, analysis in enumerate(analyses): delete = False ...
[ "def", "_keep_analyses", "(", "analyses", ",", "keep_forms", ",", "target_forms", ")", ":", "to_delete", "=", "[", "]", "for", "aid", ",", "analysis", "in", "enumerate", "(", "analyses", ")", ":", "delete", "=", "False", "for", "target", "in", "target_form...
37.5625
17.5625
def _find_impl(cls, registry): """Returns the best matching implementation from *registry* for type *cls*. Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. Note: if *registry* does not contain an implementation ...
[ "def", "_find_impl", "(", "cls", ",", "registry", ")", ":", "mro", "=", "_compose_mro", "(", "cls", ",", "registry", ".", "keys", "(", ")", ")", "match", "=", "None", "for", "t", "in", "mro", ":", "if", "match", "is", "not", "None", ":", "# If *mat...
37.740741
19.518519
def fix_e112(self, result): """Fix under-indented comments.""" line_index = result['line'] - 1 target = self.source[line_index] if not target.lstrip().startswith('#'): # Don't screw with invalid syntax. return [] self.source[line_index] = self.indent_wor...
[ "def", "fix_e112", "(", "self", ",", "result", ")", ":", "line_index", "=", "result", "[", "'line'", "]", "-", "1", "target", "=", "self", ".", "source", "[", "line_index", "]", "if", "not", "target", ".", "lstrip", "(", ")", ".", "startswith", "(", ...
32.1
14.5
def to_file(data, filename_or_file_object): """ Write ``data`` to a file specified by either filename of the file or an opened :class:`file` buffer. :param data: Object to write to file :param filename_or_file_object: filename/or opened file buffer to write to :type filename_or_file_object: basestr...
[ "def", "to_file", "(", "data", ",", "filename_or_file_object", ")", ":", "if", "isinstance", "(", "filename_or_file_object", ",", "basestring", ")", ":", "file_", "=", "open", "(", "filename_or_file_object", ",", "'w'", ")", "we_opened", "=", "True", "else", "...
31.4
19.3
def swo_disable(self, port_mask): """Disables ITM & Stimulus ports. Args: self (JLink): the ``JLink`` instance port_mask (int): mask specifying which ports to disable Returns: ``None`` Raises: JLinkException: on error """ res = s...
[ "def", "swo_disable", "(", "self", ",", "port_mask", ")", ":", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_DisableTarget", "(", "port_mask", ")", "if", "res", "!=", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "N...
25.647059
19.294118
def multisig_validate_deserialize(rawmsg, requrl=None, check_expiration=True, decode_payload=True, algorithm_name=DEFAULT_ALGO): """ Validate a general JSON serialization and return the headers and payload if all the signatures are good. ...
[ "def", "multisig_validate_deserialize", "(", "rawmsg", ",", "requrl", "=", "None", ",", "check_expiration", "=", "True", ",", "decode_payload", "=", "True", ",", "algorithm_name", "=", "DEFAULT_ALGO", ")", ":", "assert", "algorithm_name", "in", "ALGORITHM_AVAILABLE"...
35.311111
21.133333
def multi_path_generator(pathnames): """ yields (name,chunkgen) for all of the files found under the list of pathnames given. This is recursive, so directories will have their contents emitted. chunkgen is a function that can called and iterated over to obtain the contents of the file in multiple ...
[ "def", "multi_path_generator", "(", "pathnames", ")", ":", "for", "pathname", "in", "pathnames", ":", "if", "isdir", "(", "pathname", ")", ":", "for", "entry", "in", "directory_generator", "(", "pathname", ")", ":", "yield", "entry", "else", ":", "yield", ...
35.266667
17.933333
def create_database(self, database_name): """ Creates a new database in CosmosDB. """ if database_name is None: raise AirflowBadRequest("Database name cannot be None.") # We need to check to see if this database already exists so we don't try # to create it t...
[ "def", "create_database", "(", "self", ",", "database_name", ")", ":", "if", "database_name", "is", "None", ":", "raise", "AirflowBadRequest", "(", "\"Database name cannot be None.\"", ")", "# We need to check to see if this database already exists so we don't try", "# to creat...
37.105263
17.947368
def _set_line_speed(self, v, load=False): """ Setter method for line_speed, mapped from YANG variable /interface/management/line_speed (container) If this variable is read-only (config: false) in the source YANG file, then _set_line_speed is considered as a private method. Backends looking to popula...
[ "def", "_set_line_speed", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "bas...
71.04
35.56
def condition_yaw(heading, relative=False): """ Send MAV_CMD_CONDITION_YAW message to point vehicle at a specified heading (in degrees). This method sets an absolute heading by default, but you can set the `relative` parameter to `True` to set yaw relative to the current yaw heading. By default th...
[ "def", "condition_yaw", "(", "heading", ",", "relative", "=", "False", ")", ":", "if", "relative", ":", "is_relative", "=", "1", "#yaw relative to direction of travel", "else", ":", "is_relative", "=", "0", "#yaw is an absolute angle", "# create the CONDITION_YAW comman...
46.5
23.566667
def idPlayerResults(cfg, rawResult): """interpret standard rawResult for all players with known IDs""" result = {} knownPlayers = [] dictResult = {plyrRes.player_id : plyrRes.result for plyrRes in rawResult} for p in cfg.players: if p.playerID and p.playerID in dictResult: # identified playe...
[ "def", "idPlayerResults", "(", "cfg", ",", "rawResult", ")", ":", "result", "=", "{", "}", "knownPlayers", "=", "[", "]", "dictResult", "=", "{", "plyrRes", ".", "player_id", ":", "plyrRes", ".", "result", "for", "plyrRes", "in", "rawResult", "}", "for",...
48.058824
20.705882
def search(self, **kwargs): """ Method to search neighbors based on extends search. :param search: Dict containing QuerySets to find neighbors. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. ...
[ "def", "search", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ApiV4Neighbor", ",", "self", ")", ".", "get", "(", "self", ".", "prepare_url", "(", "'api/v4/neighbor/'", ",", "kwargs", ")", ")" ]
44.642857
22.071429
def validate_pluginid(value): '''Returns True if the provided value is a valid pluglin id''' valid = string.ascii_letters + string.digits + '.' return all(c in valid for c in value)
[ "def", "validate_pluginid", "(", "value", ")", ":", "valid", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'.'", "return", "all", "(", "c", "in", "valid", "for", "c", "in", "value", ")" ]
47.5
13
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on th...
[ "def", "_make_zipfile", "(", "base_name", ",", "base_dir", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "logger", "=", "None", ")", ":", "zip_filename", "=", "base_name", "+", "\".zip\"", "archive_dir", "=", "os", ".", "path", ".", "dirname",...
36.108696
21.065217
def __touch_and_multi(self, *args, **kwargs): """ Runs each tuple tuple of (redis_cmd, args) in provided inside of a Redis MULTI block, plus an increment of the last_updated value, then executes the MULTI block. If ``returns`` is specified, it returns that index from the results...
[ "def", "__touch_and_multi", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "connection", ".", "pipeline", "(", ")", "as", "pipe", ":", "pipe", ".", "incr", "(", "self", ".", "__last_update_key", ")", "[", "geta...
41.647059
19.176471
def create_document( self, parent, collection_id, document_id, document, mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new document. ...
[ "def", "create_document", "(", "self", ",", "parent", ",", "collection_id", ",", "document_id", ",", "document", ",", "mask", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", ...
44.293478
27.141304
def mode_reader(self): """MODE READER command. Instructs a mode-switching server to switch modes. See <http://tools.ietf.org/html/rfc3977#section-5.3> Returns: Boolean value indicating whether posting is allowed or not. """ code, message = self.command("MOD...
[ "def", "mode_reader", "(", "self", ")", ":", "code", ",", "message", "=", "self", ".", "command", "(", "\"MODE READER\"", ")", "if", "not", "code", "in", "[", "200", ",", "201", "]", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "...
28.466667
20.6
def get_all(self, security): """ Get all available quote data for the given ticker security. Returns a dictionary. """ url = 'http://www.google.com/finance?q=%s' % security page = self._request(url) soup = BeautifulSoup(page) snapData = soup.find...
[ "def", "get_all", "(", "self", ",", "security", ")", ":", "url", "=", "'http://www.google.com/finance?q=%s'", "%", "security", "page", "=", "self", ".", "_request", "(", "url", ")", "soup", "=", "BeautifulSoup", "(", "page", ")", "snapData", "=", "soup", "...
37.055556
18.388889
def install_default_formatters(self): """ Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url """ self.add_simple_formatter('b', '<strong>%(value)s</strong>') self.add_simple_formatter('i', '<em>%(value)s</em...
[ "def", "install_default_formatters", "(", "self", ")", ":", "self", ".", "add_simple_formatter", "(", "'b'", ",", "'<strong>%(value)s</strong>'", ")", "self", ".", "add_simple_formatter", "(", "'i'", ",", "'<em>%(value)s</em>'", ")", "self", ".", "add_simple_formatter...
52.1
26.585714
def render_none(self, context, result): """Render empty responses.""" context.response.body = b'' del context.response.content_length return True
[ "def", "render_none", "(", "self", ",", "context", ",", "result", ")", ":", "context", ".", "response", ".", "body", "=", "b''", "del", "context", ".", "response", ".", "content_length", "return", "True" ]
29.8
8.4
def parse_schedule(schedule, action): """ parses the given schedule and validates at """ error = None scheduled_at = None try: scheduled_at = dateutil.parser.parse(schedule) if scheduled_at.tzinfo is None: error = 'Timezone information is mandatory...
[ "def", "parse_schedule", "(", "schedule", ",", "action", ")", ":", "error", "=", "None", "scheduled_at", "=", "None", "try", ":", "scheduled_at", "=", "dateutil", ".", "parser", ".", "parse", "(", "schedule", ")", "if", "scheduled_at", ".", "tzinfo", "is",...
47.789474
19.368421
def chi_a(mass1, mass2, spin1z, spin2z): """ Returns the aligned mass-weighted spin difference from mass1, mass2, spin1z, and spin2z. """ return (spin2z * mass2 - spin1z * mass1) / (mass2 + mass1)
[ "def", "chi_a", "(", "mass1", ",", "mass2", ",", "spin1z", ",", "spin2z", ")", ":", "return", "(", "spin2z", "*", "mass2", "-", "spin1z", "*", "mass1", ")", "/", "(", "mass2", "+", "mass1", ")" ]
41.6
7.8
def set(self, key, value): """Only set if purview caching is enabled""" if config.CACHE_POTENTIAL_PURVIEWS: self.cache[key] = value
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "config", ".", "CACHE_POTENTIAL_PURVIEWS", ":", "self", ".", "cache", "[", "key", "]", "=", "value" ]
39
5.5
def cli(file1, file2, comments) -> int: """ Compare file1 to file2 using a filter """ sys.exit(compare_files(file1, file2, comments))
[ "def", "cli", "(", "file1", ",", "file2", ",", "comments", ")", "->", "int", ":", "sys", ".", "exit", "(", "compare_files", "(", "file1", ",", "file2", ",", "comments", ")", ")" ]
46.333333
4
def summarize_provenance_per_cache(self): """Utility function to summarize provenance files for cached items used by a Cohort, for each cache_dir that exists. Only existing cache_dirs are summarized. This is a summary of provenance files because the function checks to see whether all pa...
[ "def", "summarize_provenance_per_cache", "(", "self", ")", ":", "provenance_summary", "=", "{", "}", "df", "=", "self", ".", "as_dataframe", "(", ")", "for", "cache", "in", "self", ".", "cache_names", ":", "cache_name", "=", "self", ".", "cache_names", "[", ...
48.925926
24.833333
def create(self, path: str, k: int = 20): """ Create from a scored lexicon file (fast_align format) using vocab from a trained Sockeye model. :param path: Path to lexicon file. :param k: Number of target entries per source to keep. """ self.lex = np.zeros((len(self.vocab...
[ "def", "create", "(", "self", ",", "path", ":", "str", ",", "k", ":", "int", "=", "20", ")", ":", "self", ".", "lex", "=", "np", ".", "zeros", "(", "(", "len", "(", "self", ".", "vocab_source", ")", ",", "k", ")", ",", "dtype", "=", "np", "...
50.888889
28
def tabbedPane(self, req, tag): """ Render a tabbed pane tab for each top-level L{xmantissa.ixmantissa.IPreferenceCollection} tab """ navigation = webnav.getTabs(self.aggregator.getPreferenceCollections()) pages = list() for tab in navigation: f = inev...
[ "def", "tabbedPane", "(", "self", ",", "req", ",", "tag", ")", ":", "navigation", "=", "webnav", ".", "getTabs", "(", "self", ".", "aggregator", ".", "getPreferenceCollections", "(", ")", ")", "pages", "=", "list", "(", ")", "for", "tab", "in", "naviga...
36.944444
14.944444
def reload(*command, ignore_patterns=[]): """Reload given command""" path = "." sig = signal.SIGTERM delay = 0.25 ignorefile = ".reloadignore" ignore_patterns = ignore_patterns or load_ignore_patterns(ignorefile) event_handler = ReloadEventHandler(ignore_patterns) reloader = Reloader(c...
[ "def", "reload", "(", "*", "command", ",", "ignore_patterns", "=", "[", "]", ")", ":", "path", "=", "\".\"", "sig", "=", "signal", ".", "SIGTERM", "delay", "=", "0.25", "ignorefile", "=", "\".reloadignore\"", "ignore_patterns", "=", "ignore_patterns", "or", ...
25.75
18.5625
def main(reraise_exceptions=False, **kwargs): """Main program. Catches several common errors and displays them nicely.""" exit_status = 0 try: cli.main(**kwargs) except SoftLayer.SoftLayerAPIError as ex: if 'invalid api token' in ex.faultString.lower(): print("Authentication...
[ "def", "main", "(", "reraise_exceptions", "=", "False", ",", "*", "*", "kwargs", ")", ":", "exit_status", "=", "0", "try", ":", "cli", ".", "main", "(", "*", "*", "kwargs", ")", "except", "SoftLayer", ".", "SoftLayerAPIError", "as", "ex", ":", "if", ...
34.40625
19
def split_qname(self, cybox_id): """ Separate the namespace from the identifier in a qualified name and lookup the namespace URI associated with the given namespace. """ if ':' in cybox_id: (namespace, uid) = cybox_id.split(':', 1) else: namespace ...
[ "def", "split_qname", "(", "self", ",", "cybox_id", ")", ":", "if", "':'", "in", "cybox_id", ":", "(", "namespace", ",", "uid", ")", "=", "cybox_id", ".", "split", "(", "':'", ",", "1", ")", "else", ":", "namespace", "=", "None", "uid", "=", "cybox...
37.32
21.24
def getMaxPacketSize(self, endpoint): """ Get device's max packet size for given endpoint. Warning: this function will not always give you the expected result. See https://libusb.org/ticket/77 . You should instead consult the endpoint descriptor of current configuration and alte...
[ "def", "getMaxPacketSize", "(", "self", ",", "endpoint", ")", ":", "result", "=", "libusb1", ".", "libusb_get_max_packet_size", "(", "self", ".", "device_p", ",", "endpoint", ")", "mayRaiseUSBError", "(", "result", ")", "return", "result" ]
42.545455
20.545455
def _check_FITS_extvers(img, extname, extvers): """Returns True if all (except None) extension versions specified by the argument 'extvers' and that are of the type specified by the argument 'extname' are present in the 'img' FITS file. Returns False if some of the extension versions for a given EXTNAME...
[ "def", "_check_FITS_extvers", "(", "img", ",", "extname", ",", "extvers", ")", ":", "default_extn", "=", "1", "if", "isinstance", "(", "extname", ",", "str", ")", "else", "0", "if", "isinstance", "(", "extvers", ",", "list", ")", ":", "extv", "=", "[",...
42.75
22.3125
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, source_ip: str = None, source_port: int = None, timeout: Union[float...
[ "async", "def", "connect", "(", "self", ",", "host", ":", "str", ",", "port", ":", "int", ",", "af", ":", "socket", ".", "AddressFamily", "=", "socket", ".", "AF_UNSPEC", ",", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", "...
39.28
19.32
def seek(self, offset, whence=0): """Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: 0: start of stream (default): offset must not be negative 1: current stream position ...
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "self", ".", "_check_can_seek", "(", ")", "# Recalculate offset as an absolute file position.", "if", "whence", "==", "0", ":", "pass", "elif", "whence", "==", "1", ":", "offset", ...
35.555556
20.288889
def get(self, request, path): """Return HTML (or other related content) for Meteor.""" if path == 'meteor_runtime_config.js': config = { 'DDP_DEFAULT_CONNECTION_URL': request.build_absolute_uri('/'), 'PUBLIC_SETTINGS': self.meteor_settings.get('public', {}), ...
[ "def", "get", "(", "self", ",", "request", ",", "path", ")", ":", "if", "path", "==", "'meteor_runtime_config.js'", ":", "config", "=", "{", "'DDP_DEFAULT_CONNECTION_URL'", ":", "request", ".", "build_absolute_uri", "(", "'/'", ")", ",", "'PUBLIC_SETTINGS'", "...
43.787879
17.666667
def save_to_store(self): """Save index to store. :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') saved_data = self.save_to_data(in_place=True) data = Serializer.serialize(saved_data) ...
[ "def", "save_to_store", "(", "self", ")", ":", "if", "not", "self", ".", "_store", ":", "raise", "AttributeError", "(", "'No datastore defined!'", ")", "saved_data", "=", "self", ".", "save_to_data", "(", "in_place", "=", "True", ")", "data", "=", "Serialize...
33.636364
16.909091
def year(self, value=None): """ We do *NOT* know for what year we are converting so lets assume the year has 365 days. """ if value is None: return self.day() / 365 else: self.millisecond(self.day(value * 365))
[ "def", "year", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "self", ".", "day", "(", ")", "/", "365", "else", ":", "self", ".", "millisecond", "(", "self", ".", "day", "(", "value", "*", "365", "...
30.444444
13.333333
def haversine(lon1, lat1, lon2, lat2, earth_radius=6357000): """Calculate the great circle distance between two points on earth in Kilometers on the earth (specified in decimal degrees) .. seealso:: :func:`distance_points` :param float lon1: longitude of first place (decimal degrees) :param float ...
[ "def", "haversine", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ",", "earth_radius", "=", "6357000", ")", ":", "# convert decimal degrees to radiant", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", "=", "list", "(", "map", "(", "math", ".", "radi...
45.3
26.266667
def build_area_source_geometry(area_source): """ Returns the area source geometry as a Node :param area_source: Area source model as an instance of the :class: `openquake.hazardlib.source.area.AreaSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ geo...
[ "def", "build_area_source_geometry", "(", "area_source", ")", ":", "geom", "=", "[", "]", "for", "lon_lat", "in", "zip", "(", "area_source", ".", "polygon", ".", "lons", ",", "area_source", ".", "polygon", ".", "lats", ")", ":", "geom", ".", "extend", "(...
42.208333
19.208333
def construct_url(self): """Construct a full trakt request URI, with `params` and `query`.""" path = [self.path] path.extend(self.params) # Build URL url = self.client.base_url + '/'.join( str(value) for value in path if value ) # Append ...
[ "def", "construct_url", "(", "self", ")", ":", "path", "=", "[", "self", ".", "path", "]", "path", ".", "extend", "(", "self", ".", "params", ")", "# Build URL", "url", "=", "self", ".", "client", ".", "base_url", "+", "'/'", ".", "join", "(", "str...
24.888889
19
def post(self, query_continue=None, upload_file=None, auth=None, continuation=False, **params): """Makes an API request with the POST method :Parameters: query_continue : `dict` Optionally, the value of a query continuation 'continue' field. upload_f...
[ "def", "post", "(", "self", ",", "query_continue", "=", "None", ",", "upload_file", "=", "None", ",", "auth", "=", "None", ",", "continuation", "=", "False", ",", "*", "*", "params", ")", ":", "if", "upload_file", "is", "not", "None", ":", "files", "...
39.28125
20.75
def get_sigma(database_file_name='', e_min=np.NaN, e_max=np.NaN, e_step=np.NaN, t_kelvin=None): """retrieve the Energy and sigma axis for the given isotope :param database_file_name: path/to/file with extension :type database_file_name: string :param e_min: left energy range in eV of new interpolated d...
[ "def", "get_sigma", "(", "database_file_name", "=", "''", ",", "e_min", "=", "np", ".", "NaN", ",", "e_max", "=", "np", ".", "NaN", ",", "e_step", "=", "np", ".", "NaN", ",", "t_kelvin", "=", "None", ")", ":", "file_extension", "=", "os", ".", "pat...
39.71875
22.03125
def to_excel(self, *args): """ Dump all the data to excel, fname and path can be passed as args """ path = os.getcwd() fname = self.fname.replace(".tpl", "_tpl") + ".xlsx" idxs = self.filter_trends("") for idx in idxs: self.extract(idx) ...
[ "def", "to_excel", "(", "self", ",", "*", "args", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "fname", "=", "self", ".", "fname", ".", "replace", "(", "\".tpl\"", ",", "\"_tpl\"", ")", "+", "\".xlsx\"", "idxs", "=", "self", ".", "filter_t...
37.473684
11.052632
def serve(self, handler): """Serve calls over this connection using the given RequestHandler. :param handler: RequestHandler to process the requests through :return: A Future that resolves (to None) once the loop is done running -- which happens once this con...
[ "def", "serve", "(", "self", ",", "handler", ")", ":", "assert", "handler", ",", "\"handler is required\"", "while", "not", "self", ".", "closed", ":", "message", "=", "yield", "self", ".", "await", "(", ")", "try", ":", "handler", "(", "message", ",", ...
34.315789
17.473684
def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False trust = self.check_pin_trust(request.environ) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value is bad. This means that the ...
[ "def", "pin_auth", "(", "self", ",", "request", ")", ":", "exhausted", "=", "False", "auth", "=", "False", "trust", "=", "self", ".", "check_pin_trust", "(", "request", ".", "environ", ")", "# If the trust return value is `None` it means that the cookie is", "# set ...
34.326087
19.347826
def citedby_pid(self, pid, metaonly=False, from_heap=True): """ Retrieve citedby documents from a given PID number. pid: SciELO PID number metaonly: will retrieve only the metadata of the requested article citations including the number of citations it has received. from_heap: w...
[ "def", "citedby_pid", "(", "self", ",", "pid", ",", "metaonly", "=", "False", ",", "from_heap", "=", "True", ")", ":", "if", "from_heap", "is", "True", ":", "result", "=", "citations", ".", "raw_data", "(", "pid", ")", "if", "result", "and", "'cited_by...
34.96
27.28
def check_online(stream): """ Used to check user's online opponents and show their online/offline status on page on init """ while True: packet = yield from stream.get() session_id = packet.get('session_key') opponent_username = packet.get('username') if session_i...
[ "def", "check_online", "(", "stream", ")", ":", "while", "True", ":", "packet", "=", "yield", "from", "stream", ".", "get", "(", ")", "session_id", "=", "packet", ".", "get", "(", "'session_key'", ")", "opponent_username", "=", "packet", ".", "get", "(",...
52.851852
26.62963
def create_ellipse_mesh(points,**kwargs): """Visualize the ellipse by using the mesh of the points.""" import plotly.graph_objs as go x,y,z = points.T return (go.Mesh3d(x=x,y=y,z=z,**kwargs), go.Scatter3d(x=x, y=y, z=z, marker=dict(size=0.01), ...
[ "def", "create_ellipse_mesh", "(", "points", ",", "*", "*", "kwargs", ")", ":", "import", "plotly", ".", "graph_objs", "as", "go", "x", ",", "y", ",", "z", "=", "points", ".", "T", "return", "(", "go", ".", "Mesh3d", "(", "x", "=", "x", ",", "y",...
37.583333
10.416667
def patch_datasette(): """ Monkey patching for original Datasette """ def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect _inspect = {} files = self.files for filename in files...
[ "def", "patch_datasette", "(", ")", ":", "def", "inspect", "(", "self", ")", ":", "\" Inspect the database and return a dictionary of table metadata \"", "if", "self", ".", "_inspect", ":", "return", "self", ".", "_inspect", "_inspect", "=", "{", "}", "files", "="...
35.447368
20.157895
def GetPixelColor(self, x: int, y: int) -> int: """ Get color value of a pixel. x: int. y: int. Return int, argb color. b = argb & 0x0000FF g = (argb & 0x00FF00) >> 8 r = (argb & 0xFF0000) >> 16 a = (argb & 0xFF0000) >> 24 """ retur...
[ "def", "GetPixelColor", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "int", ":", "return", "_DllClient", ".", "instance", "(", ")", ".", "dll", ".", "BitmapGetPixel", "(", "self", ".", "_bitmap", ",", "x", ",", "y", ")" ]
30.916667
11.25
def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # bu...
[ "def", "atc", "(", "jobid", ")", ":", "# Shim to produce output similar to what __virtual__() should do", "# but __salt__ isn't available in __virtual__()", "output", "=", "_cmd", "(", "'at'", ",", "'-c'", ",", "six", ".", "text_type", "(", "jobid", ")", ")", "if", "o...
25.954545
24.318182
def _make_reversed_operation_costs(self): """ Заполняет массив _reversed_operation_costs на основе имеющегося массива operation_costs """ _reversed_operation_costs = dict() for up, costs in self.operation_costs.items(): for low, cost in costs.items(): ...
[ "def", "_make_reversed_operation_costs", "(", "self", ")", ":", "_reversed_operation_costs", "=", "dict", "(", ")", "for", "up", ",", "costs", "in", "self", ".", "operation_costs", ".", "items", "(", ")", ":", "for", "low", ",", "cost", "in", "costs", ".",...
45.166667
10
def patches(self, dwn, install, comp_sum, uncomp_sum): """Seperates packages from patches/ directory """ dwnp, installp, comp_sump, uncomp_sump = ([] for i in range(4)) for d, i, c, u in zip(dwn, install, comp_sum, uncomp_sum): if "_slack" + slack_ver() in i: ...
[ "def", "patches", "(", "self", ",", "dwn", ",", "install", ",", "comp_sum", ",", "uncomp_sum", ")", ":", "dwnp", ",", "installp", ",", "comp_sump", ",", "uncomp_sump", "=", "(", "[", "]", "for", "i", "in", "range", "(", "4", ")", ")", "for", "d", ...
41.647059
9.176471
def _is_valid_dkim(self, value): """Check if value is a valid DKIM""" validator_dict = {'h': lambda val: val in ['sha1', 'sha256'], 's': lambda val: val in ['*', 'email'], 't': lambda val: val in ['y', 's'], 'v': lambda val: v...
[ "def", "_is_valid_dkim", "(", "self", ",", "value", ")", ":", "validator_dict", "=", "{", "'h'", ":", "lambda", "val", ":", "val", "in", "[", "'sha1'", ",", "'sha256'", "]", ",", "'s'", ":", "lambda", "val", ":", "val", "in", "[", "'*'", ",", "'ema...
42.333333
14.777778
def split_code_and_text_blocks(source_file): """Return list with source file separated into code and text blocks. Returns ------- blocks : list of (label, content) List where each element is a tuple with the label ('text' or 'code'), and content string of block. """ docstring, r...
[ "def", "split_code_and_text_blocks", "(", "source_file", ")", ":", "docstring", ",", "rest_of_content", "=", "get_docstring_and_rest", "(", "source_file", ")", "blocks", "=", "[", "(", "'text'", ",", "docstring", ")", "]", "pattern", "=", "re", ".", "compile", ...
35.6
19
def _get_calibration_for_hits(hits, lookup): """Append the position, direction and t0 columns and add t0 to time""" n = len(hits) cal = np.empty((n, 9)) for i in range(n): calib = lookup[hits['dom_id'][i]][hits['channel_id'][i]] cal[i] = calib dir_x = cal[:, 3] dir_y = cal[:, 4] ...
[ "def", "_get_calibration_for_hits", "(", "hits", ",", "lookup", ")", ":", "n", "=", "len", "(", "hits", ")", "cal", "=", "np", ".", "empty", "(", "(", "n", ",", "9", ")", ")", "for", "i", "in", "range", "(", "n", ")", ":", "calib", "=", "lookup...
27.368421
20.315789
def get_line_matches(input_file: str, pattern: str, max_occurrencies: int = 0, loose_matching: bool = True) -> dict: r"""Get the line numbers of matched patterns. :parameter input_file: the file that needs to be read. :parameter pattern: the pa...
[ "def", "get_line_matches", "(", "input_file", ":", "str", ",", "pattern", ":", "str", ",", "max_occurrencies", ":", "int", "=", "0", ",", "loose_matching", ":", "bool", "=", "True", ")", "->", "dict", ":", "assert", "max_occurrencies", ">=", "0", "occurren...
37.36
18.52
def adjust_weight(self, stock_code, weight): """ 雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数 """ stock = self._search_stock_info(stock_code) if stock is None: raise exceptions.TradeError(u"没有查询要...
[ "def", "adjust_weight", "(", "self", ",", "stock_code", ",", "weight", ")", ":", "stock", "=", "self", ".", "_search_stock_info", "(", "stock_code", ")", "if", "stock", "is", "None", ":", "raise", "exceptions", ".", "TradeError", "(", "u\"没有查询要操作的股票信息\")", "...
36.425
15.55
def goal_delete(self, goal_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/goals#delete-goal" api_path = "/api/v2/goals/{goal_id}" api_path = api_path.format(goal_id=goal_id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "goal_delete", "(", "self", ",", "goal_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/goals/{goal_id}\"", "api_path", "=", "api_path", ".", "format", "(", "goal_id", "=", "goal_id", ")", "return", "self", ".", "call", "(", "api_...
54.6
14.6
def reduce(self, dimensions=None, function=None, **reduce_map): """ Reduces the Raster using functions provided via the kwargs, where the keyword is the dimension to be reduced. Optionally a label_prefix can be provided to prepend to the result Element label. """ ...
[ "def", "reduce", "(", "self", ",", "dimensions", "=", "None", ",", "function", "=", "None", ",", "*", "*", "reduce_map", ")", ":", "function", ",", "dims", "=", "self", ".", "_reduce_map", "(", "dimensions", ",", "function", ",", "reduce_map", ")", "if...
47.111111
14.888889
def destroy(self): """ A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None. """ widget = self.widget if widget is not None: parent = widget.getparent() if parent is not None: ...
[ "def", "destroy", "(", "self", ")", ":", "widget", "=", "self", ".", "widget", "if", "widget", "is", "not", "None", ":", "parent", "=", "widget", ".", "getparent", "(", ")", "if", "parent", "is", "not", "None", ":", "parent", ".", "remove", "(", "w...
26.95
14.85
def _fill_array_from_list(the_list, the_array): """Fill an `array` from a `list`""" for i, val in enumerate(the_list): the_array[i] = val return the_array
[ "def", "_fill_array_from_list", "(", "the_list", ",", "the_array", ")", ":", "for", "i", ",", "val", "in", "enumerate", "(", "the_list", ")", ":", "the_array", "[", "i", "]", "=", "val", "return", "the_array" ]
37.2
7
def connect(self, inbox): """ Connects the ``Piper`` instance to its upstream ``Pipers`` that should be given as a sequence. This connects this ``Piper.inbox`` with the upstream ``Piper.outbox`` respecting any "consume", "spawn" and "produce" arguments. Argumen...
[ "def", "connect", "(", "self", ",", "inbox", ")", ":", "if", "self", ".", "started", ":", "self", ".", "log", ".", "error", "(", "'Piper %s is started and cannot connect to %s.'", "%", "(", "self", ",", "inbox", ")", ")", "raise", "PiperError", "(", "'Pipe...
47.368421
22.026316
def get_instance(cls, device): """ This is only a slot to store and get already initialized poco instance rather than initializing again. You can simply pass the ``current device instance`` provided by ``airtest`` to get the AndroidUiautomationPoco instance. If no such AndroidUiautomatio...
[ "def", "get_instance", "(", "cls", ",", "device", ")", ":", "if", "cls", ".", "_nuis", ".", "get", "(", "device", ")", "is", "None", ":", "cls", ".", "_nuis", "[", "device", "]", "=", "AndroidUiautomationPoco", "(", "device", ")", "return", "cls", "....
42
31.125
def listen(self, log, noprint=True): """ Return a dictionary representation of the Log instance. Note: This function won't work with anonymous events. Args: log (processblock.Log): The Log instance that needs to be parsed. noprint (bool): Flag to tur...
[ "def", "listen", "(", "self", ",", "log", ",", "noprint", "=", "True", ")", ":", "try", ":", "result", "=", "self", ".", "decode_event", "(", "log", ".", "topics", ",", "log", ".", "data", ")", "except", "ValueError", ":", "return", "# api compatibilit...
28.5
22.6
def array_shift(a, n, fill="average"): """ This will return an array with all the elements shifted forward in index by n. a is the array n is the amount by which to shift (can be positive or negative) fill="average" fill the new empty elements with the average of the array fill="wrap" ...
[ "def", "array_shift", "(", "a", ",", "n", ",", "fill", "=", "\"average\"", ")", ":", "new_a", "=", "_n", ".", "array", "(", "a", ")", "if", "n", "==", "0", ":", "return", "new_a", "fill_array", "=", "_n", ".", "array", "(", "[", "]", ")", "fill...
33
23.055556
def safe_call(func, *args, **kwargs): """ 安全调用 """ try: return func(*args, **kwargs) except Exception as e: logger.error('exc occur. e: %s, func: %s', e, func, exc_info=True) # 调用方可以通过 isinstance(e, BaseException) 来判断是否发生了异常 return e
[ "def", "safe_call", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'exc occur. e: ...
27.6
16
def _len_tube(Flow, Diam, HeadLoss, conc_chem, temp, en_chem, KMinor): """Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation.""" num1 = pc.gravity.magnitude * HeadLoss * np.pi * (Diam**4) denom1 = 128 * viscosity_kinematic_chem(conc_chem, temp, en_che...
[ "def", "_len_tube", "(", "Flow", ",", "Diam", ",", "HeadLoss", ",", "conc_chem", ",", "temp", ",", "en_chem", ",", "KMinor", ")", ":", "num1", "=", "pc", ".", "gravity", ".", "magnitude", "*", "HeadLoss", "*", "np", ".", "pi", "*", "(", "Diam", "**...
54.444444
17.444444
def sign(self, privkey): """Sign this with a private key""" if self.v: raise InvalidSignature("already signed") if privkey in (0, '', '\x00' * 32): raise InvalidSignature("Zero privkey cannot sign") rawhash = sha3(rlp.encode(self, self.__class__.exclude(['v', 'r'...
[ "def", "sign", "(", "self", ",", "privkey", ")", ":", "if", "self", ".", "v", ":", "raise", "InvalidSignature", "(", "\"already signed\"", ")", "if", "privkey", "in", "(", "0", ",", "''", ",", "'\\x00'", "*", "32", ")", ":", "raise", "InvalidSignature"...
34.043478
21.956522
def fade_to_color(self, fade_milliseconds, color): """ Fade the light to a known colour in a :param fade_milliseconds: Duration of the fade in milliseconds :param color: Named color to fade to :return: None """ red, green, blue = self.color_to_rgb(color) ...
[ "def", "fade_to_color", "(", "self", ",", "fade_milliseconds", ",", "color", ")", ":", "red", ",", "green", ",", "blue", "=", "self", ".", "color_to_rgb", "(", "color", ")", "return", "self", ".", "fade_to_rgb", "(", "fade_milliseconds", ",", "red", ",", ...
37.1
14.7