_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q279200
Index.search
test
def search(self, query, verbose=0): """Searches files satisfying query It first decompose the query in ngrams, then score each document containing at least one ngram with the number. The ten document having the most ngrams in common with the query are selected. Args: query (str): what to search; results_number (int): number of results to return (default: 10) """ if verbose > 0: print("searching " + query) query = query.lower() qgram = ng(query, self.slb) qocument = set() for q in qgram: if q in self.ngrams.keys(): for i in self.ngrams[q]: qocument.add(i) self.qocument = qocument results = {}
python
{ "resource": "" }
q279201
partition
test
def partition(condition, collection) -> Tuple[List, List]: """Partitions a list into two based on a condition.""" succeed, fail = [], [] for x in collection: if condition(x):
python
{ "resource": "" }
q279202
run
test
def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path, verbose): """ Runs the program. Takes a list of postcodes or coordinates and returns various information about them. If using the cli, make sure to update the bikes database with the -u command. Locations can be either a specific postcode, or a pair of coordinates. Coordinates are passed in the form "55.948824,-3.196425". :param locations: The list of postcodes or coordinates to search. :param random: The number of random postcodes to include. :param bikes: Includes a list of stolen bikes in that area. :param crime: Includes a list of committed crimes in that area. :param nearby: Includes a list of wikipedia articles in that area. :param json: Returns the data in json format. :param update_bikes: Whether to force update bikes. :param api_server: If given, the program will instead run a rest api. :param cross_origin: :param host: :param port: Defines the port to run the rest api on. :param db_path: The path to the sqlite db to use. :param verbose: The verbosity. """ log_levels = [logging.WARNING, logging.INFO, logging.DEBUG] logging.basicConfig(level=log_levels[min(verbose, 2)]) initialize_database(db_path) loop = get_event_loop() if update_bikes: logger.info("Force updating bikes.") loop.run_until_complete(util.update_bikes()) if api_server:
python
{ "resource": "" }
q279203
bidi
test
def bidi(request): """Adds to the context BiDi related variables LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl') LANGUAGE_START -- Start of language layout ('right' for rtl, 'left' for 'ltr') LANGUAGE_END -- End of language layout ('left' for rtl, 'right' for 'ltr') LANGUAGE_MARKER -- Language marker entity ('‏' for rtl, '&lrm' for ltr) """ from django.utils import translation from django.utils.safestring import mark_safe if translation.get_language_bidi(): extra_context = {
python
{ "resource": "" }
q279204
_find_link
test
def _find_link(inst1, inst2, rel_id, phrase): ''' Find links that correspond to the given arguments. ''' metaclass1 = get_metaclass(inst1) metaclass2 = get_metaclass(inst2) if isinstance(rel_id, int): rel_id = 'R%d' % rel_id for ass in metaclass1.metamodel.associations: if ass.rel_id != rel_id: continue if (ass.source_link.from_metaclass.kind == metaclass1.kind and ass.source_link.to_metaclass.kind == metaclass2.kind and ass.source_link.phrase == phrase): return inst1, inst2, ass if
python
{ "resource": "" }
q279205
Association.formalize
test
def formalize(self): ''' Formalize the association and expose referential attributes on instances. ''' source_class = self.source_link.to_metaclass target_class = self.target_link.to_metaclass source_class.referential_attributes |= set(self.source_keys) target_class.identifying_attributes |= set(self.target_keys) def fget(inst, ref_name, alt_prop): other_inst = self.target_link.navigate_one(inst) if other_inst is None and alt_prop: return alt_prop.fget(inst) return getattr(other_inst, ref_name, None) def fset(inst, value, name, ref_name, alt_prop): kind = get_metaclass(inst).kind raise MetaException('%s.%s is a referential attribute '\ 'and cannot be assigned directly'% (kind, name)) #other_inst = self.target_link.navigate_one(inst) #if other_inst is None and alt_prop: #
python
{ "resource": "" }
q279206
Link.compute_lookup_key
test
def compute_lookup_key(self, from_instance): ''' Compute the lookup key for an instance, i.e. a foreign key that can be used to identify an instance at the end of the link. ''' kwargs = dict() for attr, other_attr in self.key_map.items(): if _is_null(from_instance, attr): return None if attr in from_instance.__dict__:
python
{ "resource": "" }
q279207
Link.compute_index_key
test
def compute_index_key(self, to_instance): ''' Compute the index key that can be used to identify an instance on the link. ''' kwargs = dict() for attr in self.key_map.values(): if _is_null(to_instance, attr): return None if attr in to_instance.__dict__:
python
{ "resource": "" }
q279208
MetaClass.attribute_type
test
def attribute_type(self, attribute_name): ''' Obtain the type of an attribute. ''' attribute_name = attribute_name.upper()
python
{ "resource": "" }
q279209
MetaClass.new
test
def new(self, *args, **kwargs): ''' Create and return a new instance. ''' inst = self.clazz() self.storage.append(inst) # set all attributes with an initial default value referential_attributes = dict() for name, ty in self.attributes: if name not in self.referential_attributes: value = self.default_value(ty) setattr(inst, name, value) # set all positional arguments for attr, value in zip(self.attributes, args): name, ty = attr if name not in self.referential_attributes: setattr(inst, name, value) else: referential_attributes[name] = value # set all named arguments for name, value in kwargs.items(): if name not in self.referential_attributes: setattr(inst, name, value) else: referential_attributes[name] = value if not referential_attributes: return inst
python
{ "resource": "" }
q279210
MetaModel.instances
test
def instances(self): ''' Obtain a sequence of all instances in the metamodel. ''' for
python
{ "resource": "" }
q279211
MetaModel.define_class
test
def define_class(self, kind, attributes, doc=''): ''' Define a new class in the metamodel, and return its metaclass. ''' ukind = kind.upper() if ukind in self.metaclasses: raise MetaModelException('A class with the name %s is already defined' % kind) metaclass = MetaClass(kind,
python
{ "resource": "" }
q279212
send
test
def send(socket, header, payload, topics=(), flags=0): """Sends header, payload, and topics through a ZeroMQ socket. :param socket: a zmq socket. :param header: a list of byte strings which represent a message header. :param payload: the serialized byte string of a payload. :param topics: a chain of topics. :param flags: zmq flags to send messages.
python
{ "resource": "" }
q279213
recv
test
def recv(socket, flags=0, capture=(lambda msgs: None)): """Receives header, payload, and topics through a ZeroMQ socket. :param socket: a zmq socket. :param flags: zmq flags to receive messages. :param capture:
python
{ "resource": "" }
q279214
dead_code
test
def dead_code(): """ This also finds code you are working on today! """ with safe_cd(SRC): if IS_TRAVIS: command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split() else: command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split()
python
{ "resource": "" }
q279215
parse_emails
test
def parse_emails(values): ''' Take a string or list of strings and try to extract all the emails ''' emails = [] if isinstance(values, str): values = [values] # now we know we have a list of strings for value in values:
python
{ "resource": "" }
q279216
rpc
test
def rpc(f=None, **kwargs): """Marks a method as RPC.""" if f is not None: if isinstance(f, six.string_types): if 'name' in kwargs: raise ValueError('name option duplicated')
python
{ "resource": "" }
q279217
rpc_spec_table
test
def rpc_spec_table(app): """Collects methods which are speced as RPC.""" table = {} for attr, value in inspect.getmembers(app): rpc_spec = get_rpc_spec(value, default=None)
python
{ "resource": "" }
q279218
normalize_postcode_middleware
test
async def normalize_postcode_middleware(request, handler): """ If there is a postcode in the url it validates and normalizes it. """ postcode: Optional[str] = request.match_info.get('postcode', None) if postcode is None or postcode == "random": return await handler(request) elif not is_uk_postcode(postcode): raise web.HTTPNotFound(text="Invalid Postcode") postcode_processed = postcode.upper().replace(" ", "") if postcode_processed == postcode:
python
{ "resource": "" }
q279219
IdGenerator.next
test
def next(self): ''' Progress to the next identifier, and return the current one. '''
python
{ "resource": "" }
q279220
MyWalker.accept_S_SYS
test
def accept_S_SYS(self, inst): ''' A System Model contains top-level packages '''
python
{ "resource": "" }
q279221
MyWalker.accept_C_C
test
def accept_C_C(self, inst): ''' A Component contains packageable elements '''
python
{ "resource": "" }
q279222
MyWalker.accept_EP_PKG
test
def accept_EP_PKG(self, inst): ''' A Package contains packageable elements '''
python
{ "resource": "" }
q279223
LightSensor.get_brightness
test
def get_brightness(self): """ Return the average brightness of the image. """ # Only download the image if it has changed if not self.connection.has_changed(): return self.image_brightness image_path = self.connection.download_image() converted_image =
python
{ "resource": "" }
q279224
switch.match
test
def match(self, *args): """ Indicate whether or not to enter a case suite. usage: ``` py for case in switch(value): if case('A'): pass elif case(1, 3): pass # for mulit-match. else: pass #
python
{ "resource": "" }
q279225
BracketMatcher._find_match
test
def _find_match(self, position): """ Given a valid position in the text document, try to find the position of the matching bracket. Returns -1 if unsuccessful. """ # Decide what character to search for and what direction to search in. document = self._text_edit.document() start_char = document.characterAt(position) search_char = self._opening_map.get(start_char) if search_char: increment = 1 else: search_char = self._closing_map.get(start_char) if search_char: increment = -1 else: return -1 # Search for the character. char = start_char depth = 0 while
python
{ "resource": "" }
q279226
BracketMatcher._selection_for_character
test
def _selection_for_character(self, position): """ Convenience method for selecting a character. """ selection = QtGui.QTextEdit.ExtraSelection() cursor = self._text_edit.textCursor()
python
{ "resource": "" }
q279227
BracketMatcher._cursor_position_changed
test
def _cursor_position_changed(self): """ Updates the document formatting based on the new cursor position. """ # Clear out the old formatting. self._text_edit.setExtraSelections([]) # Attempt to match a bracket for the new cursor position. cursor = self._text_edit.textCursor()
python
{ "resource": "" }
q279228
ContextSuite._exc_info
test
def _exc_info(self): """Bottleneck to fix up IronPython string exceptions """ e = self.exc_info() if sys.platform == 'cli': if isinstance(e[0], StringException): # IronPython throws these StringExceptions, but
python
{ "resource": "" }
q279229
create_inputhook_qt4
test
def create_inputhook_qt4(mgr, app=None): """Create an input hook for running the Qt4 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Returns ------- A pair consisting of a Qt Application (either the one given or the one found or created) and a inputhook. Notes ----- We use a custom input hook instead of PyQt4's default one, as it interacts better with the readline packages (issue #481). The inputhook function works in tandem with a 'pre_prompt_hook' which automatically restores the hook as an inputhook in case the latter has been temporarily disabled after having intercepted a KeyboardInterrupt. """ if app is None: app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([" "]) # Re-use previously created inputhook if any ip = InteractiveShell.instance() if hasattr(ip, '_inputhook_qt4'): return app, ip._inputhook_qt4 # Otherwise create the inputhook_qt4/preprompthook_qt4 pair of # hooks (they both share the got_kbdint flag) got_kbdint = [False] def inputhook_qt4(): """PyOS_InputHook python hook for Qt4. Process pending Qt events and if there's no pending keyboard input, spend a short slice of time (50ms) running the Qt event loop. As a Python ctypes callback can't raise an exception, we catch the KeyboardInterrupt and temporarily deactivate the hook, which will let a *second* CTRL+C be processed normally and go back to a clean prompt line. """ try: allow_CTRL_C() app = QtCore.QCoreApplication.instance() if not app: # shouldn't happen, but safer if it happens anyway... return 0 app.processEvents(QtCore.QEventLoop.AllEvents, 300) if not stdin_ready(): timer = QtCore.QTimer() timer.timeout.connect(app.quit)
python
{ "resource": "" }
q279230
Mapper.get
test
def get(cls, name=__name__): """Return a Mapper instance with the given name. If the name already exist return its instance. Does not work if a Mapper was created via its constructor. Using `Mapper.get()`_ is the prefered way. Args: name (str, optional): Name for the newly created instance. Defaults to `__name__`. Returns: Mapper: A mapper instance for the given name. Raises:
python
{ "resource": "" }
q279231
Mapper.url
test
def url(self, pattern, method=None, type_cast=None): """Decorator for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits your situation though. Defaults to None. type_cast (dict, optional): Mapping between the param name and one of `int`, `float` or `bool`. The value reflected by the
python
{ "resource": "" }
q279232
Mapper.s_url
test
def s_url(self, path, method=None, type_cast=None): """Decorator for registering a simple path. Args: path (str): Path to be matched. method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits your situation though. Defaults to None. type_cast (dict, optional): Mapping between the param name and one of `int`, `float` or `bool`. The value reflected by the provided
python
{ "resource": "" }
q279233
Mapper.add
test
def add(self, pattern, function, method=None, type_cast=None): """Function for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path. function (function): Function to associate with this path. method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits your situation though. Defaults to None. type_cast (dict, optional): Mapping between the param name and one of `int`, `float` or `bool`. The value reflected by the
python
{ "resource": "" }
q279234
Mapper.s_add
test
def s_add(self, path, function, method=None, type_cast=None): """Function for registering a simple path. Args: path (str): Path to be matched. function (function): Function to associate with this path. method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits your situation though. Defaults to None.
python
{ "resource": "" }
q279235
Mapper.call
test
def call(self, url, method=None, args=None): """Calls the first function matching the urls pattern and method. Args: url (str): Url for which to call a matching function. method (str, optional): The method used while registering a function. Defaults to None args (dict, optional): Additional args to be passed to the matching function. Returns: The functions return value or `None` if no function was called. """ if not args: args = {} if sys.version_info.major == 3: data = urllib.parse.urlparse(url) path = data.path.rstrip('/') + '/' _args = dict(urllib.parse.parse_qs(data.query, keep_blank_values=True)) elif sys.version_info.major == 2: data = urlparse.urlparse(url) path = data.path.rstrip('/') + '/' _args = dict(urlparse.parse_qs(data.query, keep_blank_values=True)) for elem in self._data_store: pattern = elem['pattern'] function = elem['function'] _method = elem['method'] type_cast = elem['type_cast'] result = re.match(pattern, path) # Found matching method if result and _method == method: _args = dict(_args, **result.groupdict()) # Unpack value lists (due to urllib.parse.parse_qs) in case # theres only one value available for key, val in _args.items(): if isinstance(_args[key], list) and len(_args[key]) == 1: _args[key] = _args[key][0] # Apply typ-casting if necessary
python
{ "resource": "" }
q279236
HistoryConsoleWidget.execute
test
def execute(self, source=None, hidden=False, interactive=False): """ Reimplemented to the store history. """ if not hidden: history = self.input_buffer if source is None else source executed = super(HistoryConsoleWidget, self).execute( source, hidden, interactive) if executed and not hidden: # Save the command unless it was an empty string or was identical # to the previous command. history = history.rstrip() if history and
python
{ "resource": "" }
q279237
HistoryConsoleWidget._up_pressed
test
def _up_pressed(self, shift_modifier): """ Called when the up key is pressed. Returns whether to continue processing the event. """ prompt_cursor = self._get_prompt_cursor() if self._get_cursor().blockNumber() == prompt_cursor.blockNumber(): # Bail out if we're locked. if self._history_locked() and not shift_modifier: return False # Set a search prefix based on the cursor position. col = self._get_input_buffer_cursor_column() input_buffer = self.input_buffer if self._history_index == len(self._history) or \ (self._history_prefix and col != len(self._history_prefix)): self._history_index = len(self._history) self._history_prefix = input_buffer[:col] # Perform the search. self.history_previous(self._history_prefix, as_prefix=not shift_modifier)
python
{ "resource": "" }
q279238
HistoryConsoleWidget._down_pressed
test
def _down_pressed(self, shift_modifier): """ Called when the down key is pressed. Returns whether to continue processing the event. """ end_cursor = self._get_end_cursor() if self._get_cursor().blockNumber() == end_cursor.blockNumber(): # Bail out if we're locked. if self._history_locked() and not shift_modifier: return False # Perform the search. replaced = self.history_next(self._history_prefix, as_prefix=not shift_modifier) # Emulate readline: keep the cursor position fixed for a prefix
python
{ "resource": "" }
q279239
HistoryConsoleWidget.history_previous
test
def history_previous(self, substring='', as_prefix=True): """ If possible, set the input buffer to a previous history item. Parameters: ----------- substring : str, optional If specified, search for an item with this substring. as_prefix : bool, optional If True, the substring must match at the beginning (default). Returns: -------- Whether the input buffer was changed. """ index = self._history_index replace = False while index > 0:
python
{ "resource": "" }
q279240
HistoryConsoleWidget.history_next
test
def history_next(self, substring='', as_prefix=True): """ If possible, set the input buffer to a subsequent history item. Parameters: ----------- substring : str, optional If specified, search for an item with this substring. as_prefix : bool, optional If True, the substring must match at the beginning (default). Returns: -------- Whether the input buffer was changed. """ index = self._history_index replace = False while self._history_index < len(self._history):
python
{ "resource": "" }
q279241
HistoryConsoleWidget._handle_execute_reply
test
def _handle_execute_reply(self, msg): """ Handles replies for code execution, here only session history length """ msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].pop(msg_id,None) if info and info.kind == 'save_magic' and not self._hidden: content = msg['content']
python
{ "resource": "" }
q279242
HistoryConsoleWidget._history_locked
test
def _history_locked(self): """ Returns whether history movement is locked. """ return (self.history_lock and (self._get_edited_history(self._history_index) != self.input_buffer) and
python
{ "resource": "" }
q279243
HistoryConsoleWidget._get_edited_history
test
def _get_edited_history(self, index): """ Retrieves a history item, possibly with temporary edits. """ if index in self._history_edits:
python
{ "resource": "" }
q279244
HistoryConsoleWidget._set_history
test
def _set_history(self, history): """ Replace the current history with a sequence of history items. """
python
{ "resource": "" }
q279245
HistoryConsoleWidget._store_edits
test
def _store_edits(self): """ If there are edits to the current input buffer, store them. """ current = self.input_buffer if self._history_index == len(self._history) or \
python
{ "resource": "" }
q279246
MyFrame.OnTimeToClose
test
def OnTimeToClose(self, evt): """Event handler for the button click.""" print("See ya later!") sys.stdout.flush()
python
{ "resource": "" }
q279247
build_collection
test
def build_collection(df, **kwargs): ''' Generates a list of Record objects given a DataFrame. Each Record instance has a series attribute which is a pandas.Series of the same attributes in the DataFrame. Optional data can be passed in through kwargs which will be included by the name of each object. parameters ---------- df : pandas.DataFrame kwargs : alternate arguments to be saved by name to the series of each object Returns ------- collection : list list of Record objects where each Record represents one row from a dataframe Examples -------- This is how we generate a Record Collection from a DataFrame. >>> import pandas as pd >>> import turntable >>> >>> df = pd.DataFrame({'Artist':"""Michael Jackson, Pink Floyd, Whitney Houston, Meat Loaf, Eagles, Fleetwood Mac, Bee Gees, AC/DC""".split(', '), >>> 'Album' :"""Thriller, The Dark Side of the Moon, The
python
{ "resource": "" }
q279248
collection_to_df
test
def collection_to_df(collection): ''' Converts a collection back into a pandas DataFrame parameters ---------- collection : list list of Record objects where each Record represents one row from a dataframe Returns ------- df : pandas.DataFrame DataFrame
python
{ "resource": "" }
q279249
spin_frame
test
def spin_frame(df, method): ''' Runs the full turntable process on a pandas DataFrame parameters ---------- df : pandas.DataFrame each row represents a record method : def method(record) function used to process each row Returns ------- df : pandas.DataFrame DataFrame processed by method Example ------- >>> import pandas as pd >>> import turntable >>> >>> df = pd.DataFrame({'Artist':"""Michael Jackson, Pink Floyd, Whitney Houston, Meat Loaf, Eagles, Fleetwood Mac, Bee Gees, AC/DC""".split(', '), 'Album':"""Thriller, The Dark Side of the Moon, The Bodyguard,
python
{ "resource": "" }
q279250
RecordSetter.set_attributes
test
def set_attributes(self, kwargs): ''' Initalizes the given argument structure as properties of the class to be used by name in specific method execution. Parameters ---------- kwargs : dictionary
python
{ "resource": "" }
q279251
LogWatcher.subscribe
test
def subscribe(self): """Update our SUB socket's subscriptions.""" self.stream.setsockopt(zmq.UNSUBSCRIBE, '') if '' in self.topics: self.log.debug("Subscribing to: everything") self.stream.setsockopt(zmq.SUBSCRIBE, '') else:
python
{ "resource": "" }
q279252
LogWatcher.log_message
test
def log_message(self, raw): """receive and parse a message, then log it.""" if len(raw) != 2 or '.' not in raw[0]: self.log.error("Invalid log message: %s"%raw) return else:
python
{ "resource": "" }
q279253
mergesort
test
def mergesort(list_of_lists, key=None): """ Perform an N-way merge operation on sorted lists. @param list_of_lists: (really iterable of iterable) of sorted elements (either by naturally or by C{key}) @param key: specify sort key function (like C{sort()}, C{sorted()}) Yields tuples of the form C{(item, iterator)}, where the iterator is the built-in list iterator or something you pass in, if you pre-generate the iterators. This is a stable merge; complexity O(N lg N) Examples:: >>> print list(mergesort([[1,2,3,4], ... [2,3.25,3.75,4.5,6,7], ... [2.625,3.625,6.625,9]])) [1, 2, 2, 2.625, 3, 3.25, 3.625, 3.75, 4, 4.5, 6, 6.625, 7, 9] # note stability >>> print list(mergesort([[1,2,3,4], ... [2,3.25,3.75,4.5,6,7], ... [2.625,3.625,6.625,9]], ... key=int)) [1, 2, 2, 2.625, 3, 3.25, 3.75, 3.625, 4, 4.5, 6, 6.625, 7, 9] >>> print list(mergesort([[4, 3, 2, 1], ... [7, 6, 4.5, 3.75, 3.25, 2], ... [9, 6.625, 3.625, 2.625]], ... key=lambda x: -x)) [9, 7, 6.625, 6, 4.5, 4, 3.75, 3.625, 3.25, 3, 2.625, 2, 2, 1] """ heap = [] for i, itr in enumerate(iter(pl) for pl in list_of_lists): try: item = itr.next() if key: toadd = (key(item), i, item, itr) else:
python
{ "resource": "" }
q279254
remote_iterator
test
def remote_iterator(view,name): """Return an iterator on an object living on a remote engine. """ view.execute('it%s=iter(%s)'%(name,name), block=True) while True: try: result = view.apply_sync(lambda
python
{ "resource": "" }
q279255
convert_to_this_nbformat
test
def convert_to_this_nbformat(nb, orig_version=1): """Convert a notebook to the v2 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. """ if orig_version == 1: newnb = new_notebook() ws = new_worksheet() for cell in nb.cells: if cell.cell_type == u'code': newcell = new_code_cell(input=cell.get('code'),prompt_number=cell.get('prompt_number')) elif cell.cell_type ==
python
{ "resource": "" }
q279256
get_supported_platform
test
def get_supported_platform(): """Return this platform's maximum compatible version. distutils.util.get_platform() normally reports the minimum version of Mac OS X that would be required to *use* extensions produced by distutils. But what we want when checking compatibility is to know the version of Mac OS X that we are *running*. To allow usage of packages that
python
{ "resource": "" }
q279257
get_importer
test
def get_importer(path_item): """Retrieve a PEP 302 "importer" for the given path item If there is no importer, this returns a wrapper around the builtin import machinery. The returned importer is only cached if it was created by a path hook. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for hook in sys.path_hooks: try: importer = hook(path_item) except ImportError:
python
{ "resource": "" }
q279258
StringIO
test
def StringIO(*args, **kw): """Thunk to load the real StringIO on demand""" global StringIO try: from cStringIO import StringIO
python
{ "resource": "" }
q279259
parse_version
test
def parse_version(s): """Convert a version string to a chronologically-sortable key This is a rough cross between distutils' StrictVersion and LooseVersion; if you give it versions that would work with StrictVersion, then it behaves the same; otherwise it acts like a slightly-smarter LooseVersion. It is *possible* to create pathological version coding schemes that will fool this parser, but they should be very rare in practice. The returned value will be a tuple of strings. Numeric portions of the version are padded to 8 digits so they will compare numerically, but without relying on how numbers compare relative to strings. Dots are dropped, but dashes are retained. Trailing zeros between alpha segments or dashes are suppressed, so that e.g. "2.4.0" is considered the same as "2.4".
python
{ "resource": "" }
q279260
_override_setuptools
test
def _override_setuptools(req): """Return True when distribute wants to override a setuptools dependency. We want to override when the requirement is setuptools and the version is a variant of 0.6. """ if req.project_name == 'setuptools':
python
{ "resource": "" }
q279261
WorkingSet.add
test
def add(self, dist, entry=None, insert=True, replace=False): """Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set's ``.entries`` (if it wasn't already present). `dist` is only added to the working set if it's for a project that doesn't already have a distribution in the set, unless `replace=True`. If it's added, any callbacks registered with the ``subscribe()`` method will be called. """ if insert: dist.insert_on(self.entries, entry)
python
{ "resource": "" }
q279262
WorkingSet.find_plugins
test
def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True ): """Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) map(working_set.add, distributions) # add plugins+libs to sys.path print 'Could not load', errors # display errors The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is
python
{ "resource": "" }
q279263
ResourceManager.get_cache_path
test
def get_cache_path(self, archive_name, names=()): """Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if provided, should be a sequence of path name parts "under" the egg's extraction location. This method should only be called by resource providers that need to obtain an extraction location, and only for names they intend to extract, as it tracks the generated
python
{ "resource": "" }
q279264
EntryPoint.parse
test
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1,extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional """ try: attrs = extras = () name,value = src.split('=',1) if '[' in value: value,extras = value.split('[',1) req = Requirement.parse("x["+extras) if req.specs: raise ValueError extras = req.extras if ':' in value: value,attrs = value.split(':',1) if not MODULE(attrs.rstrip()):
python
{ "resource": "" }
q279265
DistInfoDistribution._parsed_pkg_info
test
def _parsed_pkg_info(self): """Parse and cache metadata""" try: return self._pkg_info except AttributeError: from email.parser import Parser
python
{ "resource": "" }
q279266
DistInfoDistribution._compute_dependencies
test
def _compute_dependencies(self): """Recompute this distribution's dependencies.""" from _markerlib import compile as compile_marker dm = self.__dep_map = {None: []} reqs = [] # Including any condition expressions for req in self._parsed_pkg_info.get_all('Requires-Dist') or []: distvers, mark = self._preparse_requirement(req) parsed = parse_requirements(distvers).next() parsed.marker_fn = compile_marker(mark) reqs.append(parsed) def reqs_for_extra(extra): for req in reqs:
python
{ "resource": "" }
q279267
parse_filename
test
def parse_filename(fname): """Parse a notebook filename. This function takes a notebook filename and returns the notebook format (json/py) and the notebook name. This logic can be summarized as follows: * notebook.ipynb -> (notebook.ipynb, notebook, json) * notebook.json -> (notebook.json, notebook, json) * notebook.py -> (notebook.py, notebook, py) * notebook -> (notebook.ipynb, notebook, json) Parameters ---------- fname : unicode The notebook filename. The filename can use a specific filename extention (.ipynb, .json, .py) or none, in which case .ipynb will be assumed. Returns
python
{ "resource": "" }
q279268
_collapse_leading_ws
test
def _collapse_leading_ws(header, txt): """ ``Description`` header must preserve newlines; all others need not """ if header.lower() == 'description': # preserve newlines return '\n'.join([x[8:] if x.startswith(' ' * 8) else x
python
{ "resource": "" }
q279269
CompletionWidget.hideEvent
test
def hideEvent(self, event): """ Reimplemented to disconnect signal handlers and event filter. """ super(CompletionWidget, self).hideEvent(event)
python
{ "resource": "" }
q279270
CompletionWidget.showEvent
test
def showEvent(self, event): """ Reimplemented to connect signal handlers and event filter. """ super(CompletionWidget, self).showEvent(event)
python
{ "resource": "" }
q279271
CompletionWidget._current_text_cursor
test
def _current_text_cursor(self): """ Returns a cursor with text between the start position and the current position selected. """
python
{ "resource": "" }
q279272
CompletionWidget._update_current
test
def _update_current(self): """ Updates the current item based on the current text. """ prefix = self._current_text_cursor().selection().toPlainText() if prefix: items = self.findItems(prefix, (QtCore.Qt.MatchStartsWith |
python
{ "resource": "" }
q279273
registerAdminSite
test
def registerAdminSite(appName, excludeModels=[]): """Registers the models of the app with the given "appName" for the admin site""" for
python
{ "resource": "" }
q279274
disk_partitions
test
def disk_partitions(all): """Return disk partitions.""" rawlist
python
{ "resource": "" }
q279275
get_system_cpu_times
test
def get_system_cpu_times(): """Return system CPU times as a named tuple.""" user, system, idle = 0, 0, 0 # computes system global times summing each processor value for cpu_time in _psutil_mswindows.get_system_cpu_times():
python
{ "resource": "" }
q279276
get_system_per_cpu_times
test
def get_system_per_cpu_times(): """Return system per-CPU times as a list of named tuples.""" ret = [] for cpu_t in _psutil_mswindows.get_system_cpu_times(): user, system, idle = cpu_t
python
{ "resource": "" }
q279277
Win32ShellCommandController._stdin_raw_nonblock
test
def _stdin_raw_nonblock(self): """Use the raw Win32 handle of sys.stdin to do non-blocking reads""" # WARNING: This is experimental, and produces inconsistent results. # It's possible for the handle not to be appropriate for use # with WaitForSingleObject, among other things. handle = msvcrt.get_osfhandle(sys.stdin.fileno()) result = WaitForSingleObject(handle, 100) if result == WAIT_FAILED: raise ctypes.WinError() elif result == WAIT_TIMEOUT: print(".", end='') return None else: data = ctypes.create_string_buffer(256) bytesRead = DWORD(0) print('?', end='') if not ReadFile(handle, data, 256, ctypes.byref(bytesRead), None): raise ctypes.WinError()
python
{ "resource": "" }
q279278
Win32ShellCommandController._stdin_raw_block
test
def _stdin_raw_block(self): """Use a blocking stdin read""" # The big problem with the blocking read is that it doesn't # exit when it's supposed to in all contexts. An extra # key-press may be required to trigger the exit. try: data = sys.stdin.read(1) data = data.replace('\r', '\n') return data except WindowsError as we:
python
{ "resource": "" }
q279279
MainWindow.update_tab_bar_visibility
test
def update_tab_bar_visibility(self): """ update visibility of the tabBar depending of the number of tab 0 or 1 tab, tabBar hidden 2+ tabs, tabBar visible send a self.close if number of tab ==0 need to be called explicitly, or be connected to tabInserted/tabRemoved """
python
{ "resource": "" }
q279280
MainWindow.create_tab_with_current_kernel
test
def create_tab_with_current_kernel(self): """create a new frontend attached to the same kernel as the current tab""" current_widget = self.tab_widget.currentWidget() current_widget_index = self.tab_widget.indexOf(current_widget) current_widget_name = self.tab_widget.tabText(current_widget_index) widget = self.slave_frontend_factory(current_widget) if 'slave' in current_widget_name:
python
{ "resource": "" }
q279281
MainWindow.add_tab_with_frontend
test
def add_tab_with_frontend(self,frontend,name=None): """ insert a tab with a given frontend in the tab bar, and give it a name """ if not name:
python
{ "resource": "" }
q279282
MainWindow.add_menu_action
test
def add_menu_action(self, menu, action, defer_shortcut=False): """Add action to menu as well as self So that when the menu bar is invisible, its actions are still available. If defer_shortcut is True, set the shortcut context to widget-only, where it will avoid conflict with shortcuts already bound to the widgets
python
{ "resource": "" }
q279283
MainWindow._make_dynamic_magic
test
def _make_dynamic_magic(self,magic): """Return a function `fun` that will execute `magic` on active frontend. Parameters ---------- magic : string string that will be executed as is when the returned function is called Returns ------- fun : function function with no parameters, when called will execute `magic` on the current active frontend at call time See Also -------- populate_all_magic_menu : generate the "All Magics..." menu Notes ----- `fun` executes `magic` in active frontend at the moment it
python
{ "resource": "" }
q279284
MainWindow.populate_all_magic_menu
test
def populate_all_magic_menu(self, listofmagic=None): """Clean "All Magics..." menu and repopulate it with `listofmagic` Parameters ---------- listofmagic : string, repr() of a list of strings, send back by the kernel Notes ----- `listofmagic`is a repr() of list because it is fed with the result of a 'user_expression' """ for k,v in self._magic_menu_dict.items(): v.clear() self.all_magic_menu.clear() protected_magic = set(["more","less","load_ext","pycat","loadpy","load","save","psource"]) mlist=ast.literal_eval(listofmagic) for magic in mlist: cell = (magic['type'] == 'cell') name = magic['name'] mclass = magic['class'] if cell : prefix='%%' else : prefix='%' magic_menu =
python
{ "resource": "" }
q279285
MainWindow.closeEvent
test
def closeEvent(self, event): """ Forward the close event to every tabs contained by the windows """ if self.tab_widget.count() == 0: # no tabs, just close event.accept() return # Do Not loop on the widget count as it change while closing title = self.window().windowTitle() cancel = QtGui.QMessageBox.Cancel okay = QtGui.QMessageBox.Ok if self.confirm_exit: if self.tab_widget.count() > 1: msg = "Close all tabs, stop all kernels, and Quit?" else: msg = "Close console, stop kernel, and Quit?" info = "Kernels not started here (e.g. notebooks) will be left alone." closeall = QtGui.QPushButton("&Quit", self) closeall.setShortcut('Q') box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg) box.setInformativeText(info) box.addButton(cancel) box.addButton(closeall, QtGui.QMessageBox.YesRole) box.setDefaultButton(closeall)
python
{ "resource": "" }
q279286
passwd
test
def passwd(passphrase=None, algorithm='sha1'): """Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- In [1]: passwd('mypassword') Out[1]: 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: ')
python
{ "resource": "" }
q279287
passwd_check
test
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- In [1]: from IPython.lib.security import passwd_check In [2]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'mypassword') Out[2]: True In [3]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'anotherpassword') Out[3]: False
python
{ "resource": "" }
q279288
ajax_editable_boolean_cell
test
def ajax_editable_boolean_cell(item, attr, text='', override=None): """ Generate a html snippet for showing a boolean value on the admin page. Item is an object, attr is the attribute name we should display. Text is an optional explanatory text to be included in the output. This function will emit code to produce a checkbox input with its state corresponding to the item.attr attribute if no override value is passed. This input is wired to run a JS ajax updater to toggle the value. If override is passed in, ignores the attr attribute and returns a static image for the override boolean with no user interaction possible (useful for "disabled and you can't change it" situations). """ if text: text = '&nbsp;(%s)' % unicode(text)
python
{ "resource": "" }
q279289
TreeEditor.indented_short_title
test
def indented_short_title(self, item): r = "" """ Generate a short title for an object, indent it depending on the object's depth in the hierarchy. """ if hasattr(item, 'get_absolute_url'): r = '<input type="hidden" class="medialibrary_file_path" value="%s" />' % item.get_absolute_url() editable_class =
python
{ "resource": "" }
q279290
TreeEditor._collect_editable_booleans
test
def _collect_editable_booleans(self): """ Collect all fields marked as editable booleans. We do not want the user to be able to edit arbitrary fields by crafting an AJAX request by hand. """ if hasattr(self, '_ajax_editable_booleans'): return self._ajax_editable_booleans = {} for field in self.list_display: # The ajax_editable_boolean return value has to be assigned # to the ModelAdmin class item = getattr(self.__class__, field, None) if not item:
python
{ "resource": "" }
q279291
TreeEditor._toggle_boolean
test
def _toggle_boolean(self, request): """ Handle an AJAX toggle_boolean request """ try: item_id = int(request.POST.get('item_id', None)) attr = str(request.POST.get('attr', None)) except: return HttpResponseBadRequest("Malformed request") if not request.user.is_staff: logging.warning("Denied AJAX request by non-staff %s to toggle boolean %s for object #%s", request.user, attr, item_id) return HttpResponseForbidden("You do not have permission to access this object") self._collect_editable_booleans() if not self._ajax_editable_booleans.has_key(attr): return HttpResponseBadRequest("not a valid attribute %s" % attr) try: obj = self.model._default_manager.get(pk=item_id) except self.model.DoesNotExist: return HttpResponseNotFound("Object does not exist") can_change = False if hasattr(obj, "user_can") and obj.user_can(request.user, change_page=True): # Was added in c7f04dfb5d, but I've no idea what user_can is about. can_change = True else: can_change = self.has_change_permission(request, obj=obj) if not can_change: logging.warning("Denied AJAX request by %s to toggle boolean %s for object %s", request.user, attr, item_id) return HttpResponseForbidden("You do not have permission to access this object") logging.info("Processing request by %s to toggle %s on %s", request.user, attr,
python
{ "resource": "" }
q279292
TreeEditor.has_change_permission
test
def has_change_permission(self, request, obj=None): """ Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_change_permission, but also passes the obj parameter in. """ if settings.TREE_EDITOR_OBJECT_PERMISSIONS: opts = self.opts
python
{ "resource": "" }
q279293
TreeEditor.has_delete_permission
test
def has_delete_permission(self, request, obj=None): """ Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_delete_permission, but also passes the obj parameter in. """ if settings.TREE_EDITOR_OBJECT_PERMISSIONS: opts = self.opts
python
{ "resource": "" }
q279294
add_children
test
def add_children(G, parent, level, n=2): """Add children recursively to a binary tree.""" if level == 0: return for i in range(n): child = parent+str(i)
python
{ "resource": "" }
q279295
make_bintree
test
def make_bintree(levels): """Make a symmetrical binary tree with @levels""" G = nx.DiGraph() root = '0'
python
{ "resource": "" }
q279296
submit_jobs
test
def submit_jobs(view, G, jobs): """Submit jobs via client where G describes the time dependencies.""" results = {} for node in nx.topological_sort(G): with view.temp_flags(after=[ results[n] for n
python
{ "resource": "" }
q279297
validate_tree
test
def validate_tree(G, results): """Validate that jobs executed after their dependencies.""" for node in G: started = results[node].metadata.started for parent in G.predecessors(node):
python
{ "resource": "" }
q279298
make_color_table
test
def make_color_table(in_class): """Build a set of color attributes in a class. Helper function for building the *TermColors classes."""
python
{ "resource": "" }
q279299
ColorScheme.copy
test
def copy(self,name=None): """Return a full copy of the object, optionally renaming it.""" if name is None:
python
{ "resource": "" }