text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def json_serial(obj):
"""
Custom JSON serializer for objects not serializable by default.
"""
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
raise TypeError('Type {} not serializable.'.format(type(obj))) | 0.00692 |
def build_module(
name, source=None, *, sources=None, preprocess=None, output=None, output_dir='.',
build_dir='build', include_dirs=None, library_dirs=None, libraries=None, macros=None,
compiler_preargs=None, compiler_postargs=None, linker_preargs=None, linker_postargs=None, cache=True):
''... | 0.001779 |
def _get_prog_memory(resources, cores_per_job):
"""Get expected memory usage, in Gb per core, for a program from resource specification.
"""
out = None
for jvm_opt in resources.get("jvm_opts", []):
if jvm_opt.startswith("-Xmx"):
out = _str_memory_to_gb(jvm_opt[4:])
memory = resou... | 0.004255 |
def add_marker(self, marker):
"""
Adds the marker to the panel.
:param marker: Marker to add
:type marker: pyqode.core.modes.Marker
"""
self._markers.append(marker)
doc = self.editor.document()
assert isinstance(doc, QtGui.QTextDocument)
block = d... | 0.00312 |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._target_url is not None:
return False
if self._category is not None:
return False
if self._event_type is not None:
return False
if self._object_ is not None:
... | 0.005602 |
def newton_refine2(s_vals, curve1, curve2):
"""Image for :func:`.newton_refine` docstring."""
if NO_IMAGES:
return
ax = curve1.plot(256)
ax.lines[-1].zorder = 1
curve2.plot(256, ax=ax)
ax.lines[-1].zorder = 1
points = curve1.evaluate_multi(np.asfortranarray(s_vals))
colors = sea... | 0.00177 |
def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... | 0.003454 |
def namify(root_uri):
'''Turns a root uri into a less noisy representation that will probably
make sense in most circumstances. Used by Navigator's __repr__, but can be
overridden if the Navigator is created with a 'name' parameter.'''
root_uri = unidecode.unidecode(decode(unquote(root_uri), 'utf-8'))
... | 0.001183 |
def config_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Process a role that references the target nodes created by the
``lsst-config-topic`` directive.
Parameters
----------
name
The role name used in the document.
rawtext
Th... | 0.001011 |
def set_servo_angle(self, goalangle, goaltime, led):
""" Sets the servo angle (in degrees)
Enable torque using torque_on function before calling this
Args:
goalangle (int): The desired angle in degrees, range -150 to 150
goaltime (int): the time taken to move from prese... | 0.003645 |
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... | 0.001149 |
def process_mgi_note_allele_view(self, limit=None):
"""
These are the descriptive notes about the alleles.
Note that these notes have embedded HTML -
should we do anything about that?
:param limit:
:return:
"""
line_counter = 0
if self.test_mode:... | 0.002059 |
def get_i_text(node):
"""
Get the text for an Indicator node.
:param node: Indicator node.
:return:
"""
if node.tag != 'Indicator':
raise IOCParseError('Invalid tag: {}'.format(node.tag))
s = node.get('operator').upper()
return s | 0.006536 |
def _set_available_combinations(self):
"""
Generate all connected outputs combinations and
set the max display width while iterating.
"""
available = set()
combinations_map = {}
whitelist = None
if self.output_combinations:
whitelist = self.ou... | 0.0024 |
def processHierarchical(self):
"""Main process for hierarchical segmentation.
Returns
-------
est_idxs : list
List containing estimated times for each layer in the hierarchy
as np.arrays
est_labels : list
List containing estimated labels for ea... | 0.002247 |
def get_full_returns(self, jid, minions, timeout=None):
'''
This method starts off a watcher looking at the return data for
a specified jid, it returns all of the information for the jid
'''
# TODO: change this from ret to return... or the other way.
# Its inconsist... | 0.001383 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'feedback_id') and self.feedback_id is not None:
_dict['feedback_id'] = self.feedback_id
if hasattr(self, 'user_id') and self.user_id is not None:
_dict['user_i... | 0.002688 |
def closeGlyphsOverGSUB(gsub, glyphs):
""" Use the FontTools subsetter to perform a closure over the GSUB table
given the initial `glyphs` (set of glyph names, str). Update the set
in-place adding all the glyph names that can be reached via GSUB
substitutions from this initial set.
"""
subsetter... | 0.002463 |
def validate(self):
"""
validate the RevocationReason object
"""
if not isinstance(self.revocation_code, RevocationReasonCode):
msg = "RevocationReaonCode expected"
raise TypeError(msg)
if self.revocation_message is not None:
if not isinstance(... | 0.004587 |
def new_deploy(py_ver: PyVer, release_target: ReleaseTarget):
"""Job for deploying package to pypi"""
cache_file = f'app_{py_ver.name}.tar'
template = yaml.safe_load(f"""
machine:
image: circleci/classic:201710-02
steps:
- attach_workspace:
at: {cache_dir}
- checkout
... | 0.001269 |
def find_asts(self, ast_root, name):
'''
Finds an AST node with the given name and the entire subtree under it.
A function borrowed from scottfrazer. Thank you Scott Frazer!
:param ast_root: The WDL AST. The whole thing generally, but really
any portion that y... | 0.002125 |
def _cf_dictionary_from_tuples(tuples):
"""
Given a list of Python tuples, create an associated CFDictionary.
"""
dictionary_size = len(tuples)
# We need to get the dictionary keys and values out in the same order.
keys = (t[0] for t in tuples)
values = (t[1] for t in tuples)
cf_keys = ... | 0.00141 |
def blast_seqs(seqs,
blast_constructor,
blast_db=None,
blast_mat_root=None,
params={},
add_seq_names=True,
out_filename=None,
WorkingDir=None,
SuppressStderr=None,
Sup... | 0.006774 |
def check_courses(self, kcdms):
"""
检查课程是否被选
@structure [bool]
:param kcdms: 课程代码列表
:return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False
"""
selected_courses = self.get_selected_courses()
selected_kcdms = {course['课程代码'] for course in selected_courses}
re... | 0.004878 |
def _resolve_hostname(name):
"""Returns resolved hostname using the ssh config"""
if env.ssh_config is None:
return name
elif not os.path.exists(os.path.join("nodes", name + ".json")):
resolved_name = env.ssh_config.lookup(name)['hostname']
if os.path.exists(os.path.join("nodes", res... | 0.002551 |
def check_match(self, name):
"""
Check if a release version matches any of the specificed patterns.
Parameters
==========
name: str
Release name
Returns
=======
bool:
True if it matches, False otherwise.
"""
return... | 0.005348 |
def delta(f, s, d=None):
"""
Create a delta for the file `f` using the signature read from `s`. The delta
will be written to `d`. If `d` is omitted, a temporary file will be used.
This function returns the delta file `d`. All parameters must be file-like
objects.
"""
if d is None:
d ... | 0.002237 |
def create_dag_run(self, dag, session=None):
"""
This method checks whether a new DagRun needs to be created
for a DAG based on scheduling interval.
Returns DagRun if one is scheduled. Otherwise returns None.
"""
if dag.schedule_interval and conf.getboolean('scheduler', '... | 0.002581 |
def set_default(self, section, option, default_value):
"""
Set Default value for a given (section, option)
-> called when a new (section, option) is set and no default exists
"""
section = self._check_section_option(section, option)
for sec, options in self.defaults... | 0.009901 |
def _load_reports(self, report_files):
"""
Args:
report_files: list[file] reports to read in
"""
contents = []
for file_handle in report_files:
# Convert to unicode, replacing unreadable chars
contents.append(
file_handle.read()... | 0.004515 |
def encrypt_dir(self,
path,
output_path=None,
overwrite=False,
stream=True,
enable_verbose=True):
"""
Encrypt everything in a directory.
:param path: path of the dir you need to encrypt
:... | 0.004678 |
def execute_message_call(
laser_evm,
callee_address,
caller_address,
origin_address,
code,
data,
gas_limit,
gas_price,
value,
track_gas=False,
) -> Union[None, List[GlobalState]]:
"""Execute a message call transaction from all open states.
:param laser_evm:
:param ca... | 0.001451 |
def imported_member(self, node, member, name):
"""verify this is not an imported class or handle it"""
# /!\ some classes like ExtensionClass doesn't have a __module__
# attribute ! Also, this may trigger an exception on badly built module
# (see http://www.logilab.org/ticket/57299 for i... | 0.001493 |
def great_circle_Npoints(lonlat1r, lonlat2r, N):
"""
N points along the line joining lonlat1 and lonlat2
"""
ratio = np.linspace(0.0,1.0, N).reshape(-1,1)
xyz1 = lonlat2xyz(lonlat1r[0], lonlat1r[1])
xyz2 = lonlat2xyz(lonlat2r[0], lonlat2r[1])
mids = ratio * xyz2 + (1.0-ratio) * xyz1
... | 0.018987 |
def handle_existing_user(self, provider, user, access, info):
"Login user and redirect."
login(self.request, user)
return redirect(self.get_login_redirect(provider, user, access)) | 0.009852 |
def format_items(x):
"""Returns a succinct summaries of all items in a sequence as strings"""
x = np.asarray(x)
timedelta_format = 'datetime'
if np.issubdtype(x.dtype, np.timedelta64):
x = np.asarray(x, dtype='timedelta64[ns]')
day_part = (x[~pd.isnull(x)]
.astype('ti... | 0.001342 |
def set_global_tracer(value):
"""Sets the global tracer.
It is an error to pass ``None``.
:param value: the :class:`Tracer` used as global instance.
:type value: :class:`Tracer`
"""
if value is None:
raise ValueError('The global Tracer tracer cannot be None')
global tracer, is_trac... | 0.002604 |
def init(*args, **kwargs):
"""Initializes the SDK and optionally integrations.
This takes the same arguments as the client constructor.
"""
global _initial_client
client = Client(*args, **kwargs)
Hub.current.bind_client(client)
rv = _InitGuard(client)
if client is not None:
_ini... | 0.002725 |
def compute(self, base, *args, **kwargs):
'''
Returns the value of the discount.
@param base:float Computation base.
@return: Decimal
'''
return min(base, super(Discount, self).compute(base, *args, **kwargs)) | 0.007813 |
def get_available_positions(self):
"""Return a list of empty slot numbers
"""
available_positions = ["new"]
layout = self.context.getLayout()
used_positions = [int(slot["position"]) for slot in layout]
if used_positions:
used = [
pos for pos in... | 0.004167 |
def get_url(width, height, color=True):
"""
Craft the URL for a placekitten image.
By default they are in color. To retrieve a grayscale image, set
the color kwarg to False.
"""
d = dict(width=width, height=height)
return URL % d | 0.003876 |
def iteritems(self):
'''
Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs,
analagous to dict.iteritems()
'''
for i in safe_range(self.field('ma_mask') + 1):
ep = self.field('ma_table') + i
pyop_value = PyObjectPtr.from_pyobject_ptr(ep['me_va... | 0.004141 |
def safe_tag(self, tag, errors='strict'):
"""URL Encode and truncate tag to match limit (128 characters) of ThreatConnect API.
Args:
tag (string): The tag to be truncated
Returns:
(string): The truncated tag
"""
if tag is not None:
try:
... | 0.004847 |
def get_attribute(self, attribute: str) -> 'Node':
"""Returns the node representing the given attribute's value.
Use only if is_mapping() returns true.
Args:
attribute: The name of the attribute to retrieve.
Raises:
KeyError: If the attribute does not exist.
... | 0.002717 |
def boxes_intersect(box1, box2):
"""Determines if two rectangles, each input as a tuple
(xmin, xmax, ymin, ymax), intersect."""
xmin1, xmax1, ymin1, ymax1 = box1
xmin2, xmax2, ymin2, ymax2 = box2
if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \
interval_intersection_w... | 0.002475 |
def com_google_fonts_check_linegaps(ttFont):
"""Checking Vertical Metric Linegaps."""
if ttFont["hhea"].lineGap != 0:
yield WARN, Message("hhea", "hhea lineGap is not equal to 0.")
elif ttFont["OS/2"].sTypoLineGap != 0:
yield WARN, Message("OS/2", "OS/2 sTypoLineGap is not equal to 0.")
else:
yield ... | 0.013369 |
def def_coordinator(self, year):
"""Returns the coach ID for the team's DC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the DC.
"""
try:
dc_anchor = self._year_info_pq(year, 'Defensive Coordinator')('a')
... | 0.004608 |
def get_argparser(parser=None):
"""Customize a parser to get the correct options."""
parser = parser or argparse.ArgumentParser()
parser.add_argument("--host", default="0.0.0.0", help="Host listen address")
parser.add_argument("--port", "-p", default=9050, help="Listen port", type=int)
... | 0.003608 |
def str_to_datetime(ts):
"""Format a string to a datetime object.
This functions supports several date formats like YYYY-MM-DD, MM-DD-YYYY
and YY-MM-DD. When the given data is None or an empty string, the function
returns None.
:param ts: string to convert
:returns: a datetime object
:ra... | 0.001692 |
def get_node_label(self, model):
"""
Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible
"""
if model.is_proxy:
label = "(P) %s" % (model.name.title())
else:
label = "%s" % (model.name.title())
... | 0.003155 |
def do_load(self, arg):
"""Loads a saved session variables, settings and test results to the shell."""
from os import path
import json
fullpath = path.expanduser(arg)
if path.isfile(fullpath):
with open(fullpath) as f:
data = json.load(f)
... | 0.009634 |
def requests():
"""List all pending memberships, listed only for group admins."""
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 5, type=int)
memberships = Membership.query_requests(current_user, eager=True).all()
return render_template(
'invenio_groups... | 0.002257 |
def start(self):
""" Start the SSH tunnels """
if self.is_alive:
self.logger.warning('Already started!')
return
self._create_tunnels()
if not self.is_active:
self._raise(BaseSSHTunnelForwarderError,
reason='Could not establish s... | 0.002176 |
def upload(self, filename, directory=None):
"""
Upload a file ``filename`` to ``directory``
:param str filename: path to the file to upload
:param directory: destionation :class:`.Directory`, defaults to
:attribute:`.API.downloads_directory` if None
:return: the uplo... | 0.002457 |
def read_file(filename: PathLike = "experiment.yml") -> Dict[str, Any]:
"""Read and parse yaml file."""
logger.debug("Input file: %s", filename)
with open(filename, "r") as stream:
structure = yaml.safe_load(stream)
return structure | 0.003891 |
def display_user(value, arg):
''' Return 'You' if value is equal to arg.
Parameters:
value should be a userprofile
arg should be another user.
Ideally, value should be a userprofile from an object and arg the user logged in.
'''
if value.user == arg and arg.username !... | 0.004831 |
def load_and_parse(self, package_name, root_dir, relative_dirs,
resource_type, tags=None):
"""Load and parse models in a list of directories. Returns a dict
that maps unique ids onto ParsedNodes"""
extension = "[!.#~]*.sql"
if tags is None:
tags = ... | 0.002012 |
def plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400):
""" Make two panel plot to summary noise analysis with estimated flux scale """
d = pickle.load(open(mergepkl))
ndist, imstd, flagfrac = plotnoisedist(noisepkl, plot_width=plot_width/2, plot_height=plot_height)
fluxscale = calcfluxscal... | 0.00641 |
def start(name, call=None):
'''
Start a VM.
.. versionadded:: 2016.3.0
name
The name of the VM to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start my-vm
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be call... | 0.002165 |
def find_module(name, path=None):
"""imp.find_module variant that only return path of module.
The `imp.find_module` returns a filehandle that we are not interested in.
Also we ignore any bytecode files that `imp.find_module` finds.
Parameters
----------
name : str
name of module to... | 0.003236 |
def str_lstrip(x, to_strip=None):
"""Remove leading characters from a string sample.
:param str to_strip: The string to be removed
:returns: an expression containing the modified string column.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>... | 0.003021 |
def add_ret_hash_memo(self, memo_return):
"""Set the memo for the transaction to a new :class:`RetHashMemo
<stellar_base.memo.RetHashMemo>`.
:param bytes memo_return: A 32 byte hash or hex encoded string intended to be interpreted as
the hash of the transaction the sender is refundi... | 0.005906 |
def pad(img, padding, fill=0, padding_mode='constant'):
r"""Pad the given PIL Image on all sides with specified padding mode and fill value.
Args:
img (PIL Image): Image to be padded.
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all... | 0.003873 |
def do_bestfit(self):
"""
Do bestfit
"""
self.check_important_variables()
x = np.array(self.args["x"])
y = np.array(self.args["y"])
p = self.args.get("params", np.ones(self.args["num_vars"]))
self.fit_args, self.cov = opt.curve_fit(self.args["func"], x, y,... | 0.005682 |
def transform(self, mode=None):
'''
Set the current transform mode.
:param mode: CENTER or CORNER'''
if mode:
self._canvas.mode = mode
return self._canvas.mode | 0.009434 |
def update_issue_link_type(self, issue_link_type_id, data):
"""
Update the specified issue link type.
:param issue_link_type_id:
:param data: {
"name": "Duplicate",
"inward": "Duplicated by",
"outward": "Duplicat... | 0.005814 |
def ccnot_circuit(qubits: Qubits) -> Circuit:
"""Standard decomposition of CCNOT (Toffoli) gate into
six CNOT gates (Plus Hadamard and T gates.) [Nielsen2000]_
.. [Nielsen2000]
M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum
Information, Cambridge University Press (2000).
... | 0.001285 |
def isargument(self, node):
""" checks whether node aliases to a parameter."""
try:
node_id, _ = self.node_to_id(node)
return (node_id in self.name_to_nodes and
any([isinstance(n, ast.Name) and
isinstance(n.ctx, ast.Param)
... | 0.00464 |
def insert_entity(self, entity):
'''
Adds an insert entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.insert_entity` for more
information on inserts.
The operation will not be executed until the batch is committed.
:param... | 0.010606 |
def run_job(job_ini, log_level='info', log_file=None, exports='',
username=getpass.getuser(), **kw):
"""
Run a job using the specified config file and other options.
:param str job_ini:
Path to calculation config (INI-style) files.
:param str log_level:
'debug', 'info', 'war... | 0.000932 |
def _run_expiration(self, conn):
"""Return any items that have expired."""
# The logic here is sufficiently complicated, and we need
# enough random keys (Redis documentation strongly encourages
# not constructing key names in scripts) that we'll need to
# do this in multiple ste... | 0.001573 |
def get_callable_method_dict(obj):
"""Returns a dictionary of callable methods of object `obj`.
@param obj: ZOS API Python COM object
@return: a dictionary of callable methods
Notes:
the function only returns the callable attributes that are listed by dir()
function. Properties are not r... | 0.007092 |
async def confirmbalance(self, *args, **kwargs):
""" Confirm balance after trading
Accepts:
- message (signed dictionary):
- "txid" - str
- "coinid" - str
- "amount" - int
Returns:
- "address" - str
- "coinid" - str
- "amount" - int
- "... | 0.040975 |
def remap_label_indexers(data_obj, indexers, method=None, tolerance=None):
"""Given an xarray data object and label based indexers, return a mapping
of equivalent location based indexers. Also return a mapping of updated
pandas index objects (in case of multi-index level drop).
"""
if method is not ... | 0.000754 |
def produceResource(self, request, segments, webViewer):
"""
Produce a resource that traverses site-wide content, passing down the
given webViewer. This delegates to the site store's
L{IMantissaSite} adapter, to avoid a conflict with the
L{ISiteRootPlugin} interface.
Th... | 0.002279 |
def gifs_translate_get(self, api_key, s, **kwargs):
"""
Translate Endpoint
The translate API draws on search, but uses the Giphy `special sauce` to handle translating from one vocabulary to another. In this case, words and phrases to GIFs.
This method makes a synchronous HTTP request by ... | 0.003925 |
def add_group_entity(self, persons_plural, persons_ids, entity, instances_json):
"""
Add all instances of one of the model's entities as described in ``instances_json``.
"""
check_type(instances_json, dict, [entity.plural])
entity_ids = list(map(str, instances_json.keys()))
... | 0.006016 |
def clean(deltox=False):
'''Delete temporary files not under version control.
Args:
deltox: If True, delete virtual environments used by tox
'''
basedir = dirname(__file__)
print(cyan('delete temp files and dirs for packaging'))
local(flo(
'rm -rf '
'{basedir}/.eggs/ ... | 0.007299 |
def get_variables(self, *args, **kwargs):
"""Provide a warning that get_variables on Sequential always returns ()."""
tf.logging.warning(
"Calling Sequential.get_variables, which will always return an empty "
"tuple. get_variables() can only return variables created directly by "
"a Modu... | 0.002384 |
def update_utxoset(self, transaction):
"""Update the UTXO set given ``transaction``. That is, remove
the outputs that the given ``transaction`` spends, and add the
outputs that the given ``transaction`` creates.
Args:
transaction (:obj:`~bigchaindb.models.Transaction`): A ne... | 0.002663 |
def _get_rabbitmq_plugin():
'''
Returns the rabbitmq-plugin command path if we're running an OS that
doesn't put it in the standard /usr/bin or /usr/local/bin
This works by taking the rabbitmq-server version and looking for where it
seems to be hidden in /usr/lib.
'''
global RABBITMQ_PLUGINS... | 0.001667 |
def get_version_by_value(context, value):
"""
Get the latest version that matches the provided ami-id
Args:
context: a populated EFVersionContext object
value: the value of the version to look for
"""
versions = get_versions(context)
for version in versions:
if version.value == value:
retu... | 0.012072 |
def show_report(self):
"""Show report."""
self.action_show_report.setEnabled(False)
self.action_show_log.setEnabled(True)
self.load_html_file(self.report_path) | 0.010471 |
def get_info(self, account, params={}):
"""
Gets account info.
@param account: account to get info for
@param params: parameters to retrieve
@return: AccountInfo
"""
res = self.invoke(zconstant.NS_ZIMBRA_ADMIN_URL,
sconstant.GetInfoReques... | 0.005319 |
def store_json(self, filename, dict_to_store):
"""Store json files."""
filename = os.path.join(
self.data_dir,
filename + '.data'
)
fileops.dump_dict_to_file(
dict_to_store,
filename
) | 0.007353 |
def numberOfConnectedProximalSynapses(self, cells=None):
"""
Returns the number of proximal connected synapses on these cells.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells. If None return count for all cells.
"""
if cells is None:
... | 0.003953 |
def build_api(packages, input, output, sanitizer, excluded_modules=None):
"""
Builds the Sphinx documentation API.
:param packages: Packages to include in the API.
:type packages: list
:param input: Input modules directory.
:type input: unicode
:param output: Output reStructuredText files d... | 0.004257 |
def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
filter_type=None, **kwds):
""" perform a reduction operation """
return op(self.get_values(), skipna=skipna, **kwds) | 0.013889 |
def refresh(self):
""" refreshes a service """
params = {"f": "json"}
uURL = self._url + "/refresh"
res = self._get(url=uURL, param_dict=params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
... | 0.012723 |
def _parse_pool_options(options):
"""Parse connection pool options."""
max_pool_size = options.get('maxpoolsize', common.MAX_POOL_SIZE)
min_pool_size = options.get('minpoolsize', common.MIN_POOL_SIZE)
max_idle_time_ms = options.get('maxidletimems', common.MAX_IDLE_TIME_MS)
if max_pool_size is not No... | 0.000769 |
def plot_target(target, ax):
"""Ajoute la target au plot"""
ax.scatter(target[0], target[1], target[2], c="red", s=80) | 0.007937 |
def _install_hiero(use_threaded_wrapper):
"""Helper function to The Foundry Hiero support"""
import hiero
import nuke
if "--hiero" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return hiero.core.executeInMainThreadWithResult(
func, ... | 0.002494 |
def t_QUOTED_STRING(self, t):
r'\"[^\"]*\"'
t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', t.value))
return t | 0.014925 |
def constraint_matches(self, c, m):
"""
Return dict noting the substitution values (or False for no match)
"""
if isinstance(m, tuple):
d = {}
if isinstance(c, Operator) and c._op_name == m[0]:
for c1, m1 in zip(c._args, m[1:]):
... | 0.003759 |
def register(self, path, help_text=None, help_context=None):
"""
Registers email template.
Example usage:
email_templates.register('hello_template.html', help_text=u'Hello template',
help_context={'username': u'Name of user in hello expression'})
:param path... | 0.007799 |
def santalucia98_corrections(seq, pars_error):
'''Sum corrections for SantaLucia '98 method (unified parameters).
:param seq: sequence for which to calculate corrections.
:type seq: str
:param pars_error: dictionary of error corrections
:type pars_error: dict
:returns: Corrected delta_H and del... | 0.000985 |
def merge(self, resolvable, packages, parent=None):
"""Add a resolvable and its resolved packages."""
self.__tuples.append(_ResolvedPackages(resolvable, OrderedSet(packages),
parent, resolvable.is_constraint))
self._check() | 0.003597 |
def condensedDistance(dupes):
'''
Convert the pairwise list of distances in dupes to "condensed
distance matrix" required by the hierarchical clustering
algorithms. Also return a dictionary that maps the distance matrix
to the record_ids.
The formula for an index of the condensed matrix is
... | 0.001631 |
def _print_task_data(self, task):
"""Pretty-prints task data.
Args:
task: Task dict generated by Turbinia.
"""
print(' {0:s} ({1:s})'.format(task['name'], task['id']))
paths = task.get('saved_paths', [])
if not paths:
return
for path in paths:
if path.endswith('worker-log.... | 0.012146 |
def get_free_sphere_params(structure, rad_dict=None, probe_rad=0.1):
"""
Analyze the void space in the input structure using voronoi decomposition
Calls Zeo++ for Voronoi decomposition.
Args:
structure: pymatgen.core.structure.Structure
rad_dict (optional): Dictionary of radii of elemen... | 0.000475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.