_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q44300
everyonesAverage
train
def everyonesAverage(year, badFormat, length): ''' creates list of weighted average results for everyone in year Arguments: year {int} badFormat {dict} -- candNumber : [results for candidate] length {int} -- length of each row in badFormat divided by 2 returns: list -- wei...
python
{ "resource": "" }
q44301
askInitial
train
def askInitial(): '''Asks the user for what it wants the script to do Returns: [dictionary] -- answers to the questions ''' return inquirer.prompt([ inquirer.Text( 'inputPath', message="What's the path of your input file (eg input.csv)"), inquirer.List( '...
python
{ "resource": "" }
q44302
howPlotAsk
train
def howPlotAsk(goodFormat): '''plots using inquirer prompts Arguments: goodFormat {dict} -- module : [results for module] ''' plotAnswer = askPlot() if "Save" in plotAnswer['plotQ']: exportPlotsPath = pathlib.Path(askSave()) if "Show" in plotAnswer['plotQ']: plot...
python
{ "resource": "" }
q44303
read_config
train
def read_config(config_path_or_dict=None): """ Read config from given path string or dict object. :param config_path_or_dict: :type config_path_or_dict: str or dict :return: Returns config object or None if not found. :rtype: :class:`revision.config.Config` """ config = None if isi...
python
{ "resource": "" }
q44304
Config.validate
train
def validate(self): """ Check the value of the config attributes. """ for client in self.clients: for key in REQUIRED_KEYS: if key not in client: raise MissingConfigValue(key) if 'revision_file' not in client: c...
python
{ "resource": "" }
q44305
wrap
train
def wrap(func, with_func): r"""Copies the function signature from the wrapped function to the wrapping function. """ func.__name__ = with_func.__name__ func.__doc__ = with_func.__doc__ func.__dict__.update(with_func.__dict__) return func
python
{ "resource": "" }
q44306
decorator
train
def decorator(func): r"""Makes the passed decorators to support optional args. """ def wrapper(__decorated__=None, *Args, **KwArgs): if __decorated__ is None: # the decorator has some optional arguments. return lambda _func: func(_func, *Args, **KwArgs) else: return func(__decorated__, *Args,...
python
{ "resource": "" }
q44307
task
train
def task(__decorated__=None, **Config): r"""A decorator to make tasks out of functions. Config: * name (str): The name of the task. Defaults to __decorated__.__name__. * desc (str): The description of the task (optional). * alias (str): The alias for the task (optional). """ if isinstance(__decorat...
python
{ "resource": "" }
q44308
arg
train
def arg(name=None, **Config): # wraps the _arg decorator, in order to allow unnamed args r"""A decorator to configure an argument of a task. Config: * name (str): The name of the arg. When ommited the agument will be identified through the order of configuration. * desc (str): The description of the arg (o...
python
{ "resource": "" }
q44309
_arg
train
def _arg(__decorated__, **Config): r"""The worker for the arg decorator. """ if isinstance(__decorated__, tuple): # this decorator is followed by another arg decorator __decorated__[1].insert(0, Config) return __decorated__ else: return __decorated__, [Config]
python
{ "resource": "" }
q44310
group
train
def group(__decorated__, **Config): r"""A decorator to make groups out of classes. Config: * name (str): The name of the group. Defaults to __decorated__.__name__. * desc (str): The description of the group (optional). * alias (str): The alias for the group (optional). """ _Group = Group(__decorate...
python
{ "resource": "" }
q44311
exit_hook
train
def exit_hook(callable, once=True): r"""A decorator that makes the decorated function to run while ec exits. Args: callable (callable): The target callable. once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True. Note: Hooks are processedd in a LIFO order. "...
python
{ "resource": "" }
q44312
member
train
def member(Imported, **Config): r"""Helps with adding imported members to Scripts. Note: Config depends upon the Imported. It could be that of a **task** or a **group**. """ __ec_member__ = Imported.__ec_member__ __ec_member__.Config.update(**Config) state.ActiveModuleMemberQ.insert(0, __ec_member__)
python
{ "resource": "" }
q44313
ConfigStruct.configure_basic_logging
train
def configure_basic_logging(self, main_module_name, **kwargs): '''Use common logging options to configure all logging. Basic logging configuration is used to set levels for all logs from the main module and to filter out logs from other modules unless they are of one level in priority higher. ...
python
{ "resource": "" }
q44314
ConfigStruct.save
train
def save(self, conflict_resolver=choose_mine): '''Save all options in memory to the `config_file`. Options are read once more from the file (to allow other writers to save configuration), keys in conflict are resolved, and the final results are written back to the file. :param conflic...
python
{ "resource": "" }
q44315
kw_str_parse
train
def kw_str_parse(a_string): """convert a string in the form 'a=b, c=d, e=f' to a dict""" try: return dict((k, eval(v.rstrip(','))) for k, v in kw_list_re.findall(a_string)) except (AttributeError, TypeError): if isinstance(a_string, collections.Mapping): retur...
python
{ "resource": "" }
q44316
is_not_null_predicate
train
def is_not_null_predicate( raw_crash, dumps, processed_crash, processor, key='' ): """a predicate that converts the key'd source to boolean. parameters: raw_crash - dict dumps - placeholder in a fat interface - unused processed_crash - placeholder in a fat interface - unused ...
python
{ "resource": "" }
q44317
Rule.predicate
train
def predicate(self, *args, **kwargs): """the default predicate for Support Classifiers invokes any derivied _predicate function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act. An error during th...
python
{ "resource": "" }
q44318
Rule.action
train
def action(self, *args, **kwargs): """the default action for Support Classifiers invokes any derivied _action function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act and perhaps mitigate the erro...
python
{ "resource": "" }
q44319
TransformRule.function_invocation_proxy
train
def function_invocation_proxy(fn, proxy_args, proxy_kwargs): """execute the fuction if it is one, else evaluate the fn as a boolean and return that value. Sometimes rather than providing a predicate, we just give the value of True. This is shorthand for writing a predicate that always ...
python
{ "resource": "" }
q44320
TransformRuleSystem.load_rules
train
def load_rules(self, an_iterable): """cycle through a collection of Transform rule tuples loading them into the TransformRuleSystem""" self.rules = [ TransformRule(*x, config=self.config) for x in an_iterable ]
python
{ "resource": "" }
q44321
TransformRuleSystem.append_rules
train
def append_rules(self, an_iterable): """add rules to the TransformRuleSystem""" self.rules.extend( TransformRule(*x, config=self.config) for x in an_iterable )
python
{ "resource": "" }
q44322
TransformRuleSystem.apply_all_rules
train
def apply_all_rules(self, *args, **kwargs): """cycle through all rules and apply them all without regard to success or failure returns: True - since success or failure is ignored""" for x in self.rules: self._quit_check() if self.config.chatty_rules:...
python
{ "resource": "" }
q44323
get_wordset
train
def get_wordset(poems): """get all words""" words = sorted(list(set(reduce(lambda x, y: x + y, poems)))) return words
python
{ "resource": "" }
q44324
AwsStack.printStack
train
def printStack(self,wrappedStack,include=None,filters=["*"]): """Prints the stack""" rawStack = wrappedStack['rawStack'] print "==== Stack {} ====".format(rawStack.name) print "Status: {} {}".format(rawStack.stack_status,defaultify(rawStack.stack_status_reason,'')) for resourceT...
python
{ "resource": "" }
q44325
AwsStack.do_browse
train
def do_browse(self,args): """Open the current stack in a browser.""" rawStack = self.wrappedStack['rawStack'] os.system("open -a \"Google Chrome\" https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stack/detail?stackId={}".format(rawStack.stack_id))
python
{ "resource": "" }
q44326
AwsStack.do_refresh
train
def do_refresh(self,args): """Refresh view of the current stack. refresh -h for detailed help""" self.wrappedStack = self.wrapStack(AwsConnectionFactory.instance.getCfResource().Stack(self.wrappedStack['rawStack'].name))
python
{ "resource": "" }
q44327
AwsStack.do_print
train
def do_print(self,args): """Print the current stack. print -h for detailed help""" parser = CommandArgumentParser("print") parser.add_argument('-r','--refresh',dest='refresh',action='store_true',help='refresh view of the current stack') parser.add_argument('-i','--include',dest='include'...
python
{ "resource": "" }
q44328
AwsStack.do_resource
train
def do_resource(self,args): """Go to the specified resource. resource -h for detailed help""" parser = CommandArgumentParser("resource") parser.add_argument('-i','--logical-id',dest='logical-id',help='logical id of the child resource'); args = vars(parser.parse_args(args)) stack...
python
{ "resource": "" }
q44329
AwsStack.do_asg
train
def do_asg(self,args): """Go to the specified auto scaling group. asg -h for detailed help""" parser = CommandArgumentParser("asg") parser.add_argument(dest='asg',help='asg index or name'); args = vars(parser.parse_args(args)) print "loading auto scaling group {}".format(args['a...
python
{ "resource": "" }
q44330
AwsStack.do_eni
train
def do_eni(self,args): """Go to the specified eni. eni -h for detailed help.""" parser = CommandArgumentParser("eni") parser.add_argument(dest='eni',help='eni index or name'); args = vars(parser.parse_args(args)) print "loading eni {}".format(args['eni']) try: ...
python
{ "resource": "" }
q44331
AwsStack.do_logGroup
train
def do_logGroup(self,args): """Go to the specified log group. logGroup -h for detailed help""" parser = CommandArgumentParser("logGroup") parser.add_argument(dest='logGroup',help='logGroup index or name'); args = vars(parser.parse_args(args)) print "loading log group {}".format(...
python
{ "resource": "" }
q44332
AwsStack.do_stack
train
def do_stack(self,args): """Go to the specified stack. stack -h for detailed help.""" parser = CommandArgumentParser("stack") parser.add_argument(dest='stack',help='stack index or name'); args = vars(parser.parse_args(args)) print "loading stack {}".format(args['stack']) ...
python
{ "resource": "" }
q44333
AwsStack.do_template
train
def do_template(self,args): """Print the template for the current stack. template -h for detailed help""" parser = CommandArgumentParser("template") args = vars(parser.parse_args(args)) print "reading template for stack." rawStack = self.wrappedStack['rawStack'] template...
python
{ "resource": "" }
q44334
AwsStack.do_copy
train
def do_copy(self,args): """Copy specified id to stack. copy -h for detailed help.""" parser = CommandArgumentParser("copy") parser.add_argument('-a','--asg',dest='asg',nargs='+',required=False,default=[],help='Copy specified ASG info.') parser.add_argument('-o','--output',dest='output',n...
python
{ "resource": "" }
q44335
AwsStack.do_parameter
train
def do_parameter(self,args): """Print a parameter""" parser = CommandArgumentParser("parameter") parser.add_argument(dest="id",help="Parameter to print") args = vars(parser.parse_args(args)) print "printing parameter {}".format(args['id']) try: index ...
python
{ "resource": "" }
q44336
GitData.commit
train
def commit(self, msg): """ Commit outstanding data changes """ self.logger.info('Commit config: {}'.format(msg)) with Dir(self.data_path): self.cmd.check_assert('git add .') self.cmd.check_assert('git commit --allow-empty -m "{}"'.format(msg))
python
{ "resource": "" }
q44337
GitData.push
train
def push(self): """ Push changes back to data repo. Will of course fail if user does not have write access. """ self.logger.info('Pushing config...') with Dir(self.data_path): self.cmd.check_assert('git push')
python
{ "resource": "" }
q44338
prompt_for_new_password
train
def prompt_for_new_password(): """ Prompt the user to enter a new password, with confirmation """ while True: passw = getpass.getpass() passw2 = getpass.getpass() if passw == passw2: return passw print 'Passwords do not match'
python
{ "resource": "" }
q44339
unicode2Date
train
def unicode2Date(value, format=None): """ CONVERT UNICODE STRING TO UNIX TIMESTAMP VALUE """ # http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior if value == None: return None if format != None: try: if format.endswith("%S.%f") and "." not ...
python
{ "resource": "" }
q44340
listIDs
train
def listIDs(basedir): """Lists digital object identifiers of Pairtree directory structure. Walks a Pairtree directory structure to get IDs. Prepends prefix found in pairtree_prefix file. Outputs to standard output. """ prefix = '' # check for pairtree_prefix file prefixfile = os.path.join(b...
python
{ "resource": "" }
q44341
FreeIPAServer._set_conn
train
def _set_conn(self): """Establish connection to the server""" if self._tls: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) try: conn = ldap.initialize(self._url) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, self._timeout) conn.simp...
python
{ "resource": "" }
q44342
FreeIPAServer._get_ldap_msg
train
def _get_ldap_msg(e): """Extract LDAP exception message""" msg = e if hasattr(e, 'message'): msg = e.message if 'desc' in e.message: msg = e.message['desc'] elif hasattr(e, 'args'): msg = e.args[0]['desc'] return msg
python
{ "resource": "" }
q44343
FreeIPAServer._search
train
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE): """Perform LDAP search""" try: results = self._conn.search_s(base, scope, fltr, attrs) except Exception as e: log.exception(self._get_ldap_msg(e)) results = False return results
python
{ "resource": "" }
q44344
FreeIPAServer._set_fqdn
train
def _set_fqdn(self): """Get FQDN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-localhost'], scope=ldap.SCOPE_BASE ) if not results and type(results) is not list: r = None else: ...
python
{ "resource": "" }
q44345
FreeIPAServer._set_hostname_domain
train
def _set_hostname_domain(self): """Extract hostname and domain""" self._hostname, _, self._domain = str(self._fqdn).partition('.') log.debug('Hostname: %s, Domain: %s' % (self._hostname, self._domain))
python
{ "resource": "" }
q44346
FreeIPAServer._set_ip
train
def _set_ip(self): """Resolve FQDN to IP address""" self._ip = socket.gethostbyname(self._fqdn) log.debug('IP: %s' % self._ip)
python
{ "resource": "" }
q44347
FreeIPAServer._set_base_dn
train
def _set_base_dn(self): """Get Base DN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-defaultnamingcontext'], scope=ldap.SCOPE_BASE ) if results and type(results) is list: dn, attrs = results[0] ...
python
{ "resource": "" }
q44348
FreeIPAServer.users
train
def users(self, user_base='active'): """Return dict of users""" if not getattr(self, '_%s_users' % user_base): self._get_users(user_base) return getattr(self, '_%s_users' % user_base)
python
{ "resource": "" }
q44349
FreeIPAServer._get_users
train
def _get_users(self, user_base): """"Get users from LDAP""" results = self._search( getattr(self, '_%s_user_base' % user_base), '(objectClass=*)', ['*'], scope=ldap.SCOPE_ONELEVEL ) for dn, attrs in results: uid = attrs.get('uid...
python
{ "resource": "" }
q44350
FreeIPAServer.find_users_by_email
train
def find_users_by_email(self, email, user_base='active'): """Return list of users with given email address""" users = [] for user in getattr(self, 'users')(user_base).values(): mail = user.mail if mail and email in mail: users.append(user) log.debu...
python
{ "resource": "" }
q44351
expand
train
def expand(data): '''Generates configuration sets based on the YAML input contents For an introduction to the YAML mark-up, just search the net. Here is one of its references: https://en.wikipedia.org/wiki/YAML A configuration set corresponds to settings for **all** variables in the input template that need...
python
{ "resource": "" }
q44352
generate
train
def generate(variables, template): '''Yields a resolved "template" for each config set and dumps on output This function will extrapolate the ``template`` file using the contents of ``variables`` and will output individual (extrapolated, expanded) files in the output directory ``output``. Parameters: ...
python
{ "resource": "" }
q44353
I2B2CoreWithUploadId._nested_fcn
train
def _nested_fcn(f: Callable, filters: List): """ Distribute binary function f across list L :param f: Binary function :param filters: function arguments :return: chain of binary filters """ return None if len(filters) == 0 \ else filters[0] if len(filters) ==...
python
{ "resource": "" }
q44354
I2B2CoreWithUploadId._add_or_update_records
train
def _add_or_update_records(cls, conn: Connection, table: Table, records: List["I2B2CoreWithUploadId"]) -> Tuple[int, int]: """Add or update the supplied table as needed to reflect the contents of records :param table: i2b2 sql connection :param records: records to...
python
{ "resource": "" }
q44355
Group.equality
train
def equality(self, other): """Calculate equality based on equality of all group items.""" if not len(self) == len(other): return False return super().equality(other)
python
{ "resource": "" }
q44356
Group.similarity
train
def similarity(self, other): """Calculate similarity based on best matching permutation of items.""" # Select the longer list as the basis for comparison if len(self.items) > len(other.items): first, second = self, other else: first, second = other, self i...
python
{ "resource": "" }
q44357
peers
train
async def peers(client: Client, leaves: bool = False, leaf: str = "") -> dict: """ GET peering entries of every node inside the currency network :param client: Client to connect to the api :param leaves: True if leaves should be requested :param leaf: True if leaf should be requested :return: ...
python
{ "resource": "" }
q44358
peer
train
async def peer(client: Client, peer_signed_raw: str) -> ClientResponse: """ POST a Peer signed raw document :param client: Client to connect to the api :param peer_signed_raw: Peer signed raw document :return: """ return await client.post(MODULE + '/peering/peers', {'peer': peer_signed_raw}...
python
{ "resource": "" }
q44359
check_optical
train
def check_optical(disk): ''' Try to determine if a device is optical technology. Needs improvement. ''' dev = disk.dev if dev.startswith('sr') or ('cd' in dev): return True elif disk.fmt in optical_fs: return True else: return None
python
{ "resource": "" }
q44360
get_meminfo
train
def get_meminfo(opts): ''' Returns a dictionary holding the current memory info, divided by the ouptut unit. If mem info can't be read, returns None. ''' meminfo = MemInfo() outunit = opts.outunit try: with open(memfname) as infile: lines = infile.readlines() except ...
python
{ "resource": "" }
q44361
timeit
train
def timeit(func): """ Simple decorator to time functions :param func: function to decorate :type func: callable :return: wrapped function :rtype: callable """ @wraps(func) def _wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) el...
python
{ "resource": "" }
q44362
setConnStringForWindows
train
def setConnStringForWindows(): """ Set Conn String for Windiws Windows has a different way of forking processes, which causes the @worker_process_init.connect signal not to work in "CeleryDbConnInit" """ global _dbConnectString from peek_platform.file_config.PeekFileConfigABC import PeekFileC...
python
{ "resource": "" }
q44363
install_gem
train
def install_gem(gemname, version=None, conservative=True, ri=False, rdoc=False, development=False, format_executable=False, force=False, gem_source=None): """Install a ruby gem.""" cmdline = ['gem', 'install'] if conservative: cmdline.append('--conservative') if r...
python
{ "resource": "" }
q44364
is_installed
train
def is_installed(gemname, version=None): """Check if a gem is installed.""" cmdline = ['gem', 'list', '-i', gemname] if version: cmdline.extend(['-v', version]) try: subprocess.check_output(cmdline, shell=False) return True except (OSError, subprocess.CalledProcessError) as e...
python
{ "resource": "" }
q44365
Node.merge_links_from
train
def merge_links_from(self, other_node, merge_same_value_targets=False): """ Merge links from another node with ``self.link_list``. Copy links from another node, merging when copied links point to a node which this already links to. Args: other_node (Node): The node ...
python
{ "resource": "" }
q44366
Node.find_link
train
def find_link(self, target_node): """ Find the link that points to ``target_node`` if it exists. If no link in ``self`` points to ``target_node``, return None Args: target_node (Node): The node to look for in ``self.link_list`` Returns: Link: An existin...
python
{ "resource": "" }
q44367
Node.add_link_to_self
train
def add_link_to_self(self, source, weight): """ Create and add a ``Link`` from a source node to ``self``. Args: source (Node): The node that will own the new ``Link`` pointing to ``self`` weight (int or float): The weight of the newly created ``Link`` ...
python
{ "resource": "" }
q44368
Node.add_reciprocal_link
train
def add_reciprocal_link(self, target, weight): """ Add links pointing in either direction between ``self`` and ``target``. This creates a ``Link`` from ``self`` to ``target`` and a ``Link`` from ``target`` to ``self`` of equal weight. If ``target`` is a list of ``Node`` 's, repe...
python
{ "resource": "" }
q44369
Node.remove_links_to_self
train
def remove_links_to_self(self): """ Remove any link in ``self.link_list`` whose ``target`` is ``self``. Returns: None Example: >>> node_1 = Node('One') >>> node_1.add_link(node_1, 5) >>> node_1.remove_links_to_self() >>> len(node_1.link_l...
python
{ "resource": "" }
q44370
Compiler.compile
train
def compile(self, source_code, post_treatment=''.join): """Compile given source code. Return object code, modified by given post treatment. """ # read structure structure = self._structure(source_code) values = self._struct_to_values(structure, source_code) # c...
python
{ "resource": "" }
q44371
Compiler._initialize_tables
train
def _initialize_tables(self): """Create tables for structure and values, word->vocabulary""" # structure table self.table_struct, self.idnt_struct_size = self._create_struct_table() # values table self.table_values, self.idnt_values_size = self._create_values_table()
python
{ "resource": "" }
q44372
Compiler._structure
train
def _structure(self, source_code): """return structure in ACDP format.""" # define cutter as a per block reader def cutter(seq, block_size): for index in range(0, len(seq), block_size): lexem = seq[index:index+block_size] if len(lexem) == block_size: ...
python
{ "resource": "" }
q44373
Compiler._next_lexem
train
def _next_lexem(self, lexem_type, source_code, source_code_size): """Return next readable lexem of given type in source_code. If no value can be found, the neutral_value will be used""" # define reader as a lexem extractor def reader(seq, block_size): identificator = '' ...
python
{ "resource": "" }
q44374
Compiler._next_condition_lexems
train
def _next_condition_lexems(self, source_code, source_code_size): """Return condition lexem readed in source_code""" # find three lexems lexems = tuple(( self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size), self._next_lexem(LEXEM_TYPE_OPERATOR , source_...
python
{ "resource": "" }
q44375
Compiler._string_to_int
train
def _string_to_int(self, s): """Read an integer in s, in Little Indian. """ base = len(self.alphabet) return sum((self._letter_to_int(l) * base**lsb for lsb, l in enumerate(s) ))
python
{ "resource": "" }
q44376
Compiler._struct_to_values
train
def _struct_to_values(self, structure, source_code): """Return list of values readed in source_code, according to given structure. """ # iterate on source code until all values are finded # if a value is not foundable, # (ie its identificator is not in source code) ...
python
{ "resource": "" }
q44377
Compiler._create_struct_table
train
def _create_struct_table(self): """Create table identificator->vocabulary, and return it with size of an identificator""" len_alph = len(self.alphabet) len_vocb = len(self.voc_structure) identificator_size = ceil(log(len_vocb, len_alph)) # create list of lexems ...
python
{ "resource": "" }
q44378
check_arg_types
train
def check_arg_types(funcname, *args): """Raise TypeError if not all items of `args` are same string type.""" hasstr = hasbytes = False for arg in args: if isinstance(arg, str): hasstr = True elif isinstance(arg, bytes): hasbytes = True else: raise ...
python
{ "resource": "" }
q44379
posix_commonpath
train
def posix_commonpath(paths): """Given a sequence of POSIX path names, return the longest common sub-path.""" if not paths: raise ValueError('commonpath() arg is an empty sequence') check_arg_types('commonpath', *paths) if isinstance(paths[0], bytes): sep = b'/' curdir =...
python
{ "resource": "" }
q44380
nt_commonpath
train
def nt_commonpath(paths): # pylint: disable=too-many-locals """Given a sequence of NT path names, return the longest common sub-path.""" from ntpath import splitdrive if not paths: raise ValueError('commonpath() arg is an empty sequence') check_arg_types('commonpath', *paths) if ...
python
{ "resource": "" }
q44381
catches
train
def catches(exc, handler=re_raise): ''' Function decorator. Used to decorate function that handles exception class exc. An optional exception handler can be passed as a second argument. This exception handler shall have the signature handler(exc, message, traceback). ''' if not __CH...
python
{ "resource": "" }
q44382
SafeConnection.locked
train
def locked(self): """Context generator for `with` statement, yields thread-safe connection. :return: thread-safe connection :rtype: pydbal.connection.Connection """ conn = self._get_connection() try: self._lock(conn) yield conn finally: ...
python
{ "resource": "" }
q44383
SafeConnection.query
train
def query(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns rows generator. :param sql: query to execute :param args: parameters iterable :param kwargs: parameters iterable :return: rows generator :rtype: generator """ with self.loc...
python
{ "resource": "" }
q44384
SafeConnection.fetch
train
def fetch(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row or `None` """ with self.locked(...
python
{ "resource": "" }
q44385
SafeConnection.fetch_all
train
def fetch_all(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns all selected rows. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: all selected rows :rtype: list """ with...
python
{ "resource": "" }
q44386
SafeConnection.fetch_column
train
def fetch_column(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns the first column of the first row or `None`. :param sql: statement to execute :param args: parameters iterable :param kwargs: parameters iterable :return: the first row of the first column ...
python
{ "resource": "" }
q44387
ensure_bytes
train
def ensure_bytes(data: Union[str, bytes]) -> bytes: """ Convert data in bytes if data is a string :param data: Data :rtype bytes: """ if isinstance(data, str): return bytes(data, 'utf-8') return data
python
{ "resource": "" }
q44388
ensure_str
train
def ensure_str(data: Union[str, bytes]) -> str: """ Convert data in str if data are bytes :param data: Data :rtype str: """ if isinstance(data, bytes): return str(data, 'utf-8') return data
python
{ "resource": "" }
q44389
xor_bytes
train
def xor_bytes(b1: bytes, b2: bytes) -> bytearray: """ Apply XOR operation on two bytes arguments :param b1: First bytes argument :param b2: Second bytes argument :rtype bytearray: """ result = bytearray() for i1, i2 in zip(b1, b2): result.append(i1 ^ i2) return result
python
{ "resource": "" }
q44390
kompile
train
def kompile(src, raw=False, filename='<compiler>', loader=None, **kwargs): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): ...
python
{ "resource": "" }
q44391
Ping.signal_handler
train
def signal_handler(self, signum, frame): """ Handle print_exit via signals. """ self.print_exit() print("\n(Terminated with signal %d)\n" % (signum)) sys.exit(0)
python
{ "resource": "" }
q44392
Ping.header2dict
train
def header2dict(self, names, struct_format, data): """ Unpack the raw received IP and ICMP header information to a dict. """ unpacked_data = struct.unpack(struct_format, data) return dict(zip(names, unpacked_data))
python
{ "resource": "" }
q44393
Ping.do
train
def do(self): """ Send one ICMP ECHO_REQUEST and receive the response until self.timeout. """ try: # One could use UDP here, but it's obscure current_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) except socket.error as (errno, ...
python
{ "resource": "" }
q44394
Ping.send_one_ping
train
def send_one_ping(self, current_socket): """ Send one ICMP ECHO_REQUEST. """ # Header is type (8), code (8), checksum (16), id (16), sequence (16) checksum = 0 # Make a dummy header with a 0 checksum. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, chec...
python
{ "resource": "" }
q44395
Ping.receive_one_ping
train
def receive_one_ping(self, current_socket): """ Receive the ping from the socket. timeout = in ms. """ timeout = self.timeout / 1000.0 while True: # Loop while waiting for packet or timeout select_start = default_timer() inputready, outputready, exceptrea...
python
{ "resource": "" }
q44396
MQTTRouter.get_link
train
def get_link(self, peer): """ Retrieves the link to the given peer """ for access in peer.accesses: if access.type == 'mqtt': break else: # No MQTT access found return None # Get server access tuple server = (ac...
python
{ "resource": "" }
q44397
exit
train
def exit(exit_code=0): r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner. """ core.processExitHooks() if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook sys.stderr.flush() sy...
python
{ "resource": "" }
q44398
listMemberHelps
train
def listMemberHelps(TargetGroup): r"""Gets help on a group's children. """ Members = [] for Member in TargetGroup.Members.values(): # get unique children (by discarding aliases) if Member not in Members: Members.append(Member) Ret = [] for Member in Members: Config = Member.Config Ret.a...
python
{ "resource": "" }
q44399
getTypeStr
train
def getTypeStr(_type): r"""Gets the string representation of the given type. """ if isinstance(_type, CustomType): return str(_type) if hasattr(_type, '__name__'): return _type.__name__ return ''
python
{ "resource": "" }