_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q51300
Feedback.to_binary_string
train
def to_binary_string(self): """Pack the feedback to binary form and return it as string.""" timestamp = datetime_to_timestamp(self.when) token = binascii.unhexlify(self.token) return struct.pack(self.FORMAT_PREFIX + '{0}s'.format(len(token)), timestamp, len(tok...
python
{ "resource": "" }
q51301
_manage_location
train
def _manage_location(attr): """Build managed property interface. Args: attr (str): Property's name Returns: property: Managed property interface """ return property(lambda self: getattr(self, '_%s' % attr), lambda self, value: self._set_location(attr, value))
python
{ "resource": "" }
q51302
TokenTrie.has_tokens
train
def has_tokens(self, phrase): """ Checks if phrase or sub-phrase exists in the tree. If set of phrases contains phrases such as: "state", "of the" and "state of the art", look up on: "state" returns true, "of" returns null, "of the art" returns false. :param phrase: Phrase or s...
python
{ "resource": "" }
q51303
TokenTrie.find_tracked_words
train
def find_tracked_words(self, tokens): """ Finds word-ranges all of phrases in tokens stored in TokenTrie :param tokens: Sequence of tokens to find phrases in :type tokens: list of str :return: List of Tokens found in tokens """ tracked_words = [] for i i...
python
{ "resource": "" }
q51304
TokenTrie.find_optimal_allocation
train
def find_optimal_allocation(self, tokens): """ Finds longest, non-overlapping word-ranges of phrases in tokens stored in TokenTrie :param tokens: tokens tokenize :type tokens: list of str :return: Optimal allocation of tokens to phrases :rtype: list of TokenTrie.Token ...
python
{ "resource": "" }
q51305
translate
train
def translate(root_list, use_bag_semantics=False): """ Translate a list of relational algebra trees into SQL statements. :param root_list: a list of tree roots :param use_bag_semantics: flag for using relational algebra bag semantics :return: a list of SQL statements """ translator = (Trans...
python
{ "resource": "" }
q51306
match
train
def match(record, config=None): """Given a record, yield the records in INSPIRE most similar to it. This method can be used to detect if a record that we are ingesting as a submission or as an harvest is already present in the system, or to find out which record a reference should be pointing to. "...
python
{ "resource": "" }
q51307
Session.add
train
def add(self, item, safe=None): ''' Add an item into the queue of things to be inserted. Does not flush.''' item._set_session(self) if safe is None: safe = self.safe self.queue.append(SaveOp(self.transaction_id, self, item, safe)) # after the save op is recorded, the document has an _id and can be # cac...
python
{ "resource": "" }
q51308
Session.update
train
def update(self, item, id_expression=None, upsert=False, update_ops={}, safe=None, **kwargs): ''' Update an item in the database. Uses the on_update keyword to each field to decide which operations to do, or. :param item: An instance of a :class:`~ommongo.document.Document` \ subclass :param id_express...
python
{ "resource": "" }
q51309
Session.query
train
def query(self, type, exclude_subclasses=False): ''' Begin a query on the database's collection for `type`. If `type` is an instance of basesting, the query will be in raw query mode which will not check field values or transform returned results into python objects. .. seealso:: :class:`~ommongo.query....
python
{ "resource": "" }
q51310
Session.execute_query
train
def execute_query(self, query, session): ''' Get the results of ``query``. This method does flush in a transaction, so any objects retrieved which are not in the cache which would be updated when the transaction finishes will be stale ''' self.auto_ensure_indexes(query.type) kwargs = dict() if query....
python
{ "resource": "" }
q51311
Session.remove
train
def remove(self, obj, safe=None): ''' Remove a particular object from the database. If the object has no mongo ID set, the method just returns. If this is a partial document without the mongo ID field retrieved a ``FieldNotRetrieved`` will be raised :param obj: the object to save :param safe: whe...
python
{ "resource": "" }
q51312
Session.execute_remove
train
def execute_remove(self, remove): ''' Execute a remove expression. Should generally only be called implicitly. ''' safe = self.safe if remove.safe is not None: safe = remove.safe self.queue.append(RemoveOp(self.transaction_id, self, remove.type, safe, remove)) if self.autoflush: return self.flush()
python
{ "resource": "" }
q51313
Session.execute_update
train
def execute_update(self, update, safe=False): ''' Execute an update expression. Should generally only be called implicitly. ''' # safe = self.safe # if update.safe is not None: # safe = remove.safe assert len(update.update_data) > 0 self.queue.append(UpdateOp(self.transaction_id, self, update.query...
python
{ "resource": "" }
q51314
Session.clear_queue
train
def clear_queue(self, trans_id=None): ''' Clear the queue of database operations without executing any of the pending operations''' if not self.queue: return if trans_id is None: self.queue = [] return for index, op in enumerate(self.queue): if op.trans_id == trans_id: break self.queue = ...
python
{ "resource": "" }
q51315
Session.flush
train
def flush(self, safe=None): ''' Perform all database operations currently in the queue''' result = None for index, op in enumerate(self.queue): try: result = op.execute() except: self.clear_queue() self.clear_cache() raise self.clear_queue() return result
python
{ "resource": "" }
q51316
Session.refresh
train
def refresh(self, document): """ Load a new copy of a document from the database. does not replace the old one """ try: old_cache_size = self.cache_size self.cache_size = 0 obj = self.query(type(document)).filter_by(mongo_id=document.mongo_id).one() finally: self.cache_size = old_cache_size self...
python
{ "resource": "" }
q51317
Session.clone
train
def clone(self, document): ''' Serialize a document, remove its _id, and deserialize as a new object ''' wrapped = document.wrap() if '_id' in wrapped: del wrapped['_id'] return type(document).unwrap(wrapped, session=self)
python
{ "resource": "" }
q51318
Code128.width
train
def width(self, add_quiet_zone=False): """Return the barcodes width in modules for a given data and character set combination. :param add_quiet_zone: Whether quiet zone should be included in the width. :return: Width of barcode in modules, which for images translates to pixels. """ ...
python
{ "resource": "" }
q51319
Code128._validate_charset
train
def _validate_charset(data, charset): """"Validate that the charset is correct and throw an error if it isn't.""" if len(charset) > 1: charset_data_length = 0 for symbol_charset in charset: if symbol_charset not in ('A', 'B', 'C'): raise Code12...
python
{ "resource": "" }
q51320
Code128._encode
train
def _encode(cls, data, charsets): """Encode the data using the character sets in charsets. :param data: Data to be encoded. :param charsets: Sequence of charsets that are used to encode the barcode. Must be the exact amount of symbols needed to encode the data. ...
python
{ "resource": "" }
q51321
Code128.symbols
train
def symbols(self): """List of the coded symbols as strings, with special characters included.""" def _iter_symbols(symbol_values): # The initial charset doesn't matter, as the start codes have the same symbol values in all charsets. charset = 'A' shift_charset = None...
python
{ "resource": "" }
q51322
Code128.bars
train
def bars(self): """A string of the bar and space weights of the barcode. Starting with a bar and alternating. >>> barcode = Code128("Hello!", charset='B') >>> barcode.bars '2112142311131122142211142211141341112221221212412331112' :rtype: string """ return ''.joi...
python
{ "resource": "" }
q51323
Code128.modules
train
def modules(self): """A list of the modules, with 0 representing a bar and 1 representing a space. >>> barcode = Code128("Hello!", charset='B') >>> barcode.modules # doctest: +ELLIPSIS [0, 0, 1, 0, 1, 1, 0, 1, ..., 0, 0, 0, 1, 0, 1, 0, 0] :rtype: list[int] """ ...
python
{ "resource": "" }
q51324
Code128._calc_checksum
train
def _calc_checksum(values): """Calculate the symbol check character.""" checksum = values[0] for index, value in enumerate(values): checksum += index * value return checksum % 103
python
{ "resource": "" }
q51325
Code128.image
train
def image(self, height=1, module_width=1, add_quiet_zone=True): """Get the barcode as PIL.Image. By default the image is one pixel high and the number of modules pixels wide, with 10 empty modules added to each side to act as the quiet zone. The size can be modified by setting height and module...
python
{ "resource": "" }
q51326
Code128.data_url
train
def data_url(self, image_format='png', add_quiet_zone=True): """Get a data URL representing the barcode. >>> barcode = Code128('Hello!', charset='B') >>> barcode.data_url() # doctest: +ELLIPSIS 'data:image/png;base64,...' :param image_format: Either 'png' or 'bmp'. :pa...
python
{ "resource": "" }
q51327
Live._get_auth_token
train
def _get_auth_token(self): """Given the office356 tenant and client id, and client secret acquire a new authorization token """ url = '/%s/oauth2/token' % getattr( settings, 'RESTCLIENTS_O365_TENANT', 'test') headers = {'Accept': 'application/json'} data = { ...
python
{ "resource": "" }
q51328
get_method_from_module
train
def get_method_from_module(module_path, method_name): """ from a valid python module path, get the run method name passed """ top_module = __import__(module_path) module = top_module # we tunnel down until we find the module we want for submodule_name in module_path.split('.')[1:]: module =...
python
{ "resource": "" }
q51329
proxy_register
train
def proxy_register(register_funtion): """ Proxy a function to a register function. :param register_funtion: a function need to proxy. :return: a proxy wrapper """ def wrapper(function): @functools.wraps(function) def register(excepted, filter_function=None): if inspe...
python
{ "resource": "" }
q51330
get_template
train
def get_template(template_path): """ Get template object from absolute path. For example, the template has: .. code-block:: html {% macro add(a, b) -%} {{a + b}} {%- endmacro %} And call the macro as template object method. .. code-block:: python tpl = g...
python
{ "resource": "" }
q51331
render
train
def render(template_path, output_file=None, **kwargs): """ Render jinja2 template file use absolute path. **Usage** A simple template as follow: .. code-block:: jinja This is a test template {{ title }} Then write render code by single line. .. code-block:: python ...
python
{ "resource": "" }
q51332
plugin
train
def plugin(tree, file_tokens): """Walk the tree and detect invalid escape sequences.""" for token in file_tokens: if token[0] != STRING: # token[0] == token.type continue # token[1] == token.string # python 3 invalid_sequence_match = invalid_escape_sequence_match(token[1]) ...
python
{ "resource": "" }
q51333
BaseConstraint.extract_values
train
def extract_values(self, possible_solution, use_defaults=False): """Returns a tuple of the values that pertain to this constraint. It simply filters all values to by the variables this constraint uses. """ defaults = self._vardefaults if use_defaults else {} values = list(self._...
python
{ "resource": "" }
q51334
_get_appointee
train
def _get_appointee(id): """ Return a restclients.models.hrp.AppointeePerson object """ url = "%s%s.json" % (URL_PREFIX, id) response = get_resource(url) return process_json(response)
python
{ "resource": "" }
q51335
Cities.import_locations
train
def import_locations(self, data): """Parse `GNU miscfiles`_ cities data files. ``import_locations()`` returns a list containing :class:`City` objects. It expects data files in the same format that `GNU miscfiles`_ provides, that is:: ID : 1 Type ...
python
{ "resource": "" }
q51336
query_api
train
def query_api(app, client_id, imgur_id, is_album): """Query the Imgur API. :raise APIError: When Imgur responds with errors or unexpected data. :param sphinx.application.Sphinx app: Sphinx application object. :param str client_id: Imgur API client ID to use. https://api.imgur.com/oauth2 :param str...
python
{ "resource": "" }
q51337
Base.seconds_remaining
train
def seconds_remaining(self, ttl): """Return number of seconds left before Imgur API needs to be queried for this instance. :param int ttl: Number of seconds before this is considered out of date. :return: Seconds left before this is expired. 0 indicated update needed (no negatives). :r...
python
{ "resource": "" }
q51338
Node.remove_child
train
def remove_child(self, idx=None, *, name=None, node=None): """Remove a child node from the current node instance. :param idx: Index of child node to be removed. :type idx: int :param name: The first child node found with «name» will be removed. :type name: str :param n...
python
{ "resource": "" }
q51339
Node._coord
train
def _coord(self): """Attribute indicating the tree coordinates for this node. The tree coordinates of a node are expressed as a tuple of the indices of the node and its ancestors, for example: A grandchild node with node path `/root.name/root.childs[2].name/root.childs[2].child...
python
{ "resource": "" }
q51340
Node.set_data
train
def set_data(self, *keys, value): """Set a value in the instance `data` dict. :param keys: the `data` dict keys referencing the value in the `data` dict. :type keys: str :param value: the value to be set in the `data` dict. Note that `value` is a keyword-only argument. ...
python
{ "resource": "" }
q51341
Node._root
train
def _root(self): """Attribute referencing the root node of the tree. :returns: the root node of the tree containing this instance. :rtype: Node """ _n = self while _n.parent: _n = _n.parent return _n
python
{ "resource": "" }
q51342
Node._ancestors
train
def _ancestors(self): """Attribute referencing the tree ancestors of the node instance. :returns: list of node ancestors in sequence, first item is the current node instance (`self`), the last item is root. :rtype: list of Node references """ # return list of ancest...
python
{ "resource": "" }
q51343
Node.find_one_node
train
def find_one_node(self, *keys, value, decend=True): """Find a node on the branch of the instance with a `keys=data` item in the `data` dict. Nested values are accessed by specifying the keys in sequence. e.g. `node.get_data("country", "city")` would access `node.data["country"...
python
{ "resource": "" }
q51344
Node.yaml2tree
train
def yaml2tree(cls, yamltree): """Class method that creates a tree from YAML. | # Example yamltree data: | - !Node &root | name: "root node" | parent: null | data: | testpara: 111 | - !Node &child1 | name: "child node" | paren...
python
{ "resource": "" }
q51345
dyn
train
def dyn(d, **kw): # {{{1 """ Pseudo-dynamic variables. >>> SOME_VAR = 42 >>> with dyn(vars(), SOME_VAR = 37): SOME_VAR 37 >>> SOME_VAR 42 >>> import threading >>> D = threading.local() >>> D.x, D.y = 1, 2 >>> with dyn(vars(D), x = 3, y = 4): (D.x, D....
python
{ "resource": "" }
q51346
zlines
train
def zlines(f = None, sep = "\0", osep = None, size = 8192): # {{{1 """File iterator that uses alternative line terminators.""" if f is None: f = sys.stdin if osep is None: osep = sep buf = "" while True: chars = f.read(size) if not chars: break buf += chars; lines = buf.split(sep); buf = lines...
python
{ "resource": "" }
q51347
AsyncMQClient.on_connection_open
train
def on_connection_open(self, unused_connection): """ Called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection...
python
{ "resource": "" }
q51348
AsyncMQClient.add_on_connection_close_callback
train
def add_on_connection_close_callback(self): """ Add an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ self._logger.debug('Adding connection close callback') self._connection.add_on_close_callback(self....
python
{ "resource": "" }
q51349
AsyncMQClient.reconnect
train
def reconnect(self): """ Invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ # This is the old connection IOLoop instance, stop its ioloop self._connection.ioloop.stop() if not self._closing: # Create a ne...
python
{ "resource": "" }
q51350
AsyncMQClient.on_channel_open
train
def on_channel_open(self, channel): """ Invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object ...
python
{ "resource": "" }
q51351
AsyncMQClient.add_on_channel_close_callback
train
def add_on_channel_close_callback(self): """ Tell pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ self._logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed)
python
{ "resource": "" }
q51352
AsyncMQClient.on_exchange_declareok
train
def on_exchange_declareok(self, unused_frame): """ Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ self._logger.debug('Exchange declared') self.setup_queue(s...
python
{ "resource": "" }
q51353
AsyncMQClient.on_queue_declareok
train
def on_queue_declareok(self, method_frame): """ Invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete...
python
{ "resource": "" }
q51354
AsyncMQClient.close_channel
train
def close_channel(self): """ Invoke this command to close the channel with RabbitMQ by sending the Channel.Close RPC command. """ self._logger.info('Closing the channel') if self._channel: self._channel.close()
python
{ "resource": "" }
q51355
AsyncMQClient.close_connection
train
def close_connection(self): """This method closes the connection to RabbitMQ.""" self._logger.info('Closing connection') self._closing = True self._connection.close()
python
{ "resource": "" }
q51356
AsyncMQPublisher.on_bindok
train
def on_bindok(self, unused_frame): """ This method is invoked by pika when it receives the Queue.BindOk response from RabbitMQ. """ self._logger.info('Queue bound') while not self._stopping: # perform the action that publishes on this client self.p...
python
{ "resource": "" }
q51357
AsyncMQPublisher.publish
train
def publish(self, message): """ If not stopping, publish a message to RabbitMQ. :param str message: The fully encoded message to publish """ if self._stopping: return self._logger.info("publishing\t%s" % message) properties = pika.BasicProperties(cont...
python
{ "resource": "" }
q51358
AsyncMQConsumer.start_consuming
train
def start_consuming(self): """ This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify t...
python
{ "resource": "" }
q51359
AsyncMQConsumer.add_on_cancel_callback
train
def add_on_cancel_callback(self): """ Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ self._logger.info('Adding consumer cancellation callback') ...
python
{ "resource": "" }
q51360
Utils.down
train
def down(self, h, cr=True): """moves current vertical position h mm down cr True will navigate to the left margin """ if cr: self.oPdf.ln(h=0) self.oPdf.set_y(self.oPdf.get_y() + h)
python
{ "resource": "" }
q51361
kwargs_as_assignments
train
def kwargs_as_assignments(call_node, parent): """Yield NoDeclAssign nodes from kwargs in a Call node.""" if not isinstance(call_node, ast.Call): raise TypeError('node must be an ast.Call') if len(call_node.args) > 0: raise ValueError('positional args not allowed') for keyword in call_n...
python
{ "resource": "" }
q51362
rewrite_return_as_assignments
train
def rewrite_return_as_assignments(func_node, interface): """Modify FunctionDef node to directly assign instead of return.""" func_node = _RewriteReturn(interface).visit(func_node) ast.fix_missing_locations(func_node) return func_node
python
{ "resource": "" }
q51363
datetime_to_dtstr
train
def datetime_to_dtstr(dt=None): """ Comvert datetime to short text. If datetime has timezone then it will be convert to UTC0. """ if dt is None: dt = datetime.datetime.utcnow() elif timezone.is_aware(dt): dt = dt.astimezone(tz=pytz.UTC) return int2base36(int(time.mktime(dt.ti...
python
{ "resource": "" }
q51364
dtstr_to_datetime
train
def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True): """ Convert result from datetime_to_dtstr to datetime in timezone UTC0. """ try: dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3) if to_tz: dt = timezone.make_aware(dt, timezone=pytz.UTC) i...
python
{ "resource": "" }
q51365
ConfigParse.save_yaml
train
def save_yaml(self, outFile): """saves the config parameters to a json file""" with open(outFile,'w') as myfile: print(yaml.dump(self.params), file=myfile)
python
{ "resource": "" }
q51366
ConfigParse.sym_reads_new_config
train
def sym_reads_new_config(self, newDir, sym=False, mv=False): """This moves the read files and renames the glob, outputs a new ConfigParse object with updated values""" newParams = copy.copy(self) for i in range(0,len(self.params["lib_seq"])): lib_seq = self.params["lib_seq"][...
python
{ "resource": "" }
q51367
GatewayClientFactory.send
train
def send(self, notification): """Send prepared notification to the APN.""" logger.debug('Gateway send notification') if self.client is None: raise GatewayClientNotSetError() yield self.client.send(notification)
python
{ "resource": "" }
q51368
force_list
train
def force_list(data): """Force ``data`` to become a list. You should use this method whenever you don't want to deal with the fact that ``NoneType`` can't be iterated over. For example, instead of writing:: bar = foo.get('bar') if bar is not None: for el in bar: ...
python
{ "resource": "" }
q51369
remove_tags
train
def remove_tags(dirty, allowed_tags=(), allowed_trees=(), strip=None): """Selectively remove tags. This removes all tags in ``dirty``, stripping also the contents of tags matching the XPath selector in ``strip``, and keeping all tags that are subtags of tags in ``allowed_trees`` and tags in ``allowed_t...
python
{ "resource": "" }
q51370
main
train
def main(): """ 1. Reads in a meraculous config file and outputs glotk project files """ parser = CommandLine() #this block from here: http://stackoverflow.com/a/4042861/5843327 if len(sys.argv)==1: parser.parser.print_help() sys.exit(1) parser.parse() myArgs = parser.arg...
python
{ "resource": "" }
q51371
RedisQueue.connect
train
def connect(self, **kwargs): """ Connect to the Redis Server :param kwargs: Parameters passed directly to redis library :return: Boolean indicating if connection successful :kwarg host: Hostname of the Redis server :kwarg port: Port of the Redis server :kwarg pa...
python
{ "resource": "" }
q51372
RedisQueue.clear
train
def clear(self): """ Clear all Tasks in the queue. """ if not self.connected: raise QueueNotConnectedError("Queue is not Connected") self.__db.delete(self._key) self.__db.delete(self._lock_key)
python
{ "resource": "" }
q51373
RedisQueue.qsize
train
def qsize(self): """ Returns the number of items currently in the queue :return: Integer containing size of the queue :exception: ConnectionError if queue is not connected """ if not self.connected: raise QueueNotConnectedError("Queue is not Connected") ...
python
{ "resource": "" }
q51374
RedisQueue.put
train
def put(self, task): """ Inserts a Task into the queue :param task: :class:`~redisqueue.AbstractTask` instance :return: Boolean insert success state :exception: ConnectionError if queue is not connected """ if not self.connected: raise QueueNotConnec...
python
{ "resource": "" }
q51375
RedisQueue.get
train
def get(self, block=True, timeout=None): """ Get a Task from the queue :param block: Block application until a Task is received :param timeout: Timeout after n seconds :return: :class:`~redisqueue.AbstractTask` instance :exception: ConnectionError if queue is not connect...
python
{ "resource": "" }
q51376
AbstractTask.from_json
train
def from_json(self, json_data): """ Load JSON data into this Task """ try: data = json_data.decode() except Exception: data = json_data self.__dict__ = json.loads(data)
python
{ "resource": "" }
q51377
_single_mp_run
train
def _single_mp_run(x, Phi, bound, max_iter, verbose=False, pad=0, random_state=None, memory=Memory(None)): """ run of the RSSMP algorithm """ rng = check_random_state(random_state) pad = int(pad) x = np.concatenate((np.zeros(pad), x, np.zeros(pad))) n = x.size m = Phi.doth(x...
python
{ "resource": "" }
q51378
_pad
train
def _pad(X): """ add zeroes on the border to make sure the signal length is a power of two """ p_above = int(np.floor(np.log2(X.shape[1]))) M = 2 ** (p_above + 1) - X.shape[1] X = np.hstack((np.zeros((X.shape[0], M)), X)) return X, M
python
{ "resource": "" }
q51379
_denoise
train
def _denoise(seeds, x, dico, sup_bound, n_atoms, verbose=False, indep=True, stop_crit=None, selection_rule=None, pad=0, memory=Memory(None)): """ multiple rssmp runs with a smart stopping criterion using the convergence decay monitoring """ approx = [] for seed in seeds: ...
python
{ "resource": "" }
q51380
_bird_core
train
def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100, stop_crit=np.mean, selection_rule=np.sum, n_jobs=1, indep=True, random_state=None, memory=Memory(None), verbose=False): """Automatically detect when noise zone has been reached and stop MP at th...
python
{ "resource": "" }
q51381
bird
train
def bird(X, scales, n_runs, p_above, max_iter=100, random_state=None, n_jobs=1, memory=Memory(None), verbose=False): """ The BIRD algorithm as described in the paper Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be X_denoised where n_ch...
python
{ "resource": "" }
q51382
validate_email_domain
train
def validate_email_domain(email): """ Validates email domain by blacklist. """ try: domain = email.split('@', 1)[1].lower().strip() except IndexError: return if domain in dju_settings.DJU_EMAIL_DOMAIN_BLACK_LIST: raise ValidationError(_(u'Email with domain "%(domain)s" is disallo...
python
{ "resource": "" }
q51383
_get_task
train
def _get_task(name): '''Look up a task by name.''' matches = [x for x in TASKS if x.match(name)] if matches: return matches[0]
python
{ "resource": "" }
q51384
_opts_to_dict
train
def _opts_to_dict(*opts): '''Convert a tuple of options returned from getopt into a dictionary.''' ret = {} for key, val in opts: if key[:2] == '--': key = key[2:] elif key[:1] == '-': key = key[1:] if val == '': val = True ret[key.replace('-','_')] = val return ret
python
{ "resource": "" }
q51385
_highlight
train
def _highlight(string, color): '''Return a string highlighted for a terminal.''' if CONFIG['color']: if color < 8: return '\033[{color}m{string}\033[0m'.format(string = string, color = color+30) else: return '\033[{color}m{string}\033[0m'.format(string = string, color = color+82) else: return string
python
{ "resource": "" }
q51386
_taskify
train
def _taskify(func): '''Convert a function into a task.''' if not isinstance(func, _Task): func = _Task(func) spec = inspect.getargspec(func.func) if spec.args: num_args = len(spec.args) num_kwargs = len(spec.defaults or []) isflag = lambda x, y: '' if x.defaults[y] is False else '=' func.args = sp...
python
{ "resource": "" }
q51387
task
train
def task(*args, **kwargs): '''Register a function as a task, as well as applying any attributes. ''' # support @task if args and hasattr(args[0], '__call__'): return _taskify(args[0]) # as well as @task(), @task('default'), etc. else: def wrapper(func): global DEFAULT, SETUP, TEARDOWN func = _taskify(f...
python
{ "resource": "" }
q51388
require
train
def require(*reqs): '''Require tasks or files at runtime.''' for req in reqs: if type(req) is str: # does not exist and unknown generator if not os.path.exists(req) and req not in GENERATES: abort(LOCALE['abort_bad_file'].format(req)) # exists but unknown generator if req not in GENERATES: retu...
python
{ "resource": "" }
q51389
valid
train
def valid(*things): '''Return True if all tasks or files are valid. Valid tasks have been completed already. Valid files exist on the disk.''' for thing in things: if type(thing) is str and not os.path.exists(thing): return False if thing.valid is None: return False return True
python
{ "resource": "" }
q51390
shell
train
def shell(command, *args): '''Pass a command into the shell.''' if args: command = command.format(*args) print LOCALE['shell'].format(command) try: return subprocess.check_output(command, shell=True) except subprocess.CalledProcessError, ex: return ex
python
{ "resource": "" }
q51391
abort
train
def abort(message, *args): '''Raise an AbortException, halting task execution and exiting.''' if args: raise _AbortException(message.format(*args)) raise _AbortException(message)
python
{ "resource": "" }
q51392
_help
train
def _help(): '''Print all available tasks and descriptions.''' for task in sorted(TASKS, key=lambda x: (x.ns or '000') + x.name): tags = '' if task is DEFAULT: tags += '*' if task is SETUP: tags += '+' if task is TEARDOWN: tags += '-' print LOCALE['help_command'].format(task, tags, task.help) i...
python
{ "resource": "" }
q51393
_invoke
train
def _invoke(task, args): '''Invoke a task with the appropriate args; return the remaining args.''' kwargs = task.defaults.copy() if task.kwargs: temp_kwargs, args = getopt.getopt(args, '', task.kwargs) temp_kwargs = _opts_to_dict(*temp_kwargs) kwargs.update(temp_kwargs) if task.args: for arg in task.args: ...
python
{ "resource": "" }
q51394
main
train
def main(args): '''Do everything awesome.''' if SETUP: args = _invoke(SETUP, args) if not args and DEFAULT: DEFAULT() else: while args: task = _get_task(args[0]) if task is None: abort(LOCALE['error_no_task'], args[0]) args = _invoke(task, args[1:]) if TEARDOWN: TEARDOWN()
python
{ "resource": "" }
q51395
_Task.match
train
def match(self, name): '''Compare an argument string to the task name.''' if (self.ns + self.name).startswith(name): return True for alias in self.aliases: if (self.ns + alias).startswith(name): return True
python
{ "resource": "" }
q51396
_Task.aliasstr
train
def aliasstr(self): '''Concatenate the aliases tuple into a string.''' return ', '.join(repr(self.ns + x) for x in self.aliases)
python
{ "resource": "" }
q51397
_Task.kwargstr
train
def kwargstr(self): '''Concatenate keyword arguments into a string.''' temp = [' [--' + k + (' ' + str(v) if v is not False else '') + ']' for k, v in self.defaults.items()] return ''.join(temp)
python
{ "resource": "" }
q51398
JSONEmitter.serialize
train
def serialize(self, content): """ Serialize to JSON. :return string: serializaed JSON """ worker = JSONSerializer( scheme=self.resource, options=self.resource._meta.emit_options, format=self.resource._meta.emit_format, **self.resource._me...
python
{ "resource": "" }
q51399
JSONPEmitter.serialize
train
def serialize(self, content): """ Serialize to JSONP. :return string: serializaed JSONP """ content = super(JSONPEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return u'%s(%s)' % (callback, content)
python
{ "resource": "" }