code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return self.transform(lambda rdd: rdd.reduceByKey(func))
def reduceByKey(self, func, numPartitions=None)
Apply reduceByKey to every RDD. :param func: reduce function to apply :param int numPartitions: number of partitions :rtype: DStream
5.477049
6.136938
0.892473
return self.transform( lambda rdd: (rdd.repartition(numPartitions) if not isinstance(rdd, EmptyRDD) else rdd) )
def repartition(self, numPartitions)
Repartition every RDD. :rtype: DStream Example: >>> import pysparkling >>> sc = pysparkling.Context() >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1) >>> ( ... ssc ... .queueStream([['hello', 'world']]) ... .repartition(2)...
4.684434
5.993656
0.781565
self.foreachRDD( lambda time_, rdd: rdd.saveAsTextFile('{}-{:.0f}{}'.format( prefix, time_ * 1000, suffix if suffix is not None else '')) )
def saveAsTextFiles(self, prefix, suffix=None)
Save every RDD as a text file (or sets of text files). :param string prefix: path prefix of the output :param string suffix: file suffix (e.g. '.gz' to enable compression) Example: >>> from backports import tempfile >>> import os, pysparkling >>> sc = pysparkling.Cont...
5.879546
4.772616
1.231934
return self.transform(lambda time_, rdd: rdd if begin <= time_ <= end else EmptyRDD(self._context._context))
def slice(self, begin, end)
Filter RDDs to between begin and end. :param datetime.datetime|int begin: datetiem or unix timestamp :param datetime.datetime|int end: datetiem or unix timestamp :rtype: DStream
23.298571
17.289009
1.347594
if func.__code__.co_argcount == 1: one_arg_func = func func = lambda _, rdd: one_arg_func(rdd) return TransformedDStream(self, func)
def transform(self, func)
Return a new DStream where each RDD is transformed by ``f``. :param f: Function that transforms an RDD. :rtype: DStream
5.850511
4.740986
1.234028
if func.__code__.co_argcount == 2: two_arg_func = func func = lambda _, rdd_a, rdd_b: two_arg_func(rdd_a, rdd_b) return TransformedWithDStream(self, func, other)
def transformWith(self, func, other, keepSerializer=False)
Return a new DStream where each RDD is transformed by ``f``. :param f: transformation function :rtype: DStream The transformation function can have arguments ``(time, rdd_a, rdd_b)`` or ``(rdd_a, rdd_b)``.
4.908438
3.769076
1.302292
def union_rdds(rdd_a, rdd_b): return self._context._context.union((rdd_a, rdd_b)) return self.transformWith(union_rdds, other)
def union(self, other)
Union of two DStreams. :param DStream other: Another DStream. Example: >>> import pysparkling >>> sc = pysparkling.Context() >>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1) >>> odd = ssc.queueStream([[1], [3], [5]]) >>> even = ssc.queueStream([[2], [...
7.746074
6.133599
1.262892
files = [] for expr in all_expr.split(','): expr = expr.strip() files += fs.get_fs(expr).resolve_filenames(expr) log.debug('Filenames: {0}'.format(files)) return files
def resolve_filenames(all_expr)
resolve expression for a filename :param all_expr: A comma separated list of expressions. The expressions can contain the wildcard characters ``*`` and ``?``. It also resolves Spark datasets to the paths of the individual partitions (i.e. ``my_data`` gets resolve...
4.29831
4.831016
0.889732
stream = self.fs.load() stream = self.codec.decompress(stream) return stream
def load(self)
Load the data from a file. :rtype: io.BytesIO
10.388354
13.364282
0.777322
if stream is None: stream = BytesIO() if isinstance(stream, bytes): stream = BytesIO(stream) stream = self.codec.compress(stream) self.fs.dump(stream) return self
def dump(self, stream=None)
Writes a stream to a file. :param stream: A BytesIO instance. ``bytes`` are also possible and are converted to BytesIO. :rtype: File
4.6052
4.278551
1.076346
'''creates a logger obj''' # Pull the local ip and username for meaningful logging username = getpass.getuser() # Set the logger FORMAT = '%(asctime)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) extra_information = {'user': username} logger = logging.getLogger('fak...
def fake2db_logger()
creates a logger obj
6.36176
6.278772
1.013217
'''Main handler for the operation ''' rows = number_of_rows db = self.database_caller_creator(host, port, name) if custom: self.custom_db_creator(rows, db, custom) sys.exit(0) self.data_filler_simple_registration(rows, db) sel...
def fake2db_mongodb_initiator(self, host, port, number_of_rows, name=None, custom=None)
Main handler for the operation
4.500709
4.149276
1.084697
'''creates a mongodb database returns the related connection object which will be later used to spawn the cursor ''' client = pymongo.MongoClient(host, port) if name: db = client[name] else: db = client['mongodb_' + str_generator(self)] ...
def database_caller_creator(self, host, port, name=None)
creates a mongodb database returns the related connection object which will be later used to spawn the cursor
8.859854
3.727981
2.376582
'''Main handler for the operation ''' client, pipe = self.database_caller_creator(host, port, name) if custom: self.custom_db_creator(number_of_rows, pipe, custom) client.save() sys.exit(0) self.data_filler_simple_registration(number_of_rows...
def fake2db_redis_initiator(self, host, port, number_of_rows, name=None, custom=None)
Main handler for the operation
3.999002
3.713667
1.076834
'''creates a redis connection object which will be later used to modify the db ''' name = name or 0 client = redis.StrictRedis(host=host, port=port, db=name) pipe = client.pipeline(transaction=False) return client, pipe
def database_caller_creator(self, host, port, name=None)
creates a redis connection object which will be later used to modify the db
6.174116
3.361423
1.836757
'''creates keys with simple regis. information ''' try: for i in range(number_of_rows): pipe.hmset('simple_registration:%s' % i, { 'id': rnd_id_generator(self), 'email': self.faker.safe_email(), 'password': ...
def data_filler_simple_registration(self, number_of_rows, pipe)
creates keys with simple regis. information
6.90278
5.549903
1.243766
'''creates keys with detailed regis. information ''' try: for i in range(number_of_rows): pipe.hmset('detailed_registration:%s' % i, { 'id': rnd_id_generator(self), 'email': self.faker.safe_email(), 'passwor...
def data_filler_detailed_registration(self, number_of_rows, pipe)
creates keys with detailed regis. information
4.540286
3.924122
1.15702
'''creates keys with user agent data ''' try: for i in range(number_of_rows): pipe.hmset('user_agent:%s' % i, { 'id': rnd_id_generator(self), 'ip': self.faker.ipv4(), 'countrycode': self.faker.country_code()...
def data_filler_user_agent(self, number_of_rows, pipe)
creates keys with user agent data
5.295753
4.788998
1.105817
'''creates keys with company data ''' try: for i in range(number_of_rows): pipe.hmset('company:%s' % i, { 'id': rnd_id_generator(self), 'name': self.faker.company(), 'date': self.faker.date(pattern="%d-%m-%Y...
def data_filler_company(self, number_of_rows, pipe)
creates keys with company data
5.069769
4.706587
1.077165
'''creates keys with customer data ''' try: for i in range(number_of_rows): pipe.hmset('customer:%s' % i, { 'id': rnd_id_generator(self), 'name': self.faker.first_name(), 'lastname': self.faker.last_name(), ...
def data_filler_customer(self, number_of_rows, pipe)
creates keys with customer data
3.335765
3.164146
1.054239
'''Main handler for the operation ''' rows = number_of_rows cursor, conn = self.database_caller_creator(number_of_rows, **connection_kwargs) self.data_filler_simple_registration(rows, cursor, conn) self.data_filler_detailed_registration(rows, cursor, conn) self.d...
def fake2db_initiator(self, number_of_rows, **connection_kwargs)
Main handler for the operation
3.895776
3.442863
1.131551
'''creates a postgresql db returns the related connection object which will be later used to spawn the cursor ''' cursor = None conn = None if name: dbname = name else: dbname = 'postgresql_' + str_generator(self).lower() t...
def database_caller_creator(self, number_of_rows, username, password, host, port, name=None, custom=None)
creates a postgresql db returns the related connection object which will be later used to spawn the cursor
3.244154
2.593721
1.250772
'''creates and fills the table with simple regis. information ''' custom_d = faker_options_container() sqlst = "CREATE TABLE custom (id serial PRIMARY KEY," custom_payload = "INSERT INTO custom (" # form the sql query that will set the db up for c in cus...
def custom_db_creator(self, number_of_rows, cursor, conn, custom)
creates and fills the table with simple regis. information
4.948101
4.445419
1.113079
'''Main handler for the operation ''' rows = number_of_rows if name: cursor, conn = self.database_caller_creator(host, port, password, username, name) else: cursor, conn = self.database_caller_creator(host, port, password, username) if custom: ...
def fake2db_mysql_initiator(self, host, port, password, username, number_of_rows, name=None, custom=None)
Main handler for the operation
3.146988
3.038683
1.035642
'''creates a mysql db returns the related connection object which will be later used to spawn the cursor ''' cursor = None conn = None try: if name: db = name else: db = 'mysql_' + str_generator(self) ...
def database_caller_creator(self, host, port, password, username, name=None)
creates a mysql db returns the related connection object which will be later used to spawn the cursor
4.100401
2.992786
1.370095
'''creates and fills the table with simple regis. information ''' custom_d = faker_options_container() sqlst = "CREATE TABLE `custom` (`id` varchar(200) NOT NULL," custom_payload = "INSERT INTO custom (id," # form the sql query that will set the db up fo...
def custom_db_creator(self, number_of_rows, cursor, conn, custom)
creates and fills the table with simple regis. information
4.737134
4.333595
1.093119
'''creates and fills the table with company data ''' companies_data = [] try: for i in range(0, number_of_rows): companies_data.append((rnd_id_generator(self), self.faker.company(), self.faker.date(pattern="%Y-%m-%d"), ...
def data_filler_company(self, number_of_rows, cursor, conn)
creates and fills the table with company data
4.275941
4.171007
1.025158
'''creates and fills the table with customer ''' customer_data = [] try: for i in range(0, number_of_rows): customer_data.append(( rnd_id_generator(self), self.faker.first_name(), self.faker.last_name(), self.faker...
def data_filler_customer(self, number_of_rows, cursor, conn)
creates and fills the table with customer
3.265759
3.236749
1.008962
'''this helper method checks if mysql server is available in the sys if not fires up one ''' try: subprocess.check_output("pgrep mysqld", shell=True) except Exception: logger.warning( 'Your mysql server is offline, fake2db will try to launch it now!', extr...
def _mysqld_process_checkpoint()
this helper method checks if mysql server is available in the sys if not fires up one
13.235599
7.317198
1.808834
'''this helper method checks if redis server is available in the sys if not fires up one ''' try: subprocess.check_output("pgrep redis", shell=True) except Exception: logger.warning( 'Your redis server is offline, fake2db will try to launch it now!', extra...
def _redis_process_checkpoint(host, port)
this helper method checks if redis server is available in the sys if not fires up one
10.227593
6.291208
1.625696
'''Main handler for the operation ''' rows = number_of_rows conn = self.database_caller_creator(name) if custom: self.custom_db_creator(rows, conn, custom) conn.close() sys.exit(0) self.data_filler_simple_registration(rows...
def fake2db_sqlite_initiator(self, number_of_rows, name=None, custom=None)
Main handler for the operation
4.410738
4.042239
1.091162
'''creates a sqlite3 db returns the related connection object which will be later used to spawn the cursor ''' try: if name: database = name + '.db' else: database = 'sqlite_' + str_generator(self) + '.db' conn...
def database_caller_creator(self, name=None)
creates a sqlite3 db returns the related connection object which will be later used to spawn the cursor
7.760197
4.737242
1.638126
'''creates and fills the table with simple regis. information ''' cursor = conn.cursor() cursor.execute(''' CREATE TABLE simple_registration(id TEXT PRIMARY KEY, email TEXT , password TEXT) ''') conn.commit() multi_lines = [] try:...
def data_filler_simple_registration(self, number_of_rows, conn)
creates and fills the table with simple regis. information
5.368032
4.742026
1.132012
'''creates and fills the table with user agent data ''' cursor = conn.cursor() cursor.execute(''' CREATE TABLE user_agent(id TEXT PRIMARY KEY, ip TEXT, countrycode TEXT, useragent TEXT) ''') conn.commit() multi_lines = [] try: ...
def data_filler_user_agent(self, number_of_rows, conn)
creates and fills the table with user agent data
4.452007
4.234788
1.051294
'''creates and fills the table with company data ''' cursor = conn.cursor() cursor.execute(''' CREATE TABLE company(id TEXT PRIMARY KEY, name TEXT, sdate TEXT, email TEXT, domain TEXT, city TEXT) ''') conn.commit() multi_lines = [] ...
def data_filler_company(self, number_of_rows, conn)
creates and fills the table with company data
4.666805
4.531848
1.02978
'''Main handler for the operation ''' rows = number_of_rows db = self.database_caller_creator(name) if custom: self.custom_db_creator(rows, db, custom) sys.exit(0) self.data_filler_simple_registration(rows, db) self.data_fille...
def fake2db_couchdb_initiator(self, number_of_rows, name=None, custom=None)
Main handler for the operation
4.699354
4.310212
1.090284
'''creates a couchdb database returns the related connection object which will be later used to spawn the cursor ''' couch = couchdb.Server() if name: db = couch.create(name) else: n = 'couchdb_' + lower_str_generator(self) db...
def database_caller_creator(self, name=None)
creates a couchdb database returns the related connection object which will be later used to spawn the cursor
8.320346
4.386843
1.896659
'''creates and fills the table with simple regis. information ''' try: simple_registration = db for i in range(0, number_of_rows): post_simple_reg = { "id": rnd_id_generator(self), "email": self.faker.safe_email(),...
def data_filler_simple_registration(self, number_of_rows, db)
creates and fills the table with simple regis. information
6.503528
5.573548
1.166856
'''creates and fills the table with detailed regis. information ''' try: detailed_registration = db data_list = list() for i in range(0, number_of_rows): post_det_reg = { "id": rnd_id_generator(self), "e...
def data_filler_detailed_registration(self, number_of_rows, db)
creates and fills the table with detailed regis. information
4.784783
4.294452
1.114178
'''creates and fills the table with user agent data ''' try: user_agent = db data_list = list() for i in range(0, number_of_rows): post_uo_reg = { "id": rnd_id_generator(self), "ip": self.faker.ipv4(), ...
def data_filler_user_agent(self, number_of_rows, db)
creates and fills the table with user agent data
6.04046
5.672705
1.064829
'''creates and fills the table with company data ''' try: company = db data_list = list() for i in range(0, number_of_rows): post_comp_reg = { "id": rnd_id_generator(self), "name": self.faker.company(), ...
def data_filler_company(self, number_of_rows, db)
creates and fills the table with company data
5.704552
5.40248
1.055914
'''creates and fills the table with customer data ''' try: customer = db data_list = list() for i in range(0, number_of_rows): post_cus_reg = { "id": rnd_id_generator(self), "name": self.faker.first_name...
def data_filler_customer(self, number_of_rows, db)
creates and fills the table with customer data
3.818133
3.683729
1.036486
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit) # Call that method, and show where in the tree it failed if it blows # up. try: return method(node, [self.visit(n) for n in node]) except (VisitationError, UndefinedLabel): # D...
def visit(self, node)
Walk a parse tree, transforming it into another representation. Recursively descend a parse tree, dispatching to the method named after the rule in the :class:`~parsimonious.grammar.Grammar` that produced each node. If, for example, a rule was... :: bold = '<b>' ...the ``v...
5.651127
5.360306
1.054255
if not self.grammar: raise RuntimeError( "The {cls}.{method}() shortcut won't work because {cls} was " "never associated with a specific " "grammar. Fill out its " "`grammar` attribute, and try again.".format( cls=self.__cl...
def _parse_or_match(self, text, pos, method_name)
Execute a parse or match on the default grammar, followed by a visitation. Raise RuntimeError if there is no default grammar specified.
7.151314
6.453797
1.108079
# Hard-code enough of the rules to parse the grammar that describes the # grammar description language, to bootstrap: comment = Regex(r'#[^\r\n]*', name='comment') meaninglessness = OneOf(Regex(r'\s+'), comment, name='meaninglessness') _ = ZeroOrMore(meaninglessness, nam...
def _expressions_from_rules(self, rule_syntax, custom_rules)
Return the rules for parsing the grammar definition syntax. Return a 2-tuple: a dict of rule names pointing to their expressions, and then the top-level expression for the first rule.
4.777043
4.679042
1.020945
left_paren, _, expression, right_paren, _ = parenthesized return expression
def visit_parenthesized(self, node, parenthesized)
Treat a parenthesized subexpression as just its contents. Its position in the tree suffices to maintain its grouping semantics.
11.957966
13.593892
0.879657
label, equals, expression = rule expression.name = label # Assign a name to the expr. return expression
def visit_rule(self, node, rule)
Assign a name to the Expression and return it.
24.477524
11.493872
2.129615
term, other_terms = sequence return Sequence(term, *other_terms)
def visit_sequence(self, node, sequence)
A parsed Sequence looks like [term node, OneOrMore node of ``another_term``s]. Flatten it out.
14.685349
7.009081
2.095189
tilde, literal, flags, _ = regex flags = flags.text.upper() pattern = literal.literal # Pull the string back out of the Literal # object. return Regex(pattern, ignore_case='I' in flags, locale='L' in flags, ...
def visit_regex(self, node, regex)
Return a ``Regex`` expression.
6.322055
6.050665
1.044853
if isinstance(expr, LazyReference): label = text_type(expr) try: reffed_expr = rule_map[label] except KeyError: raise UndefinedLabel(expr) return self._resolve_refs(rule_map, reffed_expr, done) else: if ...
def _resolve_refs(self, rule_map, expr, done)
Return an expression with all its lazy references recursively resolved. Resolve any lazy references in the expression ``expr``, recursing into all subexpressions. :arg done: The set of Expressions that have already been or are currently being resolved, to ward off redundant...
3.799494
3.667936
1.035867
_, rules = rules_list # Map each rule's name to its Expression. Later rules of the same name # override earlier ones. This lets us define rules multiple times and # have the last declaration win, so you can extend grammars by # concatenation. rule_map = OrderedD...
def visit_rules(self, node, rules_list)
Collate all the rules into a map. Return (map, default rule). The default rule is the first one. Or, if you have more than one rule of that name, it's the last-occurring rule of that name. (This lets you override the default rule when you extend a grammar.) If there are no string-based ...
10.478147
8.945767
1.171297
num_args = len(getargspec(callable).args) if num_args == 2: is_simple = True elif num_args == 5: is_simple = False else: raise RuntimeError("Custom rule functions must take either 2 or 5 " "arguments, not %s." % num_args) class AdHocExpression...
def expression(callable, rule_name, grammar)
Turn a plain callable into an Expression. The callable can be of this simple form:: def foo(text, pos): '''If this custom expression matches starting at text[pos], return the index where it stops matching. Otherwise, return None.''' if the expression matched: ...
4.028949
3.655084
1.102286
m = self.re.match(text, pos) if m is not None: span = m.span() node = RegexNode(self, text, pos, pos + span[1] - span[0]) node.match = m # TODO: A terrible idea for cache size? return node
def _uncached_match(self, text, pos, cache, error)
Return length of match, ``None`` if no match.
4.953811
5.102558
0.970849
flags = 'ilmsuxa' return ''.join(flags[i - 1] if (1 << i) & bits else '' for i in range(1, len(flags) + 1))
def _regex_flags_from_bits(self, bits)
Return the textual equivalent of numerically encoded regex flags.
4.769846
3.949759
1.20763
for optkey, optval in self._normalize_options(options): yield optkey if isinstance(optval, (list, tuple)): assert len(optval) == 2 and optval[0] and optval[ 1], 'Option value can only be either a string or a (tuple, list) of 2 items' ...
def _gegetate_args(self, options)
Generator of args parts based on options specification.
3.883302
3.519862
1.103254
options = self._gegetate_args(self.options) options = [x for x in options] # print 'options', options if self.css: self._prepend_css(self.css) if '--xvfb' in options: options.remove('--xvfb') yield self.xvfb # auto servern...
def _command(self, path=None)
Generator of all command parts :type options: object :return:
5.304167
5.256809
1.009009
for key, value in list(options.items()): if '--' in key: normalized_key = self._normalize_arg(key) else: normalized_key = '--%s' % self._normalize_arg(key) if isinstance(value, (list, tuple)): for opt_val in value: ...
def _normalize_options(self, options)
Generator of 2-tuples (option-key, option-value). When options spec is a list, generate a 2-tuples per list item. :param options: dict {option: value} returns: iterator (option-key, option-value) - option names lower cased and prepended with '--' if necessary. Non...
2.673729
2.563086
1.043168
if (isinstance(content, io.IOBase) or content.__class__.__name__ == 'StreamReaderWriter'): content = content.read() found = {} for x in re.findall('<meta [^>]*>', content): if re.search('name=["\']%s' % self.config.meta_tag_prefix, x): ...
def _find_options_in_meta(self, content)
Reads 'content' and extracts options encoded in HTML meta tags :param content: str or file-like object - contains HTML to parse returns: dict: {config option: value}
3.123925
2.98099
1.047949
rtn = IMGKit(url, 'url', options=options, toc=toc, cover=cover, config=config, cover_first=cover_first) return rtn.to_img(output_path)
def from_url(url, output_path, options=None, toc=None, cover=None, config=None, cover_first=None)
Convert URL/URLs to IMG file/files :param url: URL or list of URLs to be saved :param output_path: path to output PDF file/files. False means file will be returned as string :param options: (optional) dict with wkhtmltopdf global and page options, with or w/o '--' :param toc: (optional) dict with toc-s...
4.580817
4.448805
1.029674
rtn = IMGKit(filename, 'file', options=options, toc=toc, cover=cover, css=css, config=config, cover_first=cover_first) return rtn.to_img(output_path)
def from_file(filename, output_path, options=None, toc=None, cover=None, css=None, config=None, cover_first=None)
Convert HTML file/files to IMG file/files :param filename: path of HTML file or list with paths or file-like object :param output_path: path to output PDF file/files. False means file will be returned as string :param options: (optional) dict with wkhtmltopdf global and page options, with or w/o '--' :...
3.446984
3.273742
1.052919
rtn = IMGKit(string, 'string', options=options, toc=toc, cover=cover, css=css, config=config, cover_first=cover_first) return rtn.to_img(output_path)
def from_string(string, output_path, options=None, toc=None, cover=None, css=None, config=None, cover_first=None)
Convert given string/strings to IMG file :param string: :param output_path: path to output PDF file/files. False means file will be returned as string :param options: (optional) dict with wkhtmltopdf global and page options, with or w/o '--' :param toc: (optional) dict with toc-specific wkhtmltopdf opt...
4.15461
3.969112
1.046736
''' Due to the random nature of hashing a salted value, this must inspect each auth_token individually to find the correct one. Tokens that have expired will be deleted and skipped ''' msg = _('Invalid token.') token = token.decode("utf-8") for auth_token...
def authenticate_credentials(self, token)
Due to the random nature of hashing a salted value, this must inspect each auth_token individually to find the correct one. Tokens that have expired will be deleted and skipped
5.11703
2.935163
1.743355
''' Calculates the hash of a token and salt. input is unhexlified token and salt must contain an even number of hex digits or a binascii.Error exception will be raised ''' digest = hashes.Hash(sha(), backend=default_backend()) digest.update(binascii.unhexlify(token)) digest.update(b...
def hash_token(token, salt)
Calculates the hash of a token and salt. input is unhexlified token and salt must contain an even number of hex digits or a binascii.Error exception will be raised
4.821759
2.047545
2.354898
service_names = [] for service in services: service_names.append(_service_name(service)) services = list(services) services.append(cls(reflection_pb2, service_names)) services.append(ServerReflectionV1Alpha(reflection_pb2_v1alpha, ...
def extend(cls, services)
Extends services list with reflection service: .. code-block:: python3 from grpclib.reflection.service import ServerReflection services = [Greeter()] services = ServerReflection.extend(services) server = Server(services, loop=loop) ... Ret...
5.825916
5.254976
1.108648
request = await stream.recv_message() checks = self._checks.get(request.service) if checks is None: await stream.send_trailing_metadata(status=Status.NOT_FOUND) elif len(checks) == 0: await stream.send_message(HealthCheckResponse( status=H...
async def Check(self, stream)
Implements synchronous periodic checks
3.742584
3.606048
1.037863
prev_value = self._value self._value = value if self._value != prev_value: # notify all watchers that this check was changed for event in self._events: event.set()
def set(self, value: Optional[bool])
Sets current status of a check :param value: ``True`` (healthy), ``False`` (unhealthy), or ``None`` (unknown)
5.60361
5.204023
1.076784
signals = set(signals) flag = [] for sig_num in signals: loop.add_signal_handler(sig_num, _exit_handler, sig_num, servers, flag) try: yield finally: for sig_num in signals: loop.remove_signal_handler(sig_num)
def graceful_exit(servers, *, loop, signals=frozenset({signal.SIGINT, signal.SIGTERM}))
Utility context-manager to help properly shutdown server in response to the OS signals By default this context-manager handles ``SIGINT`` and ``SIGTERM`` signals. There are two stages: 1. first received signal closes servers 2. subsequent signals raise ``SystemExit`` exception Example: ...
2.848389
3.960183
0.719257
message = await recv_message(self._stream, self._codec, self._recv_type) message, = await self._dispatch.recv_message(message) return message
async def recv_message(self)
Coroutine to receive incoming message from the client. If client sends UNARY request, then you can call this coroutine only once. If client sends STREAM request, then you should call this coroutine several times, until it returns None. To simplify your code in this case, :py:class:`Stre...
8.810203
13.070186
0.674069
if self._send_initial_metadata_done: raise ProtocolError('Initial metadata was already sent') headers = [ (':status', '200'), ('content-type', self._content_type), ] metadata = MultiDict(metadata or ()) metadata, = await self._dispatc...
async def send_initial_metadata(self, *, metadata=None)
Coroutine to send headers with initial metadata to the client. In gRPC you can send initial metadata as soon as possible, because gRPC doesn't use `:status` pseudo header to indicate success or failure of the current request. gRPC uses trailers for this purpose, and trailers are sent du...
3.48137
4.031064
0.863636
if 'end' in kwargs: warnings.warn('"end" argument is deprecated, use ' '"stream.send_trailing_metadata" explicitly', stacklevel=2) end = kwargs.pop('end', False) assert not kwargs, kwargs if not self._send_initial...
async def send_message(self, message, **kwargs)
Coroutine to send message to the client. If server sends UNARY response, then you should call this coroutine only once. If server sends STREAM response, then you can call this coroutine as many times as you need. :param message: message object
5.301552
5.36903
0.987432
if self._send_trailing_metadata_done: raise ProtocolError('Trailing metadata was already sent') if ( not self._cardinality.server_streaming and not self._send_message_count and status is Status.OK ): raise ProtocolError('Unary...
async def send_trailing_metadata(self, *, status=Status.OK, status_message=None, metadata=None)
Coroutine to send trailers with trailing metadata to the client. This coroutine allows sending trailers-only responses, in case of some failure conditions during handling current request, i.e. when ``status is not OK``. .. note:: This coroutine will be called implicitly at exit from ...
4.103361
4.384253
0.935932
if path is not None and (host is not None or port is not None): raise ValueError("The 'path' parameter can not be used with the " "'host' or 'port' parameters.") if self._server is not None: raise RuntimeError('Server is already started') ...
async def start(self, host=None, port=None, *, path=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None)
Coroutine to start the server. :param host: can be a string, containing IPv4/v6 address or domain name. If host is None, server will be bound to all available interfaces. :param port: port number. :param path: UNIX domain socket path. If specified, host and port should ...
1.92036
2.108808
0.910638
if self._server is None: raise RuntimeError('Server is not started') self._server.close() for handler in self._handlers: handler.close()
def close(self)
Stops accepting new connections, cancels all currently running requests. Request handlers are able to handle `CancelledError` and exit properly.
4.632984
3.759069
1.232482
if self._server is None: raise RuntimeError('Server is not started') await self._server.wait_closed() if self._handlers: await asyncio.wait({h.wait_closed() for h in self._handlers}, loop=self._loop)
async def wait_closed(self)
Coroutine to wait until all existing request handlers will exit properly.
3.703602
3.270998
1.132254
if self._send_request_done: raise ProtocolError('Request is already sent') with self._wrapper: protocol = await self._channel.__connect__() stream = protocol.processor.connection\ .create_stream(wrapper=self._wrapper) headers = [...
async def send_request(self)
Coroutine to send request headers with metadata to the server. New HTTP/2 stream will be created during this coroutine call. .. note:: This coroutine will be called implicitly during first :py:meth:`send_message` coroutine call, if not called before explicitly.
3.940068
3.853077
1.022577
if not self._send_request_done: await self.send_request() if end and self._end_done: raise ProtocolError('Stream was already ended') with self._wrapper: message, = await self._dispatch.send_message(message) await send_message(self._strea...
async def send_message(self, message, *, end=False)
Coroutine to send message to the server. If client sends UNARY request, then you should call this coroutine only once. If client sends STREAM request, then you can call this coroutine as many times as you need. .. warning:: It is important to finally end stream from the client-side ...
5.590164
5.253845
1.064014
if self._end_done: raise ProtocolError('Stream was already ended') if ( not self._cardinality.client_streaming and not self._send_message_count ): raise ProtocolError('Unary request requires a single message ' ...
async def end(self)
Coroutine to end stream from the client-side. It should be used to finally end stream from the client-side when we're finished sending messages to the server and stream wasn't closed with last DATA frame. See :py:meth:`send_message` for more details. HTTP/2 stream will have half-closed...
7.545689
7.19238
1.049123
if not self._send_request_done: raise ProtocolError('Request was not sent yet') if self._recv_initial_metadata_done: raise ProtocolError('Initial metadata was already received') try: with self._wrapper: headers = await self._stream.r...
async def recv_initial_metadata(self)
Coroutine to wait for headers with initial metadata from the server. .. note:: This coroutine will be called implicitly during first :py:meth:`recv_message` coroutine call, if not called before explicitly. May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned ...
3.603363
3.426852
1.051508
# TODO: check that messages were sent for non-stream-stream requests if not self._recv_initial_metadata_done: await self.recv_initial_metadata() with self._wrapper: message = await recv_message(self._stream, self._codec, ...
async def recv_message(self)
Coroutine to receive incoming message from the server. If server sends UNARY response, then you can call this coroutine only once. If server sends STREAM response, then you should call this coroutine several times, until it returns None. To simplify you code in this case, :py:class:`Str...
8.626314
8.415676
1.025029
if not self._end_done: raise ProtocolError('Outgoing stream was not ended') if ( not self._cardinality.server_streaming and not self._recv_message_count ): raise ProtocolError('No messages were received before waiting ' ...
async def recv_trailing_metadata(self)
Coroutine to wait for trailers with trailing metadata from the server. .. note:: This coroutine will be called implicitly at exit from this call (context manager's exit), if not called before explicitly. May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned ...
5.919785
5.599719
1.057158
if self._cancel_done: raise ProtocolError('Stream was already cancelled') with self._wrapper: await self._stream.reset() # TODO: specify error code self._cancel_done = True
async def cancel(self)
Coroutine to cancel this request/stream. Client will send RST_STREAM frame to the server, so it will be explicitly informed that there is nothing to expect from the client regarding this request/stream.
10.181912
9.121104
1.116303
if self._protocol is not None: self._protocol.processor.close() del self._protocol
def close(self)
Closes connection to the server.
7.362768
6.101413
1.206732
return self.channel.request(self.name, self._cardinality, self.request_type, self.reply_type, timeout=timeout, metadata=metadata)
def open(self, *, timeout=None, metadata=None) -> Stream
Creates and returns :py:class:`Stream` object to perform request to the server. Nothing will happen to the current underlying HTTP/2 connection during this method call. It just initializes :py:class:`Stream` object for you. Actual request will be sent only during :py:meth:`Stream.send_r...
6.457128
8.612952
0.7497
with open(PYDOCMD_CONFIG) as fp: config = yaml.load(fp) return default_config(config)
def read_config()
Reads and preprocesses the pydoc-markdown configuration file.
11.065416
6.659102
1.661698
ignored_keys = ('gens_dir', 'pages', 'headers', 'generate', 'loader', 'preprocessor', 'additional_search_paths') config = {key: value for key, value in inconf.items() if key not in ignored_keys} config['docs_dir'] = inconf['gens_dir'] if 'pages' in inconf: config['nav'] = inconf['pag...
def write_temp_mkdocs_config(inconf)
Generates a configuration for MkDocs on-the-fly from the pydoc-markdown configuration and makes sure it gets removed when this program exists.
4.040142
3.833702
1.053849
for path in config['additional_search_paths']: path = os.path.abspath(path) sys.path.append(path) # Copy all template files from the source directory into our # generated files directory. log('Started copying source files...') for root, dirs, files in os.walk(config['docs_dir']): rel_root = o...
def copy_source_files(config, pages_required=True)
Copies all files from the `docs_dir` to the `gens_dir` defined in the *config*. It also takes the MkDocs `pages` configuration into account and converts the special `<< INFILE` syntax by copying them to the `gens_dir` as well.
3.214613
2.981479
1.078194
# Import modules until we can no longer import them. Prefer existing # attributes over importing modules at each step. parts = name.split('.') current_name = parts[0] obj = import_module(current_name) scope = None for part in parts[1:]: current_name += '.' + part try: if hasattr(obj, '__...
def import_object_with_scope(name)
Imports a Python object by an absolute identifier. # Arguments name (str): The name of the Python object to import. # Returns (any, Module): The object and the module that contains it. Note that for plain modules loaded with this function, both elements of the tuple may be the same object.
4.768171
4.719225
1.010372
obj = import_object(name) module_items = list(getattr(obj, '__dict__', {}).items()) for key, value in module_items: if getattr(value, '__module__', None): import_object(name + '.' + key)
def force_lazy_import(name)
Import any modules off of "name" by iterating a new list rather than a generator so that this library works with lazy imports.
4.155989
3.898408
1.066073
codeblock_opened = False current_section = None content = self._preprocess_refs(section) lines = [] for line in content.split('\n'): if line.startswith("```"): codeblock_opened = (not codeblock_opened) if not line: current_section = None elif not codeblock_open...
def preprocess_section(self, section)
Preprocess the contents of *section*.
3.180791
3.081343
1.032274
def handler(match): mod = match.group('mod') ref = match.group('ref') parens = match.group('parens') or '' dup = match.group('dup') has_trailing_dot = False if not parens and ref.endswith('.'): ref = ref[:-1] has_trailing_dot = True if '#' in ref: ...
def _preprocess_refs(self, section)
Parses references and replaces them with markdown links Syntax is: `#anchor` for in page reference `#::mod[.submod][#item][+n]` where `mod.submod` is the module, `item` is the module member and n is the number of duplicates in case of headers: markdown conflicts. ...
3.965159
3.729255
1.063258
lines = [] in_codeblock = False keyword = None components = {} for line in section.content.split('\n'): line = line.strip() if line.startswith("```"): in_codeblock = not in_codeblock if not in_codeblock: match = re.match(r':(?:param|parameter)\s+(\w+)\s*:(.*)...
def preprocess_section(self, section)
Preprocessors a given section into it's components.
2.03044
2.007774
1.011289
if self.header_type == 'html': print('<h{depth} id="{id}">{title}</h{depth}>\n' .format(depth = self.depth, id = self.identifier, title = self.title), file = stream) elif self.header_type == 'markdown': print('\n' + ('#' * self.depth), self.title, file = stream) else: ...
def render(self, stream)
Render the section into *stream*.
3.044385
2.811347
1.082892
if not filename.endswith('.md'): raise ValueError('filename must end with `.md`') if os.path.isabs(filename): raise ValueError('filename must be relative') if filename in self.documents: raise ValueError('document filename {!r} already used'.format(filename)) if not url: ur...
def new_document(self, filename, url=None)
Create a new document. # Arguments filename (str): The filename of the document. Must end with `.md`. url (str): The relative URL of the document. If omitted, will be automatically deduced from *filename* (same without the `.md` suffix). # Raises ValueError: If *filename* does not end with `...
3.040016
2.427084
1.252539
section = Section(doc, *args, **kwargs) if section.identifier: if section.identifier in self.sections: raise ValueError('section identifier {!r} already used' .format(section.identifier)) self.sections[section.identifier] = section doc.sections.append(section) return ...
def new_section(self, doc, *args, **kwargs)
Create a new section in the specified document. The arguments for this method match the parameters for the #Section constructor. # Raises ValueError: If the section identifier is already used.
3.151965
3.0011
1.05027
assert section.identifier is not None obj, scope = import_object_with_scope(section.identifier) if '.' in section.identifier: default_title = section.identifier.rsplit('.', 1)[1] else: default_title = section.identifier section.title = getattr(obj, '__name__', default_title) ...
def load_section(self, section)
Loads the contents of a #Section. The `section.identifier` is the name of the object that we need to load. # Arguments section (Section): The section to load. Fill the `section.title` and `section.content` values. Optionally, `section.loader_context` can be filled with custom arbitrary da...
4.701087
3.946266
1.191275
for _dir in dirs: data = self.read_file(_dir, ignore=ignore) if data: self.paths[_dir] = data
def load(self, patterns, dirs, ignore=None)
Load objects from the filesystem into the ``paths`` dictionary.
4.912439
4.115937
1.193517
# TODO support JSON here # TODO sphinx way of reporting errors in logs? parser_command = ["godocjson"] _ignore = kwargs.get("ignore") if _ignore: parser_command.extend(["-e", "{0}".format("|".join(_ignore))]) parser_command.append(path) tr...
def read_file(self, path, **kwargs)
Read file input into memory, returning deserialized objects :param path: Path of file to read :param \**kwargs: * ignore (``list``): List of file patterns to ignore
5.157148
5.01519
1.028306
_type = kwargs.get("_type") obj_map = dict((cls.type, cls) for cls in ALL_CLASSES) try: # Contextual type data from children recursion if _type: LOGGER.debug("Forcing Go Type %s" % _type) cls = obj_map[_type] else: ...
def create_class(self, data, options=None, **kwargs)
Return instance of class based on Go data Data keys handled here: _type Set the object class consts, types, vars, funcs Recurse into :py:meth:`create_class` to create child object instances :param data: dictionary data from godo...
3.828459
3.515994
1.08887
slug = self.name slug = unidecode.unidecode(slug) slug = slug.replace("-", "") slug = re.sub(r"[^\w\.]+", "-", slug).strip("-") return os.path.join(*slug.split("."))
def pathname(self)
Sluggified path for filenames Slugs to a filename using the follow steps * Decode unicode to approximate ascii * Remove existing hypens * Substitute hyphens for non-word characters * Break up the string as paths
4.040332
3.640168
1.10993
parts = [root] parts.extend(self.pathname.split(os.path.sep)) return "/".join(parts)
def include_dir(self, root)
Return directory of file
5.266562
5.291913
0.995209