_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q271600 | parse_agi_result | test | def parse_agi_result(line):
"""Parse AGI results using Regular expression.
AGI Result examples::
100 result=0 Trying...
200 result=0
200 result=-1
200 result=132456
200 result= (timeout)
510 Invalid or unknown command
520-Invalid command syntax. Pr... | python | {
"resource": ""
} |
q271601 | agi_code_check | test | def agi_code_check(code=None, response=None, line=None):
"""
Check the AGI code and return a dict to help on error handling.
"""
code = int(code)
response = response or ""
result = {'status_code': code, 'result': ('', ''), 'msg': ''}
if code == 100:
result['msg'] = line
elif code... | python | {
"resource": ""
} |
q271602 | IdGenerator.reset | test | def reset(cls, uid=None):
"""Mostly used for unit testing. Allow to use a static uuid and reset
all counter"""
for instance in cls.instances:
if uid:
instance.uid = uid
instance.generator = instance.get_generator() | python | {
"resource": ""
} |
q271603 | IdGenerator.get_instances | test | def get_instances(self):
"""Mostly used for debugging"""
return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__,
i.prefix, self.uid)
for i in self.instances] | python | {
"resource": ""
} |
q271604 | get_data | test | def get_data(path):
"""
Returns data from a package directory.
'path' should be an absolute path.
"""
# Run the imported setup to get the metadata.
with FakeContext(path):
with SetupMonkey() as sm:
try:
distro = run_setup('setup.py', stop_after='config')
... | python | {
"resource": ""
} |
q271605 | get_primary_keys | test | def get_primary_keys(model):
"""Get primary key properties for a SQLAlchemy model.
:param model: SQLAlchemy model class
"""
mapper = model.__mapper__
return [mapper.get_property_by_column(column) for column in mapper.primary_key] | python | {
"resource": ""
} |
q271606 | Related._deserialize | test | def _deserialize(self, value, *args, **kwargs):
"""Deserialize a serialized value to a model instance.
If the parent schema is transient, create a new (transient) instance.
Otherwise, attempt to find an existing instance in the database.
:param value: The value to deserialize.
"... | python | {
"resource": ""
} |
q271607 | Related._get_existing_instance | test | def _get_existing_instance(self, query, value):
"""Retrieve the related object from an existing instance in the DB.
:param query: A SQLAlchemy `Query <sqlalchemy.orm.query.Query>` object.
:param value: The serialized value to mapto an existing instance.
:raises NoResultFound: if there i... | python | {
"resource": ""
} |
q271608 | SchemaMeta.get_declared_fields | test | def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):
"""Updates declared fields with fields converted from the SQLAlchemy model
passed as the `model` class Meta option.
"""
opts = klass.opts
Converter = opts.model_converter
converter = Converter(sc... | python | {
"resource": ""
} |
q271609 | ModelSchema.load | test | def load(self, data, session=None, instance=None, transient=False, *args, **kwargs):
"""Deserialize data to internal representation.
:param session: Optional SQLAlchemy session.
:param instance: Optional existing instance to modify.
:param transient: Optional switch to allow transient i... | python | {
"resource": ""
} |
q271610 | ModelSchema._split_model_kwargs_association | test | def _split_model_kwargs_association(self, data):
"""Split serialized attrs to ensure association proxies are passed separately.
This is necessary for Python < 3.6.0, as the order in which kwargs are passed
is non-deterministic, and associations must be parsed by sqlalchemy after their
i... | python | {
"resource": ""
} |
q271611 | gc | test | def gc():
"""Deletes old stellar tables that are not used anymore"""
def after_delete(database):
click.echo("Deleted table %s" % database)
app = get_app()
upgrade_from_old_version(app)
app.delete_orphan_snapshots(after_delete) | python | {
"resource": ""
} |
q271612 | snapshot | test | def snapshot(name):
"""Takes a snapshot of the database"""
app = get_app()
upgrade_from_old_version(app)
name = name or app.default_snapshot_name
if app.get_snapshot(name):
click.echo("Snapshot with name %s already exists" % name)
sys.exit(1)
else:
def before_copy(table_... | python | {
"resource": ""
} |
q271613 | list | test | def list():
"""Returns a list of snapshots"""
snapshots = get_app().get_snapshots()
click.echo('\n'.join(
'%s: %s' % (
s.snapshot_name,
humanize.naturaltime(datetime.utcnow() - s.created_at)
)
for s in snapshots
)) | python | {
"resource": ""
} |
q271614 | restore | test | def restore(name):
"""Restores the database from a snapshot"""
app = get_app()
if not name:
snapshot = app.get_latest_snapshot()
if not snapshot:
click.echo(
"Couldn't find any snapshots for project %s" %
load_config()['project_name']
... | python | {
"resource": ""
} |
q271615 | remove | test | def remove(name):
"""Removes a snapshot"""
app = get_app()
snapshot = app.get_snapshot(name)
if not snapshot:
click.echo("Couldn't find snapshot %s" % name)
sys.exit(1)
click.echo("Deleting snapshot %s" % name)
app.remove_snapshot(snapshot)
click.echo("Deleted") | python | {
"resource": ""
} |
q271616 | rename | test | def rename(old_name, new_name):
"""Renames a snapshot"""
app = get_app()
snapshot = app.get_snapshot(old_name)
if not snapshot:
click.echo("Couldn't find snapshot %s" % old_name)
sys.exit(1)
new_snapshot = app.get_snapshot(new_name)
if new_snapshot:
click.echo("Snapshot... | python | {
"resource": ""
} |
q271617 | replace | test | def replace(name):
"""Replaces a snapshot"""
app = get_app()
snapshot = app.get_snapshot(name)
if not snapshot:
click.echo("Couldn't find snapshot %s" % name)
sys.exit(1)
app.remove_snapshot(snapshot)
app.create_snapshot(name)
click.echo("Replaced snapshot %s" % name) | python | {
"resource": ""
} |
q271618 | Neg_Sampling_Data_Gen.on_epoch_end | test | def on_epoch_end(self) -> None:
'Updates indexes after each epoch for shuffling'
self.indexes = np.arange(self.nrows)
if self.shuffle:
np.random.shuffle(self.indexes) | python | {
"resource": ""
} |
q271619 | textacy_cleaner | test | def textacy_cleaner(text: str) -> str:
"""
Defines the default function for cleaning text.
This function operates over a list.
"""
return preprocess_text(text,
fix_unicode=True,
lowercase=True,
transliterate=True,
... | python | {
"resource": ""
} |
q271620 | apply_parallel | test | def apply_parallel(func: Callable,
data: List[Any],
cpu_cores: int = None) -> List[Any]:
"""
Apply function to list of elements.
Automatically determines the chunk size.
"""
if not cpu_cores:
cpu_cores = cpu_count()
try:
chunk_size = ceil(l... | python | {
"resource": ""
} |
q271621 | process_text_constructor | test | def process_text_constructor(cleaner: Callable,
tokenizer: Callable,
append_indicators: bool,
start_tok: str,
end_tok: str):
"""Generate a function that will clean and tokenize text."""
def proces... | python | {
"resource": ""
} |
q271622 | processor.process_text | test | def process_text(self, text: List[str]) -> List[List[str]]:
"""Combine the cleaner and tokenizer."""
process_text = process_text_constructor(cleaner=self.cleaner,
tokenizer=self.tokenizer,
append_indicators=s... | python | {
"resource": ""
} |
q271623 | processor.parallel_process_text | test | def parallel_process_text(self, data: List[str]) -> List[List[str]]:
"""Apply cleaner -> tokenizer."""
process_text = process_text_constructor(cleaner=self.cleaner,
tokenizer=self.tokenizer,
append_indicators... | python | {
"resource": ""
} |
q271624 | processor.generate_doc_length_stats | test | def generate_doc_length_stats(self):
"""Analyze document length statistics for padding strategy"""
heuristic = self.heuristic_pct
histdf = (pd.DataFrame([(a, b) for a, b in self.document_length_histogram.items()],
columns=['bin', 'doc_count'])
.so... | python | {
"resource": ""
} |
q271625 | processor.token_count_pandas | test | def token_count_pandas(self):
""" See token counts as pandas dataframe"""
freq_df = pd.DataFrame.from_dict(self.indexer.word_counts, orient='index')
freq_df.columns = ['count']
return freq_df.sort_values('count', ascending=False) | python | {
"resource": ""
} |
q271626 | map_param_type | test | def map_param_type(param_type):
"""
Perform param type mapping
This requires a bit of logic since this isn't standardized.
If a type doesn't map, assume str
"""
main_type, sub_type = TYPE_INFO_RE.match(param_type).groups()
if main_type in ('list', 'array'):
# Handle no sub-type: "re... | python | {
"resource": ""
} |
q271627 | parse_interfaces | test | def parse_interfaces(interfaces):
"""
Parse the conduit.query json dict response
This performs the logic of parsing the non-standard params dict
and then returning a dict Resource can understand
"""
parsed_interfaces = collections.defaultdict(dict)
for m, d in iteritems(interfaces):
... | python | {
"resource": ""
} |
q271628 | BidictBase.inverse | test | def inverse(self):
"""The inverse of this bidict.
*See also* :attr:`inv`
"""
# Resolve and return a strong reference to the inverse bidict.
# One may be stored in self._inv already.
if self._inv is not None:
return self._inv
# Otherwise a weakref is s... | python | {
"resource": ""
} |
q271629 | BidictBase._update_with_rollback | test | def _update_with_rollback(self, on_dup, *args, **kw):
"""Update, rolling back on failure."""
writelog = []
appendlog = writelog.append
dedup_item = self._dedup_item
write_item = self._write_item
for (key, val) in _iteritems_args_kw(*args, **kw):
try:
... | python | {
"resource": ""
} |
q271630 | BidictBase.copy | test | def copy(self):
"""A shallow copy."""
# Could just ``return self.__class__(self)`` here instead, but the below is faster. It uses
# __new__ to create a copy instance while bypassing its __init__, which would result
# in copying this bidict's items into the copy instance one at a time. In... | python | {
"resource": ""
} |
q271631 | OrderedBidictBase.copy | test | def copy(self):
"""A shallow copy of this ordered bidict."""
# Fast copy implementation bypassing __init__. See comments in :meth:`BidictBase.copy`.
copy = self.__class__.__new__(self.__class__)
sntl = _Sentinel()
fwdm = self._fwdm.copy()
invm = self._invm.copy()
... | python | {
"resource": ""
} |
q271632 | OrderedBidictBase.equals_order_sensitive | test | def equals_order_sensitive(self, other):
"""Order-sensitive equality check.
*See also* :ref:`eq-order-insensitive`
"""
# Same short-circuit as BidictBase.__eq__. Factoring out not worth function call overhead.
if not isinstance(other, Mapping) or len(self) != len(other):
... | python | {
"resource": ""
} |
q271633 | inverted | test | def inverted(arg):
"""Yield the inverse items of the provided object.
If *arg* has a :func:`callable` ``__inverted__`` attribute,
return the result of calling it.
Otherwise, return an iterator over the items in `arg`,
inverting each item on the fly.
*See also* :attr:`bidict.BidirectionalMappi... | python | {
"resource": ""
} |
q271634 | OrderedBidict.clear | test | def clear(self):
"""Remove all items."""
self._fwdm.clear()
self._invm.clear()
self._sntl.nxt = self._sntl.prv = self._sntl | python | {
"resource": ""
} |
q271635 | OrderedBidict.move_to_end | test | def move_to_end(self, key, last=True):
"""Move an existing key to the beginning or end of this ordered bidict.
The item is moved to the end if *last* is True, else to the beginning.
:raises KeyError: if the key does not exist
"""
node = self._fwdm[key]
node.prv.nxt = no... | python | {
"resource": ""
} |
q271636 | write_temp_file | test | def write_temp_file(text=""):
"""Create a new temporary file and write some initial text to it.
:param text: the text to write to the temp file
:type text: str
:returns: the file name of the newly created temp file
:rtype: str
"""
with NamedTemporaryFile(mode='w+t', suffix='.yml', delete=F... | python | {
"resource": ""
} |
q271637 | get_contacts | test | def get_contacts(address_books, query, method="all", reverse=False,
group=False, sort="first_name"):
"""Get a list of contacts from one or more address books.
:param address_books: the address books to search
:type address_books: list(address_book.AddressBook)
:param query: a search qu... | python | {
"resource": ""
} |
q271638 | merge_args_into_config | test | def merge_args_into_config(args, config):
"""Merge the parsed arguments from argparse into the config object.
:param args: the parsed command line arguments
:type args: argparse.Namespace
:param config: the parsed config file
:type config: config.Config
:returns: the merged config object
:r... | python | {
"resource": ""
} |
q271639 | load_address_books | test | def load_address_books(names, config, search_queries):
"""Load all address books with the given names from the config.
:param names: the address books to load
:type names: list(str)
:param config: the config instance to use when looking up address books
:type config: config.Config
:param search... | python | {
"resource": ""
} |
q271640 | prepare_search_queries | test | def prepare_search_queries(args):
"""Prepare the search query string from the given command line args.
Each address book can get a search query string to filter vcards befor
loading them. Depending on the question if the address book is used for
source or target searches different regexes have to be c... | python | {
"resource": ""
} |
q271641 | new_subcommand | test | def new_subcommand(selected_address_books, input_from_stdin_or_file,
open_editor):
"""Create a new contact.
:param selected_address_books: a list of addressbooks that were selected on
the command line
:type selected_address_books: list of address_book.AddressBook
:param input... | python | {
"resource": ""
} |
q271642 | birthdays_subcommand | test | def birthdays_subcommand(vcard_list, parsable):
"""Print birthday contact table.
:param vcard_list: the vcards to search for matching entries which should
be printed
:type vcard_list: list of carddav_object.CarddavObject
:param parsable: machine readable output: columns devided by tabulator (\t... | python | {
"resource": ""
} |
q271643 | phone_subcommand | test | def phone_subcommand(search_terms, vcard_list, parsable):
"""Print a phone application friendly contact table.
:param search_terms: used as search term to filter the contacts before
printing
:type search_terms: str
:param vcard_list: the vcards to search for matching entries which should
... | python | {
"resource": ""
} |
q271644 | list_subcommand | test | def list_subcommand(vcard_list, parsable):
"""Print a user friendly contacts table.
:param vcard_list: the vcards to print
:type vcard_list: list of carddav_object.CarddavObject
:param parsable: machine readable output: columns devided by tabulator (\t)
:type parsable: bool
:returns: None
:... | python | {
"resource": ""
} |
q271645 | modify_subcommand | test | def modify_subcommand(selected_vcard, input_from_stdin_or_file, open_editor):
"""Modify a contact in an external editor.
:param selected_vcard: the contact to modify
:type selected_vcard: carddav_object.CarddavObject
:param input_from_stdin_or_file: new data from stdin (or a file) that
should b... | python | {
"resource": ""
} |
q271646 | remove_subcommand | test | def remove_subcommand(selected_vcard, force):
"""Remove a contact from the addressbook.
:param selected_vcard: the contact to delete
:type selected_vcard: carddav_object.CarddavObject
:param force: delete without confirmation
:type force: bool
:returns: None
:rtype: None
"""
if not... | python | {
"resource": ""
} |
q271647 | source_subcommand | test | def source_subcommand(selected_vcard, editor):
"""Open the vcard file for a contact in an external editor.
:param selected_vcard: the contact to edit
:type selected_vcard: carddav_object.CarddavObject
:param editor: the eitor command to use
:type editor: str
:returns: None
:rtype: None
... | python | {
"resource": ""
} |
q271648 | merge_subcommand | test | def merge_subcommand(vcard_list, selected_address_books, search_terms,
target_uid):
"""Merge two contacts into one.
:param vcard_list: the vcards from which to choose contacts for mergeing
:type vcard_list: list of carddav_object.CarddavObject
:param selected_address_books: the add... | python | {
"resource": ""
} |
q271649 | copy_or_move_subcommand | test | def copy_or_move_subcommand(action, vcard_list, target_address_book_list):
"""Copy or move a contact to a different address book.
:action: the string "copy" or "move" to indicate what to do
:type action: str
:param vcard_list: the contact list from which to select one for the action
:type vcard_lis... | python | {
"resource": ""
} |
q271650 | Actions.get_action | test | def get_action(cls, alias):
"""Find the name of the action for the supplied alias. If no action is
asociated with the given alias, None is returned.
:param alias: the alias to look up
:type alias: str
:rturns: the name of the corresponding action or None
:rtype: str or ... | python | {
"resource": ""
} |
q271651 | Config._convert_boolean_config_value | test | def _convert_boolean_config_value(config, name, default=True):
"""Convert the named field to bool.
The current value should be one of the strings "yes" or "no". It will
be replaced with its boolean counterpart. If the field is not present
in the config object, the default value is use... | python | {
"resource": ""
} |
q271652 | CarddavObject.new_contact | test | def new_contact(cls, address_book, supported_private_objects, version,
localize_dates):
"""Use this to create a new and empty contact."""
return cls(address_book, None, supported_private_objects, version,
localize_dates) | python | {
"resource": ""
} |
q271653 | CarddavObject.from_file | test | def from_file(cls, address_book, filename, supported_private_objects,
localize_dates):
"""
Use this if you want to create a new contact from an existing .vcf
file.
"""
return cls(address_book, filename, supported_private_objects, None,
localize_dates) | python | {
"resource": ""
} |
q271654 | CarddavObject.from_user_input | test | def from_user_input(cls, address_book, user_input,
supported_private_objects, version, localize_dates):
"""Use this if you want to create a new contact from user input."""
contact = cls(address_book, None, supported_private_objects, version,
localize_dates)
... | python | {
"resource": ""
} |
q271655 | CarddavObject.from_existing_contact_with_new_user_input | test | def from_existing_contact_with_new_user_input(cls, contact, user_input,
localize_dates):
"""
Use this if you want to clone an existing contact and replace its data
with new user input in one step.
"""
contact = cls(contact.address_book, contact.filename,
... | python | {
"resource": ""
} |
q271656 | CarddavObject._get_names_part | test | def _get_names_part(self, part):
"""Get some part of the "N" entry in the vCard as a list
:param part: the name to get e.g. "prefix" or "given"
:type part: str
:returns: a list of entries for this name part
:rtype: list(str)
"""
try:
the_list = getat... | python | {
"resource": ""
} |
q271657 | CarddavObject._add_category | test | def _add_category(self, categories):
""" categories variable must be a list """
categories_obj = self.vcard.add('categories')
categories_obj.value = helpers.convert_to_vcard(
"category", categories, ObjectType.list_with_strings) | python | {
"resource": ""
} |
q271658 | CarddavObject._parse_type_value | test | def _parse_type_value(types, value, supported_types):
"""Parse type value of phone numbers, email and post addresses.
:param types: list of type values
:type types: list(str)
:param value: the corresponding label, required for more verbose
exceptions
:type value: str... | python | {
"resource": ""
} |
q271659 | list_to_string | test | def list_to_string(input, delimiter):
"""converts list to string recursively so that nested lists are supported
:param input: a list of strings and lists of strings (and so on recursive)
:type input: list
:param delimiter: the deimiter to use when joining the items
:type delimiter: str
:returns... | python | {
"resource": ""
} |
q271660 | string_to_date | test | def string_to_date(input):
"""Convert string to date object.
:param input: the date string to parse
:type input: str
:returns: the parsed datetime object
:rtype: datetime.datetime
"""
# try date formats --mmdd, --mm-dd, yyyymmdd, yyyy-mm-dd and datetime
# formats yyyymmddThhmmss, yyyy-m... | python | {
"resource": ""
} |
q271661 | AddressBook._compare_uids | test | def _compare_uids(uid1, uid2):
"""Calculate the minimum length of initial substrings of uid1 and uid2
for them to be different.
:param uid1: first uid to compare
:type uid1: str
:param uid2: second uid to compare
:type uid2: str
:returns: the length of the shorte... | python | {
"resource": ""
} |
q271662 | AddressBook._search_all | test | def _search_all(self, query):
"""Search in all fields for contacts matching query.
:param query: the query to search for
:type query: str
:yields: all found contacts
:rtype: generator(carddav_object.CarddavObject)
"""
regexp = re.compile(query, re.IGNORECASE | r... | python | {
"resource": ""
} |
q271663 | AddressBook._search_names | test | def _search_names(self, query):
"""Search in the name filed for contacts matching query.
:param query: the query to search for
:type query: str
:yields: all found contacts
:rtype: generator(carddav_object.CarddavObject)
"""
regexp = re.compile(query, re.IGNORECA... | python | {
"resource": ""
} |
q271664 | AddressBook._search_uid | test | def _search_uid(self, query):
"""Search for contacts with a matching uid.
:param query: the query to search for
:type query: str
:yields: all found contacts
:rtype: generator(carddav_object.CarddavObject)
"""
try:
# First we treat the argument as a f... | python | {
"resource": ""
} |
q271665 | AddressBook.search | test | def search(self, query, method="all"):
"""Search this address book for contacts matching the query.
The method can be one of "all", "name" and "uid". The backend for this
address book migth be load()ed if needed.
:param query: the query to search for
:type query: str
:... | python | {
"resource": ""
} |
q271666 | AddressBook.get_short_uid_dict | test | def get_short_uid_dict(self, query=None):
"""Create a dictionary of shortend UIDs for all contacts.
All arguments are only used if the address book is not yet initialized
and will just be handed to self.load().
:param query: see self.load()
:type query: str
:returns: th... | python | {
"resource": ""
} |
q271667 | AddressBook.get_short_uid | test | def get_short_uid(self, uid):
"""Get the shortend UID for the given UID.
:param uid: the full UID to shorten
:type uid: str
:returns: the shortend uid or the empty string
:rtype: str
"""
if uid:
short_uids = self.get_short_uid_dict()
for l... | python | {
"resource": ""
} |
q271668 | VdirAddressBook._find_vcard_files | test | def _find_vcard_files(self, search=None, search_in_source_files=False):
"""Find all vcard files inside this address book.
If a search string is given only files which contents match that will
be returned.
:param search: a regular expression to limit the results
:type search: st... | python | {
"resource": ""
} |
q271669 | VdirAddressBook.load | test | def load(self, query=None, search_in_source_files=False):
"""Load all vcard files in this address book from disk.
If a search string is given only files which contents match that will
be loaded.
:param query: a regular expression to limit the results
:type query: str
:p... | python | {
"resource": ""
} |
q271670 | AddressBookCollection.get_abook | test | def get_abook(self, name):
"""Get one of the backing abdress books by its name,
:param name: the name of the address book to get
:type name: str
:returns: the matching address book or None
:rtype: AddressBook or NoneType
"""
for abook in self._abooks:
... | python | {
"resource": ""
} |
q271671 | Assembler.avail_archs | test | def avail_archs(self):
''' Initialize the dictionary of architectures for assembling via keystone'''
return {
ARM32: (KS_ARCH_ARM, KS_MODE_ARM),
ARM64: (KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN),
ARM_TB: (KS_ARCH_ARM, KS_MODE_THUMB),
HEXAGON: (... | python | {
"resource": ""
} |
q271672 | Disassembler.avail_archs | test | def avail_archs(self):
''' Initialize the dictionary of architectures for disassembling via capstone'''
return {
ARM32: (CS_ARCH_ARM, CS_MODE_ARM),
ARM64: (CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN),
ARM_TB: (CS_ARCH_ARM, CS_MODE_THUMB),
MIPS32: (CS_... | python | {
"resource": ""
} |
q271673 | getargspec_permissive | test | def getargspec_permissive(func):
"""
An `inspect.getargspec` with a relaxed sanity check to support Cython.
Motivation:
A Cython-compiled function is *not* an instance of Python's
types.FunctionType. That is the sanity check the standard Py2
library uses in `inspect.getargspec()`.... | python | {
"resource": ""
} |
q271674 | dispatch | test | def dispatch(parser, argv=None, add_help_command=True,
completion=True, pre_call=None,
output_file=sys.stdout, errors_file=sys.stderr,
raw_output=False, namespace=None,
skip_unknown_args=False):
"""
Parses given list of arguments using given parser, calls the ... | python | {
"resource": ""
} |
q271675 | safe_input | test | def safe_input(prompt):
"""
Prompts user for input. Correctly handles prompt message encoding.
"""
if sys.version_info < (3,0):
if isinstance(prompt, compat.text_type):
# Python 2.x: unicode → bytes
encoding = locale.getpreferredencoding() or 'utf-8'
prompt ... | python | {
"resource": ""
} |
q271676 | encode_output | test | def encode_output(value, output_file):
"""
Encodes given value so it can be written to given file object.
Value may be Unicode, binary string or any other data type.
The exact behaviour depends on the Python version:
Python 3.x
`sys.stdout` is a `_io.TextIOWrapper` instance that accepts ... | python | {
"resource": ""
} |
q271677 | _guess | test | def _guess(kwargs):
"""
Adds types, actions, etc. to given argument specification.
For example, ``default=3`` implies ``type=int``.
:param arg: a :class:`argh.utils.Arg` instance
"""
guessed = {}
# Parser actions that accept argument 'type'
TYPE_AWARE_ACTIONS = 'store', 'append'
#... | python | {
"resource": ""
} |
q271678 | add_commands | test | def add_commands(parser, functions, namespace=None, namespace_kwargs=None,
func_kwargs=None,
# deprecated args:
title=None, description=None, help=None):
"""
Adds given functions as commands to given parser.
:param parser:
an :class:`argparse.Argu... | python | {
"resource": ""
} |
q271679 | named | test | def named(new_name):
"""
Sets given string as command name instead of the function name.
The string is used verbatim without further processing.
Usage::
@named('load')
def do_load_some_stuff_and_keep_the_original_function_name(args):
...
The resulting command will be a... | python | {
"resource": ""
} |
q271680 | arg | test | def arg(*args, **kwargs):
"""
Declares an argument for given function. Does not register the function
anywhere, nor does it modify the function in any way.
The signature of the decorator matches that of
:meth:`argparse.ArgumentParser.add_argument`, only some keywords are not
required if they ca... | python | {
"resource": ""
} |
q271681 | confirm | test | def confirm(action, default=None, skip=False):
"""
A shortcut for typical confirmation prompt.
:param action:
a string describing the action, e.g. "Apply changes". A question mark
will be appended.
:param default:
`bool` or `None`. Determines what happens when user hits :kbd:... | python | {
"resource": ""
} |
q271682 | Query.replace | test | def replace(self, **kwargs):
'''
Copy the Query object, optionally replacing the filters, order_by, or
limit information on the copy. This is mostly an internal detail that
you can ignore.
'''
data = {
'model': self._model,
'filters': self._filters... | python | {
"resource": ""
} |
q271683 | Query.like | test | def like(self, **kwargs):
'''
When provided with keyword arguments of the form ``col=pattern``, this
will limit the entities returned to those that include the provided
pattern. Note that 'like' queries require that the ``prefix=True``
option must have been provided as part of th... | python | {
"resource": ""
} |
q271684 | Query.cached_result | test | def cached_result(self, timeout):
'''
This will execute the query, returning the key where a ZSET of your
results will be stored for pagination, further operations, etc.
The timeout must be a positive integer number of seconds for which to
set the expiration time on the key (thi... | python | {
"resource": ""
} |
q271685 | Query.first | test | def first(self):
'''
Returns only the first result from the query, if any.
'''
lim = [0, 1]
if self._limit:
lim[0] = self._limit[0]
if not self._filters and not self._order_by:
for ent in self:
return ent
return None
... | python | {
"resource": ""
} |
q271686 | Query.delete | test | def delete(self, blocksize=100):
'''
Will delete the entities that match at the time the query is executed.
Used like::
MyModel.query.filter(email=...).delete()
MyModel.query.endswith(email='@host.com').delete()
.. warning:: can't be used on models on either si... | python | {
"resource": ""
} |
q271687 | _on_delete | test | def _on_delete(ent):
'''
This function handles all on_delete semantics defined on OneToMany columns.
This function only exists because 'cascade' is *very* hard to get right.
'''
seen_d = set([ent._pk])
to_delete = [ent]
seen_s = set()
to_save = []
def _set_default(ent, attr, de=NUL... | python | {
"resource": ""
} |
q271688 | redis_prefix_lua | test | def redis_prefix_lua(conn, dest, index, prefix, is_first, pattern=None):
'''
Performs the actual prefix, suffix, and pattern match operations.
'''
tkey = '%s:%s'%(index.partition(':')[0], uuid.uuid4())
start, end = _start_end(prefix)
return _redis_prefix_lua(conn,
[dest, tkey, index],
... | python | {
"resource": ""
} |
q271689 | estimate_work_lua | test | def estimate_work_lua(conn, index, prefix):
'''
Estimates the total work necessary to calculate the prefix match over the
given index with the provided prefix.
'''
if index.endswith(':idx'):
args = [] if not prefix else list(prefix)
if args:
args[0] = '-inf' if args[0] is... | python | {
"resource": ""
} |
q271690 | GeneralIndex.search | test | def search(self, conn, filters, order_by, offset=None, count=None, timeout=None):
'''
Search for model ids that match the provided filters.
Arguments:
* *filters* - A list of filters that apply to the search of one of
the following two forms:
1. ``'co... | python | {
"resource": ""
} |
q271691 | GeneralIndex.count | test | def count(self, conn, filters):
'''
Returns the count of the items that match the provided filters.
For the meaning of what the ``filters`` argument means, see the
``.search()`` method docs.
'''
pipe, intersect, temp_id = self._prepare(conn, filters)
pipe.zcard(t... | python | {
"resource": ""
} |
q271692 | _connect | test | def _connect(obj):
'''
Tries to get the _conn attribute from a model. Barring that, gets the
global default connection using other methods.
'''
from .columns import MODELS
if isinstance(obj, MODELS['Model']):
obj = obj.__class__
if hasattr(obj, '_conn'):
return obj._conn
... | python | {
"resource": ""
} |
q271693 | FULL_TEXT | test | def FULL_TEXT(val):
'''
This is a basic full-text index keygen function. Words are lowercased, split
by whitespace, and stripped of punctuation from both ends before an inverted
index is created for term searching.
'''
if isinstance(val, float):
val = repr(val)
elif val in (None, '')... | python | {
"resource": ""
} |
q271694 | refresh_indices | test | def refresh_indices(model, block_size=100):
'''
This utility function will iterate over all entities of a provided model,
refreshing their indices. This is primarily useful after adding an index
on a column.
Arguments:
* *model* - the model whose entities you want to reindex
* *blo... | python | {
"resource": ""
} |
q271695 | clean_old_index | test | def clean_old_index(model, block_size=100, **kwargs):
'''
This utility function will clean out old index data that was accidentally
left during item deletion in rom versions <= 0.27.0 . You should run this
after you have upgraded all of your clients to version 0.28.0 or later.
Arguments:
*... | python | {
"resource": ""
} |
q271696 | Session.add | test | def add(self, obj):
'''
Adds an entity to the session.
'''
if self.null_session:
return
self._init()
pk = obj._pk
if not pk.endswith(':None'):
self.known[pk] = obj
self.wknown[pk] = obj | python | {
"resource": ""
} |
q271697 | Session.get | test | def get(self, pk):
'''
Fetches an entity from the session based on primary key.
'''
self._init()
return self.known.get(pk) or self.wknown.get(pk) | python | {
"resource": ""
} |
q271698 | redis_writer_lua | test | def redis_writer_lua(conn, pkey, namespace, id, unique, udelete, delete,
data, keys, scored, prefix, suffix, geo, old_data, is_delete):
'''
... Actually write data to Redis. This is an internal detail. Please don't
call me directly.
'''
ldata = []
for pair in data.items():
... | python | {
"resource": ""
} |
q271699 | Model.save | test | def save(self, full=False, force=False):
'''
Saves the current entity to Redis. Will only save changed data by
default, but you can force a full save by passing ``full=True``.
If the underlying entity was deleted and you want to re-save the entity,
you can pass ``force=True`` to... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.