content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_parent_directory(path):
"""
Get parent directory of the path
"""
return os.path.abspath(os.path.join(path, os.pardir)) | 5,346,000 |
def generate_fig_univariate_categorical(
df_all: pd.DataFrame,
col: str,
hue: str,
nb_cat_max: int = 7,
) -> plt.Figure:
"""
Returns a matplotlib figure containing the distribution of a categorical feature.
If the feature is categorical and contains too many categories, the ... | 5,346,001 |
def pt_sharp(x, Ps, Ts, window_half, method='diff'):
"""
Calculate the sharpness of extrema
Parameters
----------
x : array-like 1d
voltage time series
Ps : array-like 1d
time points of oscillatory peaks
Ts : array-like 1d
time points of oscillatory troughs
w... | 5,346,002 |
def associate_by_email(strategy, details, user=None, *args, **kwargs):
"""Deny duplicate email addresses for new users except in specific cases
If the incoming email is associated with existing user, authentication
is denied. Exceptions are:
* the existing user does not have associated social login
... | 5,346,003 |
async def test_service_setup(hass):
"""Verify service setup works."""
assert deconz.services.DECONZ_SERVICES not in hass.data
with patch(
"homeassistant.core.ServiceRegistry.async_register", return_value=Mock(True)
) as async_register:
await deconz.services.async_setup_services(hass)
... | 5,346,004 |
def test_service(host):
"""
Check if database service is started and enabled
"""
service = ''
if host.system_info.distribution in ('debian', 'ubuntu'):
service = 'postgresql'
assert host.service(service).is_enabled
# Systemctl not available with Docker images
if 'docker' != h... | 5,346,005 |
def convert_date(string, report_date, bad_dates_rep, bad_dates_for):
"""
Converts date string in format dd/mm/yyyy
to format dd-Mmm-yyyy
"""
x = string.split('/')
try:
date = datetime.datetime(int(x[2]),int(x[1]),int(x[0]))
date_str = date.strftime("%Y-%m-%d")
return(date... | 5,346,006 |
def render_raw(request, paste, data):
"""Renders RAW content."""
return HttpResponse(paste.content, content_type="text/plain") | 5,346,007 |
def node_avg():
"""get the avg of the node stats"""
node_raw = ["average", 0, 0, 0]
for node in node_stats():
node_raw[1] += float(node[1])
node_raw[2] += float(node[2])
node_raw[3] += float(node[3])
num = len(node_stats())
node_avg = ["average",
"{:.2f}".format(... | 5,346,008 |
def decrypt_vault_password(key: bytes, password: Union[str, bytes]) -> Union[str, bool]:
"""Decrypt and return the given vault password.
:param key: The key to be used during the decryption
:param password: The password to decrypt
"""
if isinstance(password, str):
password = password.encod... | 5,346,009 |
def readData(op,filetype,config):
"""
Reads data from Hive or CSV
"""
try:
if filetype=='csv':
print('csv')
csvU=optimusCsvUtils(config)
hr=datetime.now().hour
today=str(datetime.now().date())
path=os.path.join(config['data']['DIR'],'pe... | 5,346,010 |
def get_gv_rng_if_none(rng: Optional[rnd.Generator]) -> rnd.Generator:
"""get gym-gridverse module rng if input is None"""
return get_gv_rng() if rng is None else rng | 5,346,011 |
def fill_name(f):
"""
Attempts to generate an unique id and a parent from a BioPython SeqRecord.
Mutates the feature dictionary passed in as parameter.
"""
global UNIQUE
# Get the type
ftype = f['type']
# Get gene name
gene_name = first(f, "gene")
# Will attempt to fill in the... | 5,346,012 |
def run_single_softmax_experiment(beta, alpha):
"""Run experiment with agent using softmax update rule."""
print('Running a contextual bandit experiment')
cb = ContextualBandit()
ca = ContextualAgent(cb, beta=beta, alpha=alpha)
trials = 360
for _ in range(trials):
ca.run()
df = Data... | 5,346,013 |
def test_meta_schedule_local_multiple_runs():
"""Test meta schedule local runner for multiple runs"""
# Build the module
mods = [
MatmulModule,
MatmulReluModule,
BatchMatmulModule,
]
builder = LocalBuilder()
builder_inputs = [BuilderInput(mod, Target("llvm")) for mod in m... | 5,346,014 |
def available(name):
"""
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available... | 5,346,015 |
def coincidence_rate(text):
""" Return the coincidence rate of the given text
Args:
text (string): the text to get measured
Returns:
the coincidence rate
"""
ko = 0
# measure the frequency of each letter in the cipher text
for letter in _VOCAB:
count = text.count(letter)
ko = ko + (count *... | 5,346,016 |
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
dt = numpy.dtype('>i' + str(num))
return nu... | 5,346,017 |
def test_es_connection(es):
"""Tests health and presence of connection to elasticsearch."""
try:
health = es.cluster.health()
except elasticsearch.exceptions.ConnectionError:
current_app.logger.error(
"Elasticsearch does not seem to be running on "
f"{current_app.conf... | 5,346,018 |
def search_spec(spec, search_key, recurse_key):
"""
Recursively scans spec structure and returns a list of values
keyed with 'search_key' or and empty list. Assumes values
are either list or str.
"""
value = []
if search_key in spec and spec[search_key]:
if isinstance(spec[search_ke... | 5,346,019 |
def before_class(home=None, **kwargs):
"""Like @test but indicates this should run before other class methods.
All of the arguments sent to @test work with this decorator as well.
"""
kwargs.update({'run_before_class':True})
return test(home=home, **kwargs) | 5,346,020 |
async def setuExecutor(bot: Bot, event: MessageEvent, state: T_State) -> None:
"""获取response"""
keyword: str = state['keyword']
member_id: int = event.sender.user_id
if cd.check(member_id) is False:
resp = SetuResp(code=-3, msg='技能冷却中')
else:
resp = await SetuResp.get(keyword)
... | 5,346,021 |
def get_airports(force_download=False):
"""
Gets or downloads the airports.csv in ~/.config/mss and returns all airports within
"""
global _airports, _airports_mtime
file_exists = os.path.exists(os.path.join(MSS_CONFIG_PATH, "airports.csv"))
if _airports and file_exists and os.path.getmtime(os.... | 5,346,022 |
def hellinger_distance_poisson_variants(a_means, b_means, n_samples, sample_distances):
"""
a - The coverage vec for a variant over n_samples
b - The coverage vec for a variant over n_samples
returns average hellinger distance of multiple poisson distributions
"""
# generate distirbutions for ... | 5,346,023 |
def min_threshold(x, thresh, fallback):
"""Returns x or `fallback` if it doesn't meet the threshold. Note, if you want to turn a hyper "off" below,
set it to "outside the threshold", rather than 0.
"""
return x if (x and x > thresh) else fallback | 5,346,024 |
def get_command(command, meta):
"""Construct the command."""
bits = []
# command to run
bits.append(command)
# connection params
bits.extend(connect_bits(meta))
# database name
if command == 'mysqladmin':
# these commands shouldn't take a database name
return bits
if ... | 5,346,025 |
def main(): # pragma: no cover
"""Executes model."""
import sys
try:
infile = sys.argv[1]
except IndexError:
print("Must include input file name on command line")
sys.exit(1)
em = BasicDdSt.from_file(infile)
em.run() | 5,346,026 |
def get_common_count(list1, list2):
"""
Get count of common between two lists
:param list1: list
:param list2: list
:return: number
"""
return len(list(set(list1).intersection(list2))) | 5,346,027 |
def text_present(nbwidget, text="Test"):
"""Check if a text is present in the notebook."""
if WEBENGINE:
def callback(data):
global html
html = data
nbwidget.dom.toHtml(callback)
try:
return text in html
except NameError:
return Fal... | 5,346,028 |
def multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams=defaultXtraParams):
"""multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams={})... | 5,346,029 |
def basis_lattice(lattice: str) -> np.ndarray:
"""
Description
-----------
Return a matrix whose column space is the three lattice vector
m = | a_1 b_1 c_1 |
| a_2 b_2 c_2 |
| a_3 b_3 c_3 |
the covariances (a|b|c_i) are in the crystal frame
... | 5,346,030 |
def main(url: str, **options) -> None:
"""
Displays information on a Github repository.
URL_OR_REPO_PATH must be either some form of Github Url or path
starting with username and repo such as `user/repo/whatever`.
"""
if options["set_token"]:
set_token(url)
token = get_token()
... | 5,346,031 |
def value_iteration(R, P, gamma, epsilon=1e-6):
"""
Value iteration for discounted problems.
Parameters
----------
R : numpy.ndarray
array of shape (S, A) contaning the rewards, where S is the number
of states and A is the number of actions
P : numpy.ndarray
array of sha... | 5,346,032 |
def write_quadruple(f, ent, rel, tim, q, S, P, O, T):
"""Write a quadruple to a file."""
f.write(
str(ent[q[S]])
+ "\t"
+ str(rel[q[P]])
+ "\t"
+ str(ent[q[O]])
+ "\t"
+ str(tim[q[T]])
+ "\n"
) | 5,346,033 |
def mock_api_response(response_config={}):
"""Create a mock response from the Github API."""
headers = {
'ETag': 'W/"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"',
'Cache-Control': 'public, max-age=60, s-maxage=60',
'Content-Type': 'application/json; charset=utf-8'
}
api_response = MagicMoc... | 5,346,034 |
def shouty(src, dest):
"""
Takes a string and makes it SHOUTY.
"""
dest.write(src.read().upper()) | 5,346,035 |
def files_with_extension(path: str,extension: str):
"""
Gives a list of the files in the given directory that have the given extension
Parameters
----------
path: str
The full path to the folder where the files are stored
extension: str
The extension of the files
Re... | 5,346,036 |
def get_inputs_repl_cluster_or_vol():
"""
This input is for clusters that have replication
"""
parser = argparse.ArgumentParser()
parser.add_argument('-m', type=str,
required=True,
metavar='mvip',
help='MVIP/node name or... | 5,346,037 |
def write_cases_to_latex(cases: dict, output_file: Path):
"""
Write a formatted conditionally colored table to a file
"""
for case in cases.values():
case.calculate_metric_terms()
case_keys = list(cases.keys())
n_cases = len(cases)
make_colorbar(
cell_clip=5.0, label="$d_j... | 5,346,038 |
def load_jsonl(file_path):
""" Load file.jsonl ."""
data_list = []
with open(file_path, mode='r', encoding='utf-8') as fi:
for idx, line in enumerate(tqdm(fi)):
jsonl = json.loads(line)
data_list.append(jsonl)
return data_list | 5,346,039 |
def aurora_forecast():
"""
Get the latest Aurora Forecast from http://swpc.noaa.gov.
Returns
-------
img : numpy array
The pixels of the image in a numpy array.
img_proj : cartopy CRS
The rectangular coordinate system of the image.
img_extent : tuple of floats
The ex... | 5,346,040 |
def get_number_trips(grouped_counts):
"""
Gets the frequency of number of trips the customers make
Args:
grouped_counts (Pandas.DataFrame): The grouped dataframe returned from
a get_trips method call
Returns:
Pandas.DataFrame: the dataframe co... | 5,346,041 |
def process_text(text, max_features=200, stopwords=None):
"""Splits a long text into words, eliminates the stopwords and returns
(words, counts) which is necessary for make_wordcloud().
Parameters
----------
text : string
The text to be processed.
max_features : number (default=200... | 5,346,042 |
def update_graph_map(n):
"""Update the graph rail network mapbox map.
Returns:
go.Figure: Scattermapbox of rail network graph
"""
return get_graph_map() | 5,346,043 |
def get_party_leads_sql_string_for_state(party_id, state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_votes-sr.votes) ... | 5,346,044 |
def test_read_crux(real_crux_txt):
"""Test that we parse crux files correctly"""
psms = crema.read_crux(real_crux_txt)
assert isinstance(psms.data, pd.DataFrame)
assert psms.data.shape == (21818, 11)
assert list(psms.spectra.columns) == ["scan", "spectrum precursor m/z"]
scores = {
"ref... | 5,346,045 |
def test_hash():
"""
""" | 5,346,046 |
def opcode_J(renderer, line_cap):
"""Set line cap style (see p. 216)"""
renderer.gs.line_cap = line_cap | 5,346,047 |
def dt_dataset():
"""
command line parameter checking filter for dataset files plausibility only.
>>> old_state = test_config.setup()
>>> cmdline.dataset("foo.nothing")
Traceback (most recent call last):
...
ValueError: Parameter 'foo.nothing' does not appear to be a dataset filename.
... | 5,346,048 |
def _check_nonint(logfile):
"""Do not allow opening of files through file descriptors"""
if isinstance(logfile, int):
raise TypeError('Integer logfiles not allowed') | 5,346,049 |
def add_stored_files(srr_file, store_files, in_folder="", save_paths=False,
usenet=False):
"""Add one or more files to a SRR reconstruction file.
srr_file: the srr file to add files to
store_files: a list of files to store in the srr
first file will be at the top
... | 5,346,050 |
def goods_images(goods_url):
"""
获得商品晒图
Parameters:
goods_url - str 商品链接
Returns:
image_urls - list 图片链接
"""
image_urls = []
productId = goods_url.split('/')[-1].split('.')[0]
# 评论url
comment_url = 'https://sclub.jd.com/comment/productPageComments.action'
comment_params = {'productId':productId,
'score... | 5,346,051 |
def delete_index_list(base_list, index_list):
"""
根据index_list删除base_list中指定元素
:param base_list:
:param index_list:
:return:
"""
if base_list and index_list:
return [base_list[i] for i in range(len(base_list)) if (i not in index_list)] | 5,346,052 |
def generate_mutated_template(template, outfile, changes_file, header, seedval=None):
"""Generate a mutated template and writes fasta and changes file"""
if seedval:
np.random.seed(seedval)
seed(seedval)
else:
np.random.seed()
seed()
mutated_template, changes = mutate_tem... | 5,346,053 |
def not_found():
"""Page not found."""
return make_response(
render_template("404.html"),
404
) | 5,346,054 |
def _traverseAgg(e, visitor=lambda n, v: None):
"""
Traverse a parse-tree, visit each node
if visit functions return a value, replace current node
"""
res = []
if isinstance(e, (list, ParseResults, tuple)):
res = [_traverseAgg(x, visitor) for x in e]
elif isinstance(e, CompValue)... | 5,346,055 |
def roll(image, delta):
"""Roll an image sideways
(A more detailed explanation goes here.)
"""
xsize, ysize = image.size
delta = delta % xsize
if delta == 0:
print("the delta was 0!")
return image
part1 = image.crop((0, 0, delta, ysize))
part2 = image.crop((delta... | 5,346,056 |
def make_long_format(path_list, args):
"""Output list of strings in informative line-by-line format like ls -l
Args:
path_list (list of (str, zipfile.Zipinfo)): tuples, one per file
component of zipfile, with relative file path and zipinfo
args (argparse.Namespace): user arguments to... | 5,346,057 |
def is_name_a_title(name, content):
"""Determine whether the name property represents an explicit title.
Typically when parsing an h-entry, we check whether p-name ==
e-content (value). If they are non-equal, then p-name likely
represents a title.
However, occasionally we come across an h-entry th... | 5,346,058 |
def insertTweet(details, insertDuplicates=True):
""" Adds tweet to database
@param details {Dict} contains tweet details
@param insertDuplicates {Boolean} optional, if true it
will insert even if already exists
"""
try:
if not insertDu... | 5,346,059 |
def dump_yaml(file_path, data):
"""Dump data to a file.
:param file_path: File path to dump data to
:type file_path: String
:param data: Dictionary|List data to dump
:type data: Dictionary|List
"""
with open(os.path.abspath(os.path.expanduser(file_path)), "w") as f:
yaml.safe_dump(... | 5,346,060 |
def pull_apk(package=None, regex=None, devices=None, local_dir=None,
force=False):
"""
Downloads the package apk.
If regex matches multiple packages and force is True, each package apk
will be downloaded.
Args:
package: package name as string.
regex: string.
de... | 5,346,061 |
def return_embeddings(embedding: str, vocabulary_size: int, embedding_dim: int,
worddicts: OrderedDict) -> np.ndarray:
"""Create array of word embeddings."""
word_embeddings = np.zeros((vocabulary_size, dim_word))
with open(embedding, 'r') as f:
for line in f:
words... | 5,346,062 |
def symLink(twist, dist, angle, offset):
"""
Transform matrix of this link with DH parameters.
(Use symbols)
"""
twist = twist * sympy.pi / 180
T1 = sympy.Matrix([
[1, 0, 0, dist],
[0, sympy.cos(twist), -sympy.sin(twist), 0],
[0, sympy.sin(twist), sympy.cos(twist), 0],
... | 5,346,063 |
async def _parse_action_body(service: UpnpServerService, request: aiohttp.web.Request) -> Tuple[str, Dict[str, Any]]:
"""Parse action body."""
# Parse call.
soap = request.headers.get("SOAPAction", "").strip('"')
try:
_, action_name = soap.split("#")
data = await request.text()
r... | 5,346,064 |
def get_tc_json():
"""Get the json for this testcase."""
try:
with open(GLOBAL_INPUT_JSON_PATH) as json_file:
tc = json.load(json_file)
except Exception:
return_error('Could not custom_validator_input.json')
return tc | 5,346,065 |
def dualgauss(x, x1, x2, w1, w2, a1, a2, c=0):
"""
Sum of two Gaussian distributions. For curve fitting.
Parameters
----------
x: np.array
Axis
x1: float
Center of 1st Gaussian curve
x2: float
Center of 2nd Gaussian curve
w1: float
... | 5,346,066 |
def pdg_format3( value , error1 , error2 , error3 , latex = False , mode = 'total' ) :
"""Round value/error accoridng to PDG prescription and format it for print
@see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf
@see section 5.3 of doi:10.1088/0954-3899/33/1/001
Quote:
The b... | 5,346,067 |
def getChinaHoliday(t):
"""找出距离输入日期最近的中国节日,输出距离的天数"""
date_time = datetime.datetime.strptime(t, '%d %B %Y')
y = date_time.year
# 中国阳历节日
sh = [
(y, 1, 1), # 元旦
(y, 4, 5), # 清明
(y, 5, 1), # 五一劳动节
(y, 10, 1) # 国庆节
]
# 中国阴历节日
lh = [
... | 5,346,068 |
def parse_mimetype(mimetype):
"""Parses a MIME type into its components.
:param str mimetype: MIME type
:returns: 4 element tuple for MIME type, subtype, suffix and parameters
:rtype: tuple
Example:
>>> parse_mimetype('text/html; charset=utf-8')
('text', 'html', '', {'charset': 'utf-8'})... | 5,346,069 |
def terraform_state_bucket(config):
"""Get the bucket name to be used for the remote Terraform state
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
string: The bucket name to be used for the remote Terraform state
"""
# If a bucket name is specified for ... | 5,346,070 |
def get_binary_matrix(gene_expr, libraries):
"""
Get binary matrix with genes as rows and pathways as columns.
If a gene is found in a given pathway, it is given a value of
1. Else, 0. Only the list of genes in common between that found
in the gene set libraries and the current dataset are used.
... | 5,346,071 |
def _delete_policy(policy_name):
"""
deletes a policy
:param str policy_name: the policy name
"""
url = urljoin(_base_url, 'policies/{vhost}/{name}'.format(vhost=quote(VHOST), name=quote(policy_name)))
response = requests.delete(url)
if not response.ok:
error = "Can't delete policy... | 5,346,072 |
def get_tip_downvotes(tips_id):
"""
GET function for retrieving all User objects that have downvoted a tip
"""
tip = Tips.objects.get(id=tips_id)
tips_downvotes = (tip.to_mongo())["downvotes"]
tips_downvotes_list = [
User.objects.get(id=str(user)).to_mongo() for user in tips_downvotes
... | 5,346,073 |
def count_str_in_read(read_data, string, id_map):
""" Count occuerances of a string in a read.
"""
x = np.zeros(len(read_data))
y = np.zeros_like(x)
c = np.zeros_like(x)
for i, doc in enumerate(read_data):
x[i], y[i] = id_map[doc["barcode"]]
c[i] = doc["Read"].count(string) | 5,346,074 |
def get_placements(
big_graph: nx.Graph, small_graph: nx.Graph, max_placements=100_000
) -> List[Dict]:
"""Get 'placements' mapping small_graph nodes onto those of `big_graph`.
This function considers monomorphisms with a restriction: we restrict only to unique set
of `big_graph` qubits. Some monomorph... | 5,346,075 |
def normalise(hists, integration_range=None, norm_scale=1.):
"""
Wrapper for normalisation of histograms to a given scale in a given interval
:param hists: histograms
:type hists: list of dictionary of histograms
:param integration_range: range in which integration should be performed (default fill ... | 5,346,076 |
def make_static_server_url_stop(root, host=HOST, port=PORT):
"""start a tornado static file server"""
server_args = [
"python",
str(PA11Y / "serve.py"),
f"--host={host}",
f"--port={port}",
f"--path={root}",
]
url = f"http://{host}:{port}/"
def stop():
... | 5,346,077 |
def request_url(url):
"""
get the resource associated with a url.
"""
try:
# -- todo; eliminate pesky assignment so can be put into chain of Ok then's.
user_agent = 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31'
response = requests.get(
urllib.par... | 5,346,078 |
def makecall(call, stdout=None, stderr=None, stdin=None):
"""Simplifies running system calls using the subprocess module.
stdout and sterr are written to files automatically.
"""
# streams are ignored
if stdout == None and stderr == None and stdin == None:
subprocess.call(call)
elif std... | 5,346,079 |
def _filter_baseanalysis_kwargs(function, kwargs):
"""
create two dictionaries with kwargs separated for function and AnalysisBase
Parameters
----------
function : callable
function to be called
kwargs : dict
keyword argument dictionary
Returns
-------
base_args : d... | 5,346,080 |
def torch_to_flax(torch_params, get_flax_keys):
"""Convert PyTorch parameters to nested dictionaries"""
def add_to_params(params_dict, nested_keys, param, is_conv=False):
if len(nested_keys) == 1:
key, = nested_keys
params_dict[key] = np.transpose(param, (2, 3, 1, 0)) if is_conv else np.transpose(p... | 5,346,081 |
def subset_shape(
ds: Union[xarray.DataArray, xarray.Dataset],
shape: Union[str, Path, gpd.GeoDataFrame],
raster_crs: Optional[Union[str, int]] = None,
shape_crs: Optional[Union[str, int]] = None,
buffer: Optional[Union[int, float]] = None,
start_date: Optional[str] = None,
end_date: Optiona... | 5,346,082 |
def plot_record_static(
record,
save=True,
scale=1000,
select_kw={},
x_prop='wavenumber',
**kwargs
):
"""Figure of Static data from a record.
High level function.
record: Record to get data from
save: Boolean, Save figure
scale: Scale y axis.
sel... | 5,346,083 |
def logmelspectrogram(wave: np.ndarray, conf: ConfMelspec) -> np.ndarray:
"""Convert a waveform to a scaled mel-frequency log-amplitude spectrogram.
Args:
wave::ndarray[Time,] - waveform
conf - Configuration
Returns::(Time, Mel_freq) - mel-frequency log(Bel)-amplitude spectrogram
"""
... | 5,346,084 |
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
#define a DFA
state = [{},
{'blank': 1, 'sign': 2, 'digit':3, '.':4},
{'digit':3, '.':4},
{'digit':3, '.':5, 'e':6, 'blank':9},
{'digit':5},
{'digit':5, 'e... | 5,346,085 |
def get_trainer_config(env_config, train_policies, num_workers=9, framework="tf2"):
"""Build configuration for 1 run."""
# trainer config
config = {
"env": env_name, "env_config": env_config, "num_workers": num_workers,
# "multiagent": {"policy_mapping_fn": lambda x: x, "policies": policies... | 5,346,086 |
def SamAng(Tth,Gangls,Sangl,IFCoup):
"""Compute sample orientation angles vs laboratory coord. system
:param Tth: Signed theta
:param Gangls: Sample goniometer angles phi,chi,omega,azmuth
:param Sangl: Sample angle zeros om-0, chi-0, phi-0
... | 5,346,087 |
def debye_C_V(T,thetaD,natoms):
"""
Returns the heat capacity at constant volume, C_V, of the Debeye model at a
given temperature, T, in meV/atom/K.
"""
C_V = 4*debye_func(thetaD/T)-3*(thetaD/T)/(sp.exp(thetaD/T)-1.)
C_V = 3*natoms*BOLTZCONST*C_V
return C_V | 5,346,088 |
def setup(clip=True, flip=True):
"""
Project specific data import and setup function
:param clip: bool - use clipping
:param flip: bool - use flipping
:return: data as pandas dataframe, List[LAICPMSData obj]
"""
# calibration
# Zn: y = 0.0395 kcps/(µg/g)* x + 1.308 kcps
# ... | 5,346,089 |
def go_test_macro(name, **kwargs):
"""See go/core.rst#go_test for full documentation."""
_cgo(name, kwargs)
go_test(name = name, **kwargs) | 5,346,090 |
def _verify_all_conflicts(buffer_pool_allocations):
"""Helper to verify liveness conflicts"""
for buffer_info, pool_allocation in buffer_pool_allocations.items():
_verify_conflicts(buffer_info, pool_allocation, buffer_pool_allocations) | 5,346,091 |
def choi_to_kraus(q_oper):
"""
Takes a Choi matrix and returns a list of Kraus operators.
TODO: Create a new class structure for quantum channels, perhaps as a
strict sub-class of Qobj.
"""
vals, vecs = eig(q_oper.data.todense())
vecs = list(map(array, zip(*vecs)))
return list(map(lambda... | 5,346,092 |
async def my_edit(event):
"""定义编辑文件操作"""
logger.info(f'即将执行{event.raw_text}命令')
msg_text = event.raw_text.split(' ')
SENDER = event.sender_id
path = JD_DIR
page = 0
if isinstance(msg_text, list) and len(msg_text) == 2:
text = msg_text[-1]
else:
text = None
logger.info... | 5,346,093 |
def plot_df_color_per_unit(data, variables, labels, size=(16, 9), labelsize=17, option='Time', name=None):
"""
"""
plt.clf()
input_dim = len(variables)
# cols = min(np.floor(input_dim ** 0.5).astype(int), 4)
# rows = (np.ceil(input_dim / cols)).astype(int)
cols = 4
rows = 1
gs = grid... | 5,346,094 |
def extract_file_type(file_location:str) -> str:
"""
A function to return the type of file
-> file_location: str = location of a file in string... ex : "C:\\abc\\abc\\file.xyz"
----
=> str: string of the file type, ex : "xyz"
"""
if not isinstance(file_location,str):
raise TypeError... | 5,346,095 |
def add_sphinx_context_data(sender, data, build_env, **kwargs): # pylint: disable=unused-argument
"""
Provides additional data to the sphinx context.
Data are injected in the provided context
:param sender: sender class
:param data: sphinx context
:param build_env: BuildEnvironment instance
... | 5,346,096 |
def dualMove(d1, d2, st1, st2, sp1, sp2, ac1, ac2, di1, di2, c1, c2):
"""
Move 2 steppers at the same time
Parameters
----------
d1 : AMIS30543
AMIS30543 Driver
d2 : AMIS30543
AMIS30543 Driver
st1 : int
Steps for motor 1
st2 : int
Steps for motor 2
sp... | 5,346,097 |
def re_subm(pat, repl, string):
"""
Like re.sub, but returns the replacement _and_ the match object.
>>> t, m = re_subm('g(oo+)fball', r'f\\1lish', 'goooooofball')
>>> t
'foooooolish'
>>> m.groups()
('oooooo',)
"""
class re_subm_proxy:
def ... | 5,346,098 |
def search_view(request):
"""Get user's saved keywords from the database if they exist and render search page."""
if request.method == 'GET':
try:
query = request.dbsession.query(Keyword)
user_keywords = query.filter(Association.user_id == request.authenticated_userid... | 5,346,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.