_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q280000
interpret_distro_name
test
def interpret_distro_name(location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to t...
python
{ "resource": "" }
q280001
open_with_auth
test
def open_with_auth(url): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urlparse.urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): ...
python
{ "resource": "" }
q280002
PackageIndex.fetch_distribution
test
def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None ): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `for...
python
{ "resource": "" }
q280003
get_parent
test
def get_parent(obj): ''' get parent from obj. ''' names = obj.__qualname__.split('.')[:-1] if '<locals>' in names: # locals function raise ValueError('cannot get parent from locals object.') module = sys.modules[obj.__module__] parent = module while names: parent = getatt...
python
{ "resource": "" }
q280004
EnginePUBHandler.root_topic
test
def root_topic(self): """this is a property, in case the handler is created before the engine gets registered with an id""" if isinstance(getattr(self.engine, 'id', None), int): return "engine.%i"%self.engine.id else: return "engine"
python
{ "resource": "" }
q280005
render_template
test
def render_template(content, context): """ renders context aware template """ rendered = Template(content).render(Context(context)) return rendered
python
{ "resource": "" }
q280006
Capture.configure
test
def configure(self, options, conf): """Configure plugin. Plugin is enabled by default. """ self.conf = conf if not options.capture: self.enabled = False
python
{ "resource": "" }
q280007
Capture.formatError
test
def formatError(self, test, err): """Add captured output to error report. """ test.capturedOutput = output = self.buffer self._buf = None if not output: # Don't return None as that will prevent other # formatters from formatting and remove earlier formatte...
python
{ "resource": "" }
q280008
splitBy
test
def splitBy(data, num): """ Turn a list to list of list """ return [data[i:i + num] for i in range(0, len(data), num)]
python
{ "resource": "" }
q280009
convert_to_this_nbformat
test
def convert_to_this_nbformat(nb, orig_version=2, orig_minor=0): """Convert a notebook to the v3 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. orig_minor : ...
python
{ "resource": "" }
q280010
hex_to_rgb
test
def hex_to_rgb(color): """Convert a hex color to rgb integer tuple.""" if color.startswith('#'): color = color[1:] if len(color) == 3: color = ''.join([c*2 for c in color]) if len(color) != 6: return False try: r = int(color[:2],16) g = int(color[2:4],16) ...
python
{ "resource": "" }
q280011
get_colors
test
def get_colors(stylename): """Construct the keys to be used building the base stylesheet from a templatee.""" style = get_style_by_name(stylename) fgcolor = style.style_for_token(Token.Text)['color'] or '' if len(fgcolor) in (3,6): # could be 'abcdef' or 'ace' hex, which needs '#' prefix ...
python
{ "resource": "" }
q280012
get_font
test
def get_font(family, fallback=None): """Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallba...
python
{ "resource": "" }
q280013
IPythonWidget._handle_execute_reply
test
def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': number = msg['content']['execution_count'] + 1 ...
python
{ "resource": "" }
q280014
IPythonWidget._handle_history_reply
test
def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if cont...
python
{ "resource": "" }
q280015
IPythonWidget._handle_pyout
test
def _handle_pyout(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count...
python
{ "resource": "" }
q280016
IPythonWidget._handle_display_data
test
def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the displa...
python
{ "resource": "" }
q280017
IPythonWidget._started_channels
test
def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" super(IPythonWidget, self)._started_channels() self._load_guiref_magic() self.kernel_manager.shell_channel.history(hist_access_type='tail', n=100...
python
{ "resource": "" }
q280018
IPythonWidget.execute_file
test
def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using ...
python
{ "resource": "" }
q280019
IPythonWidget._process_execute_error
test
def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # th...
python
{ "resource": "" }
q280020
IPythonWidget._process_execute_payload
test
def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False e...
python
{ "resource": "" }
q280021
IPythonWidget.set_default_style
test
def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters: ----------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ ...
python
{ "resource": "" }
q280022
IPythonWidget._edit
test
def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters: ----------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: s...
python
{ "resource": "" }
q280023
IPythonWidget._make_in_prompt
test
def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = self.in_prompt return '<span class="in-...
python
{ "resource": "" }
q280024
IPythonWidget._make_continuation_prompt
test
def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '...
python
{ "resource": "" }
q280025
IPythonWidget._style_sheet_changed
test
def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().c...
python
{ "resource": "" }
q280026
IPythonWidget._syntax_style_changed
test
def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highli...
python
{ "resource": "" }
q280027
CloudStack._handle_response
test
async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict: """ Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which means that the API call returns just a job id. The actually expec...
python
{ "resource": "" }
q280028
CloudStack._sign
test
def _sign(self, url_parameters: dict) -> dict: """ According to the CloudStack documentation, each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA-1 hash of the url ...
python
{ "resource": "" }
q280029
CloudStack._transform_data
test
def _transform_data(data: dict) -> dict: """ Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller. :param...
python
{ "resource": "" }
q280030
virtual_memory
test
def virtual_memory(): """System virtual memory as a namedutple.""" mem = _psutil_bsd.get_virtual_mem() total, free, active, inactive, wired, cached, buffers, shared = mem avail = inactive + cached + free used = active + wired + cached percent = usage_percent((total - avail), total, _round=1) ...
python
{ "resource": "" }
q280031
get_system_cpu_times
test
def get_system_cpu_times(): """Return system per-CPU times as a named tuple""" user, nice, system, idle, irq = _psutil_bsd.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle, irq)
python
{ "resource": "" }
q280032
Process.get_process_uids
test
def get_process_uids(self): """Return real, effective and saved user ids.""" real, effective, saved = _psutil_bsd.get_process_uids(self.pid) return nt_uids(real, effective, saved)
python
{ "resource": "" }
q280033
Process.get_process_gids
test
def get_process_gids(self): """Return real, effective and saved group ids.""" real, effective, saved = _psutil_bsd.get_process_gids(self.pid) return nt_gids(real, effective, saved)
python
{ "resource": "" }
q280034
Process.get_process_threads
test
def get_process_threads(self): """Return the number of threads belonging to the process.""" rawlist = _psutil_bsd.get_process_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = nt_thread(thread_id, utime, stime) retlist.append(ntuple) ...
python
{ "resource": "" }
q280035
Process.get_open_files
test
def get_open_files(self): """Return files opened by process as a list of namedtuples.""" # XXX - C implementation available on FreeBSD >= 8 only # else fallback on lsof parser if hasattr(_psutil_bsd, "get_process_open_files"): rawlist = _psutil_bsd.get_process_open_files(self...
python
{ "resource": "" }
q280036
pkg_commit_hash
test
def pkg_commit_hash(pkg_path): """Get short form of commit hash given directory `pkg_path` We get the commit hash from (in order of preference): * IPython.utils._sysinfo.commit * git output, if we are in a git repository If these fail, we return a not-found placeholder tuple Parameters -...
python
{ "resource": "" }
q280037
pkg_info
test
def pkg_info(pkg_path): """Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest """ src, hsh = pkg_commit_hash(pkg_path) ret...
python
{ "resource": "" }
q280038
sys_info
test
def sys_info(): """Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_ve...
python
{ "resource": "" }
q280039
_num_cpus_darwin
test
def _num_cpus_darwin(): """Return the number of active CPUs on a Darwin system.""" p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) return p.stdout.read()
python
{ "resource": "" }
q280040
num_cpus
test
def num_cpus(): """Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (tho...
python
{ "resource": "" }
q280041
BaseCursor.nextset
test
def nextset(self): """Advance to the next result set. Returns None if there are no more result sets. """ if self._executed: self.fetchall() del self.messages[:] db = self._get_db() nr = db.next_result() if nr == -1: return...
python
{ "resource": "" }
q280042
CursorUseResultMixIn.fetchone
test
def fetchone(self): """Fetches a single row from the cursor.""" self._check_executed() r = self._fetch_row(1) if not r: self._warning_check() return None self.rownumber = self.rownumber + 1 return r[0]
python
{ "resource": "" }
q280043
CursorUseResultMixIn.fetchmany
test
def fetchmany(self, size=None): """Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.""" self._check_executed() r = self._fetch_row(size or self.arraysize) self.rownumber = self.rownumber + len(r) ...
python
{ "resource": "" }
q280044
CursorUseResultMixIn.fetchall
test
def fetchall(self): """Fetchs all available rows from the cursor.""" self._check_executed() r = self._fetch_row(0) self.rownumber = self.rownumber + len(r) self._warning_check() return r
python
{ "resource": "" }
q280045
connect
test
def connect(com, peers, tree, pub_url, root_id): """this function will be called on the engines""" com.connect(peers, tree, pub_url, root_id)
python
{ "resource": "" }
q280046
reads_json
test
def reads_json(s, **kwargs): """Read a JSON notebook from a string and return the NotebookNode object.""" nbf, minor, d = parse_json(s, **kwargs) if nbf == 1: nb = v1.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=1) elif nbf == 2: nb = v2.to_note...
python
{ "resource": "" }
q280047
reads_py
test
def reads_py(s, **kwargs): """Read a .py notebook from a string and return the NotebookNode object.""" nbf, nbm, s = parse_py(s, **kwargs) if nbf == 2: nb = v2.to_notebook_py(s, **kwargs) elif nbf == 3: nb = v3.to_notebook_py(s, **kwargs) else: raise NBFormatError('Unsupporte...
python
{ "resource": "" }
q280048
reads
test
def reads(s, format, **kwargs): """Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string t...
python
{ "resource": "" }
q280049
writes
test
def writes(nb, format, **kwargs): """Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'p...
python
{ "resource": "" }
q280050
write
test
def write(nb, fp, format, **kwargs): """Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like...
python
{ "resource": "" }
q280051
_convert_to_metadata
test
def _convert_to_metadata(): """Convert to a notebook having notebook metadata.""" import glob for fname in glob.glob('*.ipynb'): print('Converting file:',fname) with open(fname,'r') as f: nb = read(f,u'json') md = new_metadata() if u'name' in nb: md.na...
python
{ "resource": "" }
q280052
Box.load_from_dict
test
def load_from_dict(self, src: dict, key): ''' try load value from dict. if key is not exists, mark as state unset. ''' if key in src: self.value = src[key] else: self.reset()
python
{ "resource": "" }
q280053
Selector.matches
test
def matches(self, name): """Does the name match my requirements? To match, a name must match config.testMatch OR config.include and it must not match config.exclude """ return ((self.match.search(name) or (self.include and filter(None, ...
python
{ "resource": "" }
q280054
Selector.wantClass
test
def wantClass(self, cls): """Is the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. Classes that start with _ are always excluded. """ declared = getattr(cls, '__test__', None) if declared is not None: ...
python
{ "resource": "" }
q280055
Selector.wantDirectory
test
def wantDirectory(self, dirname): """Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements. """ tail = op_basename(dirname) if ispackage(dirname): wan...
python
{ "resource": "" }
q280056
Selector.wantFile
test
def wantFile(self, file): """Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings. """ # never...
python
{ "resource": "" }
q280057
Selector.wantFunction
test
def wantFunction(self, function): """Is the function a test function? """ try: if hasattr(function, 'compat_func_name'): funcname = function.compat_func_name else: funcname = function.__name__ except AttributeError: # no...
python
{ "resource": "" }
q280058
Selector.wantMethod
test
def wantMethod(self, method): """Is the method a test method? """ try: method_name = method.__name__ except AttributeError: # not a method return False if method_name.startswith('_'): # never collect 'private' methods re...
python
{ "resource": "" }
q280059
Selector.wantModule
test
def wantModule(self, module): """Is the module a test module? The tail of the module name must match test requirements. One exception: we always want __main__. """ declared = getattr(module, '__test__', None) if declared is not None: wanted = declared ...
python
{ "resource": "" }
q280060
_file_lines
test
def _file_lines(fname): """Return the contents of a named file as a list of lines. This function never raises an IOError exception: if the file can't be read, it simply returns an empty list.""" try: outfile = open(fname) except IOError: return [] else: out = outfile.re...
python
{ "resource": "" }
q280061
Pdb.list_command_pydb
test
def list_command_pydb(self, arg): """List command to use if we have a newer pydb installed""" filename, first, last = OldPdb.parse_list_cmd(self, arg) if filename is not None: self.print_list_lines(filename, first, last)
python
{ "resource": "" }
q280062
Pdb.print_list_lines
test
def print_list_lines(self, filename, first, last): """The printing (as opposed to the parsing part of a 'list' command.""" try: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNorm...
python
{ "resource": "" }
q280063
Pdb.do_pdef
test
def do_pdef(self, arg): """The debugger interface to magic_pdef""" namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
python
{ "resource": "" }
q280064
conversion_factor
test
def conversion_factor(from_symbol, to_symbol, date): """ Generates a multiplying factor used to convert two currencies """ from_currency = Currency.objects.get(symbol=from_symbol) try: from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price except Cu...
python
{ "resource": "" }
q280065
convert_currency
test
def convert_currency(from_symbol, to_symbol, value, date): """ Converts an amount of money from one currency to another on a specified date. """ if from_symbol == to_symbol: return value factor = conversion_factor(from_symbol, to_symbol, date) if type(value) == float: output = ...
python
{ "resource": "" }
q280066
Currency.compute_return
test
def compute_return(self, start_date, end_date, rate="MID"): """ Compute the return of the currency between two dates """ if rate not in ["MID", "ASK", "BID"]: raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate)) if end_date <= start_d...
python
{ "resource": "" }
q280067
get_stream_enc
test
def get_stream_enc(stream, default=None): """Return the given stream's encoding or a default. There are cases where sys.std* might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. `default' is None i...
python
{ "resource": "" }
q280068
getdefaultencoding
test
def getdefaultencoding(): """Return IPython's guess for the default encoding for bytes as text. Asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Fall back on locale.getpreferredencoding() which should be a sensible platform default (that respects L...
python
{ "resource": "" }
q280069
KernelApp.write_connection_file
test
def write_connection_file(self): """write connection info to JSON file""" if os.path.basename(self.connection_file) == self.connection_file: cf = os.path.join(self.profile_dir.security_dir, self.connection_file) else: cf = self.connection_file write_connection_fil...
python
{ "resource": "" }
q280070
KernelApp.init_heartbeat
test
def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.ip, self.hb_port)) ...
python
{ "resource": "" }
q280071
KernelApp.log_connection_info
test
def log_connection_info(self): """display connection info, and store ports""" basename = os.path.basename(self.connection_file) if basename == self.connection_file or \ os.path.dirname(self.connection_file) == self.profile_dir.security_dir: # use shortname tai...
python
{ "resource": "" }
q280072
KernelApp.init_session
test
def init_session(self): """create our session object""" default_secure(self.config) self.session = Session(config=self.config, username=u'kernel')
python
{ "resource": "" }
q280073
KernelApp.init_io
test
def init_io(self): """Redirect input streams and set a display hook.""" if self.outstream_class: outstream_factory = import_item(str(self.outstream_class)) sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout') sys.stderr = outstream_factory(self.s...
python
{ "resource": "" }
q280074
KernelApp.init_kernel
test
def init_kernel(self): """Create the Kernel object itself""" kernel_factory = import_item(str(self.kernel_class)) self.kernel = kernel_factory(config=self.config, session=self.session, shell_socket=self.shell_socket, iopub_socket=se...
python
{ "resource": "" }
q280075
EngineFactory.init_connector
test
def init_connector(self): """construct connection function, which handles tunnels.""" self.using_ssh = bool(self.sshkey or self.sshserver) if self.sshkey and not self.sshserver: # We are using ssh directly to the controller, tunneling localhost to localhost self.sshserve...
python
{ "resource": "" }
q280076
EngineFactory.register
test
def register(self): """send the registration_request""" self.log.info("Registering with controller at %s"%self.url) ctx = self.context connect,maybe_tunnel = self.init_connector() reg = ctx.socket(zmq.DEALER) reg.setsockopt(zmq.IDENTITY, self.bident) connect(reg,...
python
{ "resource": "" }
q280077
html_to_text
test
def html_to_text(content): """ Converts html content to plain text """ text = None h2t = html2text.HTML2Text() h2t.ignore_links = False text = h2t.handle(content) return text
python
{ "resource": "" }
q280078
md_to_text
test
def md_to_text(content): """ Converts markdown content to text """ text = None html = markdown.markdown(content) if html: text = html_to_text(content) return text
python
{ "resource": "" }
q280079
domain_to_fqdn
test
def domain_to_fqdn(domain, proto=None): """ returns a fully qualified app domain name """ from .generic import get_site_proto proto = proto or get_site_proto() fdqn = '{proto}://{domain}'.format(proto=proto, domain=domain) return fdqn
python
{ "resource": "" }
q280080
NoseExclude.options
test
def options(self, parser, env=os.environ): """Define the command line options for the plugin.""" super(NoseExclude, self).options(parser, env) env_dirs = [] if 'NOSE_EXCLUDE_DIRS' in env: exclude_dirs = env.get('NOSE_EXCLUDE_DIRS','') env_dirs.extend(exclude_dirs....
python
{ "resource": "" }
q280081
NoseExclude.configure
test
def configure(self, options, conf): """Configure plugin based on command line options""" super(NoseExclude, self).configure(options, conf) self.exclude_dirs = {} # preload directories from file if options.exclude_dir_file: if not options.exclude_dirs: ...
python
{ "resource": "" }
q280082
NoseExclude.wantDirectory
test
def wantDirectory(self, dirname): """Check if directory is eligible for test discovery""" if dirname in self.exclude_dirs: log.debug("excluded: %s" % dirname) return False else: return None
python
{ "resource": "" }
q280083
build_ext.links_to_dynamic
test
def links_to_dynamic(self, ext): """Return true if 'ext' links to a dynamic lib in the same package""" # XXX this should check to ensure the lib is actually being built # XXX as dynamic, and not just using a locally-found version or a # XXX static-compiled version libnames = dict...
python
{ "resource": "" }
q280084
call_each
test
def call_each(funcs: list, *args, **kwargs): ''' call each func from func list. return the last func value or None if func list is empty. ''' ret = None for func in funcs: ret = func(*args, **kwargs) return ret
python
{ "resource": "" }
q280085
call_each_reversed
test
def call_each_reversed(funcs: list, *args, **kwargs): ''' call each func from reversed func list. return the last func value or None if func list is empty. ''' ret = None for func in reversed(funcs): ret = func(*args, **kwargs) return ret
python
{ "resource": "" }
q280086
CallableList.append_func
test
def append_func(self, func, *args, **kwargs): ''' append func with given arguments and keywords. ''' wraped_func = partial(func, *args, **kwargs) self.append(wraped_func)
python
{ "resource": "" }
q280087
CallableList.insert_func
test
def insert_func(self, index, func, *args, **kwargs): ''' insert func with given arguments and keywords. ''' wraped_func = partial(func, *args, **kwargs) self.insert(index, wraped_func)
python
{ "resource": "" }
q280088
PrettyHelpFormatter.format_usage
test
def format_usage(self, usage): """ ensure there is only one newline between usage and the first heading if there is no description """ msg = 'Usage: %s' % usage if self.parser.description: msg += '\n' return msg
python
{ "resource": "" }
q280089
BaseParallelApplication.initialize
test
def initialize(self, argv=None): """initialize the app""" super(BaseParallelApplication, self).initialize(argv) self.to_work_dir() self.reinit_logging()
python
{ "resource": "" }
q280090
BaseParallelApplication.write_pid_file
test
def write_pid_file(self, overwrite=False): """Create a .pid file in the pid_dir with my pid. This must be called after pre_construct, which sets `self.pid_dir`. This raises :exc:`PIDFileError` if the pid file exists already. """ pid_file = os.path.join(self.profile_dir.pid_dir, ...
python
{ "resource": "" }
q280091
BaseParallelApplication.remove_pid_file
test
def remove_pid_file(self): """Remove the pid file. This should be called at shutdown by registering a callback with :func:`reactor.addSystemEventTrigger`. This needs to return ``None``. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if...
python
{ "resource": "" }
q280092
BaseParallelApplication.get_pid_from_file
test
def get_pid_from_file(self): """Get the pid from the pid file. If the pid file doesn't exist a :exc:`PIDFileError` is raised. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): with open(pid_file, 'r') as f: ...
python
{ "resource": "" }
q280093
construct_parser
test
def construct_parser(magic_func): """ Construct an argument parser using the function decorations. """ kwds = getattr(magic_func, 'argcmd_kwds', {}) if 'description' not in kwds: kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArg...
python
{ "resource": "" }
q280094
real_name
test
def real_name(magic_func): """ Find the real name of the magic. """ magic_name = magic_func.__name__ if magic_name.startswith('magic_'): magic_name = magic_name[len('magic_'):] return getattr(magic_func, 'argcmd_name', magic_name)
python
{ "resource": "" }
q280095
FrontendHighlighter.highlightBlock
test
def highlightBlock(self, string): """ Highlight a block of text. Reimplemented to highlight selectively. """ if not self.highlighting_on: return # The input to this function is a unicode string that may contain # paragraph break characters, non-breaking spaces, etc. ...
python
{ "resource": "" }
q280096
FrontendHighlighter.rehighlightBlock
test
def rehighlightBlock(self, block): """ Reimplemented to temporarily enable highlighting if disabled. """ old = self.highlighting_on self.highlighting_on = True super(FrontendHighlighter, self).rehighlightBlock(block) self.highlighting_on = old
python
{ "resource": "" }
q280097
FrontendHighlighter.setFormat
test
def setFormat(self, start, count, format): """ Reimplemented to highlight selectively. """ start += self._current_offset super(FrontendHighlighter, self).setFormat(start, count, format)
python
{ "resource": "" }
q280098
FrontendWidget.copy
test
def copy(self): """ Copy the currently selected text to the clipboard, removing prompts. """ if self._page_control is not None and self._page_control.hasFocus(): self._page_control.copy() elif self._control.hasFocus(): text = self._control.textCursor().selection()...
python
{ "resource": "" }
q280099
FrontendWidget._execute
test
def _execute(self, source, hidden): """ Execute 'source'. If 'hidden', do not show any output. See parent class :meth:`execute` docstring for full details. """ msg_id = self.kernel_manager.shell_channel.execute(source, hidden) self._request_info['execute'][msg_id] = self._Execut...
python
{ "resource": "" }