text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _add_fluent_indexes(self):
"""
Add the index commands fluently specified on columns:
"""
for column in self._columns:
for index in ['primary', 'unique', 'index']:
column_index = column.get(index)
if column_index is True:
... | 0.003906 |
def object_build_class(node, member, localname):
"""create astroid for a living class object"""
basenames = [base.__name__ for base in member.__bases__]
return _base_class_object_build(node, member, basenames, localname=localname) | 0.008264 |
def add(self, doc):
"""Add a doc's annotations to the binder for serialization."""
array = doc.to_array(self.attrs)
if len(array.shape) == 1:
array = array.reshape((array.shape[0], 1))
self.tokens.append(array)
spaces = doc.to_array(SPACY)
assert array.shape[0... | 0.00396 |
def _serial_connect(self, port, request):
'''
Handle connection request.
Parameters
----------
port : str
Device name/port.
request : dict
'''
# baudrate : int
# Baud rate such as 9600 or 115200 etc.
# bytesize ... | 0.001677 |
def registered_aliases(self):
"""Return the registered aliases exposed in BUILD files.
These returned aliases aren't so useful for actually parsing BUILD files.
They are useful for generating things like http://pantsbuild.github.io/build_dictionary.html.
:returns: A new BuildFileAliases instance conta... | 0.004762 |
def measure_torsion_angles(residues):
"""Calculates the dihedral angles for a list of backbone atoms.
Parameters
----------
residues : [ampal.Residue]
List of `Residue` objects.
Returns
-------
torsion_angles : (float, float, float)
One triple for each residue, containing t... | 0.000294 |
def make_content_node(channeldir, rel_path, filename, metadata):
"""
Create ContentNode based on the file extention and metadata provided.
"""
file_key, file_ext = os.path.splitext(filename)
ext = file_ext[1:]
kind = None
if ext in content_kinds.MAPPING:
kind = content_kinds.MAPPING[... | 0.00609 |
def start_workunit(self, workunit):
"""Implementation of Reporter callback."""
if not self.is_under_main_root(workunit):
return
label_format = self._get_label_format(workunit)
if label_format == LabelFormat.FULL:
if not WorkUnitLabel.SUPPRESS_LABEL in workunit.labels:
self._emit_in... | 0.012431 |
def get_me(self, *args, **kwargs):
"""See :func:`get_me`"""
return get_me(*args, **self._merge_overrides(**kwargs)).run() | 0.014599 |
def any(pred: Callable, xs: Iterable):
"""
Check if at least one element of the iterable `xs`
fullfills predicate `pred`.
:param pred:
predicate function.
:param xs:
iterable object.
:returns: boolean
"""
b = find_first(pred, xs)
return True if b is not None else Fals... | 0.003115 |
def partial_ratio(s1, s2):
""""Return the ratio of the most similar substring
as a number between 0 and 100."""
s1, s2 = utils.make_type_consistent(s1, s2)
if len(s1) <= len(s2):
shorter = s1
longer = s2
else:
shorter = s2
longer = s1
m = SequenceMatcher(None, s... | 0.000903 |
def gaps(args):
"""
%prog gaps A_vs_B.blast
Find distribution of gap sizes betwen adjacent HSPs.
"""
p = OptionParser(gaps.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
blastfile, = args
blast = BlastSlow(blastfile)
logging.de... | 0.004098 |
def append(self, key, value):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists."""
self.__items.append((key, value))
try:
dict_getitem(self, key).append(value)
except KeyError:
dict_setitem(self, key, [value]) | 0.006579 |
def upgradedb(options):
"""
Add 'fake' data migrations for existing tables from legacy GeoNode versions
"""
version = options.get('version')
if version in ['1.1', '1.2']:
sh("python manage.py migrate maps 0001 --fake")
sh("python manage.py migrate avatar 0001 --fake")
elif versio... | 0.002146 |
def _save_feed(cls, conf, benchmarks, data, revisions, revision_to_hash):
"""
Save the results as an Atom feed
"""
filename = os.path.join(conf.html_dir, 'regressions.xml')
# Determine publication date as the date when the benchmark
# was run --- if it is missing, use t... | 0.003839 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ActivityContext for this ActivityInstance
:rtype: twilio.rest.taskrouter.v1.workspace.activity.Ac... | 0.006623 |
def tile_to_pixel(tile, centered=False):
"""Transform tile to pixel coordinates"""
pixel = [tile[0] * 256, tile[1] * 256]
if centered:
# should clip on max map size
pixel = [pix + 128 for pix in pixel]
return pixel[0], pixel[1] | 0.007067 |
def _check_ver(pyver, op, wanted):
'''
>>> _check_ver('2.7.15', 'gt', '2.7')
True
>>> _check_ver('2.7.15', 'gt', '2.7.15')
False
>>> _check_ver('2.7.15', 'ge', '2.7.15')
True
>>> _check_ver('2.7.15', 'eq', '2.7.15')
True
'''
pyver = distutils.version.LooseVersion(pyver)
w... | 0.00232 |
def register_module_classes(yaml: ruamel.yaml.YAML, modules: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML:
""" Register all classes in the given modules with the YAML object.
This is a simple helper function.
"""
# Validation
if modules is None:
modules = []
# Extract the classe... | 0.01072 |
def insertOutputModuleConfig(self, remoteConfig, migration=False):
"""
Insert Release version, application, parameter set hashes and the map(output module config).
"""
otptIdList = []
missingList = []
conn = self.dbi.connection()
try:
for c in remoteC... | 0.016425 |
def load_remote_trajectory(url, format=None):
'''Load a trajectory file from a remote location specified by *url*.
.. seealso:: load_remote_system
'''
from urllib import urlretrieve
filename, headers = urlretrieve(url)
load_trajectory(filename, format) | 0.007092 |
def LSR(value, amount, width):
"""
The ARM LSR (logical shift right) operation.
:param value: Value to shift
:type value: int or long or BitVec
:param int amount: How many bits to shift it.
:param int width: Width of the value
:return: Resultant value
:rtype int or BitVec
"""
if... | 0.002404 |
def get_chromosomes(snps):
""" Get the chromosomes of SNPs.
Parameters
----------
snps : pandas.DataFrame
Returns
-------
list
list of str chromosomes (e.g., ['1', '2', '3', 'MT'], empty list if no chromosomes
"""
if isinstance(snps, pd.DataFrame):
return list(pd.u... | 0.00542 |
def Download(campaign=0, queue='build', email=None, walltime=8, **kwargs):
'''
Submits a cluster job to the build queue to download all TPFs for a given
campaign.
:param int campaign: The `K2` campaign to run
:param str queue: The name of the queue to submit to. Default `build`
:param str email... | 0.000646 |
def query_by_tag(cat_id, kind='1'):
'''
Query recent posts of catalog.
'''
return TabPost.select().join(
TabPost2Tag,
on=(TabPost.uid == TabPost2Tag.post_id)
).where(
(TabPost.kind == kind) &
(TabPost2Tag.tag_id == cat_id)
... | 0.005263 |
def leaveEvent( self, event ):
"""
Toggles the display for the tracker item.
"""
item = self.trackerItem()
if ( item ):
item.setVisible(False) | 0.03 |
def get_from_sources(self, index, doc_type, document_id):
"""Get source stored locally"""
return self.sources.get(index, {}).get(doc_type, {}).get(document_id, {}) | 0.01676 |
def set_ssl_logging(self, enable=False, func=_ssl_logging_cb):
u''' Enable or disable SSL logging
:param True | False enable: Enable or disable SSL logging
:param func: Callback function for logging
'''
if enable:
SSL_CTX_set_info_callback(self._ctx, func)
el... | 0.005333 |
def record(self):
# type: () -> bytes
'''
A method to generate the string representing this UDF NSR Volume
Structure.
Parameters:
None.
Returns:
A string representing this UDF BEA Volume Strucutre.
'''
if not self._initialized:
... | 0.008163 |
def intervals_to_fragment_list(self, text_file, time_values):
"""
Transform a list of at least 4 time values
(corresponding to at least 3 intervals)
into a sync map fragment list and store it internally.
The first interval is a HEAD, the last is a TAIL.
For example:
... | 0.002545 |
def _convert_date(self, date):
"""Convert '106/05/01' to '2017/05/01'"""
return '/'.join([str(int(date.split('/')[0]) + 1911)] + date.split('/')[1:]) | 0.018182 |
def flush_ct_inventory(self):
"""internal method used only if ct_inventory is enabled
"""
if hasattr(self, '_ct_inventory'):
# skip self from update
self._ct_inventory = None
self.update_view = False
self.save() | 0.007042 |
def build_plane_arrays(x, y, qlist):
"""Build a 2-D array out of data taken in the same plane, for contour
plotting.
"""
if type(qlist) is not list:
return_list = False
qlist = [qlist]
else:
return_list = True
xv = x[np.where(y==y[0])[0]]
yv = y[np.where(x==... | 0.007576 |
def display(self):
"""A unicode value with the object's data, to be used for displaying
the object in your application."""
if self.title and self.organization:
disp = self.title + u' at ' + self.organization
else:
disp = self.title or self.organization or N... | 0.004739 |
def split_sequence_file_on_sample_ids_to_files(seqs,
outdir):
"""Split FASTA file on sample IDs.
Parameters
----------
seqs: file handler
file handler to demultiplexed FASTA file
outdir: string
dirpath to output split FASTA files
""... | 0.00114 |
def getlist(self, key, default=[]):
"""
Returns: The list of values for <key> if <key> is in the dictionary,
else <default>. If <default> is not provided, an empty list is
returned.
"""
if key in self:
return [node.value for node in self._map[key]]
ret... | 0.006042 |
def _include_pretrained_vocab(self, pretrained_word_dict, candidates):
"""
Include terms available via pretrained embeddings
:param pretrained_word_dict:
:param candidates:
:return:
"""
terms = Counter()
for c in candidates:
for w in c.get_pa... | 0.004367 |
def _guess_lines(ys, max_lines=50, confidence_minimum=0.0):
"""guesses and returns text inter-line distance, number of lines, y_position of first line"""
ys = ys.astype(numpy.float32)
compactness_list, means_list, diffs, deviations = [], [], [], []
start_n = 1
for k in range(star... | 0.006594 |
def from_dict(data, ctx):
"""
Instantiate a new HomeConversions from a dict (generally from loading a
JSON response). The data used to instantiate the HomeConversions is a
shallow copy of the dict passed in, with any complex child types
instantiated appropriately.
"""
... | 0.00226 |
def get_move_data(move):
"""Return the index number for the given move name. Check moves.json in the same directory."""
srcpath = path.dirname(__file__)
try:
f = open(path.join(srcpath, 'moves.json'), 'r')
except IOError:
get_moves()
f = open(path.join(srcpath, 'moves.json'), 'r'... | 0.005155 |
def finish(self):
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super(InterruptibleMixin, self).finish()
signal(SIGINT, self.original_handler) | 0.006329 |
def get_user(self):
"""Get the user informations from the server.
:return: a dict with all the informations
:rtype: dict
raises ValueError in case of protocol issues
:Example:
>>> "creationTime": <time>,
>>> "lastUpdateTime": <time>,
>>> "userId": "<em... | 0.001553 |
def dataset_initialize(self, folder):
""" initialize a folder with a a dataset configuration (metadata) file
Parameters
==========
folder: the folder to initialize the metadata file in
"""
if not os.path.isdir(folder):
raise ValueError('Invalid fo... | 0.00222 |
def new_stats_exporter(options=None, interval=None):
"""Get a stats exporter and running transport thread.
Create a new `StackdriverStatsExporter` with the given options and start
periodically exporting stats to stackdriver in the background.
Fall back to default auth if `options` is null. This will r... | 0.000758 |
def status(self):
"""
check the status of the network and the peers
:return: network_height, peer_status
"""
peer = random.choice(self.PEERS)
formatted_peer = 'http://{}:4001'.format(peer)
peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers'... | 0.003517 |
def addthisbunch(bunchdt, data, commdct, thisbunch, theidf):
"""add a bunch to model.
abunch usually comes from another idf file
or it can be used to copy within the idf file"""
key = thisbunch.key.upper()
obj = copy.copy(thisbunch.obj)
abunch = obj2bunch(data, commdct, obj)
bunchdt[key].app... | 0.002865 |
def ein(self):
"""Generate a random United States Employer Identification Number (EIN).
An United States An Employer Identification Number (EIN) is
also known as a Federal Tax Identification Number, and is
used to identify a business entity. EINs follow a format of a
two-dig... | 0.00125 |
def discover_yaml(bank=None, **meta):
"""Discovers the YAML format and registers it if available.
Install YAML support via PIP::
pip install PyYAML
:param bank: The format bank to register the format in
:param meta: Extra information associated with the format
"""
try:
import ... | 0.002092 |
def abspath(*path):
"""A method to determine absolute path for a given relative path to the
directory where this setup.py script is located"""
setup_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(setup_dir, *path) | 0.003984 |
def inasafe_place_value_name(number, feature, parent):
"""Given a number, it will return the place value name.
For instance:
* inasafe_place_value_name(10) -> Ten \n
* inasafe_place_value_name(1700) -> Thousand
It needs to be used with inasafe_place_value_coefficient.
"""
_ = feature, pa... | 0.00158 |
def dashboard(self, request):
"Basic dashboard panel"
# TODO: these should be ajax
module_set = []
for namespace, module in self.get_modules():
home_url = module.get_home_url(request)
if hasattr(module, 'render_on_dashboard'):
# Show by default, u... | 0.005908 |
def sv_variants(store, institute_obj, case_obj, variants_query, page=1, per_page=50):
"""Pre-process list of SV variants."""
skip_count = (per_page * max(page - 1, 0))
more_variants = True if variants_query.count() > (skip_count + per_page) else False
genome_build = case_obj.get('genome_build', '37')
... | 0.007874 |
def set_exception(self, exception):
"""Sets the exception on the future."""
if not self.done():
raise TransferNotDoneError(
'set_exception can only be called once the transfer is '
'complete.')
self._coordinator.set_exception(exception, override=True) | 0.00627 |
def zSetSurfaceData(self, surfNum, radius=None, thick=None, material=None, semidia=None,
conic=None, comment=None):
"""Sets surface data"""
if self.pMode == 0: # Sequential mode
surf = self.pLDE.GetSurfaceAt(surfNum)
if radius is not None:
... | 0.008475 |
def get_sampletypes(self):
"""Returns the available SampleTypes of the system
"""
query = {
"portal_type": "SampleType",
"sort_on": "sortable_title",
"sort_order": "ascending",
"is_active": True,
}
results = api.search(query, "bika_... | 0.005277 |
def parse_list_line_windows(self, b):
"""
Parsing Microsoft Windows `dir` output
:param b: response line
:type b: :py:class:`bytes` or :py:class:`str`
:return: (path, info)
:rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`)
"""
line = b.decode... | 0.001335 |
def epcrparse(self):
"""
Run BLAST, and record results to the object
"""
from Bio.Blast.Applications import NcbiblastnCommandline
while True:
sample, record, line = self.epcrparsequeue.get()
# Split the data on tabs
gene, chromosome, strand, st... | 0.004042 |
def _BuildQuery(self,
subject,
attribute=None,
timestamp=None,
limit=None,
is_prefix=False):
"""Build the SELECT query to be executed."""
args = []
subject = utils.SmartUnicode(subject)
criteria = "WHERE aff4.subje... | 0.009554 |
def _parse_file(self):
"""Preprocess and parse C file into an AST"""
# We need to set the CPU type to pull in the right register definitions
# only preprocess the file (-E) and get rid of gcc extensions that aren't
# supported in ISO C.
args = utilities.build_includes(self.arch.... | 0.006579 |
def get_layergroup(self, name, workspace=None):
'''
returns a single layergroup object.
Will return None if no layergroup is found.
Will raise an error if more than one layergroup with the same name is found.
'''
layergroups = self.get_layergroups(names=name, works... | 0.007732 |
def get_document_field_display(self, field_name, field):
""" Render a link to a document """
document = getattr(self.instance, field_name)
if document:
return mark_safe(
'<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % (
document.url,
... | 0.00363 |
def read_table(self):
"""
Read an AMQP table, and return as a Python dictionary.
Will raise BufferUnderflow if there's not enough bytes in the buffer.
Will raise UnicodeDecodeError if the text is mal-formed.
Will raise struct.error if the data is malformed
"""
# ... | 0.003155 |
def add_effect(self, effect):
"""
Add an Effect to the Frame.
:param effect: The Effect to be added.
"""
effect.register_scene(self._scene)
self._effects.append(effect) | 0.009217 |
def compute_pblum_scale(self, dataset, pblum, **kwargs):
"""
intensities should already be computed for this dataset at the time for which pblum is being provided
TODO: add documentation
"""
logger.debug("{}.compute_pblum_scale(dataset={}, pblum={})".format(self.component, datas... | 0.00625 |
def parse(schema):
"""
Parse `schema`, either a string or a file-like object, and
return a :class:`MessageRegistry` with the loaded messages.
"""
if not isinstance(schema, basestring):
# assume it is file-like
schema = schema.read()
message = re.compile(r'^\(([^,]+),\s*(\d+)\):\... | 0.000582 |
def report_exception(self, http_context=None, user=None):
""" Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
... | 0.001631 |
def merge(into, d):
"""merge two containers
into is updated, d has priority
"""
if isinstance(into, dict):
for key in d.keys():
if key not in into:
into[key] = d[key]
else:
into[key] = merge(into[key], d[key])
return into
e... | 0.005025 |
def draw(board, term, cells):
"""Draw a board to the terminal."""
for (x, y), state in board.iteritems():
with term.location(x, y):
print cells[state], | 0.005587 |
def glob_all(folder: str, filt: str) -> List[str]:
"""Recursive glob"""
import os
import fnmatch
matches = []
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, filt):
matches.append(os.path.join(root, filename))
return matches | 0.003205 |
def get_sorted_nts_omit_section(self, hdrgo_prt, hdrgo_sort):
"""Return a flat list of sections (wo/section names) with GO terms grouped and sorted."""
nts_flat = []
# print("SSSS SorterNts:get_sorted_nts_omit_section(hdrgo_prt={}, hdrgo_sort={})".format(
# hdrgo_prt, hdrgo_sort))
... | 0.008929 |
def _get_distance_segment_coefficients(self, rval):
"""
Returns the coefficients describing the distance attenuation shape
for three different distance bins, equations 12a - 12c
"""
# Get distance segment ends
nsites = len(rval)
# Equation 12a
f_0 = np.log... | 0.003035 |
def find_focusable(node):
"""
Search for the first focusable window within the node tree
"""
if not node.children:
return node
if node.focus:
return find_focusable(node.children_dict[node.focus[0]]) | 0.004237 |
def reformat(self, dtstring, before, after):
"""Edit the time string format.
See https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
for all format string options.
**中文文档**
将datetime string从一种格式转换成另一种格式。
"""
a_... | 0.014354 |
def FromBinary(cls, record_data, record_count=1):
"""Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a SetGraphOnlineRecord.
Args:
record_data (bytearr... | 0.004608 |
def set_log_level(self):
"""
Set log level according to command-line options
@returns: logger object
"""
if self.options.debug:
self.logger.setLevel(logging.DEBUG)
elif self.options.quiet:
self.logger.setLevel(logging.ERROR)
else:
... | 0.004525 |
def next(self):
"""Trigger next agent to :py:meth:`~creamas.core.CreativeAgent.act` in
the current step.
"""
# all agents acted, init next step
t = time.time()
if len(self._agents_to_act) == 0:
self._init_step()
addr = self._agents_to_act.pop(0)
... | 0.003515 |
def tcache(parser, token):
"""
This will cache the contents of a template fragment for a given amount
of time with support tags.
Usage::
{% tcache [expire_time] [fragment_name] [tags='tag1,tag2'] %}
.. some expensive processing ..
{% endtcache %}
This tag also supports ... | 0.003428 |
def merge(self, other_tc):
"""
Return the top-left ``<w:tc>`` element of a new span formed by
merging the rectangular region defined by using this tc element and
*other_tc* as diagonal corners.
"""
top, left, height, width = self._span_dimensions(other_tc)
top_tc ... | 0.004706 |
def unbroadcast(a, b):
'''
unbroadcast(a, b) yields a tuple (aa, bb) that is equivalent to (a, b) except that aa and bb
have been reshaped such that arithmetic numpy operations such as aa * bb will result in
row-wise operation instead of column-wise broadcasting.
'''
# they could be sparse:
... | 0.017161 |
def iterRun(self, sqlTail = '', raw = False) :
"""Compile filters and run the query and returns an iterator. This much more efficient for large data sets but
you get the results one element at a time. One thing to keep in mind is that this function keeps the cursor open, that means that the sqlite databae is locked... | 0.03198 |
def add_path_with_storage_account(self, remote_path, storage_account):
# type: (SourcePath, str, str) -> None
"""Add a path with an associated storage account
:param SourcePath self: this
:param str remote_path: remote path
:param str storage_account: storage account to associate... | 0.004792 |
def _create_embedded_indices(self):
'''
Create indices for all the embedded structs. For parser internal use.
'''
try:
self._target._embedded_indices.update(((k,(self,v)) for k,v in getattr(self._parser.typedef, 'inline_names', {}).items()))
except AttributeError:
... | 0.018018 |
def __add_tier(self, tier, token_tier_name):
"""
adds a tier to the document graph (either as additional attributes
to the token nodes or as a span node with outgoing edges to the token
nodes it represents)
"""
if tier.attrib['category'] == token_tier_name:
se... | 0.003817 |
def unbind(self, *args):
"""Unsubscribes from events or :class:`~pydispatch.properties.Property` updates
Multiple arguments can be given. Each of which can be either the method
that was used for the original call to :meth:`bind` or an instance
object.
If an instance of an objec... | 0.00597 |
def accumulator(init, update):
"""
Generic accumulator function.
.. code-block:: python
# Simplest Form
>>> a = 'this' + ' '
>>> b = 'that'
>>> c = functools.reduce(accumulator, a, b)
>>> c
'this that'
# The type of the initial value determines outp... | 0.003008 |
def handshake_timed_out(self):
"""
Checks if the handshake has timed out.
If `start_handshake` wasn't called before the call to this function,
the return value will always be `False`. If the handshake completed
before a timeout was reached, the return value will be `False`
... | 0.003731 |
def get_action(self):
"""Returns the action to be taken from the request. Returns None if no
action is found
"""
action = self.request.get("workflow_action_id", None)
action = self.request.get("workflow_action", action)
if not action:
return None
# A ... | 0.003315 |
def ceil(x, context=None):
"""
Return the next higher or equal integer to x.
If the result is not exactly representable, it will be rounded according to
the current context. Note that the rounding step means that it's possible
for the result to be smaller than ``x``. For example::
>>> x ... | 0.000973 |
def _relevant_checkers(self, path):
"""
Get set of checkers for the given path.
TODO: currently this is based off the file extension. We would like to
honor magic bits as well, so that python binaries, shell scripts, etc
but we're not guaranteed that `path` currently exists on ... | 0.003788 |
def authenticate(self):
"""Authenticate user by any means and return either true or false.
Args:
Returns:
tuple (is_valid, username): True is valid user, False if not
"""
basic_auth = request.authorization
is_valid = False
user = None
if basi... | 0.001852 |
def bulk_update(object_list, ignore_errors=False, delete_first=False, verbosity=0):
'''Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list.
Returns any delta in the number of rows in the database table that resulted from the update.
If nonze... | 0.003956 |
def run(cmd, output_fpath=None, input_fpath=None, checks=None, stdout_to_outputfile=True,
stdout_tx=True, reuse=False, env_vars=None):
"""Run the provided command, logging details and checking for errors.
"""
if output_fpath and reuse:
if verify_file(output_fpath, silent=True):
i... | 0.004891 |
def externals_finder(dirname, filename):
"""Find any 'svn:externals' directories"""
found = False
f = open(filename,'rt')
for line in iter(f.readline, ''): # can't use direct iter!
parts = line.split()
if len(parts)==2:
kind,length = parts
data = f.read(int(len... | 0.010542 |
def select(self, *args, **kwargs):
"""Python3 raises `ValueError` if socket is closed, because fd == -1"""
try:
return super(PatroniSequentialThreadingHandler, self).select(*args, **kwargs)
except ValueError as e:
raise select.error(9, str(e)) | 0.010309 |
def process_edge_flow(self, source, sink, i, j, algo, q):
'''
API: process_edge_flow(self, source, sink, i, j, algo, q)
Description:
Used by by max_flow_preflowpush() method. Processes edges along
prefolow push.
Input:
source: Source node name of flow graph.
... | 0.001928 |
def usage(self, subcommand):
"""
Returns *how to use command* text.
"""
usage = ' '.join(['%prog', subcommand, '[options]'])
if self.args:
usage = '%s %s' % (usage, str(self.args))
return usage | 0.007905 |
def long2ip(l):
"""Convert a network byte order 32-bit integer to a dotted quad ip
address.
>>> long2ip(2130706433)
'127.0.0.1'
>>> long2ip(MIN_IP)
'0.0.0.0'
>>> long2ip(MAX_IP)
'255.255.255.255'
>>> long2ip(None) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call l... | 0.001514 |
def prune_urls(url_set, start_url, allowed_list, ignored_list):
"""Prunes URLs that should be ignored."""
result = set()
for url in url_set:
allowed = False
for allow_url in allowed_list:
if url.startswith(allow_url):
allowed = True
break
... | 0.001372 |
def clean_traceback(tb):
'''Fixes up the traceback to remove the from the file paths the part
preceeding the project root.
@param tb: C{str}
@rtype: C{str}'''
prefix = __file__[:__file__.find("feat/common/error.py")]
regex = re.compile("(\s*File\s*\")(%s)([a-zA-Z-_\. \\/]*)(\".*)"
... | 0.006861 |
def page_factory(request):
""" Page factory.
Config models example:
.. code-block:: python
models = {
'': [WebPage, CatalogResource],
'catalogue': CatalogResource,
'news': NewsResource,
}
"""
prefix = request.matchdict['prefix'] # /{prefix}/pag... | 0.000524 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.