Search is not available for this dataset
text
stringlengths
75
104k
def write_connection_file(fname=None, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0, ip=LOCALHOST, key=b''): """Generates a JSON config file, including the selection of random ports. Parameters ---------- fname : unicode The path to the file to write she...
def base_launch_kernel(code, fname, stdin=None, stdout=None, stderr=None, executable=None, independent=False, extra_arguments=[], cwd=None): """ Launches a localhost kernel, binding to the specified ports. Parameters ---------- code : str, A strin...
def create_zipfile(context): """This is the actual zest.releaser entry point Relevant items in the context dict: name Name of the project being released tagdir Directory where the tag checkout is placed (*if* a tag checkout has been made) version Version we're rel...
def fix_version(context): """Fix the version in metadata.txt Relevant context dict item for both prerelease and postrelease: ``new_version``. """ if not prerequisites_ok(): return lines = codecs.open('metadata.txt', 'rU', 'utf-8').readlines() for index, line in enumerate(lines): ...
def mappable(obj): """return whether an object is mappable or not.""" if isinstance(obj, (tuple,list)): return True for m in arrayModules: if isinstance(obj,m['type']): return True return False
def getPartition(self, seq, p, q): """Returns the pth partition of q partitions of seq.""" # Test for error conditions here if p<0 or p>=q: print "No partition exists." return remainder = len(seq)%q basesize = len(seq)//q hi = [] ...
def pexpect_monkeypatch(): """Patch pexpect to prevent unhandled exceptions at VM teardown. Calling this function will monkeypatch the pexpect.spawn class and modify its __del__ method to make it more robust in the face of failures that can occur if it is called when the Python VM is shutting down. ...
def main(): """Run as a command-line script.""" parser = optparse.OptionParser(usage=MAIN_USAGE) newopt = parser.add_option newopt('--ipython',action='store_const',dest='mode',const='ipython', help='IPython interactive runner (default).') newopt('--python',action='store_const',dest='mode...
def run_file(self,fname,interact=False,get_output=False): """Run the given file interactively. Inputs: -fname: name of the file to execute. See the run_source docstring for the meaning of the optional arguments.""" fobj = open(fname,'r') try: out...
def run_source(self,source,interact=False,get_output=False): """Run the given source code interactively. Inputs: - source: a string of code to be executed, or an open file object we can iterate over. Optional inputs: - interact(False): if true, start to interact...
def main(self,argv=None): """Run as a command-line script.""" parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__) newopt = parser.add_option newopt('-i','--interact',action='store_true',default=False, help='Interact with the program after the script is r...
def report(self, morfs, outfile=None): """Generate a Cobertura-compatible XML report for `morfs`. `morfs` is a list of modules or filenames. `outfile` is a file object to write the XML to. """ # Initial setup. outfile = outfile or sys.stdout # Create the DOM t...
def xml_file(self, cu, analysis): """Add to the XML report for a single file.""" # Create the 'lines' and 'package' XML elements, which # are populated later. Note that a package == a directory. package_name = rpartition(cu.name, ".")[0] className = cu.name package = s...
def phistogram(view, a, bins=10, rng=None, normed=False): """Compute the histogram of a remote array a. Parameters ---------- view IPython DirectView instance a : str String name of the remote array bins : int Number of histogram bins ...
def fetch_pi_file(filename): """This will download a segment of pi from super-computing.org if the file is not already present. """ import os, urllib ftpdir="ftp://pi.super-computing.org/.2/pi200m/" if os.path.exists(filename): # we already have it return else: # down...
def reduce_freqs(freqlist): """ Add up a list of freq counts to get the total counts. """ allfreqs = np.zeros_like(freqlist[0]) for f in freqlist: allfreqs += f return allfreqs
def compute_n_digit_freqs(filename, n): """ Read digits of pi from a file and compute the n digit frequencies. """ d = txt_file_to_digits(filename) freqs = n_digit_freqs(d, n) return freqs
def txt_file_to_digits(filename, the_type=str): """ Yield the digits of pi read from a .txt file. """ with open(filename, 'r') as f: for line in f.readlines(): for c in line: if c != '\n' and c!= ' ': yield the_type(c)
def one_digit_freqs(digits, normalize=False): """ Consume digits of pi and compute 1 digit freq. counts. """ freqs = np.zeros(10, dtype='i4') for d in digits: freqs[int(d)] += 1 if normalize: freqs = freqs/freqs.sum() return freqs
def two_digit_freqs(digits, normalize=False): """ Consume digits of pi and compute 2 digits freq. counts. """ freqs = np.zeros(100, dtype='i4') last = digits.next() this = digits.next() for d in digits: index = int(last + this) freqs[index] += 1 last = this th...
def n_digit_freqs(digits, n, normalize=False): """ Consume digits of pi and compute n digits freq. counts. This should only be used for 1-6 digits. """ freqs = np.zeros(pow(10,n), dtype='i4') current = np.zeros(n, dtype=int) for i in range(n): current[i] = digits.next() for d in...
def plot_two_digit_freqs(f2): """ Plot two digits frequency counts using matplotlib. """ f2_copy = f2.copy() f2_copy.shape = (10,10) ax = plt.matshow(f2_copy) plt.colorbar() for i in range(10): for j in range(10): plt.text(i-0.2, j+0.2, str(j)+str(i)) plt.ylabel('...
def plot_one_digit_freqs(f1): """ Plot one digit frequency counts using matplotlib. """ ax = plt.plot(f1,'bo-') plt.title('Single digit counts in pi') plt.xlabel('Digit') plt.ylabel('Count') return ax
def __extend_uri(self, short): """ Extend a prefixed uri with the help of a specific dictionary of prefixes :param short: Prefixed uri to be extended :return: """ if short == 'a': return RDF.type for prefix in sorted(self.__prefixes, key=lambda x: len(...
def get_object_or_none(qs, *args, **kwargs): """ Try to retrieve a model, and return None if it is not found. Useful if you do not want to bother with the try/except block. """ try: return qs.get(*args, **kwargs) except models.ObjectDoesNotExist: return None
def extract_vars(*names,**kw): """Extract a set of variables by name from another frame. :Parameters: - `*names`: strings One or more variable names which will be extracted from the caller's frame. :Keywords: - `depth`: integer (0) How many frames in the stack to walk when ...
def extract_vars_above(*names): """Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names are exctracted exactly from above the caller. This is simply a convenience function so that the very common case (for us) of skipping e...
def debugx(expr,pre_msg=''): """Print the value of an expression from the caller's frame. Takes an expression, evaluates it in the caller's frame and prints both the given expression and the resulting value (as well as a debug mark indicating the name of the calling function. The input must be of a fo...
def extract_module_locals(depth=0): """Returns (module, locals) of the funciton `depth` frames away from the caller""" f = sys._getframe(depth + 1) global_ns = f.f_globals module = sys.modules[global_ns['__name__']] return (module, f.f_locals)
def reverse(view, *args, **kwargs): ''' User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse` as `args` and `kwargs` arguments, respectively. The special optional keyword argument `query` is a dictionary of query (or GET) parameters that can be appended to the `reverse`d URL. Example...
def is_private(prefix, base): """prefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (a...
def _extract_future_flags(globs): """ Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). """ flags = 0 for fname in __future__.all_feature_names: feature = globs.get(fname, None) if feature is getattr(__future__...
def _normalize_module(module, depth=2): """ Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. ...
def _exception_traceback(exc_info): """ Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). """ # Get a traceback message. excout = StringIO() exc_type, exc_val, exc_tb = exc_info traceback.print_exception(exc_type, exc_val, exc_tb...
def run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0): """ Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is...
def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative...
def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" testsrc = script_from_examples(src) debug_script(testsrc, pm, globs)
def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb # Note that tempfile.NameTemporaryFile() cannot be used. As the # docs say, a file so created cannot be opened by name a second time # on modern Windows boxes, and execfile() needs to ...
def debug(module, name, pm=False): """Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. """ module = _normalize_module(module) te...
def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, ...
def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. ""...
def hset(self, hashroot, key, value): """ hashed set """ hroot = self.root / hashroot if not hroot.isdir(): hroot.makedirs() hfile = hroot / gethashfile(key) d = self.get(hfile, {}) d.update( {key : value}) self[hfile] = d
def hdict(self, hashroot): """ Get all data contained in hashed category 'hashroot' as dict """ hfiles = self.keys(hashroot + "/*") hfiles.sort() last = len(hfiles) and hfiles[-1] or '' if last.endswith('xx'): # print "using xx" hfiles = [last] + hfiles[:-...
def hcompress(self, hashroot): """ Compress category 'hashroot', so hset is fast again hget will fail if fast_only is True for compressed items (that were hset before hcompress). """ hfiles = self.keys(hashroot + "/*") all = {} for f in hfiles: # pri...
def keys(self, globpat = None): """ All keys in DB, or all keys matching a glob""" if globpat is None: files = self.root.walkfiles() else: files = [Path(p) for p in glob.glob(self.root/globpat)] return [self._normalized(p) for p in files if p.isfile()]
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype in( QtCore.QEvent.KeyPress, QtCore.QEvent.FocusOut ): s...
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ if not items : return self.cancel_completion() strng = text.columnize(items) self._console_widget._fill_temporary_buffer(cu...
def allow(self, record): """returns whether this record should be printed""" if not self: # nothing to filter return True return self._allow(record) and not self._deny(record)
def _any_match(matchers, record): """return the bool of whether `record` starts with any item in `matchers`""" def record_matches_key(key): return record == key or record.startswith(key + '.') return anyp(bool, map(record_matches_key, matchers))
def options(self, parser, env): """Register commandline options. """ parser.add_option( "--nologcapture", action="store_false", default=not env.get(self.env_opt), dest="logcapture", help="Disable logging capture plugin. " "Logging configurtion...
def configure(self, options, conf): """Configure plugin. """ self.conf = conf # Disable if explicitly disabled, or if logging is # configured via logging config file if not options.logcapture or conf.loggingConfig: self.enabled = False self.logformat =...
def formatError(self, test, err): """Add captured log messages to error output. """ # logic flow copied from Capture.formatError test.capturedLogging = records = self.formatLogRecords() if not records: return err ec, ev, tb = err return (ec, self.addCa...
def embed(**kwargs): """Call this to embed IPython at the current point in your program. The first invocation of this will create an :class:`InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. Here is a simple example:: from IPython...
def mainloop(self, local_ns=None, module=None, stack_depth=0, display_banner=None, global_ns=None): """Embeds IPython into a running python program. Input: - header: An optional header message can be specified. - local_ns, module: working local namespace (a dict) ...
def dir2(obj): """dir2(obj) -> list of strings Extended version of the Python builtin dir(), which does a few extra checks, and supports common objects with unusual internals that confuse dir(), such as Traits and PyCrust. This version is guaranteed to return only a list of true strings, whereas ...
def _get_all_po_filenames(locale_root, lang, po_files_path): """ Get all po filenames from locale folder and return list of them. Assumes a directory structure: <locale_root>/<lang>/<po_files_path>/<filename>. """ all_files = os.listdir(os.path.join(locale_root, lang, po_files_path)) return ...
def _get_new_csv_writers(trans_title, meta_title, trans_csv_path, meta_csv_path): """ Prepare new csv writers, write title rows and return them. """ trans_writer = UnicodeWriter(trans_csv_path) trans_writer.writerow(trans_title) meta_writer = UnicodeWriter(meta_csv_path...
def _prepare_locale_dirs(languages, locale_root): """ Prepare locale dirs for writing po files. Create new directories if they doesn't exist. """ trans_languages = [] for i, t in enumerate(languages): lang = t.split(':')[0] trans_languages.append(lang) lang_path = os.path...
def _prepare_polib_files(files_dict, filename, languages, locale_root, po_files_path, header): """ Prepare polib file object for writing/reading from them. Create directories and write header if needed. For each language, ensure there's a translation file named "filename" in the...
def _write_entries(po_files, languages, msgid, msgstrs, metadata, comment): """ Write msgstr for every language with all needed metadata and comment. Metadata are parser from string into dict, so read them only from gdocs. """ start = re.compile(r'^[\s]+') end = re.compile(r'[\s]+$') for i, ...
def _write_header(po_path, lang, header): """ Write header into po file for specific lang. Metadata are read from settings file. """ po_file = open(po_path, 'w') po_file.write(header + '\n') po_file.write( 'msgid ""' + '\nmsgstr ""' + '\n"MIME-Version: ' + settings.ME...
def _write_new_messages(po_file_path, trans_writer, meta_writer, msgids, msgstrs, languages): """ Write new msgids which appeared in po files with empty msgstrs values and metadata. Look for all new msgids which are diffed with msgids list provided as an argument. """ po_...
def _get_new_msgstrs(po_file_path, msgids): """ Write new msgids which appeared in po files with empty msgstrs values and metadata. Look for all new msgids which are diffed with msgids list provided as an argument. """ po_file = polib.pofile(po_file_path) msgstrs = {} for entry in po_f...
def po_to_csv_merge(languages, locale_root, po_files_path, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv): """ Converts po file to csv GDocs spreadsheet readable format. Merges them if some msgid aren't in the spreadsheet. :param languages: list...
def csv_to_po(trans_csv_path, meta_csv_path, locale_root, po_files_path, header=None): """ Converts GDocs spreadsheet generated csv file into po file. :param trans_csv_path: path to temporary file with translations :param meta_csv_path: path to temporary file with meta information :par...
def subscribe_user(self, user): """ method to subscribe a user to a service """ url = self.root_url + "subscribe_user" values = {} values["username"] = user return self._query(url, values)
def send_notification(self, to=None, msg=None, label=None, title=None, uri=None): """ method to send a message to a user Parameters: to -> recipient msg -> message to send label -> application description titl...
def send_message(self, to=None, msg=None): """ method to send a message to a user Parameters: to -> recipient msg -> message to send """ url = self.root_url + "send_message" values = {} if to is not None: values["to"] = to ...
def _query(self, url, data = None): """ query method to do HTTP POST/GET Parameters: url -> the url to POST/GET data -> header_data as a dict (only for POST) Returns: Parsed JSON data as dict or None on err...
def init_parser(): """ function to init option parser """ usage = "usage: %prog -u user -s secret -n name [-l label] \ [-t title] [-c callback] [TEXT]" parser = OptionParser(usage, version="%prog " + notifo.__version__) parser.add_option("-u", "--user", action="store", dest="user", ...
def main(): """ main function """ # get options and arguments (parser, options, args) = init_parser() # initialize result variable result = None # check for values which are always needed if not options.user: parser.error("No user given.") if not options.secret: parser....
def rsplit1(s, sep): """The same as s.rsplit(sep, 1), but works in 2.3""" parts = s.split(sep) return sep.join(parts[:-1]), parts[-1]
def run_python_module(modulename, args): """Run a python module, as though with ``python -m name args...``. `modulename` is the name of the module, possibly a dot-separated name. `args` is the argument array to present as sys.argv, including the first element naming the module being executed. """ ...
def run_python_file(filename, args, package=None): """Run a python file as if it were the main program on the command line. `filename` is the path to the file to execute, it need not be a .py file. `args` is the argument array to present as sys.argv, including the first element naming the file being ex...
def make_code_from_py(filename): """Get source from `filename` and make a code object of it.""" # Open the source file. try: source_file = open_source(filename) except IOError: raise NoSource("No file to run: %r" % filename) try: source = source_file.read() finally: ...
def make_code_from_pyc(filename): """Get a code object from a .pyc file.""" try: fpyc = open(filename, "rb") except IOError: raise NoCode("No file to run: %r" % filename) try: # First four bytes are a version-specific magic number. It has to # match or we won't run the ...
def html_tableify(item_matrix, select=None, header=None , footer=None) : """ returnr a string for an html table""" if not item_matrix : return '' html_cols = [] tds = lambda text : u'<td>'+text+u' </td>' trs = lambda text : u'<tr>'+text+u'</tr>' tds_items = [map(tds, row) for row in ite...
def current(self, value): """set current cursor position""" current = min(max(self._min, value), self._max) self._current = current if current > self._stop : self._stop = current self._start = current-self._width elif current < self._start : ...
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() ...
def cancel_completion(self): """Cancel the completion should be called when the completer have to be dismissed This reset internal variable, clearing the temporary buffer of the console where the completion are shown. """ self._consecutive_tab = 0 self._slice_st...
def _select_index(self, row, col): """Change the selection index, and make sure it stays in the right range A little more complicated than just dooing modulo the number of row columns to be sure to cycle through all element. horizontaly, the element are maped like this : to r <...
def select_up(self): """move cursor up""" r, c = self._index self._select_index(r-1, c)
def select_down(self): """move cursor down""" r, c = self._index self._select_index(r+1, c)
def select_left(self): """move cursor left""" r, c = self._index self._select_index(r, c-1)
def select_right(self): """move cursor right""" r, c = self._index self._select_index(r, c+1)
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ if not items : return self._start_position = cursor.position() self._consecutive_tab = 1 items_m, ci = text.compute_item_ma...
def _update_list(self, hilight=True): """ update the list of completion and hilight the currently selected completion """ self._sliding_interval.current = self._index[0] head = None foot = None if self._sliding_interval.start > 0 : head = '...' if self._slid...
def _complete_current(self): """ Perform the completion with the currently selected item. """ i = self._index item = self._items[i[0]][i[1]] item = item.strip() if item : self._current_text_cursor().insertText(item) self.cancel_completion()
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return fre...
def print_wordfreq(freqs, n=10): """Print the n most common words and counts in the freqs dict.""" words, counts = freqs.keys(), freqs.values() items = zip(counts, words) items.sort(reverse=True) for (count, word) in items[:n]: print(word, count)
def tostring(self): """Return the string representation of the job description XML.""" root = self.as_element() indent(root) txt = ET.tostring(root, encoding="utf-8") # Now remove the tokens used to order the attributes. txt = re.sub(r'_[A-Z]_','',txt) txt = '<?xm...
def write(self, filename): """Write the XML job description to a file.""" txt = self.tostring() with open(filename, 'w') as f: f.write(txt)
def validate_pin(pin): """ Validate the given pin against the schema. :param dict pin: The pin to validate: :raises pypebbleapi.schemas.DocumentError: If the pin is not valid. """ v = _Validator(schemas.pin) if v.validate(pin): return else: raise schemas.DocumentError(errors...
def send_shared_pin(self, topics, pin, skip_validation=False): """ Send a shared pin for the given topics. :param list topics: The list of topics. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentE...
def delete_shared_pin(self, pin_id): """ Delete a shared pin. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not self.api_key: raise ValueError("You need to specify an api_key.") ...
def send_user_pin(self, user_token, pin, skip_validation=False): """ Send a user pin. :param str user_token: The token of the user. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the va...
def delete_user_pin(self, user_token, pin_id): """ Delete a user pin. :param str user_token: The token of the user. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('DELET...
def subscribe(self, user_token, topic): """ Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('POST', ...
def list_subscriptions(self, user_token): """ Get the list of the topics which a user is subscribed to. :param str user_token: The token of the user. :return: The list of the topics. :rtype: list :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. ...
def monitored(total: int, name=None, message=None): """ Decorate a function to automatically begin and end a task on the progressmonitor. The function must have a parameter called 'monitor' """ def decorator(f): nonlocal name monitor_index = list(inspect.signature(f).parameters.keys(...