INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns n random bytes generated with given seed --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/ octet - stream responses: 200: description: Bytes.
def random_bytes(n): """Returns n random bytes generated with given seed --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Bytes. """ n = min(n, 100 * 1024) ...
Streams n random bytes generated with given seed at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/ octet - stream responses: 200: description: Bytes.
def stream_random_bytes(n): """Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/octet-stream responses: 200: description: Byt...
Streams n random bytes generated with given seed at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: numbytes type: int produces: - application/ octet - stream responses: 200: description: Bytes.
def range_request(numbytes): """Streams n random bytes generated with given seed, at given chunk size per packet. --- tags: - Dynamic data parameters: - in: path name: numbytes type: int produces: - application/octet-stream responses: 200: descript...
Generate a page containing n links to other pages which do the same. --- tags: - Dynamic data parameters: - in: path name: n type: int - in: path name: offset type: int produces: - text/ html responses: 200: description: HTML links.
def link_page(n, offset): """Generate a page containing n links to other pages which do the same. --- tags: - Dynamic data parameters: - in: path name: n type: int - in: path name: offset type: int produces: - text/html responses: 200...
Returns a simple image of the type suggest by the Accept header. --- tags: - Images produces: - image/ webp - image/ svg + xml - image/ jpeg - image/ png - image/ * responses: 200: description: An image.
def image(): """Returns a simple image of the type suggest by the Accept header. --- tags: - Images produces: - image/webp - image/svg+xml - image/jpeg - image/png - image/* responses: 200: description: An image. """ headers = get_headers() ...
Returns a value from choices chosen by weighted random selection
def weighted_choice(choices): """Returns a value from choices chosen by weighted random selection choices should be a list of (value, weight) tuples. eg. weighted_choice([('val1', 5), ('val2', 0.3), ('val3', 1)]) """ values, weights = zip(*choices) total = 0 cum_weights = [] for w in ...
X - Runtime Flask Response Decorator.
def x_runtime(f, *args, **kwargs): """X-Runtime Flask Response Decorator.""" _t0 = now() r = f(*args, **kwargs) _t1 = now() r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0))) return r
GZip Flask Response Decorator.
def gzip(f, *args, **kwargs): """GZip Flask Response Decorator.""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data gzip_buffer = BytesIO() gzip_file = gzip2.GzipFile( mode='wb', compresslevel=4, fileobj=...
Deflate Flask Response Decorator.
def deflate(f, *args, **kwargs): """Deflate Flask Response Decorator.""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflater = zlib.compressobj() deflated_data = deflater.compress(content) deflated_data += deflater.flu...
Brotli Flask Response Decorator
def brotli(f, *args, **kwargs): """Brotli Flask Response Decorator""" data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflated_data = _brotli.compress(content) if isinstance(data, Response): data.data = deflated_data ...
Parses the version out of libjsonnet. h
def get_version(): """ Parses the version out of libjsonnet.h """ with open(os.path.join(DIR, 'include/libjsonnet.h')) as f: for line in f: if '#define' in line and 'LIB_JSONNET_VERSION' in line: v_code = line.partition('LIB_JSONNET_VERSION')[2].strip('\n "') ...
Get fractal coordinates from query string call mandelbrot to generate image.
def handle_fractal(): """Get fractal coordinates from query string, call mandelbrot to generate image. Returns: The image, wrapped in an HTML response. """ if check_etag(): return flask.make_response(), 304 level = int(flask.request.args.get("l", "0")) x = float(int(flask.requ...
Return a copy of the config with $ { - } handled.
def preprocess(config): """Return a copy of the config with ${-} handled.""" def aux(ctx, service_name, service): compiler, _ = get_compiler(config, service) r2 = compiler.preprocess(ctx, service_name, service) ctx = ctx + [service_name] for child_name, child in compiler.childre...
Create all required build artefacts modify config to refer to them.
def get_build_artefacts(config): """Create all required build artefacts, modify config to refer to them.""" def aux(ctx, service_name, service): compiler, environment = get_compiler(config, service) new_service, service_barts = compiler.getBuildArtefacts(environment, ctx, service) ctx =...
Load the input - hidden weight matrix from the original C word2vec - tool format. Note that the information stored in the file is incomplete ( the binary tree is missing ) so while you can query for word similarity etc. you cannot continue training with a model loaded this way. binary is a boolean indicating whether th...
def load_word2vec_format( cls, fname, fvocab=None, binary=False, encoding='utf8', unicode_errors='strict', limit=None, datatype=REAL): """ Load the input-hidden weight matrix from the original C word2vec-tool...
Accept a single word as input. Returns the word s representations in vector space as a 1D numpy array. If use_norm is True returns the normalized word vector. Example:: >>> trained_model [ office ] array ( [ - 1. 40128313e - 02... ] )
def word_vec(self, word, use_norm=False): """ Accept a single word as input. Returns the word's representations in vector space, as a 1D numpy array. If `use_norm` is True, returns the normalized word vector. Example:: >>> trained_model['office'] array([ -1.40...
Get nearest words with KDTree ranking by cosine distance
def neighbours(self, word, size = 10): """ Get nearest words with KDTree, ranking by cosine distance """ word = word.strip() v = self.word_vec(word) [distances], [points] = self.kdt.query(array([v]), k = size, return_distance = True) assert len(distances) == len(p...
Turn seed into a np. random. RandomState instance. Method originally from maciejkula/ glove - python and written by
def get_random_state(seed): """ Turn seed into a np.random.RandomState instance. Method originally from maciejkula/glove-python, and written by @joshloyal. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (numbers.Integral, np.integer)): ...
Return a file - like object ready to be read from the beginning. input is either a filename ( gz/ bz2 also supported ) or a file - like object supporting seek.
def file_or_filename(input): """ Return a file-like object ready to be read from the beginning. `input` is either a filename (gz/bz2 also supported) or a file-like object supporting seek. """ if isinstance(input, string_types): # input was a filename: open as file yield smart_open(i...
Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring.
def deaccent(text): """ Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring. Return input string with accents removed, as unicode. >>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek") u'Sef chomutovskych komunistu dostal post...
Recursively copy a directory ala shutils. copytree but hardlink files instead of copying. Available on UNIX systems only.
def copytree_hardlink(source, dest): """ Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying. Available on UNIX systems only. """ copy2 = shutil.copy2 try: shutil.copy2 = os.link shutil.copytree(source, dest) finally: shutil.copy2 ...
Iteratively yield tokens as unicode strings removing accent marks and optionally lowercasing the unidoce string by assigning True to one of the parameters lowercase to_lower or lower.
def tokenize( text, lowercase=False, deacc=False, encoding='utf8', errors="strict", to_lower=False, lower=False): """ Iteratively yield tokens as unicode strings, removing accent marks and optionally lowercasing the unidoce string by assigning True ...
Convert a document into a list of tokens.
def simple_preprocess(doc, deacc=False, min_len=2, max_len=15): """ Convert a document into a list of tokens. This lowercases, tokenizes, de-accents (optional). -- the output are final tokens = unicode strings, that won't be processed any further. """ tokens = [ token for token in toke...
Convert a string ( unicode or bytestring in encoding ) to bytestring in utf8.
def any2utf8(text, errors='strict', encoding='utf8'): """Convert a string (unicode or bytestring in `encoding`), to bytestring in utf8.""" if isinstance(text, unicode): return text.encode('utf8') # do bytestring -> unicode -> utf8 full circle, to ensure valid utf8 return unicode(text, encoding, ...
Convert a string ( bytestring in encoding or unicode ) to unicode.
def any2unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors)
Check if an object is Number
def is_digit(obj): ''' Check if an object is Number ''' return isinstance(obj, (numbers.Integral, numbers.Complex, numbers.Real))
return True if ch is Chinese character. full - width puncts/ latins are not counted in.
def is_zh(ch): """return True if ch is Chinese character. full-width puncts/latins are not counted in. """ x = ord(ch) # CJK Radicals Supplement and Kangxi radicals if 0x2e80 <= x <= 0x2fef: return True # CJK Unified Ideographs Extension A elif 0x3400 <= x <= 0x4dbf: retu...
load stop words
def _load_stopwords(file_path): ''' load stop words ''' global _stopwords if sys.version_info[0] < 3: words = open(file_path, 'r') else: words = open(file_path, 'r', encoding='utf-8') stopwords = words.readlines() for w in stopwords: _stopwords.add(any2unicode(w)....
segment words with jieba
def _segment_words(sen): ''' segment words with jieba ''' words, tags = [], [] m = _tokenizer.cut(sen, HMM=True) # HMM更好的识别新词 for x in m: words.append(x.word) tags.append(x.flag) return words, tags
load word2vec model
def _load_w2v(model_file=_f_model, binary=True): ''' load word2vec model ''' if not os.path.exists(model_file): print("os.path : ", os.path) raise Exception("Model file [%s] does not exist." % model_file) return KeyedVectors.load_word2vec_format( model_file, binary=binary, un...
get word2vec data by sentence sentence is segmented string.
def _get_wv(sentence, ignore=False): ''' get word2vec data by sentence sentence is segmented string. ''' global _vectors vectors = [] for y in sentence: y_ = any2unicode(y).strip() if y_ not in _stopwords: syns = nearby(y_)[0] # print("sentence %s word...
Return the Levenshtein distance between two strings. Based on: http:// rosettacode. org/ wiki/ Levenshtein_distance#Python
def _levenshtein_distance(sentence1, sentence2): ''' Return the Levenshtein distance between two strings. Based on: http://rosettacode.org/wiki/Levenshtein_distance#Python ''' first = any2utf8(sentence1).decode('utf-8', 'ignore') second = any2utf8(sentence2).decode('utf-8', 'ignore') ...
使用空间距离近的词汇优化编辑距离计算
def _nearby_levenshtein_distance(s1, s2): ''' 使用空间距离近的词汇优化编辑距离计算 ''' s1_len, s2_len = len(s1), len(s2) maxlen = s1_len if s1_len == s2_len: first, second = sorted([s1, s2]) elif s1_len < s2_len: first = s1 second = s2 maxlen = s2_len else: first = ...
compute similarity with distance measurement
def _similarity_distance(s1, s2, ignore): ''' compute similarity with distance measurement ''' g = 0.0 try: g_ = cosine(_flat_sum_array(_get_wv(s1, ignore)), _flat_sum_array(_get_wv(s2, ignore))) if is_digit(g_): g = g_ except: pass u = _nearby_levenshtein_distance(s1, s2) ...
Nearby word
def nearby(word): ''' Nearby word ''' w = any2unicode(word) # read from cache if w in _cache_nearby: return _cache_nearby[w] words, scores = [], [] try: for x in _vectors.neighbours(w): words.append(x[0]) scores.append(x[1]) except: pass # ignore key ...
compare similarity s1: sentence1 s2: sentence2 seg: True: The original sentences need jieba. cut Flase: The original sentences have been cut. ignore: True: ignore OOV words False: get vector randomly for OOV words
def compare(s1, s2, seg=True, ignore=False, stopwords=False): ''' compare similarity s1 : sentence1 s2 : sentence2 seg : True : The original sentences need jieba.cut Flase : The original sentences have been cut. ignore: True: ignore OOV words False: get vector randomly for ...
Add a sample to the metric.
def add_sample(self, name, labels, value, timestamp=None, exemplar=None): """Add a sample to the metric. Internal-only, do not use.""" self.samples.append(Sample(name, labels, value, timestamp, exemplar))
Add a metric to the metric family.
def add_metric(self, labels, value, created=None, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: The value of the metric created: Optional unix timestamp the child was created at. """ self.samples.append(S...
Add a metric to the metric family.
def add_metric(self, labels, count_value, sum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values count_value: The count value of the metric. sum_value: The sum value of the metric. """ self.samples.append(Samp...
Add a metric to the metric family.
def add_metric(self, labels, buckets, sum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values buckets: A list of lists. Each inner list can be a pair of bucket name and value, or a triple of bucket name, valu...
Add a metric to the metric family.
def add_metric(self, labels, buckets, gsum_value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values buckets: A list of pairs of bucket names and values. The buckets must be sorted, and +Inf present. gsum_value: The su...
Add a metric to the metric family.
def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: A dict of labels """ self.samples.append(Sample( self.name + '_info', dict(dict(zip(self._labelnames, labels...
Add a metric to the metric family.
def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: A dict of string state names to booleans """ labels = tuple(labels) for state, enabled in sorted(value.items()): ...
Create a WSGI app which serves the metrics from a registry.
def make_wsgi_app(registry=REGISTRY): """Create a WSGI app which serves the metrics from a registry.""" def prometheus_app(environ, start_response): params = parse_qs(environ.get('QUERY_STRING', '')) r = registry encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT')) ...
Starts a WSGI server for prometheus metrics as a daemon thread.
def start_wsgi_server(port, addr='', registry=REGISTRY): """Starts a WSGI server for prometheus metrics as a daemon thread.""" app = make_wsgi_app(registry) httpd = make_server(addr, port, app, handler_class=_SilentHandler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start...
Starts an HTTP server for prometheus metrics as a daemon thread
def start_http_server(port, addr='', registry=REGISTRY): """Starts an HTTP server for prometheus metrics as a daemon thread""" CustomMetricsHandler = MetricsHandler.factory(registry) httpd = _ThreadingSimpleServer((addr, port), CustomMetricsHandler) t = threading.Thread(target=httpd.serve_forever) t...
Write metrics to the given path.
def write_to_textfile(path, registry): """Write metrics to the given path. This is intended for use with the Node exporter textfile collector. The path must end in .prom for the textfile collector to process it.""" tmppath = '%s.%s.%s' % (path, os.getpid(), threading.current_thread().ident) with op...
Default handler that implements HTTP/ HTTPS connections.
def default_handler(url, method, timeout, headers, data): """Default handler that implements HTTP/HTTPS connections. Used by the push_to_gateway functions. Can be re-used by other handlers.""" def handle(): request = Request(url, data=data) request.get_method = lambda: method for k...
Handler that implements HTTP/ HTTPS connections with Basic Auth.
def basic_auth_handler(url, method, timeout, headers, data, username=None, password=None): """Handler that implements HTTP/HTTPS connections with Basic Auth. Sets auth headers using supplied 'username' and 'password', if set. Used by the push_to_gateway functions. Can be re-used by other handlers.""" ...
Push metrics to the given pushgateway.
def push_to_gateway( gateway, job, registry, grouping_key=None, timeout=30, handler=default_handler): """Push metrics to the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defa...
Delete metrics from the given pushgateway.
def delete_from_gateway( gateway, job, grouping_key=None, timeout=30, handler=default_handler): """Delete metrics from the given pushgateway. `gateway` the url for your push gateway. Either of the form 'http://pushgateway.local', or 'pushgateway.local'. Scheme defaults to 'h...
Grouping key with instance set to the IP Address of this host.
def instance_ip_grouping_key(): """Grouping key with instance set to the IP Address of this host.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s: s.connect(('localhost', 0)) return {'instance': s.getsockname()[0]}
Returns a dynamic MetricsHandler class tied to the passed registry.
def factory(cls, registry): """Returns a dynamic MetricsHandler class tied to the passed registry. """ # This implementation relies on MetricsHandler.registry # (defined above and defaulted to REGISTRY). # As we have unicode_literals, we need to create a str() ...
Parse Prometheus text format from a file descriptor.
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = None allowed_names = [] eof = F...
Add a collector to the registry.
def register(self, collector): """Add a collector to the registry.""" with self._lock: names = self._get_names(collector) duplicates = set(self._names_to_collectors).intersection(names) if duplicates: raise ValueError( 'Duplicated t...
Remove a collector from the registry.
def unregister(self, collector): """Remove a collector from the registry.""" with self._lock: for name in self._collector_to_names[collector]: del self._names_to_collectors[name] del self._collector_to_names[collector]
Get names of timeseries the collector produces.
def _get_names(self, collector): """Get names of timeseries the collector produces.""" desc_func = None # If there's a describe function, use it. try: desc_func = collector.describe except AttributeError: pass # Otherwise, if auto describe is enabl...
Yields metrics from the collectors in the registry.
def collect(self): """Yields metrics from the collectors in the registry.""" collectors = None with self._lock: collectors = copy.copy(self._collector_to_names) for collector in collectors: for metric in collector.collect(): yield metric
Returns object that only collects some metrics.
def restricted_registry(self, names): """Returns object that only collects some metrics. Returns an object which upon collect() will return only samples with the given names. Intended usage is: generate_latest(REGISTRY.restricted_registry(['a_timeseries'])) Experim...
Returns the sample value or None if not found.
def get_sample_value(self, name, labels=None): """Returns the sample value, or None if not found. This is inefficient, and intended only for use in unittests. """ if labels is None: labels = {} for metric in self.collect(): for s in metric.samples: ...
Do bookkeeping for when one process dies in a multi - process setup.
def mark_process_dead(pid, path=None): """Do bookkeeping for when one process dies in a multi-process setup.""" if path is None: path = os.environ.get('prometheus_multiproc_dir') for f in glob.glob(os.path.join(path, 'gauge_livesum_{0}.db'.format(pid))): os.remove(f) for f in glob.glob(o...
Merge metrics from given mmap files.
def merge(files, accumulate=True): """Merge metrics from given mmap files. By default, histograms are accumulated, as per prometheus wire format. But if writing the merged data back to mmap files, use accumulate=False to avoid compound accumulation. """ metrics = {} ...
A replacement for inspect. getargspec
def getargspec(f): """A replacement for inspect.getargspec""" spec = getfullargspec(f) return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
decorate ( func caller ) decorates a function using a caller.
def decorate(func, caller): """ decorate(func, caller) decorates a function using a caller. """ evaldict = dict(_call_=caller, _func_=func) fun = FunctionMaker.create( func, "return _call_(_func_, %(shortsignature)s)", evaldict, __wrapped__=func) if hasattr(func, '__qualname__'):...
decorator ( caller ) converts a caller function into a decorator
def decorator(caller, _func=None): """decorator(caller) converts a caller function into a decorator""" if _func is not None: # return a decorated function # this is obsolete behavior; you should use decorate instead return decorate(_func, caller) # else return a decorator function if in...
Append a to the list of the virtual ancestors unless it is already included.
def append(a, vancestors): """ Append ``a`` to the list of the virtual ancestors, unless it is already included. """ add = True for j, va in enumerate(vancestors): if issubclass(va, a): add = False break if issubclass(a, va): vancestors[j] = a ...
Parse Prometheus text format from a file descriptor.
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = '' documentation = '' typ = 'un...
Format a key for use in the mmap file.
def mmap_key(metric_name, name, labelnames, labelvalues): """Format a key for use in the mmap file.""" # ensure labels are in consistent order for identity labels = dict(zip(labelnames, labelvalues)) return json.dumps([metric_name, name, labels], sort_keys=True)
Initialize a value. Lock must be held by caller.
def _init_value(self, key): """Initialize a value. Lock must be held by caller.""" encoded = key.encode('utf-8') # Pad to be 8-byte aligned. padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8)) value = struct.pack('i{0}sd'.format(len(padded)).encode(), len(encoded), padded, 0...
Yield ( key value pos ). No locking is performed.
def _read_all_values(self): """Yield (key, value, pos). No locking is performed.""" pos = 8 # cache variables to local ones and prevent attributes lookup # on every loop iteration used = self._used data = self._m unpack_from = struct.unpack_from while p...
Return the child for the given labelset.
def labels(self, *labelvalues, **labelkwargs): """Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTT...
Remove the given labelset from the metric.
def remove(self, *labelvalues): if not self._labelnames: raise ValueError('No label names were set when constructing %s' % self) """Remove the given labelset from the metric.""" if len(labelvalues) != len(self._labelnames): raise ValueError('Incorrect label count (expect...
Call the provided function to return the Gauge value.
def set_function(self, f): """Call the provided function to return the Gauge value. The function must return a float, and may be called from multiple threads. All other methods of the Gauge become NOOPs. """ def samples(self): return (('', {}, float(f())),) ...
Observe the given amount.
def observe(self, amount): """Observe the given amount.""" self._count.inc(1) self._sum.inc(amount)
Observe the given amount.
def observe(self, amount): """Observe the given amount.""" self._sum.inc(amount) for i, bound in enumerate(self._upper_bounds): if amount <= bound: self._buckets[i].inc(1) break
Set info metric.
def info(self, val): """Set info metric.""" if self._labelname_set.intersection(val.keys()): raise ValueError('Overlapping labels for Info metric, metric: %s child: %s' % ( self._labelnames, val)) with self._lock: self._value = dict(val)
Set enum metric state.
def state(self, state): """Set enum metric state.""" with self._lock: self._value = self._states.index(state)
Returns an instance from given settings.
def from_settings(cls, settings): """Returns an instance from given settings. This uses by default the key ``dupefilter:<timestamp>``. When using the ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as it needs to pass the spider name in the key. Parameters ...
Returns True if request was already seen.
def request_seen(self, request): """Returns True if request was already seen. Parameters ---------- request : scrapy.http.Request Returns ------- bool """ fp = self.request_fingerprint(request) # This returns the number of values added, ...
Logs given request.
def log(self, request, spider): """Logs given request. Parameters ---------- request : scrapy.http.Request spider : scrapy.spiders.Spider """ if self.debug: msg = "Filtered duplicate request: %(request)s" self.logger.debug(msg, {'request'...
Process items from a redis queue.
def process_items(r, keys, timeout, limit=0, log_every=1000, wait=.1): """Process items from a redis queue. Parameters ---------- r : Redis Redis connection instance. keys : list List of keys to read the items from. timeout: int Read timeout. """ limit = limit o...
Returns a redis client instance from given Scrapy settings object.
def get_redis_from_settings(settings): """Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` sett...
Returns a redis client instance.
def get_redis(**kwargs): """Returns a redis client instance. Parameters ---------- redis_cls : class, optional Defaults to ``redis.StrictRedis``. url : str, optional If given, ``redis_cls.from_url`` is used to instantiate the class. **kwargs Extra parameters to be passed...
Returns a str if a bytes object is given.
def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given.""" if six.PY3 and isinstance(s, bytes): return s.decode(encoding) return s
Setup redis connection and idle signal.
def setup_redis(self, crawler=None): """Setup redis connection and idle signal. This should be called after the spider has set its crawler object. """ if self.server is not None: return if crawler is None: # We allow optional crawler argument to keep bac...
Returns a request to be scheduled or none.
def next_requests(self): """Returns a request to be scheduled or none.""" use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET) fetch_one = self.server.spop if use_set else self.server.lpop # XXX: Do we need to use a timeout here? found = 0 ...
Returns a Request instance from data coming from Redis.
def make_request_from_data(self, data): """Returns a Request instance from data coming from Redis. By default, ``data`` is an encoded URL. You can override this method to provide your own message decoding. Parameters ---------- data : bytes Message from redi...
Schedules a request if available
def schedule_next_requests(self): """Schedules a request if available""" # TODO: While there is capacity, schedule a batch of redis requests. for req in self.next_requests(): self.crawler.engine.crawl(req, spider=self)
Encode a request object
def _encode_request(self, request): """Encode a request object""" obj = request_to_dict(request, self.spider) return self.serializer.dumps(obj)
Decode an request previously encoded
def _decode_request(self, encoded_request): """Decode an request previously encoded""" obj = self.serializer.loads(encoded_request) return request_from_dict(obj, self.spider)
Push a request
def push(self, request): """Push a request""" self.server.lpush(self.key, self._encode_request(request))
Push a request
def push(self, request): """Push a request""" data = self._encode_request(request) score = -request.priority # We don't use zadd method as the order of arguments change depending on # whether the class is Redis or StrictRedis, and the option of using # kwargs only accepts...
Pop a request timeout not support in this queue class
def pop(self, timeout=0): """ Pop a request timeout not support in this queue class """ # use atomic range/remove using multi/exec pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count...
Find the closest xterm - 256 approximation to the given RGB value.
def rgb2short(r, g, b): """ Find the closest xterm-256 approximation to the given RGB value. @param r,g,b: each is a number between 0-255 for the Red, Green, and Blue values @returns: integer between 0 and 255, compatible with xterm. >>> rgb2short(18, 52, 86) 23 >>> rgb2short(255, 255, 255) ...
Given a string name of one of the properties of this class returns the value of the property as a string when the value is greater than 1. When it is not greater than one returns an empty string.
def n_or_empty(self, _key): """Given a string name of one of the properties of this class, returns the value of the property as a string when the value is greater than 1. When it is not greater than one, returns an empty string. As an example, if you want to show an icon for new files, ...
If the user has asked for each directory name to be shortened will return the name up to their specified length. Otherwise returns the full name.
def maybe_shorten_name(powerline, name): """If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.""" max_size = powerline.segment_conf("cwd", "max_dir_size") if max_size: return name[:max_size] r...
Returns the foreground and background color to use for the given name.
def get_fg_bg(powerline, name, is_last_dir): """Returns the foreground and background color to use for the given name. """ if requires_special_home_display(powerline, name): return (powerline.theme.HOME_FG, powerline.theme.HOME_BG,) if is_last_dir: return (powerline.theme.CWD_FG, powerl...
Determine and check the current working directory for validity.
def get_valid_cwd(): """Determine and check the current working directory for validity. Typically, an directory arises when you checkout a different branch on git that doesn't have this directory. When an invalid directory is found, a warning is printed to the screen, but the directory is still returne...
Brutally simple email address validation. Note unlike most email address validation * raw ip address ( literal ) domain parts are not allowed. * John Doe <local_part@domain. com > style pretty email addresses are processed * the local part check is extremely basic. This raises the possibility of unicode spoofing but no...
def validate_email(value: str) -> Tuple[str, str]: """ Brutally simple email address validation. Note unlike most email address validation * raw ip address (literal) domain parts are not allowed. * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed * the local part check...
Create a DSN from from connection settings.
def make_dsn( *, driver: str, user: str = None, password: str = None, host: str = None, port: str = None, name: str = None, query: Dict[str, Any] = None, ) -> str: """ Create a DSN from from connection settings. Stolen approximately from sqlalchemy/engine/url.py:URL. """...