docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Returns a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted help message.
def get_help(self, prefix='', include_special_flags=True): flags_by_module = self.flags_by_module_dict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = sys.argv[0] if main_module in modules: module...
175,781
Returns the help string for a list of modules. Private to absl.flags package. Args: modules: List[str], a list of modules to get the help string for. prefix: str, a string that is prepended to each generated help line. include_special_flags: bool, whether to include description of SP...
def _get_help_for_modules(self, modules, prefix, include_special_flags): output_lines = [] for module in modules: self._render_our_module_flags(module, output_lines, prefix) if include_special_flags: self._render_module_flags( 'absl.flags', six.itervalues(_helpers.SPECIA...
175,782
Returns a help string for the key flags of a given module. Args: module: module|str, the module to render key flags for. output_lines: [str], a list of strings. The generated help message lines will be appended to this list. prefix: str, a string that is prepended to each generated hel...
def _render_our_module_key_flags(self, module, output_lines, prefix=''): key_flags = self.get_key_flags_for_module(module) if key_flags: self._render_module_flags(module, key_flags, output_lines, prefix)
175,785
Describes the key flags of a module. Args: module: module|str, the module to describe the key flags for. Returns: str, describing the key flags of a module.
def module_help(self, module): helplist = [] self._render_our_module_key_flags(module, helplist) return '\n'.join(helplist)
175,786
Returns the value of a flag (if not None) or a default value. Args: name: str, the name of a flag. default: Default value to use if the flag value is None. Returns: Requested flag value or default.
def get_flag_value(self, name, default): # pylint: disable=invalid-name value = self.__getattr__(name) if value is not None: # Can't do if not value, b/c value might be '0' or "" return value else: return default
175,788
Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. Args: flagfile_str: str, the flagfile string. Returns: str, the filename from ...
def _extract_filename(self, flagfile_str): if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: rais...
175,790
Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from https://github.com/gflags/gflags. Args: filename: str, name of the file.
def append_flags_into_file(self, filename): with open(filename, 'a') as out_file: out_file.write(self.flags_into_string())
175,794
Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from https://github.com/gflags/gflags. We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by th...
def write_help_in_xml_format(self, outfile=None): doc = minidom.Document() all_flag = doc.createElement('AllFlags') doc.appendChild(all_flag) all_flag.appendChild(_helpers.create_xml_dom_element( doc, 'program', os.path.basename(sys.argv[0]))) usage_doc = sys.modules['__main__'].__doc...
175,795
Converts an absl log level to a cpp log level. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in Abseil C++.
def absl_to_cpp(level): if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level >= 0: # C++ log levels must be >= 0 return 0 else: return -level
175,797
Converts an integer level from the absl value to the standard value. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in standard logging.
def absl_to_standard(level): if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level < ABSL_FATAL: level = ABSL_FATAL if level <= ABSL_DEBUG: return ABSL_TO_STANDARD[level] # Maps to vlog levels. return STANDARD_DEBUG - level + 1
175,798
Converts an integer level from the standard value to the absl value. Args: level: int, a Python standard logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in absl logging.
def standard_to_absl(level): if not isinstance(level, int): raise TypeError('Expect an int level, found {}'.format(type(level))) if level < 0: level = 0 if level < STANDARD_DEBUG: # Maps to vlog levels. return STANDARD_DEBUG - level + 1 elif level < STANDARD_INFO: return ABSL_DEBUG elif...
175,799
Tries to parse the flags, print usage, and exit if unparseable. Args: args: [str], a non-empty list of the command line arguments including program name. Returns: [str], a non-empty list of remaining command line arguments after parsing flags, including program name.
def parse_flags_with_usage(args): try: return FLAGS(args) except flags.Error as error: sys.stderr.write('FATAL Flags parsing error: %s\n' % error) sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n') sys.exit(1)
175,800
Writes __main__'s docstring to stderr with some help text. Args: shorthelp: bool, if True, prints only flags from the main module, rather than all flags. writeto_stdout: bool, if True, writes help message to stdout, rather than to stderr. detailed_error: str, additional detail about why u...
def usage(shorthelp=False, writeto_stdout=False, detailed_error=None, exitcode=None): if writeto_stdout: stdfile = sys.stdout else: stdfile = sys.stderr doc = sys.modules['__main__'].__doc__ if not doc: doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] doc = flags.text_wrap(doc, indent='...
175,807
Installs an exception handler. Args: handler: ExceptionHandler, the exception handler to install. Raises: TypeError: Raised when the handler was not of the correct type. All installed exception handlers will be called if main() exits via an abnormal exception, i.e. not one of SystemExit, KeyboardInte...
def install_exception_handler(handler): if not isinstance(handler, ExceptionHandler): raise TypeError('handler of type %s does not inherit from ExceptionHandler' % type(handler)) EXCEPTION_HANDLERS.append(handler)
175,808
Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item.
def parse(self, arguments): new_values = self._parse(arguments) if self.present: self.value.extend(new_values) else: self.value = new_values self.present += len(new_values)
175,819
Ensures that flags are not None during program execution. Recommended usage: if __name__ == '__main__': flags.mark_flags_as_required(['flag1', 'flag2', 'flag3']) app.run() Args: flag_names: Sequence[str], names of the flags. flag_values: flags.FlagValues, optional FlagValues instance wher...
def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS): for flag_name in flag_names: mark_flag_as_required(flag_name, flag_values)
175,825
Ensures that only one flag among flag_names is True. Args: flag_names: [str], names of the flags. required: bool. If true, exactly one flag must be True. Otherwise, at most one flag can be True, and it is valid for all flags to be False. flag_values: flags.FlagValues, optional FlagValues instance...
def mark_bool_flags_as_mutual_exclusive(flag_names, required=False, flag_values=_flagvalues.FLAGS): for flag_name in flag_names: if not flag_values[flag_name].boolean: raise _exceptions.ValidationError( 'Flag --{} is not Boolean, which is required for fla...
175,827
Register new flags validator to be checked. Args: fv: flags.FlagValues, the FlagValues instance to add the validator. validator_instance: validators.Validator, the validator to add. Raises: KeyError: Raised when validators work with a non-existing flag.
def _add_validator(fv, validator_instance): for flag_name in validator_instance.get_flags_names(): fv[flag_name].validators.append(validator_instance)
175,828
Constructor to create all validators. Args: checker: function to verify the constraint. Input of this method varies, see SingleFlagValidator and multi_flags_validator for a detailed description. message: str, error message to be shown to the user.
def __init__(self, checker, message): self.checker = checker self.message = message Validator.validators_count += 1 # Used to assert validators in the order they were registered. self.insertion_index = Validator.validators_count
175,829
Verifies that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: flags.FlagValues, the FlagValues instance to get flags from. Raises: Error: Raised if constraint is not satisfied.
def verify(self, flag_values): param = self._get_input_to_checker_function(flag_values) if not self.checker(param): raise _exceptions.ValidationError(self.message)
175,830
Given flag values, returns the input to be given to checker. Args: flag_values: flags.FlagValues, the FlagValues instance to get flags from. Returns: dict, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc).
def _get_input_to_checker_function(self, flag_values): return dict([key, flag_values[key].value] for key in self.flag_names)
175,833
Sets the logging verbosity. Causes all messages of level <= v to be logged, and all messages of level > v to be silently discarded. Args: v: int|str, the verbosity level as an integer or string. Legal string values are those that can be coerced to an integer as well as case-insensitive 'debu...
def set_verbosity(v): try: new_level = int(v) except ValueError: new_level = converter.ABSL_NAMES[v.upper()] FLAGS.verbosity = new_level
175,837
Sets the stderr threshold to the value passed in. Args: s: str|int, valid strings values are case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'; valid integer values are logging.DEBUG|INFO|WARNING|ERROR|FATAL. Raises: ValueError: Raised when s is an invalid value.
def set_stderrthreshold(s): if s in converter.ABSL_LEVELS: FLAGS.stderrthreshold = converter.ABSL_LEVELS[s] elif isinstance(s, str) and s.upper() in converter.ABSL_NAMES: FLAGS.stderrthreshold = s else: raise ValueError( 'set_stderrthreshold only accepts integer absl logging level ' ...
175,838
Logs 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: int, the absl logging level at which to log. msg: str, the message to be logged. n: int, the number of times this should be called before it is logged. *args:...
def log_every_n(level, msg, n, *args): count = _get_next_log_count_per_token(get_absl_logger().findCaller()) log_if(level, msg, not (count % n), *args)
175,839
Tests if 'num_seconds' have passed since 'token' was requested. Not strictly thread-safe - may log with the wrong frequency if called concurrently from multiple threads. Accuracy depends on resolution of 'timeit.default_timer()'. Always returns True on the first call for a given 'token'. Args: token: T...
def _seconds_have_elapsed(token, num_seconds): now = timeit.default_timer() then = _log_timer_per_token.get(token, None) if then is None or (now - then) >= num_seconds: _log_timer_per_token[token] = now return True else: return False
175,840
Logs 'msg % args' at level 'level' iff 'n_seconds' elapsed since last call. Logs the first call, logs subsequent calls if 'n' seconds have elapsed since the last logging call from the same call site (file + line). Not thread-safe. Args: level: int, the absl logging level at which to log. msg: str, the m...
def log_every_n_seconds(level, msg, n_seconds, *args): should_log = _seconds_have_elapsed(get_absl_logger().findCaller(), n_seconds) log_if(level, msg, should_log, *args)
175,841
Checks if vlog is enabled for the given level in caller's source file. Args: level: int, the C++ verbose logging level at which to log the message, e.g. 1, 2, 3, 4... While absl level constants are also supported, callers should prefer level_debug|level_info|... calls for checking those. ...
def vlog_is_on(level): if level > converter.ABSL_DEBUG: # Even though this function supports level that is greater than 1, users # should use logging.vlog instead for such cases. # Treat this as vlog, 1 is equivalent to DEBUG. standard_level = converter.STANDARD_DEBUG - (level - 1) else: if ...
175,844
Returns the name of the log file. For Python logging, only one file is used and level is ignored. And it returns empty string if it logs to stderr/stdout or the log stream has no `name` attribute. Args: level: int, the absl.logging level. Raises: ValueError: Raised when `level` has an invalid value...
def get_log_file_name(level=INFO): if level not in converter.ABSL_LEVELS: raise ValueError('Invalid absl.logging level {}'.format(level)) stream = get_absl_handler().python_handler.stream if (stream == sys.stderr or stream == sys.stdout or not hasattr(stream, 'name')): return '' else: retur...
175,845
Returns the most suitable directory to put log files into. Args: log_dir: str|None, if specified, the logfile(s) will be created in that directory. Otherwise if the --log_dir command-line flag is provided, the logfile will be created in that directory. Otherwise the logfile will be crea...
def find_log_dir(log_dir=None): # Get a list of possible log dirs (will try to use them in order). if log_dir: # log_dir was explicitly specified as an arg, so use it and it alone. dirs = [log_dir] elif FLAGS['log_dir'].value: # log_dir flag was provided, so use it and it alone (this mimics the ...
175,847
Returns the absl log prefix for the log record. Args: record: logging.LogRecord, the record to get prefix for.
def get_absl_log_prefix(record): created_tuple = time.localtime(record.created) created_microsecond = int(record.created % 1.0 * 1e6) critical_prefix = '' level = record.levelno if _is_non_absl_fatal_record(record): # When the level is FATAL, but not logged from absl, lower the level so # it's tre...
175,848
Emits the record to stderr. This temporarily sets the handler stream to stderr, calls StreamHandler.emit, then reverts the stream back. Args: record: logging.LogRecord, the record to log.
def _log_to_stderr(self, record): # emit() is protected by a lock in logging.Handler, so we don't need to # protect here again. old_stream = self.stream self.stream = sys.stderr try: super(PythonHandler, self).emit(record) finally: self.stream = old_stream
175,861
Prints a record out to some streams. If FLAGS.logtostderr is set, it will print to sys.stderr ONLY. If FLAGS.alsologtostderr is set, it will print to sys.stderr. If FLAGS.logtostderr is not set, it will log to the stream associated with the current thread. Args: record: logging.LogRecord, ...
def emit(self, record): # People occasionally call logging functions at import time before # our flags may have even been defined yet, let alone even parsed, as we # rely on the C++ side to define some flags for us and app init to # deal with parsing. Match the C++ library behavior of notify and e...
175,862
Appends the message from the record to the results of the prefix. Args: record: logging.LogRecord, the record to be formatted. Returns: The formatted string representing the record.
def format(self, record): if (not FLAGS['showprefixforinfo'].value and FLAGS['verbosity'].value == converter.ABSL_INFO and record.levelno == logging.INFO and _absl_handler.python_handler.stream == sys.stderr): prefix = '' else: prefix = get_absl_log_prefix(record) re...
175,866
Logs a message at a cetain level substituting in the supplied arguments. This method behaves differently in python and c++ modes. Args: level: int, the standard logging level at which to log the message. msg: str, the text of the message to log. *args: The arguments to substitute in the mess...
def log(self, level, msg, *args, **kwargs): if level >= logging.FATAL: # Add property to the LogRecord created by this logger. # This will be used by the ABSLHandler to determine whether it should # treat CRITICAL/FATAL logs as really FATAL. extra = kwargs.setdefault('extra', {}) ...
175,870
Initializes ArgumentParser. Args: **kwargs: same as argparse.ArgumentParser, except: 1. It also accepts `inherited_absl_flags`: the absl flags to inherit. The default is the global absl.flags.FLAGS instance. Pass None to ignore absl flags. 2. The `prefix_chars` a...
def __init__(self, **kwargs): prefix_chars = kwargs.get('prefix_chars', '-') if prefix_chars != '-': raise ValueError( 'argparse_flags.ArgumentParser only supports "-" as the prefix ' 'character, found "{}".'.format(prefix_chars)) # Remove inherited_absl_flags before calling ...
175,874
Initializes _FlagAction. Args: option_strings: See argparse.Action. dest: Ignored. The flag is always defined with dest=argparse.SUPPRESS. help: See argparse.Action. metavar: See argparse.Action. flag_instance: absl.flags.Flag, the absl flag instance.
def __init__(self, option_strings, dest, help, metavar, flag_instance): # pylint: disable=redefined-builtin del dest self._flag_instance = flag_instance super(_FlagAction, self).__init__( option_strings=option_strings, dest=argparse.SUPPRESS, help=help, metavar=metavar)
175,878
Initializes _BooleanFlagAction. Args: option_strings: See argparse.Action. dest: Ignored. The flag is always defined with dest=argparse.SUPPRESS. help: See argparse.Action. metavar: See argparse.Action. flag_instance: absl.flags.Flag, the absl flag instance.
def __init__(self, option_strings, dest, help, metavar, flag_instance): # pylint: disable=redefined-builtin del dest self._flag_instance = flag_instance flag_names = [self._flag_instance.name] if self._flag_instance.short_name: flag_names.append(self._flag_instance.short_name) self._flag...
175,880
Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: _ModuleObjectAndName - pair of module object & module name. Returns (None, None) if the module could not be ...
def get_module_object_and_name(globals_dict): name = globals_dict.get('__name__', None) module = sys.modules.get(name, None) # Pick a more informative name for the main module. return _ModuleObjectAndName(module, (sys.argv[0] if name == '__main__' else name))
175,883
Returns an XML DOM element with name and text value. Args: doc: minidom.Document, the DOM document it should create nodes from. name: str, the tag of XML element. value: object, whose string representation will be used as the value of the XML element. Illegal or highly discouraged xml 1.0 ...
def create_xml_dom_element(doc, name, value): s = str_or_unicode(value) if six.PY2 and not isinstance(s, unicode): # Get a valid unicode string. s = s.decode('utf-8', 'ignore') if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. s = s.lower() # Remove i...
175,885
Removes indentation from triple-quoted strings. This is the function specified in PEP 257 to handle docstrings: https://www.python.org/dev/peps/pep-0257/. Args: docstring: str, a python docstring. Returns: str, docstring with indentation removed.
def trim_docstring(docstring): if not docstring: return '' # If you've got a line longer than this you have other problems... max_indent = 1 << 29 # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determin...
175,890
Init the pool from a json file. Args: filename (str, optional): if the filename is provided, proxies will be load from it.
def __init__(self, filename=None): self.idx = {'http': 0, 'https': 0} self.test_url = { 'http': 'http://www.sina.com.cn', 'https': 'https://www.taobao.com' } self.proxies = {'http': {}, 'https': {}} self.addr_list = {'http': [], 'https': []} ...
176,097
Get the number of proxies in the pool Args: protocol (str, optional): 'http' or 'https' or None. (default None) Returns: If protocol is None, return the total number of proxies, otherwise, return the number of proxies of corresponding protocol.
def proxy_num(self, protocol=None): http_num = len(self.proxies['http']) https_num = len(self.proxies['https']) if protocol == 'http': return http_num elif protocol == 'https': return https_num else: return http_num + https_num
176,098
Check if a proxy is valid Args: addr: A string in the form of 'ip:port' protocol: Either 'http' or 'https', different test urls will be used according to protocol. timeout: A integer indicating the timeout of connecting the test url. Returns: ...
def is_valid(self, addr, protocol='http', timeout=5): start = time.time() try: r = requests.get(self.test_url[protocol], timeout=timeout, proxies={protocol: 'http://' + addr}) except KeyboardInterrupt: rai...
176,106
Target function of validation threads Args: proxy_scanner: A ProxyScanner object. expected_num: Max number of valid proxies to be scanned. queue_timeout: Timeout for getting a proxy from the queue. val_timeout: An integer passed to `is_valid` as argument `timeout...
def validate(self, proxy_scanner, expected_num=20, queue_timeout=3, val_timeout=5): while self.proxy_num() < expected_num: try: candidate_proxy = proxy_scanner.proxy_queue.get( timeout=qu...
176,107
Register a scan function Args: func_name: The function name of a scan function. func_kwargs: A dict containing arguments of the scan function.
def register_func(self, func_name, func_kwargs): self.scan_funcs.append(func_name) self.scan_kwargs.append(func_kwargs)
176,111
Scan candidate proxies from http://ip84.com Args: region: Either 'mainland' or 'overseas'. page: An integer indicating how many pages to be scanned.
def scan_ip84(self, region='mainland', page=1): self.logger.info('start scanning http://ip84.com for proxy list...') for i in range(1, page + 1): if region == 'mainland': url = 'http://ip84.com/dlgn/{}'.format(i) elif region == 'overseas': ...
176,112
Check whether the item has been in the cache If the item has not been seen before, then hash it and put it into the cache, otherwise indicates the item is duplicated. When the cache size exceeds capacity, discard the earliest items in the cache. Args: item (object): The ite...
def is_duplicated(self, item): if isinstance(item, dict): hashable_item = json.dumps(item, sort_keys=True) elif isinstance(item, list): hashable_item = frozenset(item) else: hashable_item = item if hashable_item in self._cache: ret...
176,118
Set signals. Args: signals: A dict(key-value pairs) of all signals. For example {'signal1': True, 'signal2': 10}
def set(self, **signals): for name in signals: if name not in self._signals: self._init_status[name] = signals[name] self._signals[name] = signals[name]
176,127
Feed urls once Args: url_template: A string with parameters replaced with "{}". keyword: A string indicating the searching keyword. offset: An integer indicating the starting index. max_num: An integer indicating the max number of images to be crawled. ...
def feed(self, url_template, keyword, offset, max_num, page_step): for i in range(offset, offset + max_num, page_step): url = url_template.format(keyword, i) self.out_queue.put(url) self.logger.debug('put url to url_queue: {}'.format(url))
176,149
Connect two ThreadPools. The ``in_queue`` of the second pool will be set as the ``out_queue`` of the current pool, thus all the output will be input to the second pool. Args: component (ThreadPool): the ThreadPool to be connected. Returns: ThreadPool: the modifi...
def connect(self, component): if not isinstance(component, ThreadPool): raise TypeError('"component" must be a ThreadPool object') component.in_queue = self.out_queue return component
176,159
Set offset of file index. Args: file_idx_offset: It can be either an integer or 'auto'. If set to an integer, the filename will start from ``file_idx_offset`` + 1. If set to ``'auto'``, the filename will start from existing max file index plus 1.
def set_file_idx_offset(self, file_idx_offset=0): if isinstance(file_idx_offset, int): self.file_idx_offset = file_idx_offset elif file_idx_offset == 'auto': self.file_idx_offset = self.storage.max_file_idx() else: raise ValueError('"file_idx_offset" ...
176,161
Set the path where the image will be saved. The default strategy is to use an increasing 6-digit number as the filename. You can override this method if you want to set custom naming rules. The file extension is kept if it can be obtained from the url, otherwise ``default_ext`` is used ...
def get_filename(self, task, default_ext): url_path = urlparse(task['file_url'])[2] extension = url_path.split('.')[-1] if '.' in url_path else default_ext file_idx = self.fetched_num + self.file_idx_offset return '{:06d}.{}'.format(file_idx, extension)
176,162
Download the image and save it to the corresponding path. Args: task (dict): The task dict got from ``task_queue``. timeout (int): Timeout of making requests for downloading images. max_retry (int): the max retry times if the request fails. **kwargs: reserved arg...
def download(self, task, default_ext, timeout=5, max_retry=3, overwrite=False, **kwargs): file_url = task['file_url'] task['success'] = False task['filename'] = None retry = max...
176,164
Decide whether to keep the image Compare image size with ``min_size`` and ``max_size`` to decide. Args: response (Response): response of requests. min_size (tuple or None): minimum size of required images. max_size (tuple or None): maximum size of required images. ...
def keep_file(self, task, response, min_size=None, max_size=None): try: img = Image.open(BytesIO(response.content)) except (IOError, OSError): return False task['img_size'] = img.size if min_size and not self._size_gt(img.size, min_size): retu...
176,169
Set storage backend for downloader For full list of storage backend supported, please see :mod:`storage`. Args: storage (dict or BaseStorage): storage backend configuration or instance
def set_storage(self, storage): if isinstance(storage, BaseStorage): self.storage = storage elif isinstance(storage, dict): if 'backend' not in storage and 'root_dir' in storage: storage['backend'] = 'FileSystem' try: backend_c...
176,182
Init session with default or custom headers Args: headers: A dict of headers (default None, thus using the default header to init the session)
def set_session(self, headers=None): if headers is None: headers = { 'User-Agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)' ' AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/48.0.2564.116 Safari/537.36') ...
176,183
Start crawling This method will start feeder, parser and download and wait until all threads exit. Args: feeder_kwargs (dict, optional): Arguments to be passed to ``feeder.start()`` parser_kwargs (dict, optional): Arguments to be passed to ``parser.start()`` ...
def crawl(self, feeder_kwargs=None, parser_kwargs=None, downloader_kwargs=None): self.signal.reset() self.logger.info('start crawling...') feeder_kwargs = {} if feeder_kwargs is None else feeder_kwargs parser_kwargs = {} if parser_kwarg...
176,184
CapitalFlow constructor. Args: * amount (float): Amount to adjust by
def __init__(self, amount): super(CapitalFlow, self).__init__() self.amount = float(amount)
176,231
Close a child position - alias for rebalance(0, child). This will also flatten (close out all) the child's children. Args: * child (str): Child, specified by name.
def close(self, child): c = self.children[child] # flatten if children not None if c.children is not None and len(c.children) != 0: c.flatten() if c.value != 0. and not np.isnan(c.value): c.allocate(-c.value)
176,259
Set commission (transaction fee) function. Args: fn (fn(quantity, price)): Function used to determine commission amount.
def set_commissions(self, fn): self.commission_fn = fn for c in self._childrenv: if isinstance(c, StrategyBase): c.set_commissions(fn)
176,261
Setup Security with universe. Speeds up future runs. Args: * universe (DataFrame): DataFrame of prices with security's name as one of the columns.
def setup(self, universe): # if we already have all the prices, we will store them to speed up # future updates try: prices = universe[self.name] except KeyError: prices = None # setup internal data if prices is not None: self...
176,267
This allocates capital to the Security. This is the method used to buy/sell the security. A given amount of shares will be determined on the current price, a commission will be calculated based on the parent's commission fn, and any remaining capital will be passed back up to parent as...
def allocate(self, amount, update=True): # will need to update if this has been idle for a while... # update if needupdate or if now is stale # fetch parent's now since our now is stale if self._needupdate or self.now != self.parent.now: self.update(self.parent.now)...
176,269
Determines the complete cash outlay (including commission) necessary given a quantity q. Second returning parameter is a commission itself. Args: * q (float): quantity
def outlay(self, q): fee = self.commission(q, self._price * self.multiplier) outlay = q * self._price * self.multiplier return outlay + fee, outlay, fee
176,270
Load or create a precise model Args: model_name: Name of model params: Parameters used to create the model Returns: model: Loaded Keras model
def create_model(model_name: Optional[str], params: ModelParams) -> 'Sequential': if model_name and isfile(model_name): print('Loading from ' + model_name + '...') model = load_precise_model(model_name) else: from keras.layers.core import Dense from keras.layers.recurrent im...
176,578
Load the vectorized representations of the stored data files Args: train: Whether to load train data test: Whether to load test data
def load(self, train=True, test=True, shuffle=True) -> tuple: return self.__load(self.__load_files, train, test, shuffle=shuffle)
176,597
Converts an HD5F file from Keras to a .pb for use with TensorFlow Args: model_path: location of Keras model out_file: location to write protobuf
def convert(model_path: str, out_file: str): print('Converting', model_path, 'to', out_file, '...') import tensorflow as tf from precise.model import load_precise_model from keras import backend as K out_dir, filename = split(out_file) out_dir = out_dir or '.' os.makedirs(out_dir, exi...
176,664
Gets an AsYouTypeFormatter for the specific region. Arguments: region_code -- The region where the phone number is being entered Return an AsYouTypeFormatter} object, which could be used to format phone numbers in the specific region "as you type"
def __init__(self, region_code): self._clear() self._default_country = region_code.upper() self._current_metadata = _get_metadata_for_region(self._default_country) self._default_metadata = self._current_metadata
176,895
Normalizes a string of characters representing a phone number. This converts wide-ascii and arabic-indic numerals to European numerals, and strips punctuation and alpha characters (optional). Arguments: number -- a string representing a phone number keep_non_digits -- whether to keep non-digits ...
def normalize_digits_only(number, keep_non_digits=False): number = unicod(number) number_length = len(number) normalized_digits = U_EMPTY_STRING for ii in range(number_length): d = unicode_digit(number[ii], -1) if d != -1: normalized_digits += unicod(d) elif keep...
176,969
Gets the national significant number of a phone number. Note that a national significant number doesn't contain a national prefix or any formatting. Arguments: numobj -- The PhoneNumber object for which the national significant number is needed. Returns the national significant numb...
def national_significant_number(numobj): # If leading zero(s) have been set, we prefix this now. Note this is not a # national prefix. national_number = U_EMPTY_STRING if numobj.italian_leading_zero: num_zeros = numobj.number_of_leading_zeros if num_zeros is None: num_ze...
176,989
Gets a valid number for the specified number type (it may belong to any country). Arguments: num_type -- The type of number that is needed. Returns a valid number for the specified type. Returns None when the metadata does not contain such information. This should only happen when no numbers of th...
def _example_number_anywhere_for_type(num_type): for region_code in SUPPORTED_REGIONS: example_numobj = example_number_for_type(region_code, num_type) if example_numobj is not None: return example_numobj # If there wasn't an example number for a region, try the non-geographical ...
176,996
Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. Returns None when the metadata does not contain such information,...
def example_number_for_non_geo_entity(country_calling_code): metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None) if metadata is not None: # For geographical entities, fixed-line data is always present. However, for non-geographical # entities, this is not the cas...
176,997
Gets the type of a valid phone number. Arguments: numobj -- The PhoneNumber object that we want to know the type of. Returns the type of the phone number, as a PhoneNumberType value; returns PhoneNumberType.UNKNOWN if it is invalid.
def number_type(numobj): region_code = region_code_for_number(numobj) metadata = PhoneMetadata.metadata_for_region_or_calling_code(numobj.country_code, region_code) if metadata is None: return PhoneNumberType.UNKNOWN national_number = national_significant_number(numobj) return _number_t...
177,000
Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers). Arguments: numobj -- The phone number object whose origin we want to know Returns the region wh...
def region_code_for_number(numobj): country_code = numobj.country_code regions = COUNTRY_CODE_TO_REGION_CODE.get(country_code, None) if regions is None: return None if len(regions) == 1: return regions[0] else: return _region_code_for_number_from_list(numobj, regions)
177,004
Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid. Arguments: region_code -- The region that we want to get the country calling code for. Returns the country calling code for the...
def country_code_for_valid_region(region_code): metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: raise Exception("Invalid region code %s" % region_code) return metadata.country_code
177,006
Truncate a number object that is too long. Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified. Arguments...
def truncate_too_long_number(numobj): if is_valid_number(numobj): return True numobj_copy = PhoneNumber() numobj_copy.merge_from(numobj) national_number = numobj.national_number while not is_valid_number(numobj_copy): # Strip a digit off the RHS national_number = nation...
177,013
Strip extension from the end of a number string. Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it. Arguments: number -- the non-normalized telephone number that we wis...
def _maybe_strip_extension(number): match = _EXTN_PATTERN.search(number) # If we find a potential extension, and the number preceding this is a # viable number, we assume it is an extension. if match and _is_viable_phone_number(number[:match.start()]): # The numbers are captured into groups...
177,019
Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability. Arguments: region_code -- the region for which we want to know whether it supports mobile number portability or not.
def is_mobile_number_portable_region(region_code): metadata = PhoneMetadata.metadata_for_region(region_code, None) if metadata is None: return False return metadata.mobile_number_portable_region
177,031
As time_zones_for_geographical_number() but explicitly checks the validity of the number passed in. Arguments: numobj -- a valid phone number for which we want to get the time zones to which it belongs Returns a list of the corresponding time zones or a single element list with the default unknown ...
def time_zones_for_number(numobj): ntype = number_type(numobj) if ntype == PhoneNumberType.UNKNOWN: return _UNKNOWN_TIME_ZONE_LIST elif not is_number_type_geographical(ntype, numobj.country_code): return _country_level_time_zones_for_number(numobj) return time_zones_for_geographical...
177,037
Returns the list of time zones corresponding to the country calling code of a number. Arguments: numobj -- the phone number to look up Returns a list of the corresponding time zones or a single element list with the default unknown time zone if no other time zone was found or if the number was invalid
def _country_level_time_zones_for_number(numobj): cc = str(numobj.country_code) for prefix_len in range(TIMEZONE_LONGEST_PREFIX, 0, -1): prefix = cc[:(1 + prefix_len)] if prefix in TIMEZONE_DATA: return TIMEZONE_DATA[prefix] return _UNKNOWN_TIME_ZONE_LIST
177,038
Returns True if the groups of digits found in our candidate phone number match our expectations. Arguments: numobj -- the original number we found when parsing normalized_candidate -- the candidate number, normalized to only contain ASCII digits, but with non-digits (spaces etc) retained ...
def _all_number_groups_remain_grouped(numobj, normalized_candidate, formatted_number_groups): from_index = 0 if numobj.country_code_source != CountryCodeSource.FROM_DEFAULT_COUNTRY: # First skip the country code if the normalized candidate contained it. country_code = str(numobj.country_cod...
177,072
Returns True if the groups of digits found in our candidate phone number match our expectations. Arguments: numobj -- the original number we found when parsing normalized_candidate -- the candidate number, normalized to only contain ASCII digits, but with non-digits (spaces etc) retained ...
def _all_number_groups_are_exactly_present(numobj, normalized_candidate, formatted_number_groups): candidate_groups = re.split(NON_DIGITS_PATTERN, normalized_candidate) # Set this to the last group, skipping it if the number has an extension. if numobj.extension is not None: candidate_number_gr...
177,074
Attempts to find the next subsequence in the searched sequence on or after index that represents a phone number. Returns the next match, None if none was found. Arguments: index -- The search index to start searching at. Returns the phone number match found, None if none can be found.
def _find(self, index): match = _PATTERN.search(self.text, index) while self._max_tries > 0 and match is not None: start = match.start() candidate = self.text[start:match.end()] # Check for extra numbers at the end. # TODO: This is the place to s...
177,081
Attempts to extract a match from a candidate string. Arguments: candidate -- The candidate text that might contain a phone number. offset -- The offset of candidate within self.text Returns the match found, None if none can be found
def _extract_match(self, candidate, offset): # Skip a match that is more likely a publication page reference or a # date. if (_SLASH_SEPARATED_DATES.search(candidate)): return None # Skip potential time-stamps. if _TIME_STAMPS.search(candidate): ...
177,085
Attempts to extract a match from candidate if the whole candidate does not qualify as a match. Arguments: candidate -- The candidate text that might contain a phone number offset -- The current offset of candidate within text Returns the match found, None if none can be found
def _extract_inner_match(self, candidate, offset): for possible_inner_match in _INNER_MATCHES: group_match = possible_inner_match.search(candidate) is_first_match = True while group_match and self._max_tries > 0: if is_first_match: ...
177,086
Parses a phone number from the candidate using phonenumberutil.parse and verifies it matches the requested leniency. If parsing and verification succeed, a corresponding PhoneNumberMatch is returned, otherwise this method returns None. Arguments: candidate -- The candidate match. ...
def _parse_and_verify(self, candidate, offset): try: # Check the candidate doesn't contain any formatting which would # indicate that it really isn't a phone number. if (not fullmatch(_MATCHING_BRACKETS, candidate) or _PUB_PAGES.search(candidate)): re...
177,087
Check whether a short number is a possible number when dialled from a region. This provides a more lenient check than is_valid_short_number_for_region. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the region from which the number is dialed ...
def is_possible_short_number_for_region(short_numobj, region_dialing_from): if not _region_dialing_from_matches_number(short_numobj, region_dialing_from): return False metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if metadata is None: # pragma no cover return ...
177,093
Check whether a short number is a possible number. If a country calling code is shared by multiple regions, this returns True if it's possible in any of them. This provides a more lenient check than is_valid_short_number. Arguments: numobj -- the short number to check Return whether the numbe...
def is_possible_short_number(numobj): region_codes = region_codes_for_country_code(numobj.country_code) short_number_len = len(national_significant_number(numobj)) for region in region_codes: metadata = PhoneMetadata.short_metadata_for_region(region) if metadata is None: co...
177,094
Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the ...
def is_valid_short_number_for_region(short_numobj, region_dialing_from): if not _region_dialing_from_matches_number(short_numobj, region_dialing_from): return False metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if metadata is None: # pragma no cover return Fal...
177,095
Tests whether a short number matches a valid pattern. If a country calling code is shared by multiple regions, this returns True if it's valid in any of them. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. See is_valid_shor...
def is_valid_short_number(numobj): region_codes = region_codes_for_country_code(numobj.country_code) region_code = _region_code_for_short_number_from_region_list(numobj, region_codes) if len(region_codes) > 1 and region_code is not None: # If a matching region had been found for the phone numbe...
177,096
Gets a valid short number for the specified region. Arguments: region_code -- the region for which an example short number is needed. Returns a valid short number for the specified region. Returns an empty string when the metadata does not contain such information.
def _example_short_number(region_code): metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is None: return U_EMPTY_STRING desc = metadata.short_code if desc.example_number is not None: return desc.example_number return U_EMPTY_STRING
177,100
Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified region and cost category. Returns an empty string when the...
def _example_short_number_for_cost(region_code, cost): metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is None: return U_EMPTY_STRING desc = None if cost == ShortNumberCost.TOLL_FREE: desc = metadata.toll_free elif cost == ShortNumberCost.STANDARD_RAT...
177,101
Calculates refund transactions based on line items and shipping. When you want to create a refund, you should first use the calculate endpoint to generate accurate refund transactions. Args: order_id: Order ID for which the Refund has to created. shipping: Specify how much...
def calculate(cls, order_id, shipping=None, refund_line_items=None): data = {} if shipping: data['shipping'] = shipping data['refund_line_items'] = refund_line_items or [] body = {'refund': data} resource = cls.post( "calculate", order_id=order_id...
177,145
Retrieves project name for given project id Args: projects: List of projects project_id: project id Returns: Project name or None if there is no match
def get_project_name(project_id, projects): for project in projects: if project_id == project.id: return project.name
179,908
Create an instance of the AuthenticatedClient class. Args: key (str): Your API key. b64secret (str): The secret key matching your API key. passphrase (str): Passphrase chosen when setting up key. api_url (Optional[str]): API URL. Defaults to cbpro API.
def __init__(self, key, b64secret, passphrase, api_url="https://api.pro.coinbase.com"): super(AuthenticatedClient, self).__init__(api_url) self.auth = CBProAuth(key, b64secret, passphrase) self.session = requests.Session()
180,219
Repay funding. Repays the older funding records first. Args: amount (int): Amount of currency to repay currency (str): The currency, example USD Returns: Not specified by cbpro.
def repay_funding(self, amount, currency): params = { 'amount': amount, 'currency': currency # example: USD } return self._send_message('post', '/funding/repay', data=json.dumps(params))
180,231
Close position. Args: repay_only (bool): Undocumented by cbpro. Returns: Undocumented
def close_position(self, repay_only): params = {'repay_only': repay_only} return self._send_message('post', '/position/close', data=json.dumps(params))
180,233
Withdraw funds to a crypto address. Args: amount (Decimal): The amount to withdraw currency (str): The type of currency (eg. 'BTC') crypto_address (str): Crypto address to withdraw to. Returns: dict: Withdraw details. Example:: { ...
def crypto_withdraw(self, amount, currency, crypto_address): params = {'amount': amount, 'currency': currency, 'crypto_address': crypto_address} return self._send_message('post', '/withdrawals/crypto', data=json.dumps(params)...
180,236
Create cbpro API public client. Args: api_url (Optional[str]): API URL. Defaults to cbpro API.
def __init__(self, api_url='https://api.pro.coinbase.com', timeout=30): self.url = api_url.rstrip('/') self.auth = None self.session = requests.Session()
180,247
Send API request. Args: method (str): HTTP method (get, post, delete, etc.) endpoint (str): Endpoint (to be added to base URL) params (Optional[dict]): HTTP request parameters data (Optional[str]): JSON-encoded string payload for POST Returns: ...
def _send_message(self, method, endpoint, params=None, data=None): url = self.url + endpoint r = self.session.request(method, url, params=params, data=data, auth=self.auth, timeout=30) return r.json()
180,251
Change the bytecode to use the given library address. Args: hex_code (bin): The bytecode encoded in hexadecimal. library_name (str): The library that will be resolved. library_address (str): The address of the library. Returns: bin: The bytecode encoded in hexadecimal with the ...
def solidity_resolve_address(hex_code, library_symbol, library_address): if library_address.startswith('0x'): raise ValueError('Address should not contain the 0x prefix') try: decode_hex(library_address) except TypeError: raise ValueError( 'library_address contains ...
181,196