content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def for_four():
""" Number pattern '4' using Python for loop"""
for row in range(5):
for col in range(5):
if col==3 or row==3 or row+col==3:
print('*', end = ' ')
else:
... | 5,318,500 |
def hash_params(params):
"""
Construct a data structure of parameters that is hashable.
This requires changing any mutable data structures into immutable ones.
We chose a frozenset because role parameters have to be unique.
.. warning:: this does not handle unhashable scalars. Two things
... | 5,318,501 |
def get_validate_result_form(tel_num, validate_code):
"""
Assemble form for get_validate_result
:param tel_num: Tel number
:param validate_code: Validate code from capcha image
:return: Param in dict
"""
post_data_dict = dict()
post_data_dict['source'] = 'wsyyt'
post_data_dict['telno... | 5,318,502 |
def create_user():
"""Create a new user record."""
request = flask.request.get_json()
try:
# NOTE(jk0): We expect all of these keys to exist to be considered a
# valid user record. Ignore all others.
user = _lookup_user(request["userid"])
if user:
flask.abort(40... | 5,318,503 |
def test_create_prf_mean():
"""
Check if create_prf works correctly on simulated data.
"""
prf = create_prf(image, positions, psf_size, subsampling=1, mode='mean')
assert_allclose(prf._prf_array[0, 0], test_psf, atol=1E-8) | 5,318,504 |
def setBoxColors(bp, num):
"""
sets the colors of the box plots pairs
"""
m=0
for i in range(0, num):
setp(bp['boxes'][i], color=colors[i])
setp(bp['caps'][2*i], color=colors[i])
setp(bp['caps'][2*i+1], color=colors[i])
setp(bp['whiskers'][2*i], color=colors[i])
... | 5,318,505 |
def softmax_cross_entropy(logits, labels):
"""
Cross-entropy loss applied to softmax.
"""
one_hot = hk.one_hot(labels, logits.shape[-1])
return -jnp.sum(jax.nn.log_softmax(logits) * one_hot, axis=-1) | 5,318,506 |
def alarm_disarm(hass, code=None, entity_id=None):
"""Send the alarm the command for disarm."""
data = {}
if code:
data[ATTR_CODE] = code
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_ALARM_DISARM, data) | 5,318,507 |
async def test_nexus_2_remote_mirror_kill_one(
containers, mayastors, nexus_uuid, create_nexus
):
"""
This test does the following steps:
- creates mayastor instances
- creates pools on mayastor 1 and 2
- creates replicas on those pools
- creates a nexus on mayastor 3
... | 5,318,508 |
def get_category_detail(comp_id, cat_id):
"""Retrives information about the category and the reviews in it"""
json = [Category.query.filter_by(id=cat_id).filter_by(comp_id=comp_id).first_or_404().to_json()]
submissions = Submission.query.filter_by(comp_id=comp_id).all()
cat_submissions = []
for _, s... | 5,318,509 |
def build_input_from_segments(persona, history, reply, vocab,
labels=False, with_eos=True):
"""
Build a sequence of input from 3 segments:
persona, history and last reply.
"""
bos, eos, speaker1, speaker2 = vocab[SPECIAL_TOKENS[:-1]]
sequence = [[bos] + list(chain(*... | 5,318,510 |
def dual_gaussian(x, amp1=1.0, mean1=0.0, std1=1.0, amp2=1.0, mean2=0.0, std2=1.0):
"""Sum of two Gaussians.
Parameters
----------
x : array
Function argument
amp1: float
Amplitude parameter of the first Gaussian
mean1: float
Mean parameter of the first Gaussian
std1: floa... | 5,318,511 |
def getFileInfoFromXML(thisfile):
""" Get the PFN from the XML """
pfn = thisfile.getElementsByTagName("pfn")[0].getAttribute("name")
# lfn will not be present in XML any longer, get it from the PFN - possible problem with LFN file name extensions
# lfn = thisfile.getElementsByTagName("lfn")[0].getAttr... | 5,318,512 |
def get_district_info(request, code):
"""
Get district info by 'code'
"""
try:
district = District.objects.get(code=code)
child_districts = District.objects.filter(parent=district.code)
data = district_model2dict(district)
children = [district_model2dict(c) for c in child... | 5,318,513 |
def calculate_price(prices, concentrations):
"""
From a list of prices in $USD / kg and concentrations in mass %,
calculate the price of the formulation in $USD / kg
"""
# Normalise ingredient concentrations
concentrations = np.asarray(concentrations) / np.sum(concentrations)
# Calculate a... | 5,318,514 |
def check_for_ambiguity(filter_group, filter_ids, key):
"""
Check if all filters numbered the same way have the same tag 'key'
(nome, casa, channel, description). Returns an error if it
doesn't. This is needed to group filters under the same
filter set.
-- filter_group: pandas grouby object, g... | 5,318,515 |
def cos_convolve(evidence):
"""Take as input the classifier evidence for single trials in dictionary format
and return alligned evidence and evidence convolved with a cosine.
Input:
dictionary:
accuracy : ndarray
dimensions: time
matrix containing class predi... | 5,318,516 |
def get_image_info(real_image_type, body):
""" only in webp, gif, png, jpeg, bmp
"""
image_fp = StringIO(body)
if real_image_type == 'webp':
data = image_fp.read()
width, height = decode.GetInfo(data)
image_pix_count = int(width) * int(height)
else:
image = Image.ope... | 5,318,517 |
def estimate_ranks(layer):
""" Unfold the 2 modes of the Tensor the decomposition will
be performed on, and estimates the ranks of the matrices using VBMF
source: https://github.com/jacobgil/pytorch-tensor-decompositions/blob/master/decompositions.py
"""
weights = layer.weight.data
unfold_0 = ... | 5,318,518 |
def _add_batch_dim(img):
"""Many TF functions require NWHC input. Convert WHC image to NWHC of batch size 1."""
get_hwc(img) # validate dimensions
return tf.expand_dims(img, 0) | 5,318,519 |
def configure_parser(parser):
""" Configure Parser """
qisys.parsers.project_parser(parser)
qibuild.parsers.cmake_build_parser(parser)
qisys.parsers.deploy_parser(parser) | 5,318,520 |
def update():
"""
Runs command to update OS site packages.
"""
_update_os() | 5,318,521 |
def read_inventory_file(inventory):
"""
Read an inventory file, return the list of dicts
:param str inventory: The inventory file
:return list[dict, ..]: List of hostname and IP definitions
"""
log.info("Reading and validating inventory file")
inventory_hosts = load_json(inventory)
if no... | 5,318,522 |
def ground_truth_to_word(ground_truth):
"""
Return the word string based on the input ground_truth
"""
try:
return ''.join([config.CHAR_VECTOR[np.argmax(arr)] for arr in ground_truth if np.argmax(arr) < len(config.CHAR_VECTOR)])
except Exception as ex:
print(ground_truth)
... | 5,318,523 |
def test_bind_with_context_io_result():
"""Ensures that functions can be composed and return type is correct."""
binded = bind(_context_io_result_function)
assert binded(RequiresContextIOResult.from_success(3))(5) == IOSuccess(8) | 5,318,524 |
def build_dataframe(dimension_names, dimension_members, data_values,
null_values, sd_values):
"""Build a dataframe from dimensions and data.
Adds the cartesian product of dimension members plus the series of data.
Args:
dimension_names (list of string)
dimension_memb... | 5,318,525 |
def test_inline_dictionary():
"""Tests that inline dictionary values are correctly handled"""
assert hug.types.inline_dictionary('1:2') == {'1': '2'}
assert hug.types.inline_dictionary('1:2|3:4') == {'1': '2', '3': '4'}
with pytest.raises(ValueError):
hug.types.inline_dictionary('1') | 5,318,526 |
def fs_url_exists(fs_url):
"""
verifies for a valid fs url
:param fs_url: fs_url string
:return: boolean
"""
try:
fs.open_fs(fs_url)
except fs.errors.CreateFailed:
return False
return True | 5,318,527 |
def _serialize_noise_model(config):
"""Traverse the dictionary looking for noise_model keys and apply
a transformation so it can be serialized.
Args:
config (dict): The dictionary to traverse
Returns:
dict: The transformed dictionary
"""
for k, v in config.items(... | 5,318,528 |
def create_app() -> falcon.API:
"""
Typical application factory style setup.
Returns:
falcon.API: The falcon API object.
"""
engine = create_engine("sqlite:///")
app = falcon.API(middleware=[DbSessionMiddleware(engine)])
app.add_route("/", ExampleResource())
return app | 5,318,529 |
def pushd(newDir):
""" Change directory and go back to previous directory when context is left """
# See https://stackoverflow.com/a/13847807
oldDir = os.getcwd()
logging.debug(f"Current directory: '{oldDir}'")
os.chdir(newDir)
logging.debug(f"Changed directory to: '{os.getcwd()}'")
try:
... | 5,318,530 |
def show_tracker(secure=False):
"""
Output the analytics tracker code.
"""
google = getattr(settings, 'ANALYTICS', {})
if google:
analytics_code = google.get('ANALYTICS_CODE')
if analytics_code:
return {"analytics_code": analytics_code}
return {} | 5,318,531 |
async def formatCommand(cls:"PhaazebotDiscord", Command:DiscordCommand, CommandContext:DiscordCommandContext, direct_call:bool=False) -> dict:
"""
This function is suppost to do everything.
It takes the placeholder in Command.content and replaces them with the wanted data.
That also applies to module/function ca... | 5,318,532 |
def k8s_net_client(k8s_conf):
"""
Retrieves the kubernetes networking client
:param k8s_conf: the k8s configuration used to deploy the cluster
:return: a kubernetes.client.NetworkingV1Api instance
"""
logger.debug('Retrieving K8s networking API client')
return client.NetworkingV1Api(get_clie... | 5,318,533 |
def sequential_name(folder, basename):
"""
Given a proposed name for a file (string 'basename') to be saved in a
folder (identified by its path in string 'folder'), produces a new
name to use that avoids overwriting other files - as long as their
names were made with this function, too.
"""
if not os.acc... | 5,318,534 |
def metric_max_over_ground_truths(metric_fn, predictions, ground_truths):
"""Take the average best score against all ground truth answers.
This is a bit different than SQuAD in that there are multiple answers
**and** predictions that we average over. For some situations (e.g., *top k*
beams or multiple human r... | 5,318,535 |
def parse_gsod_data(filename):
"""Parse Global Summary of the Day (GSOD) data from a comma separated
.txt file.
Source: https://www7.ncdc.noaa.gov/CDO/cdoselect.cmd?datasetabbv=GSOD&countryabbv=&georegionabbv=
Format Specification: https://www7.ncdc.noaa.gov/CDO/GSOD_DESC.txt
Parameters:
... | 5,318,536 |
def deserialize(xml):
""" Deserializes a Pubmed response into an article object."""
article = {}
root = ET.fromstring(xml)
article_el = root.find('.//PubmedArticle')
if article_el is None:
print('INFO: XML did not contain a Pubmed Article.')
return None
pmid_el = article_el.find('.//MedlineC... | 5,318,537 |
def attSummaryDict(request, reqs, flist):
""" Return a dictionary summarizing the field values for the chosen most interesting fields """
sumd = {}
for req in reqs:
for f in flist:
if f in req and req[f]:
if not f in sumd: sumd[f] = {}
if not req[f] i... | 5,318,538 |
def immutable_kwargs(
kwargs: tp.Dict[str, str]
) -> tp.Tuple[tp.Tuple[str, str], ...]:
"""
Convert str-typed kwargs into a hashable tuple.
"""
return tuple((k, v) for k, v in kwargs.items()) | 5,318,539 |
def get_markings(catalogue_dir, cid, result):
"""
Take a directory of catalogue entries and extract the specific metadata related to CID
Add it to fields as defined in serene_metadata
"""
catalogue = load_markings(os.path.normpath(catalogue_dir))
catalogue_markings = catalogue[cid]
for c... | 5,318,540 |
def revise_max_intake(
max_intake, total_digestibility, energy_intake, energy_maintenance,
degr_protein_intake, protein_req, animal_type, CRD1, CRD2):
"""Calculate revised maximum intake from protein content of the diet.
When animals are unable to obtain enough protein from the diet to mai... | 5,318,541 |
def load_fcs_file(input_fcs: str, genome: str = None) -> MultimodalData:
"""Load Cyto data from a FCS file, support v2.0, v3.0 and v3.1.
Parameters
----------
input_fcs : `str`
The FCS file.
genome : `str`, optional (default None)
The genome reference. If None, use "unknown" instea... | 5,318,542 |
def ext_bottom_up_cut_rod(price, length):
""" bottom up implementation of cut rod memoized algorithm """
incomelst = [float("-Inf") for _ in range(length + 1)]
cutlst = [0 for _ in range(length + 1)]
# set zero income for zero length
incomelst[0] = 0
for j in range(1, length + 1):
income... | 5,318,543 |
def enable_generated_file_wrapper(
wrapped_target = None,
tags = None,
testonly = None,
enable_generated_file = True,
enable_presubmit_generated_file = False):
"""The function is a placeholder for enable_generated_file_wrapper.
The function is intended to be empty.
... | 5,318,544 |
def _build_config_dict(cfg_node):
"""
Updates the config dict provided from the given etcd node, which
should point at a config directory.
"""
config_dict = {}
for child in cfg_node.children:
key = child.key.rsplit("/").pop()
value = str(child.value)
config_dict[key] = va... | 5,318,545 |
def clearGlobalDB():
"""Start from scratch
This is currently only used in unit tests.
"""
global _DB_FNAME
global _LOCK
global _LOCKED
global _OPENED_DB
_DB_FNAME = None
_LOCK = None
_LOCKED = 0
_OPENED_DB = None
_REFCOUNT = 0 | 5,318,546 |
async def deploy_users(
users: list[dict[str, Any]], default_roles: dict[str, Any]
) -> None:
"""Create users in the database."""
for user in users:
name = user["name"]
attrib = {}
data: dict[str, Any] = {}
for key in ["fullname", "email"]:
if key in user:
... | 5,318,547 |
def stamp_to_ymd(timestamp):
"""
Caller sends a timestamp in seconds of epoch. Return string for
year month day of that time as YYYYMMDD' as used by url requests, as in
http://<fitsstore_server>/qaforgui/20130616
parameters: <float>, seconds of epochs.
return: <string>, YYYYMMDD of passed ... | 5,318,548 |
def ESMP_GridCreateCubedSphere(tilesize, regDecompPTile=None,
#decompFlagPTile=None, deLabelList=None,
staggerLocList=None, name=None):
"""
Preconditions: ESMP has been initialized.\n
Postconditions: An ESMP_Grid has been created.\n
Arguments... | 5,318,549 |
def extract_asymbox2(image,left_in,right_in, ycen=None, weight_image=None):
""" Extract the total flux within a variable window at many positions. This routine will accept an asymmetric/variable window
specified by the left_in and right_in traces. The ycen position is optional. If it is not provied, it is assu... | 5,318,550 |
def exists(b, d, n):
"""Check if the folder specified by the given parameters exists"""
return os.path.isdir("../Output/B" +
str(b) + " D" + str(d) + " N" + str(n)) | 5,318,551 |
def version() -> str:
"""็ๆฌๅท"""
return f'Version: {VERSION}' | 5,318,552 |
def UnpackMessage(swig_obj_pointer, msg_name):
"""Unpack a SWIG-wrapped memory object into an AIO message.
Args:
swig_obj_pointer: A SWIG-wrapped memory object pointing to the raw AIO
message payload.
msg_name: Name or short name of the message type.
Returns:
An AIO message struct.
"""
... | 5,318,553 |
def a2b_hashed_base58(s):
"""
If the passed string is hashed_base58, return the binary data.
Otherwise raises an EncodingError.
"""
data = a2b_base58(s)
data, the_hash = data[:-4], data[-4:]
if double_sha256(data)[:4] == the_hash:
return data
raise EncodingError("hashed base58 ha... | 5,318,554 |
def test_node_exists(mock_path_exists, atts, expected):
"""Tests node's exist method."""
mock_path_exists.return_value = expected
node = Node(atts)
assert expected == node.exists()
if atts['path'] is not None:
mock_path_exists.assert_called_once_with(atts['path']) | 5,318,555 |
def predict(theta, X):
""" computes the predictions for X using a threshold at 0.5
(i.e., if sigmoid(theta'*x) >= 0.5, predict 1)
"""
return np.array([1 if theta.dot(xi) >= 0.5 else 0 for xi in X]) | 5,318,556 |
def index_data(filebase, db, ext='d3C', verbose=False):
"""
Import function for data from antelope export_to_mspass.
This function is an import function for Seismogram objects created
by the antelope program export_to_mspass. That program writes
header data as a yaml file and the sample data as ... | 5,318,557 |
def add_tracks(track_ids, playlist_name, user=user):
"""
Function to add the recommeded tracks playlist
"""
playlists = sp.user_playlists(user)
for playlist in playlists['items']:
if playlist['name'] == playlist_name:
play_id = playlist['id']
sp.trace = False
results = s... | 5,318,558 |
def not_contains(a, b):
"""Evaluates a does not contain b"""
result = False if b in a else True
return result | 5,318,559 |
def build_positional_encoding(cfg, default_args=None):
"""Builder for Position Encoding."""
return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args) | 5,318,560 |
def client_info(name, address, city, vat):
"""Add the client information."""
invoice_dictio['client_name'] = name
invoice_dictio['client_address'] = address
invoice_dictio['client_city'] = city
invoice_dictio['client_vat'] = vat | 5,318,561 |
def main(*argv):
""" main driver of program """
try:
# Inputs
#
adminUsername = argv[0]
adminPassword = argv[1]
siteURL = argv[2]
groupName = argv[3]
# Logic
#
sh = arcrest.AGOLTokenSecurityHandler(adminUsername, adminPassword)
... | 5,318,562 |
def create_func_result_identifier(func, params_str, key=None, key_separator="__"):
"""
Creates a string of the following format:
If ``key`` is None:
``<FUNC_NAME><PARAMS_STR>``
If ``key`` is not None:
``<FUNC_NAME><PARAMS_STR>__key``
In both cases, ``<FUNC_NAME>`` represents... | 5,318,563 |
def update(path, **kwargs):
"""update plist file data"""
old = dict(read(path))
new = dict(old)
new.update(kwargs)
new = {k: v for k, v in new.items() if v}
if old != new:
write(path, new) | 5,318,564 |
async def _read_stream(stream, cb):
"""
Wait for an event on stdout/stderr, read the line, and send it to our lambda functions
"""
while True:
line = await stream.readline()
if line:
cb(line.strip().decode())
else:
break | 5,318,565 |
def quat_to_euler(q):
"""
Converts a unit quaternion:
q = (w, x, y, z) = w + (x i, y j, z k)
into the aircraft Euler angles (roll, pitch, yaw) = (phi, th, psi).
"""
R00 = 1 - 2*q[2]**2 - 2*q[3]**2
R10 = 2*q[1]*q[2] + 2*q[3]*q[0]
if np.sqrt(R00**2 + R10**2) >= .000001:
phi = np... | 5,318,566 |
def idc_get_local_type_name(*args):
"""
idc_get_local_type_name(ordinal) -> char
"""
return _ida_typeinf.idc_get_local_type_name(*args) | 5,318,567 |
def import_town(data_file):
"""
Reads town raster data from a CSV file.
Parameters
----------
data_file : str
Name of CSV raster data file to use for the town.
Returns
-------
town : list
List (cols) of lists (rows) representing raster data of the town.
"""
# ... | 5,318,568 |
def init_network():
"""์ ๊ฒฝ๋ง(neural network)์์ ์ฌ์ฉ๋๋ ๊ฐ์ค์น ํ๋ ฌ๊ณผ bias ํ๋ ฌ์ ์์ฑ
๊ต์ฌ p.88
์
๋ ฅ์ธต: (x1, x2) -> 1x2 ํ๋ ฌ
์๋์ธต:
- 1st ์๋์ธต: ๋ด๋ฐ 3๊ฐ (x @ W1 + b1)
- 2nd ์๋์ธต: ๋ด๋ฐ 2๊ฐ
์ถ๋ ฅ์ธต: (y1, y2) -> 1x2 ํ๋ ฌ
W1, W2, W3, b1, b2, b3๋ฅผ ๋์๋ก ์์ฑ
1x2 2x3 3x2
"""
np.random.seed(1... | 5,318,569 |
def reduce_detections(detections, detection_indices, img_w, img_h):
"""
Removes overlapping detections
Important note: Tensorflow detections are already sorted by detection score!
(optional)
TODO: Could tweak this paramter based on num of faces (2 ears, 1 of each class, per... | 5,318,570 |
def load_fiveplates_summary(platerun):
"""
"""
summary_file = paths.fiveplates_summary(platerun)
if summary_file.exists():
pass
else:
raise FileNotFoundError(os.fspath(summary_file))
return Table.read(os.fspath(summary_file), format='ascii') | 5,318,571 |
def make_connection():
"""Connection function to establish database connection. During development, the connection information will be
hard coded, however during actual deployment to AWS, the connection information will be retrieved from
other services eg aws secret manager etc.
Returns:
... | 5,318,572 |
def _start_trfserver():
""" Starts the traffic gen server"""
# disable-tcp-checksumming
# trfgen-server non daemon
host = env.hosts[0].split(':')[0]
port = env.hosts[0].split(':')[1]
key = env.key_filename
# set tty on cbreak mode as background ssh process breaks indentation
local('ssh -... | 5,318,573 |
def main():
"""
This function actually runs the simulation and is called if the script is called externally.
The timing is the following:
1. Create the agents
2. Setup global network externality provider choice functions.
These functions have as many elements as there are providers ... | 5,318,574 |
def doesDiscountExist(db, discountID):
"""
Does this discount exist?
:param db: database pointer
:param discountID: int
:return: -
"""
db.session.query(Discount).filter(Discount.id == discountID).first() | 5,318,575 |
def a_noun(random=random, *args, **kwargs):
"""
Return a noun, but with an 'a' in front of it. Or an 'an', depending!
>>> mock_random.seed(0)
>>> a_noun(random=mock_random)
'an onion'
>>> a_noun(random=mock_random, capitalize=True)
'A Chimp'
>>> a_noun(random=mock_random, slugi... | 5,318,576 |
def _tree_flatten_with_names(tree):
"""Populates tree_flatten with leaf names.
This function populates output of tree_flatten with leaf names, using a
custom traversal that produces names is provided. The custom traversal does
NOT have to traverse tree in the same order as jax, as we take care of
automatical... | 5,318,577 |
def inhomogeneous_poisson_process(rate, as_array=False,
refractory_period=None):
"""
Returns a spike train whose spikes are a realization of an inhomogeneous
Poisson process with the given rate profile.
Parameters
----------
rate : neo.AnalogSignal
A `n... | 5,318,578 |
def check_E_n_Jhat(th_n_opt, n):
"""
Check the influence of the number of domains $n$ used for the expectation operator.
:param th_n_opt: optimal policy parameter determined from n domains
:param n: number of domains $n$ used for determining the policy parameters
"""
# "Manual" expectation usin... | 5,318,579 |
def enumerate_quotes(filename, encoding="utf-8", empty_name="Inconnu"):
"""
Enumerates quote from a filename or a stream
@param filename filename or stream
@param encoding applicable only if filename
@param empty_name replces an empty author name
@return ... | 5,318,580 |
def _params_to_df(params: Parameters) -> DataFrame:
"""Convert lmfit.Parameters to pandas.DataFrame."""
return DataFrame(
[
(p.name, p.vary, p.value, p.stderr, p.min, p.max, p.brute_step, p.expr)
for p in params.values()
],
columns=(
"name",
... | 5,318,581 |
def w(P, T, region = 0):
""" Speed of sound [m / s]"""
if region is 0:
region = idRegion(P, T)
if region is 1:
return region1.w(P, T)
elif region is 2:
return region2.w(P, T)
else:
return 0.000 | 5,318,582 |
def drop_item(items: list[str]) -> None:
"""Drop an item at the specified inventory location."""
inventory_location: int = int(input('Number: '))
if not _is_inventory_location(inventory_location, items):
print(f'There is no item number {inventory_location}!')
else:
item = items.pop... | 5,318,583 |
def WaitForOperation(api_version, response, asynchronous):
"""Handles waiting for the operation and printing information about it.
Args:
api_version: Cloud Domains API version to call.
response: Response from the API call
asynchronous: If true, do not wait for the operation
Returns:
The last inf... | 5,318,584 |
def generateVtBar(symbol, d):
"""็ๆK็บฟ"""
bar = VtBarData()
bar.symbol = symbol
bar.vtSymbol = symbol
bar.open = d['open']
bar.high = d['high']
bar.low = d['low']
bar.close = d['close']
bar.volume = d['volume']
bar.openInterest = d['open_oi']
bar.datetime = datetime.fromt... | 5,318,585 |
def import_from_file(file):
"""Set credentials from a local file.
Args:
file (str | Path): The cbc credential file.
"""
parser = configparser.ConfigParser()
parser.read(file)
for section in parser.sections():
# reusing the parsing of the credentials because it is redundant to im... | 5,318,586 |
def produce_validation_report(stages, jobs, validation_json, **kwargs):
"""Produce validation report inside CI pipeline.
@param stages: the GitLab CI stages to consider
@param jobs: the job names to consider
@param validation_json: local job path to validation JSON output
@return summary of valida... | 5,318,587 |
def search_file(drive_service, num_of_responses, query):
"""
Search for files and store results of query in pd.DataFrame
"""
results = (
drive_service.files()
.list(
pageSize=num_of_responses,
q=query,
fields="nextPageToken, files(id, name, kind, expor... | 5,318,588 |
def plot_sqrtdeltachisqmain(data, scenario):
"""
Plots larger sqrt deltachisq plot. Similar to plot_sqrtdeltachisq.
"""
bbninterpfn = get_chisq_marg_interpolation(data, type='BBN')
bbnominterpfn = get_chisq_marg_interpolation(data, type='BBN+Omegab')
cmbinterpfn = get_chisq_marg_interpolation(da... | 5,318,589 |
def list_targets(board_manager_script, json_flag, verbose_level):
"""
List available targets.
"""
_log_app_envvar(verbose_level)
import json
from vznncv.mbed.greentea._test_runner import list_targets
from mbed_os_tools.test.mbed_test_api import log_mbed_devices_in_table
targets = list_t... | 5,318,590 |
def L6_summary_daily(ds,series_dict):
"""
Purpose:
Calculate the daily averages or sums of various quantities and write
them to a worksheet in an Excel workbook.
Usage:
L6_summary_daily(ds,series_dict)
where ds is an OzFluxQC data structure
series_dict is a dictionary of vario... | 5,318,591 |
def check_eol(file, eol):
"""Check file EOL.
:param file: Path to file to check
:param eol: Expected End of Line
:return: Resulting error messages
:rtype: str
"""
error = ''
with open(file, 'rb') as open_file:
content = open_file.read()
if eol == '\n':
if b'\r\n' i... | 5,318,592 |
def pe44(limit=1500):
"""
>>> pe44()
(5482660, 7042750, 1560090, 2166, 1019)
"""
pents = [i * (3 * i - 1) >> 1 for i in range(1, limit << 1)]
ps = set(pents)
for i in range(limit):
p1 = pents[i]
for j in range(i + 1, (limit << 1) - 1):
p2 = pents[j]
di... | 5,318,593 |
def text_cut(questions):
"""
This def will cut the text into words by jieba and del the stopwords then return the words,else return a string when
fail to find the stop_list.
:param questions: A list of text.
:return: A list of cut-words
Raises: FileNotFoundError: An error occurred searching stop... | 5,318,594 |
def mask_3D(hPa, sect, MBL=True, res='4x5', extra_mask=None,
M_all=False, use_multiply_method=True, trop_limit=False,
verbose=True, debug=False):
"""
Creates Maskes by pressure array (required shape: 72,46,47),
with conditions (lower and upper bounds) set by given cases for
MBL,... | 5,318,595 |
def export_visible_cells(
self,
export_keyword="FLUXNUM",
visible_active_cells_value=1,
hidden_active_cells_value=0,
inactive_cells_value=0,
):
"""Export special properties for all visible cells.
Arguments:
export_keyword (string): The keyword to export.
Choices: 'FLUXNUM' o... | 5,318,596 |
def sanitize_markdown(markdown_body):
"""
There are some symbols used in the markdown body, which when go through Markdown -> HTML
conversion, break. This does a global replace on markdown strings for these symbols.
"""
return markdown_body.replace(
# This is to solve the issue where <s> and... | 5,318,597 |
def ProjectsInsightTypeInsightsService(api_version):
"""Returns the service class for the Project insights."""
client = RecommenderClient(api_version)
return client.projects_locations_insightTypes_insights | 5,318,598 |
def get_course_dict(only_active=True):
""" Return a dictionary of courses.
By default only active courses.
key will be course ID.
courses[cid] = {id:, name:, title:}
"""
cdict = {}
reload_if_needed()
for course in COURSES:
if only_active:
if COURSES[cours... | 5,318,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.