_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q265500
DataStore.get_translated_data
validation
def get_translated_data(self): """ Translate the data with the translation table """ j = {} for k in self.data: d = {} for l in self.data[k]: d[self.translation_keys[l]] = self.data[k][l] j[k] = d return j
python
{ "resource": "" }
q265501
DataStore.get_json
validation
def get_json(self, prettyprint=False, translate=True): """ Get the data in JSON form """ j = [] if translate: d = self.get_translated_data() else: d = self.data for k in d: j.append(d[k]) if prettyprint: j = ...
python
{ "resource": "" }
q265502
DataStore.get_json_tuples
validation
def get_json_tuples(self, prettyprint=False, translate=True): """ Get the data as JSON tuples """ j = self.get_json(prettyprint, translate) if len(j) > 2: if prettyprint: j = j[1:-2] + ",\n" else: j = j[1:-1] + "," e...
python
{ "resource": "" }
q265503
ShirtsIORequest.get
validation
def get(self, url, params={}): """ Issues a GET request against the API, properly formatting the params :param url: a string, the url you are requesting :param params: a dict, the key-value of all the paramaters needed in the request :returns: a dict parse...
python
{ "resource": "" }
q265504
ShirtsIORequest.post
validation
def post(self, url, params={}, files=None): """ Issues a POST request against the API, allows for multipart data uploads :param url: a string, the url you are requesting :param params: a dict, the key-value of all the parameters needed in the request :para...
python
{ "resource": "" }
q265505
ConfigStore.load_values
validation
def load_values(self): """ Go through the env var map, transferring the values to this object as attributes. :raises: RuntimeError if a required env var isn't defined. """ for config_name, evar in self.evar_defs.items(): if evar.is_required and evar.name not...
python
{ "resource": "" }
q265506
embed_data
validation
def embed_data(request): """ Create a temporary directory with input data for the test. The directory contents is copied from a directory with the same name as the module located in the same directory of the test module. """ result = _EmbedDataFixture(request) result.delete_data_dir() re...
python
{ "resource": "" }
q265507
_EmbedDataFixture.assert_equal_files
validation
def assert_equal_files(self, obtained_fn, expected_fn, fix_callback=lambda x:x, binary=False, encoding=None): ''' Compare two files contents. If the files differ, show the diff and write a nice HTML diff file into the data directory. Searches for the filenames both inside and outside th...
python
{ "resource": "" }
q265508
_EmbedDataFixture._generate_html_diff
validation
def _generate_html_diff(self, expected_fn, expected_lines, obtained_fn, obtained_lines): """ Returns a nice side-by-side diff of the given files, as a string. """ import difflib differ = difflib.HtmlDiff() return differ.make_file( fromlines=expected_lines, ...
python
{ "resource": "" }
q265509
Network.add_peer
validation
def add_peer(self, peer): """ Add a peer or multiple peers to the PEERS variable, takes a single string or a list. :param peer(list or string) """ if type(peer) == list: for i in peer: check_url(i) self.PEERS.extend(peer) elif type...
python
{ "resource": "" }
q265510
Network.remove_peer
validation
def remove_peer(self, peer): """ remove one or multiple peers from PEERS variable :param peer(list or string): """ if type(peer) == list: for x in peer: check_url(x) for i in self.PEERS: if x in i: ...
python
{ "resource": "" }
q265511
Network.status
validation
def status(self): """ check the status of the network and the peers :return: network_height, peer_status """ peer = random.choice(self.PEERS) formatted_peer = 'http://{}:4001'.format(peer) peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers'...
python
{ "resource": "" }
q265512
Network.broadcast_tx
validation
def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''): """broadcasts a transaction to the peerslist using ark-js library""" peer = random.choice(self.PEERS) park = Park( peer, 4001, constants.ARK_NETHASH, '1.1.1' ...
python
{ "resource": "" }
q265513
OrbApiFactory.register
validation
def register(self, service, name=''): """ Exposes a given service to this API. """ try: is_model = issubclass(service, orb.Model) except StandardError: is_model = False # expose an ORB table dynamically as a service if is_model: ...
python
{ "resource": "" }
q265514
main
validation
def main(): """ Main entry point, expects doctopt arg dict as argd. """ global DEBUG argd = docopt(USAGESTR, version=VERSIONSTR, script=SCRIPT) DEBUG = argd['--debug'] width = parse_int(argd['--width'] or DEFAULT_WIDTH) or 1 indent = parse_int(argd['--indent'] or (argd['--INDENT'] or 0)) pr...
python
{ "resource": "" }
q265515
debug
validation
def debug(*args, **kwargs): """ Print a message only if DEBUG is truthy. """ if not (DEBUG and args): return None # Include parent class name when given. parent = kwargs.get('parent', None) with suppress(KeyError): kwargs.pop('parent') # Go back more than once when given. b...
python
{ "resource": "" }
q265516
parse_int
validation
def parse_int(s): """ Parse a string as an integer. Exit with a message on failure. """ try: val = int(s) except ValueError: print_err('\nInvalid integer: {}'.format(s)) sys.exit(1) return val
python
{ "resource": "" }
q265517
try_read_file
validation
def try_read_file(s): """ If `s` is a file name, read the file and return it's content. Otherwise, return the original string. Returns None if the file was opened, but errored during reading. """ try: with open(s, 'r') as f: data = f.read() except FileNotFoundError: ...
python
{ "resource": "" }
q265518
Vim.wait
validation
def wait(self, timeout=None): """ Wait for response until timeout. If timeout is specified to None, ``self.timeout`` is used. :param float timeout: seconds to wait I/O """ if timeout is None: timeout = self._timeout while self._process.check_readable(...
python
{ "resource": "" }
q265519
make_seekable
validation
def make_seekable(fileobj): """ If the file-object is not seekable, return ArchiveTemp of the fileobject, otherwise return the file-object itself """ if sys.version_info < (3, 0) and isinstance(fileobj, file): filename = fileobj.name fileobj = io.FileIO(fileobj.fileno(), closefd=Fal...
python
{ "resource": "" }
q265520
Tracy.init_app
validation
def init_app(self, app): """Setup before_request, after_request handlers for tracing. """ app.config.setdefault("TRACY_REQUIRE_CLIENT", False) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['restpoints'] = self app.before_request(self._...
python
{ "resource": "" }
q265521
Tracy._before
validation
def _before(self): """Records the starting time of this reqeust. """ # Don't trace excluded routes. if request.path in self.excluded_routes: request._tracy_exclude = True return request._tracy_start_time = monotonic() client = request.headers.get(...
python
{ "resource": "" }
q265522
Tracy._after
validation
def _after(self, response): """Calculates the request duration, and adds a transaction ID to the header. """ # Ignore excluded routes. if getattr(request, '_tracy_exclude', False): return response duration = None if getattr(request, '_tracy_start_time...
python
{ "resource": "" }
q265523
FormatBlock.expand_words
validation
def expand_words(self, line, width=60): """ Insert spaces between words until it is wide enough for `width`. """ if not line.strip(): return line # Word index, which word to insert on (cycles between 1->len(words)) wordi = 1 while len(strip_codes(line)) < widt...
python
{ "resource": "" }
q265524
FormatBlock.iter_add_text
validation
def iter_add_text(self, lines, prepend=None, append=None): """ Prepend or append text to lines. Yields each line. """ if (prepend is None) and (append is None): yield from lines else: # Build up a format string, with optional {prepend}/{append} fmtpcs = ['{pre...
python
{ "resource": "" }
q265525
FormatBlock.iter_char_block
validation
def iter_char_block(self, text=None, width=60, fmtfunc=str): """ Format block by splitting on individual characters. """ if width < 1: width = 1 text = (self.text if text is None else text) or '' text = ' '.join(text.split('\n')) escapecodes = get_codes(text) ...
python
{ "resource": "" }
q265526
FormatBlock.iter_space_block
validation
def iter_space_block(self, text=None, width=60, fmtfunc=str): """ Format block by wrapping on spaces. """ if width < 1: width = 1 curline = '' text = (self.text if text is None else text) or '' for word in text.split(): possibleline = ' '.join((curline, wo...
python
{ "resource": "" }
q265527
FormatBlock.squeeze_words
validation
def squeeze_words(line, width=60): """ Remove spaces in between words until it is small enough for `width`. This will always leave at least one space between words, so it may not be able to get below `width` characters. """ # Start removing spaces to "squeeze"...
python
{ "resource": "" }
q265528
CachedHTTPBL.check_ip
validation
def check_ip(self, ip): """ Check IP trough the httpBL API :param ip: ipv4 ip address :return: httpBL results or None if any error is occurred """ self._last_result = None if is_valid_ipv4(ip): key = None if self._use_cache: ...
python
{ "resource": "" }
q265529
CachedHTTPBL.is_threat
validation
def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None): """ Check if IP is a threat :param result: httpBL results; if None, then results from last check_ip() used (optional) :param harmless_age: harmless age for check if httpBL age is older (optional) ...
python
{ "resource": "" }
q265530
CachedHTTPBL.is_suspicious
validation
def is_suspicious(self, result=None): """ Check if IP is suspicious :param result: httpBL results; if None, then results from last check_ip() used (optional) :return: True or False """ result = result if result is not None else self._last_result suspicious = Fal...
python
{ "resource": "" }
q265531
CachedHTTPBL.invalidate_ip
validation
def invalidate_ip(self, ip): """ Invalidate httpBL cache for IP address :param ip: ipv4 IP address """ if self._use_cache: key = self._make_cache_key(ip) self._cache.delete(key, version=self._cache_version)
python
{ "resource": "" }
q265532
CachedHTTPBL.invalidate_cache
validation
def invalidate_cache(self): """ Invalidate httpBL cache """ if self._use_cache: self._cache_version += 1 self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key))
python
{ "resource": "" }
q265533
Consumer.run
validation
def run(self): """Runs the consumer.""" self.log.debug('consumer is running...') self.running = True while self.running: self.upload() self.log.debug('consumer exited.')
python
{ "resource": "" }
q265534
Consumer.upload
validation
def upload(self): """Upload the next batch of items, return whether successful.""" success = False batch = self.next() if len(batch) == 0: return False try: self.request(batch) success = True except Exception as e: self.log...
python
{ "resource": "" }
q265535
Consumer.next
validation
def next(self): """Return the next batch of items to upload.""" queue = self.queue items = [] item = self.next_item() if item is None: return items items.append(item) while len(items) < self.upload_size and not queue.empty(): item = self.n...
python
{ "resource": "" }
q265536
Consumer.next_item
validation
def next_item(self): """Get a single item from the queue.""" queue = self.queue try: item = queue.get(block=True, timeout=5) return item except Exception: return None
python
{ "resource": "" }
q265537
Consumer.request
validation
def request(self, batch, attempt=0): """Attempt to upload the batch and retry before raising an error """ try: q = self.api.new_queue() for msg in batch: q.add(msg['event'], msg['value'], source=msg['source']) q.submit() except: if ...
python
{ "resource": "" }
q265538
_camelcase_to_underscore
validation
def _camelcase_to_underscore(url): """ Translate camelCase into underscore format. >>> _camelcase_to_underscore('minutesBetweenSummaries') 'minutes_between_summaries' """ def upper2underscore(text): for char in text: if char.islower(): yield char ...
python
{ "resource": "" }
q265539
create_tree
validation
def create_tree(endpoints): """ Creates the Trello endpoint tree. >>> r = {'1': { \ 'actions': {'METHODS': {'GET'}}, \ 'boards': { \ 'members': {'METHODS': {'DELETE'}}}} \ } >>> r == create_tree([ \ 'GET /1/actions/[idA...
python
{ "resource": "" }
q265540
main
validation
def main(): """ Prints the complete YAML. """ ep = requests.get(TRELLO_API_DOC).content root = html.fromstring(ep) links = root.xpath('//a[contains(@class, "reference internal")]/@href') pages = [requests.get(TRELLO_API_DOC + u) for u in links if u.endswith('index.html')] ...
python
{ "resource": "" }
q265541
Wmi.query
validation
def query(self, wql): """Connect by wmi and run wql.""" try: self.__wql = ['wmic', '-U', self.args.domain + '\\' + self.args.user + '%' + self.args.password, '//' + self.args.host, '--namespace', self.args.namespac...
python
{ "resource": "" }
q265542
DataReporter.log
validation
def log(self, url=None, credentials=None, do_verify_certificate=True): """ Wrapper for the other log methods, decide which one based on the URL parameter. """ if url is None: url = self.url if re.match("file://", url): self.log_file(url) el...
python
{ "resource": "" }
q265543
DataReporter.log_file
validation
def log_file(self, url=None): """ Write to a local log file """ if url is None: url = self.url f = re.sub("file://", "", url) try: with open(f, "a") as of: of.write(str(self.store.get_json_tuples(True))) except IOError as e:...
python
{ "resource": "" }
q265544
DataReporter.log_post
validation
def log_post(self, url=None, credentials=None, do_verify_certificate=True): """ Write to a remote host via HTTP POST """ if url is None: url = self.url if credentials is None: credentials = self.credentials if do_verify_certificate is None: ...
python
{ "resource": "" }
q265545
DataReporter.register_credentials
validation
def register_credentials(self, credentials=None, user=None, user_file=None, password=None, password_file=None): """ Helper method to store username and password """ # lets store all kind of credential data into this dict if credentials is not None: self.credentials = ...
python
{ "resource": "" }
q265546
set_connection
validation
def set_connection(host=None, database=None, user=None, password=None): """Set connection parameters. Call set_connection with no arguments to clear.""" c.CONNECTION['HOST'] = host c.CONNECTION['DATABASE'] = database c.CONNECTION['USER'] = user c.CONNECTION['PASSWORD'] = password
python
{ "resource": "" }
q265547
set_delegate
validation
def set_delegate(address=None, pubkey=None, secret=None): """Set delegate parameters. Call set_delegate with no arguments to clear.""" c.DELEGATE['ADDRESS'] = address c.DELEGATE['PUBKEY'] = pubkey c.DELEGATE['PASSPHRASE'] = secret
python
{ "resource": "" }
q265548
Address.balance
validation
def balance(address): """ Takes a single address and returns the current balance. """ txhistory = Address.transactions(address) balance = 0 for i in txhistory: if i.recipientId == address: balance += i.amount if i.senderId == addres...
python
{ "resource": "" }
q265549
Address.balance_over_time
validation
def balance_over_time(address): """returns a list of named tuples, x.timestamp, x.amount including block rewards""" forged_blocks = None txhistory = Address.transactions(address) delegates = Delegate.delegates() for i in delegates: if address == i.address: ...
python
{ "resource": "" }
q265550
value_to_bool
validation
def value_to_bool(config_val, evar): """ Massages the 'true' and 'false' strings to bool equivalents. :param str config_val: The env var value. :param EnvironmentVariable evar: The EVar object we are validating a value for. :rtype: bool :return: True or False, depending on the value. ...
python
{ "resource": "" }
q265551
validate_is_not_none
validation
def validate_is_not_none(config_val, evar): """ If the value is ``None``, fail validation. :param str config_val: The env var value. :param EnvironmentVariable evar: The EVar object we are validating a value for. :raises: ValueError if the config value is None. """ if config_val is ...
python
{ "resource": "" }
q265552
validate_is_boolean_true
validation
def validate_is_boolean_true(config_val, evar): """ Make sure the value evaluates to boolean True. :param str config_val: The env var value. :param EnvironmentVariable evar: The EVar object we are validating a value for. :raises: ValueError if the config value evaluates to boolean False. ...
python
{ "resource": "" }
q265553
value_to_python_log_level
validation
def value_to_python_log_level(config_val, evar): """ Convert an evar value into a Python logging level constant. :param str config_val: The env var value. :param EnvironmentVariable evar: The EVar object we are validating a value for. :return: A validated string. :raises: ValueError if ...
python
{ "resource": "" }
q265554
register_range_type
validation
def register_range_type(pgrange, pyrange, conn): """ Register a new range type as a PostgreSQL range. >>> register_range_type("int4range", intrange, conn) The above will make sure intrange is regarded as an int4range for queries and that int4ranges will be cast into intrange when fetching rows...
python
{ "resource": "" }
q265555
get_api_error
validation
def get_api_error(response): """Acquires the correct error for a given response. :param requests.Response response: HTTP error response :returns: the appropriate error for a given response :rtype: APIError """ error_class = _status_code_to_class.get(response.status_code, APIError) return error_class(res...
python
{ "resource": "" }
q265556
get_param_values
validation
def get_param_values(request, model=None): """ Converts the request parameters to Python. :param request: <pyramid.request.Request> || <dict> :return: <dict> """ if type(request) == dict: return request params = get_payload(request) # support in-place editing formatted reques...
python
{ "resource": "" }
q265557
get_context
validation
def get_context(request, model=None): """ Extracts ORB context information from the request. :param request: <pyramid.request.Request> :param model: <orb.Model> || None :return: {<str> key: <variant> value} values, <orb.Context> """ # convert request parameters to python param_values =...
python
{ "resource": "" }
q265558
OrderBook._real_time_thread
validation
def _real_time_thread(self): """Handles real-time updates to the order book.""" while self.ws_client.connected(): if self.die: break if self.pause: sleep(5) continue message = self.ws_client.receive() if message is None: break message_type ...
python
{ "resource": "" }
q265559
WSClient._keep_alive_thread
validation
def _keep_alive_thread(self): """Used exclusively as a thread which keeps the WebSocket alive.""" while True: with self._lock: if self.connected(): self._ws.ping() else: self.disconnect() self._thread = None return sleep(30)
python
{ "resource": "" }
q265560
WSClient.connect
validation
def connect(self): """Connects and subscribes to the WebSocket Feed.""" if not self.connected(): self._ws = create_connection(self.WS_URI) message = { 'type':self.WS_TYPE, 'product_id':self.WS_PRODUCT_ID } self._ws.send(dumps(message)) # There will be only one keep...
python
{ "resource": "" }
q265561
cached_httpbl_exempt
validation
def cached_httpbl_exempt(view_func): """ Marks a view function as being exempt from the cached httpbl view protection. """ # We could just do view_func.cached_httpbl_exempt = True, but decorators # are nicer if they don't have side-effects, so we return a new # function. def wrapped_view(*ar...
python
{ "resource": "" }
q265562
CounterPool.get_conn
validation
def get_conn(self, aws_access_key=None, aws_secret_key=None): ''' Hook point for overriding how the CounterPool gets its connection to AWS. ''' return boto.connect_dynamodb( aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, )
python
{ "resource": "" }
q265563
CounterPool.get_schema
validation
def get_schema(self): ''' Hook point for overriding how the CounterPool determines the schema to be used when creating a missing table. ''' if not self.schema: raise NotImplementedError( 'You must provide a schema value or override the get_schema metho...
python
{ "resource": "" }
q265564
CounterPool.create_table
validation
def create_table(self): ''' Hook point for overriding how the CounterPool creates a new table in DynamooDB ''' table = self.conn.create_table( name=self.get_table_name(), schema=self.get_schema(), read_units=self.get_read_units(), w...
python
{ "resource": "" }
q265565
CounterPool.get_table
validation
def get_table(self): ''' Hook point for overriding how the CounterPool transforms table_name into a boto DynamoDB Table object. ''' if hasattr(self, '_table'): table = self._table else: try: table = self.conn.get_table(self.get_tabl...
python
{ "resource": "" }
q265566
CounterPool.create_item
validation
def create_item(self, hash_key, start=0, extra_attrs=None): ''' Hook point for overriding how the CouterPool creates a DynamoDB item for a given counter when an existing item can't be found. ''' table = self.get_table() now = datetime.utcnow().replace(microsecond=0).isofo...
python
{ "resource": "" }
q265567
CounterPool.get_item
validation
def get_item(self, hash_key, start=0, extra_attrs=None): ''' Hook point for overriding how the CouterPool fetches a DynamoDB item for a given counter. ''' table = self.get_table() try: item = table.get_item(hash_key=hash_key) except DynamoDBKeyNotFoun...
python
{ "resource": "" }
q265568
CounterPool.get_counter
validation
def get_counter(self, name, start=0): ''' Gets the DynamoDB item behind a counter and ties it to a Counter instace. ''' item = self.get_item(hash_key=name, start=start) counter = Counter(dynamo_item=item, pool=self) return counter
python
{ "resource": "" }
q265569
many_to_one
validation
def many_to_one(clsname, **kw): """Use an event to build a many-to-one relationship on a class. This makes use of the :meth:`.References._reference_table` method to generate a full foreign key relationship to the remote table. """ @declared_attr def m2o(cls): cls._references((cls.__nam...
python
{ "resource": "" }
q265570
one_to_many
validation
def one_to_many(clsname, **kw): """Use an event to build a one-to-many relationship on a class. This makes use of the :meth:`.References._reference_table` method to generate a full foreign key relationship from the remote table. """ @declared_attr def o2m(cls): cls._references((clsname...
python
{ "resource": "" }
q265571
DjeffParser.handle_data
validation
def handle_data(self, data): """ Djeffify data between tags """ if data.strip(): data = djeffify_string(data) self.djhtml += data
python
{ "resource": "" }
q265572
References._reference_table
validation
def _reference_table(cls, ref_table): """Create a foreign key reference from the local class to the given remote table. Adds column references to the declarative class and adds a ForeignKeyConstraint. """ # create pairs of (Foreign key column, primary key column) ...
python
{ "resource": "" }
q265573
prepare_path
validation
def prepare_path(path): """ Path join helper method Join paths if list passed :type path: str|unicode|list :rtype: str|unicode """ if type(path) == list: return os.path.join(*path) return path
python
{ "resource": "" }
q265574
read_from_file
validation
def read_from_file(file_path, encoding="utf-8"): """ Read helper method :type file_path: str|unicode :type encoding: str|unicode :rtype: str|unicode """ with codecs.open(file_path, "r", encoding) as f: return f.read()
python
{ "resource": "" }
q265575
write_to_file
validation
def write_to_file(file_path, contents, encoding="utf-8"): """ Write helper method :type file_path: str|unicode :type contents: str|unicode :type encoding: str|unicode """ with codecs.open(file_path, "w", encoding) as f: f.write(contents)
python
{ "resource": "" }
q265576
copy_file
validation
def copy_file(src, dest): """ Copy file helper method :type src: str|unicode :type dest: str|unicode """ dir_path = os.path.dirname(dest) if not os.path.exists(dir_path): os.makedirs(dir_path) shutil.copy2(src, dest)
python
{ "resource": "" }
q265577
get_path_extension
validation
def get_path_extension(path): """ Split file name and extension :type path: str|unicode :rtype: one str|unicode """ file_path, file_ext = os.path.splitext(path) return file_ext.lstrip('.')
python
{ "resource": "" }
q265578
split_path
validation
def split_path(path): """ Helper method for absolute and relative paths resolution Split passed path and return each directory parts example: "/usr/share/dir" return: ["usr", "share", "dir"] @type path: one of (unicode, str) @rtype: list """ resu...
python
{ "resource": "" }
q265579
RESTClient._create_api_uri
validation
def _create_api_uri(self, *parts): """Creates fully qualified endpoint URIs. :param parts: the string parts that form the request URI """ return urljoin(self.API_URI, '/'.join(map(quote, parts)))
python
{ "resource": "" }
q265580
RESTClient._format_iso_time
validation
def _format_iso_time(self, time): """Makes sure we have proper ISO 8601 time. :param time: either already ISO 8601 a string or datetime.datetime :returns: ISO 8601 time :rtype: str """ if isinstance(time, str): return time elif isinstance(time, datetime): return time.strftime('...
python
{ "resource": "" }
q265581
RESTClient._handle_response
validation
def _handle_response(self, response): """Returns the given response or raises an APIError for non-2xx responses. :param requests.Response response: HTTP response :returns: requested data :rtype: requests.Response :raises APIError: for non-2xx responses """ if not str(response.status_code)....
python
{ "resource": "" }
q265582
PaginationClient._check_next
validation
def _check_next(self): """Checks if a next message is possible. :returns: True if a next message is possible, otherwise False :rtype: bool """ if self.is_initial: return True if self.before: if self.before_cursor: return True else: return False else: ...
python
{ "resource": "" }
q265583
Colors._wrap_color
validation
def _wrap_color(self, code, text, format=None, style=None): """ Colors text with code and given format """ color = None if code[:3] == self.bg.PREFIX: color = self.bg.COLORS.get(code, None) if not color: color = self.fg.COLORS.get(code, None) if not color...
python
{ "resource": "" }
q265584
SymbolDatabase.RegisterMessage
validation
def RegisterMessage(self, message): """Registers the given message type in the local database. Args: message: a message.Message, to be registered. Returns: The provided message. """ desc = message.DESCRIPTOR self._symbols[desc.full_name] = message if desc.file.name not in self...
python
{ "resource": "" }
q265585
RuntimePath.insert
validation
def insert(self, index, value): """ Insert object before index. :param int index: index to insert in :param string value: path to insert """ self._list.insert(index, value) self._sync()
python
{ "resource": "" }
q265586
RuntimePath.parse
validation
def parse(self, string): """ Parse runtime path representation to list. :param string string: runtime path string :return: list of runtime paths :rtype: list of string """ var, eq, values = string.strip().partition('=') assert var == 'runtimepath' ...
python
{ "resource": "" }
q265587
Asset.add_bundle
validation
def add_bundle(self, *args): """ Add some bundle to build group :type bundle: static_bundle.bundles.AbstractBundle @rtype: BuildGroup """ for bundle in args: if not self.multitype and self.has_bundles(): first_bundle = self.get_first_bundle() ...
python
{ "resource": "" }
q265588
Asset.collect_files
validation
def collect_files(self): """ Return collected files links :rtype: list[static_bundle.files.StaticFileResult] """ self.files = [] for bundle in self.bundles: bundle.init_build(self, self.builder) bundle_files = bundle.prepare() self.fil...
python
{ "resource": "" }
q265589
Asset.get_minifier
validation
def get_minifier(self): """ Asset minifier Uses default minifier in bundle if it's not defined :rtype: static_bundle.minifiers.DefaultMinifier|None """ if self.minifier is None: if not self.has_bundles(): raise Exception("Unable to get default...
python
{ "resource": "" }
q265590
StandardBuilder.render_asset
validation
def render_asset(self, name): """ Render all includes in asset by names :type name: str|unicode :rtype: str|unicode """ result = "" if self.has_asset(name): asset = self.get_asset(name) if asset.files: for f in asset.files:...
python
{ "resource": "" }
q265591
StandardBuilder.collect_links
validation
def collect_links(self, env=None): """ Return links without build files """ for asset in self.assets.values(): if asset.has_bundles(): asset.collect_files() if env is None: env = self.config.env if env == static_bundle.ENV_PRODUCTIO...
python
{ "resource": "" }
q265592
_default_json_default
validation
def _default_json_default(obj): """ Coerce everything to strings. All objects representing time get output according to default_date_fmt. """ if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): return obj.strftime(default_date_fmt) else: return str(obj)
python
{ "resource": "" }
q265593
init_logs
validation
def init_logs(path=None, target=None, logger_name='root', level=logging.DEBUG, maxBytes=1*1024*1024, backupCount=5, application_name='default', server_hostname=None, fields=None): """Initialize the zlogge...
python
{ "resource": "" }
q265594
JsonFormatter.format
validation
def format(self, record): """formats a logging.Record into a standard json log entry :param record: record to be formatted :type record: logging.Record :return: the formatted json string :rtype: string """ record_fields = record.__dict__.copy() self._set...
python
{ "resource": "" }
q265595
includeme
validation
def includeme(config): """ Initialize the model for a Pyramid app. Activate this setup using ``config.include('baka_model')``. """ settings = config.get_settings() should_create = asbool(settings.get('baka_model.should_create_all', False)) should_drop = asbool(settings.get('baka_model.shou...
python
{ "resource": "" }
q265596
AbstractPath.get_abs_and_rel_paths
validation
def get_abs_and_rel_paths(self, root_path, file_name, input_dir): """ Return absolute and relative path for file :type root_path: str|unicode :type file_name: str|unicode :type input_dir: str|unicode :rtype: tuple """ # todo: change relative path resolvi...
python
{ "resource": "" }
q265597
DescriptorPool.AddEnumDescriptor
validation
def AddEnumDescriptor(self, enum_desc): """Adds an EnumDescriptor to the pool. This method also registers the FileDescriptor associated with the message. Args: enum_desc: An EnumDescriptor. """ if not isinstance(enum_desc, descriptor.EnumDescriptor): raise TypeError('Expected instance...
python
{ "resource": "" }
q265598
DescriptorPool.FindFileContainingSymbol
validation
def FindFileContainingSymbol(self, symbol): """Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file can not be found in th...
python
{ "resource": "" }
q265599
DescriptorPool.FindMessageTypeByName
validation
def FindMessageTypeByName(self, full_name): """Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descript...
python
{ "resource": "" }