content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def _get_stops() -> None:
"""Import stop words either from a text file or stopwords corpus"""
global stops
import Settings
filename=Settings.dir_name + 'patentstops.txt'
if filename:
f = File(filename).openText()
for line in f.readlines():
stops += line.split()
f.close()
else:
stops = stopwords.words('english')
| 5,345,400 |
def failed_revisions_for_case_study(
case_study: CaseStudy, result_file_type: MetaReport
) -> tp.List[str]:
"""
Computes all revisions of this case study that have failed.
Args:
case_study: to work on
result_file_type: report type of the result files
Returns:
a list of failed revisions
"""
total_failed_revisions = set(
get_failed_revisions(case_study.project_name, result_file_type)
)
return [
rev for rev in case_study.revisions
if rev[:10] in total_failed_revisions
]
| 5,345,401 |
def _removeTwoSentenceCommonNode(syncSrc1, syncSrc2, matchListT1, matchListT2, prefix):
"""
Identify and remove a node that appears to be in both of the target sentences,
and is also a currently active link
"""
raise DeprecationWarning, "Now finding split points before individual pairs"
# a useful rule splits the node into tgt1 and tgt2,
# with information on how to structure both
src1LinkPos = set([ tuple(syncSrc1.findLink(l)) for l in syncSrc1.links() ])
src2LinkPos = set([ tuple(syncSrc2.findLink(l)) for l in syncSrc2.links() ])
if PRINT_DEBUG_SPLIT: print "Set1 links:",src1LinkPos,"\t\tSet2 links:",src2LinkPos
commonAncestorsLinks = set((commonAncestorPositions(p1,p2) for p1 in src1LinkPos for p2 in src2LinkPos))
if PRINT_DEBUG_SPLIT:
print "commonAncestorsLinks:", commonAncestorsLinks
# not sure if I need this test. It might be enough to get a clean split
# if len(src1LinkPos-src2LinkPos)==0: raise ValueError, "No separate information in tgt1"
# if len(src2LinkPos-src1LinkPos)==0: raise ValueError, "No separate information in tgt2"
if len(src1LinkPos-src2LinkPos)==0 or len(src2LinkPos-src1LinkPos)==0:
print "Rule contains nothing to split the sentences"
linksToRemove = [ prefix+l for l in (commonAncestorsLinks) ]
print "linksToRemove:",linksToRemove
refMatchListT1 = [ (ms,mt) for (ms,mt) in matchListT1 if ms.treeposition() not in linksToRemove ]
refMatchListT2 = [ (ms,mt) for (ms,mt) in matchListT2 if ms.treeposition() not in linksToRemove ]
raise SystemExit,"common nodes"
return refMatchListT1, refMatchListT2, False
ancestorsIn1 = commonAncestorsLinks&src1LinkPos
ancestorsIn2 = commonAncestorsLinks&src2LinkPos
crossAncestors1 = [ a for a in ancestorsIn1 for d in src2LinkPos if _isDirectDescendent(d, a) ]
crossAncestors2 = [ a for a in ancestorsIn2 for d in src1LinkPos if _isDirectDescendent(d, a) ]
if PRINT_DEBUG_SPLIT:
print "crossAncestors1:", crossAncestors1
print "crossAncestors2:", crossAncestors2
if len(crossAncestors1)==0 and len(crossAncestors2)==0:
# print "Nothing to change"
return matchListT1, matchListT2, True
# remove the common ancestor nodes
linksToRemove = [ prefix+l for l in (crossAncestors1+crossAncestors2) ]
if PRINT_DEBUG_SPLIT: print "linksToRemove:",linksToRemove
refMatchListT1 = [ (ms,mt) for (ms,mt) in matchListT1 if ms.treeposition() not in linksToRemove ]
refMatchListT2 = [ (ms,mt) for (ms,mt) in matchListT2 if ms.treeposition() not in linksToRemove ]
if PRINT_DEBUG_SPLIT:
print "\nAfter removing common ancestor nodes,\nrefMatchListT1:"
printAllMatchListInfo(refMatchListT1)
print "refMatchListT2:"
printAllMatchListInfo(refMatchListT2)
raise SystemExit,"common nodes"
return refMatchListT1, refMatchListT2, False
| 5,345,402 |
def bytes_load(path):
"""Load bytest from a file."""
with open(path, 'rb') as f:
return f.read()
| 5,345,403 |
def get_relationship_length_fam_mean(data):
"""Calculate mean length of relationship for families DataDef 43
Arguments:
data - data frames to fulfill definiton id
Modifies:
Nothing
Returns: added_members
mean_relationship_length - mean relationship length of families
"""
families = data[1]
return families['max_days_since_first_service'].mean()
| 5,345,404 |
def create_jar(jar_file, entries):
"""
Create JAR from given entries.
:param jar_file: filename of the created JAR
:type jar_file: str
:param entries: files to put into the JAR
:type entries: list[str]
:return: None
"""
# 'jar' adds separate entries for directories, also for empty ones.
with ZipFile(jar_file, "w") as jar:
jar.writestr("META-INF/", "")
jar.writestr("META-INF/MANIFEST.MF", Manifest().get_data())
for entry in entries:
jar.write(entry)
if os.path.isdir(entry):
for root, dirs, files in os.walk(entry):
for filename in dirs + files:
jar.write(os.path.join(root, filename))
| 5,345,405 |
def convert_hapmap(input_dataframe, recode=False, index_col=0):
""" Specifically deals with hapmap and 23anMe Output
"""
complement = {'G/T': 'C/A', 'C/T': 'G/A', "G/A" : "G/A", "C/A": "C/A", "A/G" : "A/G",
"A/C": "A/C"}
dataframe = input_dataframe.copy()
if recode:
recode = dataframe.ix[:, index_col].apply(lambda x: complement[x])
dataframe.ix[:,0] = recode
new_dataframe = dataframe.apply(_single_column_allele, axis=1)
return new_dataframe
| 5,345,406 |
def visualize_labels(
labels, title="Visualization of labels", mode: str = "lines"
) -> None:
"""
Plot labels.
Parameters
----------
title: str
Title of the plot.
mode: str
Determines the drawing mode for this scatter trace. If
the provided `mode` includes "text" then the `text`
elements appear at the coordinates. Otherwise, the
`text` elements appear on hover. If there are less than
20 points and the trace is not stacked then the default
is "lines+markers". Otherwise, "lines".
"""
if len(labels.shape) == 1:
labels = pd.DataFrame(labels, columns=["labels"])
fig = go.Figure()
fig.update_layout(title=title)
fig.update_yaxes(title_text="labels")
for i in range(labels.shape[1]):
fig.add_trace(
go.Scatter(
x=labels.index,
y=labels.iloc[:, i],
name=labels.columns[i],
mode=mode,
)
)
fig.show()
| 5,345,407 |
def to_base64(message):
"""
Returns the base64 representation of a string or bytes.
"""
return b64encode(to_bytes(message)).decode('ascii')
| 5,345,408 |
def create_alerts():
"""
Function to create alerts.
"""
try:
# validate post json data
content = request.json
print(content)
if not content: raise ValueError("Empty value")
if not 'timestamp' in content or not 'camera_id' in content or not 'class_id' in content: raise KeyError("Invalid dictionary keys")
if not isinstance(content.get('timestamp'), int): raise TypeError("Timestamp must be in int64 type")
if not isinstance(content.get('camera_id'), int): raise TypeError("Camera_id must be in int32 type")
class_id = content.get('class_id')
if not isinstance(class_id, list): raise TypeError("Class_id must be an array")
for val in class_id:
if not isinstance(val, int): raise TypeError("Array class_id values must be in int32 type")
except (ValueError, KeyError, TypeError) as e:
traceback.print_exc()
resp = Response({"Json format error"}, status=400, mimetype='application/json')
return resp
try:
record_created = db.alerts.insert_one(content)
return jsonify(id=str(record_created.inserted_id)), 201
except:
#traceback.print_exc()
return jsonify(error="Internal server error"), 500
| 5,345,409 |
def read_envs():
"""Function will read in all environment variables into a dictionary
:returns: Dictionary containing all environment variables or defaults
:rtype: dict
"""
envs = {}
envs['QUEUE_INIT_TIMEOUT'] = os.environ.get('QUEUE_INIT_TIMEOUT', '3600')
envs['VALIDATION_TIMEOUT'] = os.environ.get('VALIDATION_TIMEOUT', '28800')
envs['VALIDATION_HOME'] = os.environ.get('VALIDATION_HOME', '/opt/aif-validator')
envs['VALIDATION_FLAGS'] = os.environ.get('VALIDATION_FLAGS')
envs['S3_VALIDATION_BUCKET'] = os.environ.get('S3_VALIDATION_BUCKET')
envs['S3_VALIDATION_PREFIX'] = os.environ.get('S3_VALIDATION_PREFIX')
envs['AWS_BATCH_JOB_ID'] = os.environ.get('AWS_BATCH_JOB_ID')
envs['AWS_BATCH_JOB_NODE_INDEX'] = os.environ.get('AWS_BATCH_JOB_NODE_INDEX')
envs['AWS_DEFAULT_REGION'] = os.environ.get('AWS_DEFAULT_REGION', 'us-east-1')
return envs
| 5,345,410 |
def generate(env):
"""Add Builders and construction variables for rmic to an Environment."""
env['BUILDERS']['RMIC'] = RMICBuilder
env['RMIC'] = 'rmic'
env['RMICFLAGS'] = SCons.Util.CLVar('')
env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}'
env['JAVACLASSSUFFIX'] = '.class'
| 5,345,411 |
def get_platform():
""" Get system platform metadata.
"""
detected_os = platform.system()
detected_distro = platform.platform()
if detected_os == "Darwin":
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
is_supported=True,
help_message="",
label="")
elif detected_os == "Linux":
if os.path.isfile('/proc/device-tree/hat/uuid'):
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
is_supported=False,
help_message="%s "
"Please visit %s to get started hosting "
"machine-payable servers on your Bitcoin "
"Computer." % (SUPPORTED_SYSTEMS, PING21_LEARN_URL),
label="21bc")
elif 'boot2docker' in detected_distro.lower():
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
is_supported=False,
help_message="The `21 sell` service manager is not "
"yet supported within another boot2docker VM.",
label="boot2docker")
elif (os.path.isfile('/sys/hypervisor/uuid') or os.path.isdir('/var/lib/digitalocean')) and (
'debian-8.' in detected_distro.lower() or
'ubuntu-14.04' in detected_distro.lower() or
'ubuntu-16.04' in detected_distro.lower()):
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
is_supported=True,
help_message="",
label="debian")
elif os.path.isfile('/sys/hypervisor/uuid') and (
'centos-7' in detected_distro.lower()):
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
is_supported=True,
help_message="",
label="centos")
elif os.path.isfile('/sys/hypervisor/uuid') and (
'fedora-24' in detected_distro.lower()):
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
is_supported=True,
help_message="",
label="fedora")
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
is_supported=False,
help_message=SUPPORTED_SYSTEMS,
label="")
| 5,345,412 |
def load_catalog_npy(catalog_path):
"""
Load a numpy catalog (extension ".npy")
@param catalog_path: str
@return record array
"""
return numpy.load(catalog_path)
| 5,345,413 |
def pgd(fname, n_gg=20, n_mm=20, n_kk=20, n_scale=1001):
"""
:param fname: data file name
:param n_gg: outer iterations
:param n_mm: intermediate iterations
:param n_kk: inner iterations
:param n_scale: number of discretized points, arbitrary
:return:
"""
n_buses, Qmax, Qmin, Y, V_mod, P_pq, Q_pq, P_pv, I0_pq, n_pv, n_pq = read_grid_data(fname)
SSk, SSp, SSq = init_apparent_powers_decomposition(n_buses, n_scale, P_pq, Q_pq, Qmin, Qmax)
VVk, VVp, VVq = init_voltages_decomposition(n_mm, n_buses, n_scale)
IIk, IIp, IIq = init_currents_decomposition(n_gg, n_mm, n_buses, n_scale)
n_max = n_gg * n_mm * n_kk
iter_count = 1
idx_i = 0
idx_v = 1
for gg in range(n_gg): # outer loop: iterate on γ to solve the power flow as such
for mm in range(n_mm): # intermediate loop: iterate on i to find the superposition of terms of the I tensor.
# define the new C
CCk, CCp, CCq, Nc, Nv, n = fun_C(SSk, SSp, SSq,
VVk, VVp, VVq,
IIk, IIp, IIq,
idx_i, idx_v,
n_buses, n_scale)
# initialize the residues we have to find
IIk1 = (np.random.rand(n_buses) - np.random.rand(n_buses)) * 1 # could also try to set IIk1 = VVk1
IIp1 = (np.random.rand(n_buses) - np.random.rand(n_buses)) * 1
IIq1 = (np.random.rand(n_scale) - np.random.rand(n_scale)) * 1
for kk in range(n_kk): # inner loop: iterate on Γ to find the residues.
# compute IIk1 (residues on Ik)
RHSk = np.zeros(n_buses, dtype=complex)
for ii in range(Nc):
prodRK = np.dot(IIp1, CCp[ii]) * np.dot(IIq1, CCq[ii])
RHSk += prodRK * CCk[ii]
LHSk = np.zeros(n_buses, dtype=complex)
for ii in range(Nv):
prodLK = np.dot(IIp1, VVp[ii] * IIp1) * np.dot(IIq1, VVq[ii] * IIq1)
LHSk += prodLK * VVk[ii]
IIk1 = RHSk / LHSk
# compute IIp1 (residues on Ip)
RHSp = np.zeros(n_buses, dtype=complex)
for ii in range(Nc):
prodRP = np.dot(IIk1, CCk[ii]) * np.dot(IIq1, CCq[ii])
RHSp += prodRP * CCp[ii]
LHSp = np.zeros(n_buses, dtype=complex)
for ii in range(Nv):
prodLP = np.dot(IIk1, VVk[ii] * IIk1) * np.dot(IIq1, VVq[ii] * IIq1)
LHSp += prodLP * VVp[ii]
IIp1 = RHSp / LHSp
# compute IIq1 (residues on Iq)
RHSq = np.zeros(n_scale, dtype=complex)
for ii in range(Nc):
prodRQ = np.dot(IIk1, CCk[ii]) * np.dot(IIp1, CCp[ii])
RHSq += prodRQ * CCq[ii]
LHSq = np.zeros(n_scale, dtype=complex)
for ii in range(Nv):
prodLQ = np.dot(IIk1, VVk[ii] * IIk1) * np.dot(IIp1, VVp[ii] * IIp1)
LHSq += prodLQ * VVq[ii]
IIq1 = RHSq / LHSq
progress_bar(iter_count, n_max, 50) # display the inner operations
iter_count += 1
IIk[idx_i, :] = IIk1
IIp[idx_i, :] = IIp1
IIq[idx_i, :] = IIq1
idx_i += 1
for ii in range(n_mm):
VVk[ii, :] = np.conj(sp_linalg.spsolve(Y, IIk[ii]))
VVp[ii, :] = IIp[ii]
VVq[ii, :] = IIq[ii]
# try to add I0 this way:
VVk[n_mm, :] = np.conj(sp_linalg.spsolve(Y, I0_pq))
VVp[n_mm, :] = np.ones(n_buses)
VVq[n_mm, :] = np.ones(n_scale)
idx_v = n_mm + 1
# VVk: size (n_mm + 1, nbus)
# VVp: size (n_mm + 1, nbus)
# VVq: size (n_mm + 1, n_scale)
v_map = build_map(VVk, VVp, VVq)
# SSk: size (2, nbus)
# SSp: size (2, nbus)
# SSq: size (2, n_scale)
s_map = build_map(SSk, SSp, SSq)
# IIk: size (n_gg * n_mm, nbus)
# IIp: size (n_gg * n_mm, nbus)
# IIq: size (n_gg * n_mm, n_scale)
i_map = build_map(IIk, IIp, IIq)
# the size of the maps is nbus, nbus, n_scale
return v_map, s_map, i_map
| 5,345,414 |
def test_bingmdx_tr_sanity():
""" test bingmdx_tr sanity. """
assert bingmdx_tr("test") # '试验;检测;考试;测验'
assert "试验" in bingmdx_tr("test")
| 5,345,415 |
def find_first_empty(rect):
"""
Scan a rectangle and find first open square
@param {Array} rect Board layout (rectangle)
@return {tuple} x & y coordinates of the leftmost top blank square
"""
return _find_first_empty_wrapped(len(rect[0]))(rect)
| 5,345,416 |
def parseArticle(text: str) -> str:
"""
Parses and filters an article. It uses the `wikitextparser` and custom logic.
"""
# clear the image attachments and links
text = re.sub("\[\[Податотека:.+\]\][ \n]", '', text)
text = wikipedia.filtering.clearCurlyBrackets(text)
# replace everything after "Надворешни врски"
links_location = re.search("[\=]+[ ]+(Поврзано|Наводи|Надворешни врски)[ ]+[\=]+", text)
if links_location != None:
text = text[:links_location.span()[0]]
# remove headings and break lines
text = re.sub("([\=]+.+[\=]+.+\n)|(<br />)", '\n', text)
# parse the file using the wikitextparser
parsed = wtp.parse(text)
return parsed.plain_text()
| 5,345,417 |
def plot_spectrum(x, y, filename, title, con_start_vel, con_end_vel, sigma_tau):
"""
Output a plot of opacity vs LSR velocity to a specified file.
:param x: The velocity data
:param y: The opacity values for each velocity step
:param filename: The file the plot should be written to. Should be
an .eps or .pdf file.
:param title: The title for the plot
:param con_start_vel: The minimum velocity that the continuum was measured at.
:param con_end_vel: The maximum velocity that the continuum was measured at.
"""
fig = plt.figure()
plt.plot(x/1000, y)
if len(sigma_tau) > 0:
tau_max = 1 + sigma_tau
tau_min = 1 - sigma_tau
plt.fill_between(x/1000, tau_min, tau_max, facecolor='lightgray', color='lightgray')
plt.axhline(1, color='r')
plt.axvline(con_start_vel, color='g', linestyle='dashed')
plt.axvline(con_end_vel, color='g', linestyle='dashed')
plt.xlabel(r'Velocity relative to LSR (km/s)')
plt.ylabel(r'$e^{(-\tau)}$')
plt.title(title)
plt.grid(True)
plt.savefig(filename)
#plt.show()
plt.close()
return
| 5,345,418 |
def exp2(input, *args, **kwargs):
"""
Computes the base two exponential function of ``input``.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.exp2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0]))
tensor([6.2500e-02, 5.0000e-01, 1.0000e+00, 4.0000e+00, 2.7858e+01, 2.5600e+02])
>>> ttorch.exp2(ttorch.tensor({
... 'a': [-4.0, -1.0, 0, 2.0, 4.8, 8.0],
... 'b': {'x': [[-2.0, 1.2, 0.25],
... [16.0, 3.75, -2.34]]},
... }))
<Tensor 0x7ff90a4c3af0>
├── a --> tensor([6.2500e-02, 5.0000e-01, 1.0000e+00, 4.0000e+00, 2.7858e+01, 2.5600e+02])
└── b --> <Tensor 0x7ff90a4c3be0>
└── x --> tensor([[2.5000e-01, 2.2974e+00, 1.1892e+00],
[6.5536e+04, 1.3454e+01, 1.9751e-01]])
"""
return torch.exp2(input, *args, **kwargs)
| 5,345,419 |
def list_default_storage_policy_of_datastore(
datastore,
host=None,
vcenter=None,
username=None,
password=None,
protocol=None,
port=None,
verify_ssl=True,
):
"""
Returns a list of datastores assign the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
salt '*' vsphere.list_default_storage_policy_of_datastore datastore=ds1
"""
log.trace("Listing the default storage policy of datastore '{}'" "".format(datastore))
if salt.utils.platform.is_proxy():
details = __salt__["vmware_info.get_proxy_connection_details"]()
else:
details = __salt__["vmware_info.get_connection_details"](
host=host,
vcenter=vcenter,
username=username,
password=password,
protocol=protocol,
port=port,
verify_ssl=verify_ssl,
)
service_instance = saltext.vmware.utils.vmware.get_service_instance(**details)
# Find datastore
target_ref = __salt__["vmware_info.get_proxy_target"](service_instance)
ds_refs = saltext.vmware.utils.vmware.get_datastores(
service_instance, target_ref, datastore_names=[datastore]
)
if not ds_refs:
raise VMwareObjectRetrievalError("Datastore '{}' was not " "found".format(datastore))
profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
policy = salt.utils.pbm.get_default_storage_policy_of_datastore(profile_manager, ds_refs[0])
return saltext.vmware.utils.get_policy_dict(policy)
| 5,345,420 |
def action_stats(env, md_action, cont_action):
"""
Get information on `env`'s action space.
Parameters
----------
md_action : bool
Whether the `env`'s action space is multidimensional.
cont_action : bool
Whether the `env`'s action space is continuous.
Returns
-------
n_actions_per_dim : list of length (action_dim,)
The number of possible actions for each dimension of the action space.
action_ids : list or None
A list of all valid actions within the space. If `cont_action` is
True, this value will be None.
action_dim : int or None
The number of dimensions in a single action.
"""
if cont_action:
action_dim = 1
action_ids = None
n_actions_per_dim = [numpy.inf]
if md_action:
action_dim = env.action_space.shape[0]
n_actions_per_dim = [numpy.inf for _ in range(action_dim)]
else:
if md_action:
n_actions_per_dim = [
space.n if hasattr(space, "n") else numpy.inf
for space in env.action_space.spaces
]
action_ids = (
None
if numpy.inf in n_actions_per_dim
else list(product(*[range(i) for i in n_actions_per_dim]))
)
action_dim = len(n_actions_per_dim)
else:
action_dim = 1
n_actions_per_dim = [env.action_space.n]
action_ids = list(range(n_actions_per_dim[0]))
return n_actions_per_dim, action_ids, action_dim
| 5,345,421 |
def count(pred: Pred, seq: Seq) -> int:
"""
Count the number of occurrences in which predicate is true.
"""
pred = to_callable(pred)
return sum(1 for x in seq if pred(x))
| 5,345,422 |
def lambda_k(W, Z, k):
"""Coulomb function $\lambda_k$ as per Behrens et al.
:param W: Total electron energy in units of its rest mass
:param Z: Proton number of daughter
:param k: absolute value of kappa
"""
#return 1.
gammak = np.sqrt(k**2.0-(ALPHA*Z)**2.0)
gamma1 = np.sqrt(1.-(ALPHA*Z)**2.0)
R = 1.2e-15*(2.5*Z)**(1./3.)/NATURALLENGTH
return generalizedFermiFunction(W, Z, R, k)/generalizedFermiFunction(W, Z, R, 1)*(k+gammak)/(k*(1+gamma1))
| 5,345,423 |
def tryJsonOrPlain(text):
"""Return json formatted, if possible. Otherwise just return."""
try:
return pprint.pformat( json.loads( text ), indent=1 )
except:
return text
| 5,345,424 |
def test_get_yesterday_alias():
"""Test getting date object for 'yesterday' alias"""
assert helpers.get_date_object_for_alias('yesterday') == date(2021, 12, 31)
| 5,345,425 |
def create_signaling(args):
"""
Create a signaling method based on command-line arguments.
"""
if args.signaling == "apprtc":
if aiohttp is None or websockets is None: # pragma: no cover
raise Exception("Please install aiohttp and websockets to use appr.tc")
if not args.signaling_room:
args.signaling_room = "".join(
[random.choice("0123456789") for x in range(10)]
)
return ApprtcSignaling(args.signaling_room)
elif args.signaling == "tcp-socket":
return TcpSocketSignaling(args.signaling_host, args.signaling_port)
elif args.signaling == "unix-socket":
return UnixSocketSignaling(args.signaling_path)
else:
return CopyAndPasteSignaling()
| 5,345,426 |
def fitswrite(img, imgname, **kwargs):
"""
Write FITS image to disk.
Parameters
----------
img : numpy array
2D or 3D numpy array
imgname : string
Name of the output FITS image
Optional Keywords
-----------------
header : pyFITS header
FITS header object
Return
------
None
"""
try:
if kwargs.has_key('header'):
hdu = pyfits.PrimaryHDU(img, header = kwargs['header'])
else:
hdu = pyfits.PrimaryHDU(img)
hdu.writeto(imgname)
except IOError:
print "FITSWRITE: Unable to write FITS image %s. Stopping." %imgname
return
| 5,345,427 |
def signup(DB_MAN: DB_manager, DB_CONN: Connection) -> None:
"""This function represents a view to the signup page.
Args:
DB_MAN (DB_manager): database manager.
DB_CONN (Connection): database connection.
"""
# signup form to retrieve the information from the user.
st.subheader("Signup")
with st.form("signup"):
name = st.text_input("Full name *")
email = st.text_input("Email")
username = st.text_input("Username *")
password = st.text_input("Password *", type="password")
submit = st.form_submit_button("signup")
# if user clicks on the submit button, the information is saved in the database.
if submit:
user = User(
id=1,
name=name,
username=username,
password=password,
created_at=date.today(),
email=email if email else None,
)
user_created = DB_MAN.create_user(DB_CONN, user)
if user_created:
st.success(f"Welcome {user.name}")
st.session_state["user"] = user
st.experimental_rerun()
else:
st.error("Username/password is incorrect")
| 5,345,428 |
def get_corpus_gene_adjacency(corpus_id):
"""Generate a nugget table."""
corpus = get_corpus(corpus_id)
data = get_gene_adjacency(corpus)
return jsonify(data), 200
| 5,345,429 |
def get_pool_health(pool):
""" Get ZFS list info. """
pool_name = pool.split()[0]
pool_capacity = pool.split()[6]
pool_health = pool.split()[9]
return pool_name, pool_capacity, pool_health
| 5,345,430 |
def resize_short(img, target_size):
""" resize_short """
percent = float(target_size) / min(img.shape[0], img.shape[1])
resized_width = int(round(img.shape[1] * percent))
resized_height = int(round(img.shape[0] * percent))
resized_width = normwidth(resized_width)
resized_height = normwidth(resized_height)
resized = cv2.resize(img, (resized_width, resized_height))
return resized
| 5,345,431 |
def _scale(aesthetic, name=None, breaks=None, labels=None, limits=None, expand=None, na_value=None, guide=None,
trans=None, **other):
"""
Create a scale (discrete or continuous)
:param aesthetic
The name of the aesthetic that this scale works with
:param name
The name of the scale - used as the axis label or the legend title
:param breaks
A numeric vector of positions (of ticks)
:param labels
A vector of labels (on ticks)
:param limits
A numeric vector of length two providing limits of the scale.
:param expand
A numeric vector of length two giving multiplicative and additive expansion constants.
:param na_value
Value to use for missing values
:param guide
Type of legend. Use 'colorbar' for continuous color bar, or 'legend' for discrete values.
:param trans
Name of built-in transformation. ('identity', 'log10', 'sqrt', 'reverse')
:return:
"""
# flatten the 'other' sub-dictionary
args = locals().copy()
args.pop('other')
return FeatureSpec('scale', **args, **other)
| 5,345,432 |
def test_del_alarm():
"""Tests del_alarm method
"""
#WARNING: This test will clear all the alarms that have been saved
test_alarm1 = {"title":"test_alarm1","content":"content"}
test_alarm2 = {"title":"test_alarm2","content":"content"}
test_alarm3 = {"title":"test_alarm3","content":"content"}
COVID_briefing_application.undismissed_alarms = [test_alarm1,test_alarm2,test_alarm3]
del_alarm("test_alarm2")
assert len(COVID_briefing_application.undismissed_alarms) == 2
assert test_alarm2 not in COVID_briefing_application.undismissed_alarms
reset_persistent_data()
| 5,345,433 |
def logsubexp(x, y):
"""
Helper function to compute the exponential
of a difference between two numbers
Computes: ``x + np.log1p(-np.exp(y-x))``
Parameters
----------
x, y : float or array_like
Inputs
"""
if np.any(x < y):
raise RuntimeError('cannot take log of negative number '
f'{str(x)!s} - {str(y)!s}')
return x + np.log1p(-np.exp(y - x))
| 5,345,434 |
async def test_exception_handling():
"""Test handling of exceptions."""
send_messages = []
user = MockUser()
refresh_token = Mock()
conn = websocket_api.ActiveConnection(
logging.getLogger(__name__), None, send_messages.append, user, refresh_token
)
for (exc, code, err) in (
(exceptions.Unauthorized(), websocket_api.ERR_UNAUTHORIZED, "Unauthorized"),
(
vol.Invalid("Invalid something"),
websocket_api.ERR_INVALID_FORMAT,
"Invalid something. Got {'id': 5}",
),
(asyncio.TimeoutError(), websocket_api.ERR_TIMEOUT, "Timeout"),
(
exceptions.HomeAssistantError("Failed to do X"),
websocket_api.ERR_UNKNOWN_ERROR,
"Failed to do X",
),
(ValueError("Really bad"), websocket_api.ERR_UNKNOWN_ERROR, "Unknown error"),
):
send_messages.clear()
conn.async_handle_exception({"id": 5}, exc)
assert len(send_messages) == 1
assert send_messages[0]["error"]["code"] == code
assert send_messages[0]["error"]["message"] == err
| 5,345,435 |
def is_sequence_of_list(items):
"""Verify that the sequence contains only items of type list.
Parameters
----------
items : sequence
The items.
Returns
-------
bool
True if all items in the sequence are of type list.
False otherwise.
Examples
--------
>>> is_sequence_of_list([[1], [1], [1]])
True
"""
return all(isinstance(item, list) for item in items)
| 5,345,436 |
def sum_fib_dp(m, n):
"""
A dynamic programming version.
"""
if m > n: m, n = n, m
large, small = 1, 0
# a running sum for Fibbo m ~ n + 1
running = 0
# dynamically update the two variables
for i in range(n):
large, small = large + small, large
# note that (i + 1) -> small is basically mapping m -> F[m]
if m <= i + 1 <= n:
running += small
return running
| 5,345,437 |
def fibo_dyn2(n):
"""
return
the n-th fibonacci number
"""
if n < 2:
return 1
else:
a, b = 1, 1
for _ in range(1,n):
a, b = b, a+b
return b
| 5,345,438 |
def upload_model(source, destination, tmpfile):
"""Uploads a file to the bucket."""
urllib.request.urlretrieve(source, tmpfile)
storage_client = storage.Client()
bucket = storage_client.get_bucket(BUCKET_NAME)
blob = bucket.blob("/".join([FOLDER_NAME, destination]))
blob.upload_from_filename(tmpfile)
| 5,345,439 |
def test_get_offline_wikis(fs):
"""Local wiki names are found."""
fs.create_file("/data1/frwiki-20201020-md5sums.txt")
fs.create_file("/data2/enwiki-20201020-md5sums.txt")
wct = ww.CorporaTracker(local_dirs=["/data1", "/data2"], online=False, verbose=False)
assert len(wct.list_local_wikis()) == 2
assert "enwiki" in wct.list_local_wikis()
| 5,345,440 |
def build_all(box, request_list):
"""
box is [handle, left, top, bottom] \n
request_list is the array about dic \n
****** Attention
before running the function, you should be index.
After build_all, function will close the windows about train troop
"""
# get the box of windows
left = box[1]
top = box[2]
positions = init_pos_army()
# get the information about request
request = request_deal(request_list[0]['str'])
num_army = int(request_list[0]['army']['max'])
num_spells = int(request_list[0]['spells']['max'])
num_devices = int(request_list[0]['device']['max'])
num_army_fill_in = int(request_list[0]['army']['fill_in'])
num_spells_fill_in = int(request_list[0]['spells']['fill_in'])
num_device_fill_in = int(request_list[0]['device']['fill_in'])
# open army
time.sleep(0.2)
Click(left + positions['army'][0], top + positions['army'][1])
# select dragon
if request[0] != None:
# open train troops
time.sleep(0.2)
Click(left + positions['train_troops'][0], top + positions['train_troops'][1])
if ( num_army - num_army_fill_in ) >= num_housing_space[request[0]]:
for index in range( math.floor( ( num_army - num_army_fill_in ) / num_housing_space[request[0]] ) ):
time.sleep(0.2)
Click(left + positions[request[0]][0], top + positions[request[0]][1])
# select speed increase
if request[1] != None:
# open brew spells
time.sleep(0.2)
Click(left + positions['Brew_spells'][0], top + positions['Brew_spells'][1])
if ( num_spells - num_spells_fill_in ) >= num_housing_space[request[1]]:
for index in range( math.floor( ( num_spells - num_spells_fill_in ) / num_housing_space[request[1]] ) ):
time.sleep(0.2)
Click(left + positions[request[1]][0], top + positions[request[1]][1])
# select device
# if request[2] != None:
# open brew spells
##
# close the army
time.sleep(0.2)
Click(left + positions['close_army'][0], top + positions['close_army'][1])
print('close the army')
return True
| 5,345,441 |
def select_results(results):
"""Select relevant images from results
Selects most recent image for location, and results with positive fit index.
"""
# Select results with positive bestFitIndex
results = [x for x in results['items'] if x['bestFitIndex'] > 0]
# counter_dict schema:
# counter_dict = {
# bounds: {
# 'dateCreated': date,
# 'downloadURL'
# }
# }
counter_dict = {}
for result in results:
bounds = result_to_bounds(result)
# does something already exist with these bounds?
existing = counter_dict.get(bounds)
# If exists, check if newer
if existing is not None:
existing_date = existing['dateCreated']
this_date = date_parse(result['dateCreated'])
if this_date < existing_date:
continue
# Doesn't exist yet or is newer, so add to dict
counter_dict[bounds] = {
'dateCreated': date_parse(result['dateCreated']),
'downloadURL': result['downloadURL']}
return [x['downloadURL'] for x in counter_dict.values()]
| 5,345,442 |
def dc_session(virtual_smoothie_env, monkeypatch):
"""
Mock session manager for deck calibation
"""
ses = endpoints.SessionManager()
monkeypatch.setattr(endpoints, 'session', ses)
return ses
| 5,345,443 |
def is_available(_cache={}):
"""Return version tuple and None if OmnisciDB server is accessible or
recent enough. Otherwise return None and the reason about
unavailability.
"""
if not _cache:
omnisci = next(global_omnisci_singleton)
try:
version = omnisci.version
except Exception as msg:
_cache['reason'] = 'failed to get OmniSci version: %s' % (msg)
else:
print(' OmnisciDB version', version)
if version[:2] >= (4, 6):
_cache['version'] = version
else:
_cache['reason'] = (
'expected OmniSci version 4.6 or greater, got %s'
% (version,))
return _cache.get('version', ()), _cache.get('reason', '')
| 5,345,444 |
def pitch_info_from_pitch_string(pitch_str: str) -> PitchInfo:
"""
Parse a pitch string representation. E.g. C#4, A#5, Gb8
"""
parts = tuple((c for c in pitch_str))
size = len(parts)
pitch_class = register = accidental = None
if size == 1:
(pitch_class,) = parts
elif size == 2:
(pitch_class, register) = parts
elif size >= 3:
(pitch_class, accidental, register) = parts[:3]
accidental = Accidental.SHARP if accidental == '#' \
else Accidental.FLAT if accidental == 'b' \
else Accidental.NATURAL
register = int(register)
pitch_info = PitchInfo(pitch_class=pitch_class, accidental=accidental)
matching_chromatic_pitch_info, _ = next(
matching_pitch_info_generator(pitch_info, CHROMATIC_PITCHES_INFO)
)
final_pitch_info = copy.deepcopy(matching_chromatic_pitch_info)
final_pitch_info.register = register
if is_enharmonic_match(pitch_info, matching_chromatic_pitch_info):
final_pitch_info.swap_enharmonic()
return final_pitch_info
| 5,345,445 |
def test_multiple_meta() -> None:
"""Test parsing multiple meta."""
docstring = parse(
"""
Short description
Parameters
----------
spam
asd
1
2
3
Raises
------
bla
herp
yay
derp
"""
)
assert docstring.short_description == "Short description"
assert len(docstring.meta) == 3
assert docstring.meta[0].args == ["param", "spam"]
assert docstring.meta[0].arg_name == "spam"
assert docstring.meta[0].description == "asd\n1\n 2\n3"
assert docstring.meta[1].args == ["raises", "bla"]
assert docstring.meta[1].type_name == "bla"
assert docstring.meta[1].description == "herp"
assert docstring.meta[2].args == ["raises", "yay"]
assert docstring.meta[2].type_name == "yay"
assert docstring.meta[2].description == "derp"
| 5,345,446 |
def dump_one_page(title: str, page_id: str, content: str):
"""
保存文章
$title: 文章标题
$page_id: 文章的 id
$content: 文章的 html 文档
"""
print(f"\n***[SAVING {page_id}]***")
html_file = f"files/{title} - {page_id}.html"
md_file = f"files/{title} - {page_id}.md"
print(f"Saving the article to {html_file}...")
with open(f"{html_file}", "w", encoding="utf-8") as f:
f.write(content)
print("Converting html to md...")
os.system(f'pandoc -o "{md_file}" "{html_file}"')
print("Cleaning the md...")
with open(f"{md_file}") as f:
lines = f.readlines()
text = re.sub(r"{\..*?}", "", "".join(lines), flags=re.S)
while re.search(r"{\..*?}", text, flags=re.S):
text = re.sub(r"{\..*?}", "", text, flags=re.S)
text = text.replace("\\\n", "").replace(":::", "")
with open(f"{md_file}", "w", encoding="utf-8") as f:
f.write(text)
if DEL_HTML:
print(f"Removing {html_file}...")
os.remove(f"{html_file}")
| 5,345,447 |
def determine_word_type(tag):
"""
Determines the word type by checking the tag returned by the nltk.pos_tag(arr[str]) function.
Each word in the array is marked with a special tag which can be used to find the correct type of a word.
A selection is given in the dictionaries.
Args:
tag : String tag from the nltk.pos_tag(str) function that classified the particular word with a tag
Returns:
str: Word type as a string
"""
types = {
"noun" : {"NN", "NNS", "NNPS", "FW"},
"adjective" : {"JJ", "JJR", "JJS"},
"verb" : {"VB", "VBD", "VBG", "VBN", "VBP", "VBZ"},
"adverb" : {"RB", "RBR"}
}
for type_, set_ in types.iteritems():
if tag in set_:
return type_
return "noun"
| 5,345,448 |
def get_normalized_map_from_google(normalization_type, connection=None, n_header_lines=0):
"""
get normalized voci or titoli mapping from gdoc spreadsheets
:param: normalization_type (t|v)
:param: connection - (optional) a connection to the google account (singleton)
:param: n_header_lines - (optional) n. of lines to ignore
:ret: a dict, containing the consuntivo and preventivo sheets
"""
# get all gdocs keys
gdoc_keys = settings.GDOC_KEYS
if normalization_type == 't':
gdoc_key = gdoc_keys['titoli_map']
elif normalization_type == 'v':
gdoc_key = gdoc_keys['voci_map']
else:
raise Exception("normalization_type arg accepts 't' or 'v' as possible values")
if connection is None:
connection = get_connection()
# open the list worksheet
list_sheet = None
try:
list_sheet = connection.open_by_key(gdoc_key)
except exceptions.SpreadsheetNotFound:
raise Exception("Error: gdoc url not found: {0}".format(
gdoc_key
))
logger.info("normalized mapping gdoc read. key: {0}".format(
gdoc_key
))
# put the mapping into the voci_map dict
# preventivo and consuntivo sheets are appended in a single list
# the first two rows are removed (labels)
try:
logger.info("reading preventivo ...")
voci_map_preventivo = list_sheet.worksheet("preventivo").get_all_values()[n_header_lines:]
logger.info("reading consuntivo ...")
voci_map_consuntivo = list_sheet.worksheet("consuntivo").get_all_values()[n_header_lines:]
except URLError:
raise Exception("Connection error to Gdrive")
logger.info("done with reading the mapping list.")
return {
'preventivo': voci_map_preventivo,
'consuntivo': voci_map_consuntivo,
}
| 5,345,449 |
def parse_file(fname, is_true=True):
"""Parse file to get labels."""
labels = []
with io.open(fname, "r", encoding="utf-8", errors="igore") as fin:
for line in fin:
label = line.strip().split()[0]
if is_true:
assert label[:9] == "__label__"
label = label[9:]
labels.append(label)
return labels
| 5,345,450 |
def main(event, context):
"""
Args:
package: Python Package to build and deploy
return:
execution_arn: ARN of the state machine execution that is building the package
"""
packages = get_config.get_packages()
execution_arns =[]
for package in packages:
client = boto3.client('stepfunctions')
execution_time = datetime.now().isoformat().replace('-', '').replace(':', '')[:14]
response = client.start_execution(
stateMachineArn=os.environ['PIPELINE_ARN'],
name=f"{package}_{execution_time}",
input=json.dumps({"package": package})
)
execution_arns.append(response['executionArn'])
return {"arns": execution_arns}
| 5,345,451 |
def make_mesh(object_name, object_colour=(0.25, 0.25, 0.25, 1.0), collection="Collection"):
"""
Create a mesh then return the object reference and the mesh object
:param object_name: Name of the object
:type object_name: str
:param object_colour: RGBA colour of the object, defaults to a shade of grey
:type object_colour: (float, float, float, float)
:param collection: Where you want the objected to be added, defaults to Collection
:type collection: str
:return: Object reference and mesh reference
"""
# Make the block
mesh = bpy.data.meshes.new(object_name) # add the new mesh
obj = bpy.data.objects.new(mesh.name, mesh)
create_emission_node(obj, object_colour)
col = bpy.data.collections.get(collection)
col.objects.link(obj)
bpy.context.view_layer.objects.active = obj
return obj, mesh
| 5,345,452 |
def _OptionParser():
"""Returns the options parser for run-bisect-perf-regression.py."""
usage = ('%prog [options] [-- chromium-options]\n'
'Used by a try bot to run the bisection script using the parameters'
' provided in the auto_bisect/bisect.cfg file.')
parser = optparse.OptionParser(usage=usage)
parser.add_option('-w', '--working_directory',
type='str',
help='A working directory to supply to the bisection '
'script, which will use it as the location to checkout '
'a copy of the chromium depot.')
parser.add_option('-p', '--path_to_goma',
type='str',
help='Path to goma directory. If this is supplied, goma '
'builds will be enabled.')
parser.add_option('--path_to_config',
type='str',
help='Path to the config file to use. If this is supplied, '
'the bisect script will use this to override the default '
'config file path. The script will attempt to load it '
'as a bisect config first, then a perf config.')
parser.add_option('--extra_src',
type='str',
help='Path to extra source file. If this is supplied, '
'bisect script will use this to override default behavior.')
parser.add_option('--dry_run',
action="store_true",
help='The script will perform the full bisect, but '
'without syncing, building, or running the performance '
'tests.')
return parser
| 5,345,453 |
def calc_radiance(wavel, Temp):
"""
Calculate the blackbody radiance
Parameters
----------
wavel: float or array
wavelength (meters)
Temp: float
temperature (K)
Returns
-------
Llambda: float or arr
monochromatic radiance (W/m^2/m/sr)
"""
Llambda_val = c1 / (wavel**5. * (np.exp(c2 / (wavel * Temp)) - 1))
return Llambda_val
| 5,345,454 |
def load_config(filename):
"""
Returns:
dict
"""
config = json.load(open(filename, 'r'))
# back-compat
if 'csvFile' in config:
config['modelCategoryFile'] = config['csvFile']
del config['csvFile']
required_files = ["prefix", "modelCategoryFile", "colorFile"]
for f in required_files:
assert f in config, 'Invalid config! key <{}> is missing!'.format(f)
assert os.path.exists(config[f]), 'Invalid config! path <{}> not exists!'.format(config[f])
if ('File' in f):
assert os.path.isfile(config[f]), 'Invalid config! <{}> is not a valid file!'.format(config[f])
return config
| 5,345,455 |
def _JMS_to_Fierz_III_IV_V(C, qqqq):
"""From JMS to 4-quark Fierz basis for Classes III, IV and V.
`qqqq` should be of the form 'sbuc', 'sdcc', 'ucuu' etc."""
#case dduu
classIII = ['sbuc', 'sbcu', 'dbuc', 'dbcu', 'dsuc', 'dscu']
classVdduu = ['sbuu' , 'dbuu', 'dsuu', 'sbcc' , 'dbcc', 'dscc']
if qqqq in classIII + classVdduu:
f1 = dflav[qqqq[0]]
f2 = dflav[qqqq[1]]
f3 = uflav[qqqq[2]]
f4 = uflav[qqqq[3]]
return {
'F' + qqqq + '1' : C["V1udLL"][f3, f4, f1, f2]
- C["V8udLL"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '2' : C["V8udLL"][f3, f4, f1, f2] / 2,
'F' + qqqq + '3' : C["V1duLR"][f1, f2, f3, f4]
- C["V8duLR"][f1, f2, f3, f4] / (2 * Nc),
'F' + qqqq + '4' : C["V8duLR"][f1, f2, f3, f4] / 2,
'F' + qqqq + '5' : C["S1udRR"][f3, f4, f1, f2]
- C["S8udduRR"][f3, f2, f1, f4] / 4
- C["S8udRR"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '6' : -C["S1udduRR"][f3, f2, f1, f4] / 2
+ C["S8udduRR"][f3, f2, f1, f4] /(4 * Nc)
+ C["S8udRR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '7' : -C["V8udduLR"][f4, f1, f2, f3].conj(),
'F' + qqqq + '8' : -2 * C["V1udduLR"][f4, f1, f2, f3].conj()
+ C["V8udduLR"][f4, f1, f2, f3].conj() / Nc,
'F' + qqqq + '9' : -C["S8udduRR"][f3, f2, f1, f4] / 16,
'F' + qqqq + '10' : -C["S1udduRR"][f3, f2, f1, f4] / 8
+ C["S8udduRR"][f3, f2, f1, f4] / (16 * Nc),
'F' + qqqq + '1p' : C["V1udRR"][f3, f4, f1, f2]
- C["V8udRR"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '2p' : C["V8udRR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '3p' : C["V1udLR"][f3, f4, f1, f2]
- C["V8udLR"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '4p' : C["V8udLR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '5p' : C["S1udRR"][f4, f3, f2, f1].conj() -
C["S8udduRR"][f4, f1, f2, f3].conj() / 4
- C["S8udRR"][f4, f3, f2, f1].conj() / (2 * Nc),
'F' + qqqq + '6p' : -C["S1udduRR"][f4, f1, f2, f3].conj() / 2 +
C["S8udduRR"][f4, f1, f2, f3].conj()/(4 * Nc)
+ C["S8udRR"][f4, f3, f2, f1].conj() / 2,
'F' + qqqq + '7p' : -C["V8udduLR"][f3, f2, f1, f4],
'F' + qqqq + '8p' : - 2 * C["V1udduLR"][f3, f2, f1, f4]
+ C["V8udduLR"][f3, f2, f1, f4] / Nc,
'F' + qqqq + '9p' : -C["S8udduRR"][f4, f1, f2, f3].conj() / 16,
'F' + qqqq + '10p' : -C["S1udduRR"][f4, f1, f2, f3].conj() / 8
+ C["S8udduRR"][f4, f1, f2, f3].conj() / 16 / Nc
}
classVuudd = ['ucdd', 'ucss', 'ucbb']
if qqqq in classVuudd:
f3 = uflav[qqqq[0]]
f4 = uflav[qqqq[1]]
f1 = dflav[qqqq[2]]
f2 = dflav[qqqq[3]]
return {
'F' + qqqq + '1' : C["V1udLL"][f3, f4, f1, f2]
- C["V8udLL"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '2' : C["V8udLL"][f3, f4, f1, f2] / 2,
'F' + qqqq + '3p' : C["V1duLR"][f1, f2, f3, f4]
- C["V8duLR"][f1, f2, f3, f4] / (2 * Nc),
'F' + qqqq + '4p' : C["V8duLR"][f1, f2, f3, f4] / 2,
'F' + qqqq + '5' : C["S1udRR"][f3, f4, f1, f2]
- C["S8udduRR"][f3, f2, f1, f4] / 4
- C["S8udRR"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '6' : -C["S1udduRR"][f3, f2, f1, f4] / 2
+ C["S8udduRR"][f3, f2, f1, f4] /(4 * Nc)
+ C["S8udRR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '7p' : -C["V8udduLR"][f4, f1, f2, f3].conj(),
'F' + qqqq + '8p' : -2 * C["V1udduLR"][f4, f1, f2, f3].conj()
+ C["V8udduLR"][f4, f1, f2, f3].conj() / Nc,
'F' + qqqq + '9' : -C["S8udduRR"][f3, f2, f1, f4] / 16,
'F' + qqqq + '10' : -C["S1udduRR"][f3, f2, f1, f4] / 8
+ C["S8udduRR"][f3, f2, f1, f4] / (16 * Nc),
'F' + qqqq + '1p' : C["V1udRR"][f3, f4, f1, f2]
- C["V8udRR"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '2p' : C["V8udRR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '3' : C["V1udLR"][f3, f4, f1, f2]
- C["V8udLR"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '4' : C["V8udLR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '5p' : C["S1udRR"][f4, f3, f2, f1].conj() -
C["S8udduRR"][f4, f1, f2, f3].conj() / 4
- C["S8udRR"][f4, f3, f2, f1].conj() / (2 * Nc),
'F' + qqqq + '6p' : -C["S1udduRR"][f4, f1, f2, f3].conj() / 2 +
C["S8udduRR"][f4, f1, f2, f3].conj()/(4 * Nc)
+ C["S8udRR"][f4, f3, f2, f1].conj() / 2,
'F' + qqqq + '7' : -C["V8udduLR"][f3, f2, f1, f4],
'F' + qqqq + '8' : - 2 * C["V1udduLR"][f3, f2, f1, f4]
+ C["V8udduLR"][f3, f2, f1, f4] / Nc,
'F' + qqqq + '9p' : -C["S8udduRR"][f4, f1, f2, f3].conj() / 16,
'F' + qqqq + '10p' : -C["S1udduRR"][f4, f1, f2, f3].conj() / 8
+ C["S8udduRR"][f4, f1, f2, f3].conj() / 16 / Nc
}
#case dddd
classIV = ['sbsd', 'dbds', 'bsbd']
classVdddd = ['sbss', 'dbdd', 'dsdd', 'sbbb', 'dbbb', 'dsss']
classVddddind = ['sbdd', 'dsbb', 'dbss']
if qqqq in classIV + classVdddd + classVddddind:
f1 = dflav[qqqq[0]]
f2 = dflav[qqqq[1]]
f3 = dflav[qqqq[2]]
f4 = dflav[qqqq[3]]
return {
'F'+ qqqq +'1' : C["VddLL"][f3, f4, f1, f2],
'F'+ qqqq +'2' : C["VddLL"][f1, f4, f3, f2],
'F'+ qqqq +'3' : C["V1ddLR"][f1, f2, f3, f4]
- C["V8ddLR"][f1, f2, f3, f4]/(2 * Nc),
'F'+ qqqq +'4' : C["V8ddLR"][f1, f2, f3, f4] / 2,
'F'+ qqqq +'5' : C["S1ddRR"][f3, f4, f1, f2]
- C["S8ddRR"][f3, f2, f1,f4] / 4
- C["S8ddRR"][f3, f4, f1, f2] / (2 * Nc),
'F'+ qqqq +'6' : -C["S1ddRR"][f1, f4, f3, f2] / 2
+ C["S8ddRR"][f3, f2, f1, f4] / (4 * Nc)
+ C["S8ddRR"][f3, f4, f1, f2] / 2,
'F'+ qqqq +'7' : -C["V8ddLR"][f1, f4, f3, f2],
'F'+ qqqq +'8' : -2 * C["V1ddLR"][f1, f4, f3, f2]
+ C["V8ddLR"][f1, f4, f3, f2] / Nc,
'F'+ qqqq +'9' : -C["S8ddRR"][f3, f2, f1, f4] / 16,
'F'+ qqqq +'10' : -C["S1ddRR"][f1, f4, f3, f2] / 8
+ C["S8ddRR"][f3, f2, f1, f4] / (16 * Nc),
'F'+ qqqq +'1p' : C["VddRR"][f3, f4, f1, f2],
'F'+ qqqq +'2p' : C["VddRR"][f1, f4, f3, f2],
'F'+ qqqq +'3p' : C["V1ddLR"][f3, f4, f1, f2]
- C["V8ddLR"][f3, f4, f1,f2] / (2 * Nc),
'F'+ qqqq +'4p' : C["V8ddLR"][f3, f4, f1, f2] / 2,
'F'+ qqqq +'5p' : C["S1ddRR"][f4, f3, f2, f1].conj() -
C["S8ddRR"][f4, f1, f2, f3].conj() / 4
-C["S8ddRR"][f4, f3, f2, f1].conj() / 2 / Nc,
'F'+ qqqq +'6p' : -C["S1ddRR"][f4, f1, f2, f3].conj() / 2 +
C["S8ddRR"][f4, f1, f2, f3].conj() / 4 / Nc
+ C["S8ddRR"][f4, f3, f2, f1].conj() / 2,
'F'+ qqqq +'7p' : -C["V8ddLR"][f3, f2, f1, f4],
'F'+ qqqq +'8p' : -2 * C["V1ddLR"][f3, f2, f1, f4]
+ C["V8ddLR"][f3, f2, f1, f4] / Nc,
'F'+ qqqq +'9p' : -C["S8ddRR"][f4, f1, f2, f3].conj() / 16,
'F'+ qqqq +'10p' : -C["S1ddRR"][f4, f1, f2, f3].conj() / 8 +
C["S8ddRR"][f4, f1, f2, f3].conj() / 16 / Nc
}
#case uuuu
classVuuuu = ['ucuu', 'cucc', 'cuuu', 'uccc']
if qqqq in classVuuuu:
f1 = uflav[qqqq[0]]
f2 = uflav[qqqq[1]]
f3 = uflav[qqqq[2]]
f4 = uflav[qqqq[3]]
return {
'F' + qqqq + '1' : C["VuuLL"][f3, f4, f1, f2],
'F' + qqqq + '2' : C["VuuLL"][f1, f4, f3, f2],
'F' + qqqq + '3' : C["V1uuLR"][f1, f2, f3, f4]
- C["V8uuLR"][f1, f2, f3, f4] / (2 * Nc),
'F' + qqqq + '4' : C["V8uuLR"][f1, f2, f3, f4] / 2,
'F' + qqqq + '5' : C["S1uuRR"][f3, f4, f1, f2]
- C["S8uuRR"][f3, f2, f1, f4] / 4
- C["S8uuRR"][f3, f4, f1, f2] / (2 * Nc),
'F' + qqqq + '6' : -C["S1uuRR"][f1, f4, f3, f2] / 2
+ C["S8uuRR"][f3, f2, f1, f4] / (4 * Nc)
+ C["S8uuRR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '7' : -C["V8uuLR"][f1, f4, f3, f2],
'F' + qqqq + '8' : -2 * C["V1uuLR"][f1, f4, f3, f2]
+ C["V8uuLR"][f1, f4, f3, f2] / Nc,
'F' + qqqq + '9' : -C["S8uuRR"][f3, f2, f1, f4] / 16,
'F' + qqqq + '10' : -C["S1uuRR"][f1, f4, f3, f2] / 8
+ C["S8uuRR"][f3, f2, f1, f4] / (16 * Nc),
'F'+ qqqq + '1p': C["VuuRR"][f3, f4, f1, f2],
'F' + qqqq + '2p': C["VuuRR"][f1, f3, f4, f2],
'F' + qqqq + '3p' : C["V1uuLR"][f3, f4, f1, f2]
- C["V8uuLR"][f3, f4, f1,f2] / (2 * Nc),
'F' + qqqq + '4p' : C["V8uuLR"][f3, f4, f1, f2] / 2,
'F' + qqqq + '5p' : C["S1uuRR"][f4, f3, f2, f1].conj() -
C["S8uuRR"][f4, f1, f2, f3].conj() / 4 -
C["S8uuRR"][f4, f3, f2, f1].conj() / 2 / Nc,
'F' + qqqq + '6p' : -C["S1uuRR"][f4, f1, f2, f3].conj() / 2 +
C["S8uuRR"][f4, f1, f2, f3].conj() / 4 / Nc
+ C["S8uuRR"][f4, f3, f2, f1].conj() / 2,
'F' + qqqq + '7p' : -C["V8uuLR"][f3, f2, f1, f4],
'F' + qqqq + '8p' : -2 * C["V1uuLR"][f3, f2, f1, f4]
+ C["V8uuLR"][f3, f2, f1, f4] / Nc,
'F' + qqqq + '9p' : -C["S8uuRR"][f4, f1, f2, f3].conj() / 16,
'F' + qqqq + '10p' : -C["S1uuRR"][f4, f1, f2, f3].conj() / 8 +
C["S8uuRR"][f4, f1, f2, f3].conj() / 16 / Nc
}
else:
raise ValueError(f"Case not implemented: {qqqq}")
| 5,345,456 |
def get_parsed_args() -> Any:
"""Return Porcupine's arguments as returned by :func:`argparse.parse_args`."""
assert _parsed_args is not None
return _parsed_args
| 5,345,457 |
def get_license_description(license_code):
"""
Gets the description of the given license code. For example, license code '1002' results in 'Accessory Garage'
:param license_code: The license code
:return: The license description
"""
global _cached_license_desc
return _cached_license_desc[license_code]
| 5,345,458 |
def db_keys_unlock(passphrase) -> bool:
"""Unlock secret key with pass phrase"""
global _secretkeyfile
try:
with open(_secretkeyfile, "rb") as f:
secretkey = pickle.load(f)
if not secretkey["locked"]:
print("Secret key file is already unlocked")
return True
if passphrase:
usepass = passphrase
else:
usepass = getpass("Enter pass phrase: ")
print("")
if usepass:
if secretkey["hash"] == blake2b(str.encode(usepass)).hexdigest():
k = Fernet(password_to_key(usepass))
secretkey["secret"] = k.decrypt(str.encode(secretkey["secret"])).decode()
secretkey["locked"] = False
db_keys_set(secretkey, False)
else:
print("Pass phrase did not match, secret key remains locked")
return False
except Exception:
print("Error locking secret key content")
return False
print("Secret key successfully unlocked")
return True
| 5,345,459 |
def list_domains():
"""
Return a list of the salt_id names of all available Vagrant VMs on
this host without regard to the path where they are defined.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_domains --log-level=info
The log shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date.
"""
vms = []
cmd = 'vagrant global-status'
reply = __salt__['cmd.shell'](cmd)
log.info('--->\n%s', reply)
for line in reply.split('\n'): # build a list of the text reply
tokens = line.strip().split()
try:
_ = int(tokens[0], 16) # valid id numbers are hexadecimal
except (ValueError, IndexError):
continue # skip lines without valid id numbers
machine = tokens[1]
cwd = tokens[-1]
name = get_machine_id(machine, cwd)
if name:
vms.append(name)
return vms
| 5,345,460 |
def get_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint
"""
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
}
| 5,345,461 |
def line_crops_and_labels(iam: IAM, split: str):
"""Load IAM line labels and regions, and load line image crops."""
crops = []
labels = []
for filename in iam.form_filenames:
if not iam.split_by_id[filename.stem] == split:
continue
image = util.read_image_pil(filename)
image = ImageOps.grayscale(image)
image = ImageOps.invert(image)
labels += iam.line_strings_by_id[filename.stem]
crops += [
image.crop([region[_] for _ in ["x1", "y1", "x2", "y2"]])
for region in iam.line_regions_by_id[filename.stem]
]
assert len(crops) == len(labels)
return crops, labels
| 5,345,462 |
def convert(chinese):
"""converts Chinese numbers to int
in: string
out: string
"""
numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无':90}
units = {'个':1, '十':10, '百':100, '千':1000, '万':10000, '亿':100000000,'万亿':1000000000000, '拾':10, '佰':100, '仟':1000}
number, pureNumber = 0, True
for i in range(len(chinese)):
if chinese[i] in units or chinese[i] in ['廿', '卅', '卌', '虚', '圆', '近', '枯', '无']:
pureNumber = False
break
if chinese[i] in numbers:
number = number * 10 + numbers[chinese[i]]
if pureNumber:
return number
number = 0
for i in range(len(chinese)):
if chinese[i] in numbers or chinese[i] == '十' and (i == 0 or chinese[i - 1] not in numbers or chinese[i - 1] == '零'):
base, currentUnit = 10 if chinese[i] == '十' and (i == 0 or chinese[i] == '十' and chinese[i - 1] not in numbers or chinese[i - 1] == '零') else numbers[chinese[i]], '个'
for j in range(i + 1, len(chinese)):
if chinese[j] in units:
if units[chinese[j]] >= units[currentUnit]:
base, currentUnit = base * units[chinese[j]], chinese[j]
number = number + base
return number
| 5,345,463 |
def computeZvector(idata, hue, control, features_to_eval):
"""
:param all_data: dataframe
:return:
"""
all_data = idata.copy()
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
m_indexes = list(all_data[hue].unique().astype('str'))
query_one = ""
for el in control:
if el in m_indexes:
query_one = query_one + hue + "==\'" + str(el) + "\'|"
else:
break
query_one = query_one[:-1] # remove last character
df_q = all_data.query(query_one).copy()
eps = 1e-15
# Compute average for each feature, per each treatment
avg_vec = pd.DataFrame()
for el in m_indexes:
data_calc = all_data.query(hue + "==\'" + str(el) + "\'").copy()
for col in data_calc.select_dtypes(include=numerics):
if col in features_to_eval:
avg_vec.loc[el, col] = data_calc[col].mean()
# Compute length of vector
all_data.loc[:, 'length'] = 0
for feature in features_to_eval:
all_data['length'] = all_data['length'] + all_data[feature] ** 2
all_data['length'] = np.sqrt(all_data['length'])
# Compute cosine
# Dot product of each vector per each mean v*w
all_data.loc[:, 'cosine'] = 0
for el in m_indexes:
for feature in features_to_eval:
all_data.loc[all_data['Gene'] == el, 'cosine'] = all_data.loc[all_data['Gene'] == el, 'cosine'] + \
all_data[all_data['Gene'] == el][feature] * avg_vec.loc[
el, feature]
# Norm of avg_vec
v_avg_norm = np.sqrt(np.sum(avg_vec ** 2, axis=1))
for el in m_indexes:
all_data.loc[all_data['Gene'] == el, 'cosine'] = all_data.loc[all_data['Gene'] == el, 'cosine'] / (
all_data.loc[all_data['Gene'] == el, 'length'] * v_avg_norm[el])
all_data['projection'] = all_data['length'] * all_data['cosine']
return all_data
| 5,345,464 |
def getjflag(job):
"""Returns flag if job in finished state"""
return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0
| 5,345,465 |
def describe_snapshot_schedule(VolumeARN=None):
"""
Describes the snapshot schedule for the specified gateway volume. The snapshot schedule information includes intervals at which snapshots are automatically initiated on the volume. This operation is only supported in the cached volume and stored volume architectures.
See also: AWS API Documentation
Examples
Describes the snapshot schedule for the specified gateway volume including intervals at which snapshots are automatically initiated.
Expected Output:
:example: response = client.describe_snapshot_schedule(
VolumeARN='string'
)
:type VolumeARN: string
:param VolumeARN: [REQUIRED]
The Amazon Resource Name (ARN) of the volume. Use the ListVolumes operation to return a list of gateway volumes.
:rtype: dict
:return: {
'VolumeARN': 'string',
'StartAt': 123,
'RecurrenceInHours': 123,
'Description': 'string',
'Timezone': 'string'
}
"""
pass
| 5,345,466 |
def json_parse(ddict):
"""
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/test_json/test_functions.json
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/json/benchmark_timeseries/gluonts_m5.json
"deepar": {
"model_pars": {
"model_uri" : "model_gluon.gluonts_model",
"model_name" : "deepar",
"model_pars" : {
"prediction_length": 12,
"freq": "D",
"distr_output" : {"uri" : "gluonts.distribution.neg_binomial:NegativeBinomialOutput"},
"distr_output" : "uri::gluonts.distribution.neg_binomial:NegativeBinomialOutput",
"""
import copy
js = ddict
js2 = copy.deepcopy(js)
def parse2(d2):
if "uri" in d2:
# Be careful not to include heavy compute
return json_to_object(d2)
else:
return json_norm(d2)
for k, val in js.items():
if isinstance(val, dict):
js2[k] = parse2(val)
elif "uri::" in val: # Shortcut when nor argument
js2[k] = json_to_object({"uri": val.split("uri::")[-1]})
else:
js2[k] = json_norm_val(val)
return js2
| 5,345,467 |
def read_viz_icons(style='icomoon', fname='infinity.png'):
""" Read specific icon from specific style
Parameters
----------
style : str
Current icon style. Default is icomoon.
fname : str
Filename of icon. This should be found in folder HOME/.dipy/style/.
Default is infinity.png.
Returns
--------
path : str
Complete path of icon.
"""
folder = pjoin(dipy_home, 'icons', style)
return pjoin(folder, fname)
| 5,345,468 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="12345",
domain=DOMAIN,
data={CONF_API_KEY: "tskey-MOCK", CONF_SYSTEM_ID: 12345},
unique_id="12345",
)
| 5,345,469 |
def get_mnist_loader(batch_size, train, perm=0., Nparts=1, part=0, seed=0, taskid=0, pre_processed=True, **loader_kwargs):
"""Builds and returns Dataloader for MNIST and SVHN dataset."""
transform = transforms.Compose([
transforms.Grayscale(),
transforms.ToTensor(),
transforms.Normalize((0.0,), (1.0,)),
transforms.Lambda(lambda x: x.view([28,28]))])
dataset = datasets.MNIST(root='./data', download=True, transform=transform, train = train)
if perm>0:
permute_dataset(dataset, perm, seed=seed)
if Nparts>1:
partition_dataset(dataset, Nparts,part)
if pre_processed:
dataset = preprocess_dataset(dataset)
DL = DataLoaderPreProcessed
else:
DL = DataLoader
loader = DL(dataset=dataset,
batch_size=batch_size,
shuffle=train,
**loader_kwargs)
loader.taskid = taskid
loader.name = 'MNIST_{}'.format(taskid,part)
loader.short_name = 'MNIST'
return loader
| 5,345,470 |
def gradients_summary(y, x, norm=tf.abs, name='gradients_y_wrt_x'):
"""Summary gradients w.r.t. x.
Sum of norm of :math:`\\nabla_xy`.
:param y: y
:param x: w.r.t x
:param norm: norm function, default is tf.abs
:param name: name of gradients summary
:return: None
"""
grad = tf.reduce_sum(norm(tf.gradients(y, x)))
scalar_summary(name, grad)
| 5,345,471 |
def read_data(filename):
"""
Reads orbital map file into a list
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip().split('\n')
f.close()
return data
| 5,345,472 |
def _form_factor_pipi(
self, s: Union[float, npt.NDArray[np.float64]], imode: int = 1
) -> Union[complex, npt.NDArray[np.complex128]]:
"""
Compute the pi-pi-V form factor.
Parameters
----------
s: Union[float,npt.NDArray[np.float64]
Square of the center-of-mass energy in MeV.
imode: Optional[int]
Iso-spin channel. Default is 1.
Returns
-------
ff: Union[complex,npt.NDArray[np.complex128]]
Form factor from pi-pi-V.
"""
return __ff_pipi(
s * 1e-6, # Convert to GeV
self._ff_pipi_params,
self._gvuu,
self._gvdd,
)
| 5,345,473 |
def lecture():
"""
lecture()
Lee archivos "tmdb_5000_credits.csv" y "tmdb_5000_movies.csv"
para luego transformarlos en pandas.DataFrame.
Parameters
----------
None.
Returns
-------
credits, movies : [pandas.DataFrame, pandas.DataFrame]
Es una lista del DataFrame credits y DataFrame movies.
"""
try:
credits = pd.read_csv(os.path.join("data","tmdb_5000_credits.csv"))
movies = pd.read_csv(os.path.join("data","tmdb_5000_movies.csv"))
print("Datos correctamente leídos")
return credits, movies
except:
print("Datos incorrectamente leídos")
return None, None
| 5,345,474 |
def string_to_epoch(s):
"""
Convert argument string to epoch if possible
If argument looks like int + s,h,md (ie, 30d), we'll pass as-is
since pushshift can accept this. Per docs, pushshift supports:
Epoch value or Integer + "s,m,h,d" (i.e. 30d for 30 days)
:param s: str
:return: int | str
"""
if s is not None:
s = s.strip()
if re.search('^[0-9]+[smhd]$', s):
return s
try:
s = dp.parse(s).timestamp()
s = int(s)
except ValueError:
raise click.BadParameter("could not convert argument to "
"a datetime: {}".format(s))
return s
| 5,345,475 |
def spline_filter(Iin, lmbda=5.0):
"""Smoothing spline (cubic) filtering of a rank-2 array.
Filter an input data set, `Iin`, using a (cubic) smoothing spline of
fall-off `lmbda`.
"""
intype = Iin.dtype.char
hcol = array([1.0,4.0,1.0],'f')/6.0
if intype in ['F','D']:
Iin = Iin.astype('F')
ckr = cspline2d(Iin.real,lmbda)
cki = cspline2d(Iin.imag,lmbda)
outr = sepfir2d(ckr,hcol,hcol)
outi = sepfir2d(cki,hcol,hcol)
out = (outr + 1j*outi).astype(intype)
elif intype in ['f','d']:
ckr = cspline2d(Iin,lmbda)
out = sepfir2d(ckr, hcol, hcol)
out = out.astype(intype)
else:
raise TypeError("Invalid data type for Iin")
return out
| 5,345,476 |
def set_logging_level(level=logging.INFO):
"""Sets the log level for the global logger
:param level: Log level to set
:type level: str
"""
logger.setLevel(level)
ch.setLevel(level)
| 5,345,477 |
def _construct_aline_collections(alines, dtix=None):
"""construct arbitrary line collections
Parameters
----------
alines : sequence
sequences of segments, which are sequences of lines,
which are sequences of two or more points ( date[time], price ) or (x,y)
date[time] may be (a) pandas.to_datetime parseable string,
(b) pandas Timestamp, or
(c) python datetime.datetime or datetime.date
alines may also be a dict, containing
the following keys:
'alines' : the same as defined above: sequence of price, or dates, or segments
'colors' : colors for the above alines
'linestyle' : line types for the above alines
'linewidths' : line types for the above alines
dtix: date index for the x-axis, used for converting the dates when
x-values are 'evenly spaced integers' (as when skipping non-trading days)
Returns
-------
ret : list
lines collections
"""
if alines is None:
return None
if isinstance(alines,dict):
aconfig = _process_kwargs(alines, _valid_lines_kwargs())
alines = aconfig['alines']
else:
aconfig = _process_kwargs({}, _valid_lines_kwargs())
#print('aconfig=',aconfig)
#print('alines=',alines)
alines = _alines_validator(alines, returnStandardizedValue=True)
if alines is None:
raise ValueError('Unable to standardize alines value: '+str(alines))
alines = _convert_segment_dates(alines,dtix)
lw = aconfig['linewidths']
co = aconfig['colors']
ls = aconfig['linestyle']
al = aconfig['alpha']
lcollection = LineCollection(alines,colors=co,linewidths=lw,linestyles=ls,antialiaseds=(0,),alpha=al)
return lcollection
| 5,345,478 |
def is_mergeable(*ts_or_tsn):
"""Check if all objects(FermionTensor or FermionTensorNetwork)
are part of the same FermionSpace
"""
if isinstance(ts_or_tsn, (FermionTensor, FermionTensorNetwork)):
return True
fs_lst = []
site_lst = []
for obj in ts_or_tsn:
if isinstance(obj, FermionTensor):
if obj.fermion_owner is None:
return False
hashval, fsobj, tid = obj.fermion_owner
fs_lst.append(hashval)
site_lst.append(fsobj()[tid][1])
elif isinstance(obj, FermionTensorNetwork):
fs_lst.append(hash(obj.fermion_space))
site_lst.extend(obj.filled_sites)
else:
raise TypeError("unable to find fermionspace")
return all([fs==fs_lst[0] for fs in fs_lst]) and len(set(site_lst)) == len(site_lst)
| 5,345,479 |
def fetch_file(url, config):
"""
Fetch a file from a provider.
"""
# pylint: disable=fixme
# FIXME: the handled checking should be in each handler module (possibly handle_file(parsed_url,
# config) => bool)
parsed_url = urllib.parse.urlparse(url)
if parsed_url.scheme == 'github':
file_contents = github.fetch_file(parsed_url, config)
elif parsed_url.scheme == 'file' or (parsed_url.scheme == '' and parsed_url.netloc == ''):
purl = list(parsed_url)
purl[0] = 'file'
parsed_url = urllib.parse.ParseResult(*purl)
file_contents = file.fetch_file(parsed_url, config)
elif parsed_url.scheme in ('http', 'https'):
file_contents = http.fetch_file(parsed_url, config)
else:
raise NotImplementedError(f'Unknown fetch backend: {parsed_url.scheme}')
return file_contents
| 5,345,480 |
def query_for_account(account_rec, region):
""" Performs the public ip query for the given account
:param account: Account number to query
:param session: Initial session
:param region: Region to query
:param ip_data: Initial list. Appended to and returned
:return: update ip_data list
"""
ip_data = []
session = boto3.session.Session(region_name=region)
assume = rolesession.assume_crossact_audit_role(
session, account_rec['accountNum'], region)
if assume:
for ip_addr in assume.client('ec2').describe_addresses()['Addresses']:
ip_data.append(
dict(PublicIP=(ip_addr.get('PublicIp')),
InstanceId=(ip_addr.get('InstanceId')), # Prevents a crash
PrivateIP=(ip_addr.get('PrivateIpAddress')),
NetworkInterface=(ip_addr.get('NetworkInterfaceId')),
AccountNum=account_rec['accountNum'],
AccountAlias=(account_rec['alias'])))
for instance in assume.resource('ec2').instances.filter():
if instance.public_ip_address:
ip_data.append(
dict(InstanceId=(instance.instance_id),
PublicIP=(instance.public_ip_address),
PrivateIP=(instance.private_ip_address),
AccountNum=account_rec['accountNum'],
AccountAlias=(account_rec['alias'])))
else:
pass
return ip_data
| 5,345,481 |
def main():
"""Invoke the command-line entrypoint."""
mecha(prog_name="mecha")
| 5,345,482 |
def filter_list_of_dicts(list_of_dicts: list, **filters) -> List[dict]:
"""Filter a list of dicts by any given key-value pair.
Support simple logical operators like: '<,>,<=,>=,!'. Supports
filtering by providing a list value i.e. openJobsCount=[0, 1, 2].
"""
for key, value in filters.items():
filter_function = make_dict_filter(key, value)
list_of_dicts = list(filter(filter_function, list_of_dicts))
return list_of_dicts
| 5,345,483 |
def test_database_init():
"""Test creating a fresh instance of the database."""
db = DB(connect_url=TEST_URL)
db.init()
| 5,345,484 |
def construct_pos_line(elem, coor, tags):
"""
Do the opposite of the parse_pos_line
"""
line = "{elem} {x:.10f} {y:.10f} {z:.10f} {tags}"
return line.format(elem=elem, x=coor[0], y=coor[1], z=coor[2], tags=tags)
| 5,345,485 |
def compute_pcs(predicts, labels, label_mapper, dataset):
"""
compute correctly predicted full spans. If cues and scopes are predicted jointly, convert cue labels to I/O labels depending on the
annotation scheme for the considered dataset
:param predicts:
:param labels:
:return:
"""
def trim_and_convert(predict, label, label_mapper, dataset):
temp_1 = []
temp_2 = []
for j, m in enumerate(predict):
if label_mapper[label[j]] != 'X' and label_mapper[label[j]] != 'CLS' and label_mapper[label[j]] != 'SEP':
temp_1.append(label_mapper[label[j]])
temp_2.append(label_mapper[m])
if 'joint' in dataset:
if cue_in_scope[dataset] is True:
replacement= 'I'
else: replacement = 'O'
for j, m in enumerate(temp_1):
if m == 'C':
temp_1[j] = replacement
for j, m in enumerate(temp_2):
if m == 'C':
temp_2[j] = replacement
return temp_2, temp_1
tp = 0.
for predict, label in zip(predicts, labels):
predict, label = trim_and_convert(predict, label, label_mapper,dataset)
if predict == label:
tp += 1
return tp/len(predicts)
| 5,345,486 |
def echoError(msg):
"""colored cli feedback"""
click.echo(click.style(msg, fg="red"))
| 5,345,487 |
def pentomino():
"""
Main pentomino routine
@return {string} solution as rectangles separated by a blank line
"""
return _stringify(
_pent_wrapper1(tree_main_builder())(rect_gen_boards()))
| 5,345,488 |
def do_login(request, username, password):
""" Check credentials and log in """
if request.access.verify_user(username, password):
request.response.headers.extend(remember(request, username))
return {"next": request.app_url()}
else:
return HTTPForbidden()
| 5,345,489 |
def _interpolate(format1):
"""
Takes a format1 string and returns a list of 2-tuples of the form
(boolean, string) where boolean says whether string should be evaled
or not.
from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee)
"""
from tokenize import Token
def matchorfail(text, pos):
tokenprog = re.compile(Token)
match = tokenprog.match(text, pos)
if match is None:
raise _ItplError(text, pos)
return match, match.end()
namechars = "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
chunks = []
pos = 0
while 1:
dollar = format1.find("$", pos)
if dollar < 0:
break
nextchar = format1[dollar + 1]
if nextchar == "{":
chunks.append((0, format1[pos:dollar]))
pos, level = dollar + 2, 1
while level:
match, pos = matchorfail(format1, pos)
tstart, tend = match.regs[3]
token = format1[tstart:tend]
if token == "{":
level = level + 1
elif token == "}":
level = level - 1
chunks.append((1, format1[dollar + 2:pos - 1]))
elif nextchar in namechars:
chunks.append((0, format1[pos:dollar]))
match, pos = matchorfail(format1, dollar + 1)
while pos < len(format1):
if format1[pos] == "." and \
pos + 1 < len(format1) and format1[pos + 1] in namechars:
match, pos = matchorfail(format1, pos + 1)
elif format1[pos] in "([":
pos, level = pos + 1, 1
while level:
match, pos = matchorfail(format1, pos)
tstart, tend = match.regs[3]
token = format1[tstart:tend]
if token[0] in "([":
level = level + 1
elif token[0] in ")]":
level = level - 1
else:
break
chunks.append((1, format1[dollar + 1:pos]))
else:
chunks.append((0, format1[pos:dollar + 1]))
pos = dollar + 1 + (nextchar == "$")
if pos < len(format1):
chunks.append((0, format1[pos:]))
return chunks
| 5,345,490 |
def approxIndex(iterable, item, threshold):
"""Same as the python index() function but with a threshold from wich values are considerated equal."""
for i, iterableItem in rev_enumerate(iterable):
if abs(iterableItem - item) < threshold:
return i
return None
| 5,345,491 |
def delete_important_words(word_list, replace=''):
"""
randomly detele an important word in the query or replace (not in QUERY_SMALL_CHANGE_SETS)
"""
# replace can be [MASK]
important_word_list = set(word_list) - set(QUERY_SMALL_CHANGE_SETS)
target = random.sample(important_word_list, 1)[0]
if replace:
new_word_list = [item if item!=target else item.replace(target, replace) for item in word_list]
else:
new_word_list = [item for item in word_list if item!=target]
return new_word_list
| 5,345,492 |
def prot(vsini, st_rad):
"""
Function to convert stellar rotation velocity vsini in km/s to rotation period in days.
Parameters:
----------
vsini: Rotation velocity of star in km/s.
st_rad: Stellar radius in units of solar radii
Returns
------
Prot: Period of rotation of the star in days.
"""
import numpy as np
vsini=np.array(vsini)
prot=(2*np.pi*st_rad*rsun)/(vsini*24*60*60)
return prot
| 5,345,493 |
def dialog_sleep():
"""Return the time to sleep as set by the --exopy-sleep option.
"""
return DIALOG_SLEEP
| 5,345,494 |
def required_overtime (db, user, frm) :
""" If required_overtime flag is set for overtime_period of dynamic
user record at frm, we return the overtime_period belonging to
this dyn user record. Otherwise return None.
"""
dyn = get_user_dynamic (db, user, frm)
if dyn and dyn.overtime_period :
otp = db.overtime_period.getnode (dyn.overtime_period)
if otp.required_overtime :
return otp
return None
| 5,345,495 |
def get_best_fit_member(*args):
"""
get_best_fit_member(sptr, offset) -> member_t
Get member that is most likely referenced by the specified offset.
Useful for offsets > sizeof(struct).
@param sptr (C++: const struc_t *)
@param offset (C++: asize_t)
"""
return _ida_struct.get_best_fit_member(*args)
| 5,345,496 |
def convert_time(time):
"""Convert given time to srt format."""
stime = '%(hours)02d:%(minutes)02d:%(seconds)02d,%(milliseconds)03d' % \
{'hours': time / 3600,
'minutes': (time % 3600) / 60,
'seconds': time % 60,
'milliseconds': (time % 1) * 1000}
return stime
| 5,345,497 |
def Returns1(target_bitrate, result):
"""Score function that returns a constant value."""
# pylint: disable=W0613
return 1.0
| 5,345,498 |
def task_imports():
"""find imports from a python module"""
base_path = pathlib.Path("youtube_dl_gui")
pkg_modules = ModuleSet(base_path.glob("**/*.py"))
for name, module in pkg_modules.by_name.items():
yield {
"name": name,
"file_dep": [module.path],
"actions": [(get_imports, (pkg_modules, module.path))],
}
| 5,345,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.