content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def corpus_loader(folder: str) -> List[str]:
"""
A corpus loader function which takes in a path to a
folder and returns a list of strings.
""" | 5,336,700 |
def socket_port(ip, port):
"""
输入IP和端口号,扫描判断端口是否占用
"""
try:
if port:
print u'端口扫描结束'
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
result=s.connect_ex((ip, port))
if result == 0:
lock.acquire()
print ip,u':', port,u'端口已被占用'
... | 5,336,701 |
def parse_debug_node_name(node_name):
"""Parse the name of a debug node.
Args:
node_name: Name of the debug node.
Returns:
1. Name of the watched node, as a str.
2. Output slot index of the watched tensor, as an int.
3. Index of the debug node, as an int.
4. Name of the debug op, as a str, e.g... | 5,336,702 |
def run_basic():
"""Check that the windows all open ok (i.e. is GUI functioning?)."""
_initialize()
s = 'Simulation'
p = 'Plots'
menu_paths = [ (s,'Test Pattern'),
(s,'Model Editor'),
(p,'Activity'),
(p,'Connection Fields'),
... | 5,336,703 |
def node_to_evenly_discretized(node):
"""
Parses the evenly discretized mfd node to an instance of the
:class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD,
or to None if not all parameters are available
"""
if not all([node.attrib["minMag"], node.attrib["binWidth"],
... | 5,336,704 |
def delete_comment(request, collection_id, comment_id):
"""Delete comment if the staff or comment owner want to delete."""
collection = get_object_or_404(Collection, id=collection_id)
comment = get_object_or_404(Comment, id=comment_id, collection=collection)
if not request.user.is_authenticated:
... | 5,336,705 |
def final_messages(systems_created_counter, systems_updated_counter, systems_skipped_counter, systems_multiple_counter, systems_multiple_list, request):
""" final messages if function was called from 'system_instant' and 'system_upload' """
# call final messages
if systems_created_counter > 0:
if s... | 5,336,706 |
def insert_row(key, translation, idx_language):
"""Create a database AgentXlate.agent row.
Args:
key: AgentXlate key
translation: AgentXlate translation
idx_language: Language table index
Returns:
None
"""
# Insert and get the new agent value
with db.db_modify(... | 5,336,707 |
def layers_weights_as_vector(model, initial=True):
"""
Creates a list holding the weights of each layer (Conv and Dense) in the CNN as a vector.
model: A reference to the instance from the cnn.Model class.
initial: When True, the function returns the initial weights of the CNN. When False, the t... | 5,336,708 |
def calculate_moist_adiabatic_lapse_rate(t, p):
"""calculate moist adiabatic lapse rate from pressure, temperature
p: pressure in hPa
t: temperature in Kelvin
returns: moist adiabatic lapse rate in Kelvin/m
"""
es = 611.2*np.exp(17.67*(t-273.15)/(t-29.65)) # Bolton formula, es in Pa
qs... | 5,336,709 |
def main():
"""
Primary entrypoint to dynamic inventory script
"""
parser = create_parser()
args = parser.parse_args()
getSplunkInventory(inventory)
if args.write_to_file:
with open(os.path.join("/opt/container_artifact", "ansible_inventory.json"), "w") as outfile:
json.... | 5,336,710 |
def test_setext_headings_extra_59():
"""
Test case extra 59: SetExt heading with inline image with newline between image chars, invalidating it.
"""
# Arrange
source_markdown = """a!
[Foo](/uri "testing")a
---"""
expected_tokens = [
"[setext(3,1):-:3::(1,1)]",
"[text(1,1):a!\n:... | 5,336,711 |
def read_cat_file(genomeCatFile):
""" Read in genome categories and create dictionary of category name and
genomes in that category"""
inFile = open(genomeCatFile, 'r')
catDict = {}
for line in inFile:
line = line.strip()
entries = line.split()
genome = entries[0]
ca... | 5,336,712 |
def logprint(log):
"""wrapper for printing data inside userSetup.py
:param log: The string to pring
:return:
"""
print('userSetup.py: %s' % log) | 5,336,713 |
def receive_message():
"""
Receive message from server
:return: None
"""
while True:
try:
msg = client.recv(1024).decode('utf-8')
print(msg)
except:
print("[EXCEPTION WHILE RECEVING]")
client.close()
break | 5,336,714 |
def _check_axes(axes):
"""Check if "axes" is an instance of an axis object. If not, use `gca`."""
if axes is None:
import matplotlib.pyplot as plt
axes = plt.gca()
elif not isinstance(axes, Axes):
raise ValueError(
"`axes` must be an instance of matplotlib.axes.A... | 5,336,715 |
def StronglyEntanglingCircuitBlock(weights, periodic=True, r=1, imprimitive=CNOT, wires=None):
"""pennylane.template.StronglyEntanglingCircuitBlock(weights, periodic=True, r=1, imprimitive=qml.CNOT, wires)
An individual block of a strongly entangling circuit.
Args:
weights (array[float]): shape ``(... | 5,336,716 |
def gauss_method_mpc(filename, bodyname, obs_arr=None, r2_root_ind_vec=None, refiters=0, plot=True):
"""Gauss method high-level function for minor planets (asteroids, comets,
etc.) orbit determination from MPC-formatted ra/dec tracking data. Roots of
8-th order Gauss polynomial are computed using np.roots f... | 5,336,717 |
def removeCable(n, edges):
"""
@param n 道路
@param edges 连通情况
"""
fa = initFa(n)
totalW, nodes = 0, []
for x, y, w in edges:
node = Node(x, y, w)
nodes.append(node)
totalW += w
def getW(node):
return node.w
nodes.sort(key=getW)
tmpW = 0
... | 5,336,718 |
def attach_vnc(caller_id, vm_id):
"""
Attaches VNC redirection to VM.
@cmview_user
@param_post{vm_id,int} id of the VM to have attached VM redirection
"""
vm = VM.get(caller_id, vm_id)
vm.attach_vnc()
try:
vm.save()
except:
raise CMException('vnc_attach') | 5,336,719 |
def test_date_time_max_inclusive003_1133_date_time_max_inclusive003_1133_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=maxInclusive and
value=1999-05-12T10:31:00 and document value=1985-04-12T10:30:00
"""
assert_bindings(
schema="msData/datatypes/Facets/date... | 5,336,720 |
def upload():
"""POST route through which downloading sequence is triggered
:param checked: which pins were selected by user
:returns: log of arrays with pins, files downloaded counts, and notes
"""
DASHRlut = findSNs(compCrawl())
checked = request.get_json()
from read_file import read_sele... | 5,336,721 |
def verify_credentials():
"""Verify credentials to gdrive for the current user"""
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('authorize_app', _external=True))
credentials = client.OAuth2Credentials.from_json(
flask.session['credentials'])
if credentials.access_token_exp... | 5,336,722 |
def _gaussian_blur(heatmaps, kernel=11):
"""Modulate heatmap distribution with Gaussian.
sigma = 0.3*((kernel_size-1)*0.5-1)+0.8
sigma~=3 if k=17
sigma=2 if k=11;
sigma~=1.5 if k=7;
sigma~=1 if k=3;
Note:
batch_size: N
num_keypoints: K
heatmap height: H
... | 5,336,723 |
def pose_vec2mat(vec):
"""Converts 6DoF parameters to transformation matrix
Args:
vec: 6DoF parameters in the order of tx, ty, tz, rx, ry, rz -- [B, 6]
Returns:
A transformation matrix -- [B, 4, 4]
"""
# batch_size, _ = vec.get_shape().as_list()
batch_size = tf.shape(vec)[0]
... | 5,336,724 |
def get_gradients_through_compute_gradients(optimizer, loss, activations):
"""Compute gradients to send to TPU embedding.
Args:
optimizer: a subclass of optimizer.Optimizer, usually CrossShardOptimizer.
Used to call compute_gradients().
loss: a Tensor to call optimizer.compute_gradients() on.
act... | 5,336,725 |
def distance_to_mesh(mesh, pts, engine="auto", bvh=None):
""" Compute the distance from a set of points to a mesh.
Args:
mesh (:class:`Mesh`): A input mesh.
pts (:class:`numpy.ndarray`): A :math:`N \\times dim` array of query
points.
engine (``string``): BVH engine na... | 5,336,726 |
def parse_config(settings: Any) -> Tuple[Dict[str, Queue], Dict[str, dict]]:
"""
SAQ configuration parsing.
Args:
settings: The settings (can be pydantic.BaseSettings).
Returns:
Tuple[Dict[str, Queue], Dict[str, dict]]: The SAQ queues and the queue settings.
"""
saq_queues: Di... | 5,336,727 |
async def test_manual_setup_connection_exception(hass: HomeAssistant):
"""Test configuration flow with a connection error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] ... | 5,336,728 |
def create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True):
"""Create a slot initialized to 0 with same shape as the primary object.
Args:
primary: The primary `Variable` or `Output`.
name: Name to use for the slot variable.
dtype: Type of the slot variable. Defaults to the type of `... | 5,336,729 |
def AdditionalMedicareTax(e00200, MARS,
AMEDT_ec, sey, AMEDT_rt,
FICA_mc_trt, FICA_ss_trt,
ptax_amc, payrolltax):
"""
Computes Additional Medicare Tax (Form 8959) included in payroll taxes.
Notes
-----
Tax Law Parameters:... | 5,336,730 |
def append_step_list(step_list, step, value, go_next, mode, tag):
"""from step_list, append the number of times a step needs to be repeated
if runmode or retry is present
:Arguments:
step_list = Ordered list of steps to be executed
step = Current step
value = attempts in runmode/re... | 5,336,731 |
def test_sorted_h5_keys_many():
"""
Test to check a key is returned with many entries
"""
with TempDirectory() as tempdir:
# Creating some dummy data
d1 = np.random.random(size=(10, 20))
hf = h5py.File(tempdir.path + "data.h5", "w")
# Adding entries in different order
... | 5,336,732 |
def load_license(request, project_slug):
"""
Reload the license input queryset with the right options for the
access form's current access policy choice. Called via ajax.
"""
user = request.user
project = ActiveProject.objects.filter(slug=project_slug)
if project:
project = project.g... | 5,336,733 |
def populate_db() -> None:
"""Populate the database using sample data"""
users = [
{
"username": "user1",
"password": "pass_user1",
"name": "User 1",
"email": "user1@usermail.com",
"role": "USER",
"daily_calories": 2500,
... | 5,336,734 |
def wt():
"""Return default word tokenizer."""
return WordTokenizer() | 5,336,735 |
def test_template_params():
"""
Should print out text with passed params
"""
runner = CliRunner()
result = runner.invoke(template.template, ['--name', 'Caesar was here', '--choose'])
print(f'result: {result.output}')
assert result.output == ('value: Caesar was here\n'
... | 5,336,736 |
def test_roller_value_changed(hass, mock_openzwave):
"""Test position changed."""
hass.data[zwave.zwave.DATA_NETWORK] = MagicMock()
node = MockNode()
value = MockValue(data=None, node=node,
command_class=const.COMMAND_CLASS_SWITCH_MULTILEVEL)
values = MockEntityValues(primary=v... | 5,336,737 |
def InstallAppengineDatabaseBackend():
"""Installs the appengine database backend into Django.
The appengine database lives in the db/ subdirectory of this package, but is
known as "appengine" to Django. This function installs the module where
Django expects to find its database backends.
"""
from appengin... | 5,336,738 |
def assert_(val: bool):
"""
usage.scipy: 916
usage.skimage: 18
usage.statsmodels: 351
"""
... | 5,336,739 |
def epochplot(epochs, *, ax=None, height=None, fc='0.5', ec='0.5',
alpha=0.5, hatch='////', label=None, hc=None,**kwargs):
"""Docstring goes here.
"""
if ax is None:
ax = plt.gca()
ymin, ymax = ax.get_ylim()
if height is None:
height = ymax - ymin
if hc is ... | 5,336,740 |
def training(dataset,
database_path,
resize,
channels,
normalization,
transformations,
lr,
epochs,
batch_size,
train_iterations,
valid_iterations,
... | 5,336,741 |
def do_db_sync():
"""
Place a database under migration control and upgrade,
creating first if necessary.
"""
api.db_sync(api.get_engine(), CONF.command.version) | 5,336,742 |
def run_dag(
dag_id,
run_id=None,
conf=None,
replace_microseconds=True,
execution_date=None,
):
"""Runs DAG specified by dag_id
:param dag_id: DAG ID
:param run_id: ID of the dag_run
:param conf: configuration
:param replace_microseconds: whether microseconds should be zeroed
... | 5,336,743 |
def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True) -> Any:
"""Download the given URL and return a binary-mode file object to access the data."""
assert is_url(url)
assert num_attempts >= 1
# Lookup from cache.
url_md5 = hashlib.md5(url.encode("utf-8")).hexdi... | 5,336,744 |
def main_ploting(
title_: str or None,
xlabel_: str or None,
ylabel_: str or None,
legends_: [str] or None,
average_color_: str,
average_fill_: str,
):
"""
if you want to edit the information of your graphic, edit this function
"""
if title_:
... | 5,336,745 |
def get_function_handle(method, var):
"""
Return a function handle to a given calculation method.
Parameters
----------
method : str
Identifier of the calculation method to return a handle to.
var : dict
Local variables needed in the mu update method.
Returns
-------
... | 5,336,746 |
def build_receiver_model(params, ds_meta, utt_len: int, vocab_size: int, pre_conv=None) -> ReceiverModel:
"""
given the size of images from a dataset, and a desired vocab size and utterance length,
creates a ReceiverModel, which will take in images, and utterances, and classify
the images as being consi... | 5,336,747 |
def closeSeleniumWebDriver(web_driver):
"""
This method fetches all child (grandchild and all ancestors) process ids that was open in
Selenium's Web Driver initialization.
We're calling web_driver.quit() and then we're killing all ancestor's processes.
If the process was meanwhile terminated, we're... | 5,336,748 |
def test_triangle_number_factors():
"""
test Problem test_problem_12(answer)
:return:
"""
from euler_python.easiest import p012
output = p012.triangle_number_factors(5)
expected_output = 28
assert output == expected_output | 5,336,749 |
def fermi_fitness(strategy_pair, N, i, utilities, selection_intensity=1):
"""
Return the fermi fitness of a strategy pair in a population with
N total individuals and i individuals of the first type.
"""
F, G = [math.exp(k) for k in fitness(strategy_pair, N, i, utilities)]
return F / (F + G), G... | 5,336,750 |
def diff_smf(mstar_arr, volume, h1_bool, colour_flag=False):
"""
Calculates differential stellar mass function in units of h=1.0
Parameters
----------
mstar_arr: numpy array
Array of stellar masses
volume: float
Volume of survey or simulation
h1_bool: boolean
True ... | 5,336,751 |
def get_parameter(dbutils, parameter_name: str, default_value='') -> str:
"""Creates a text widget and gets parameter value. If ran from ADF, the value is taken from there."""
dbutils.widgets.text(parameter_name, default_value)
return dbutils.widgets.get(parameter_name) | 5,336,752 |
def single_init(cfg: GenomeConfig):
"""Random initialized floating GRU value, calculated via a normal distribution."""
return clip(gauss(cfg.gru_init_mean, cfg.gru_init_stdev), a_min=cfg.gru_min_value, a_max=cfg.gru_max_value) | 5,336,753 |
def get_recent_articles(request):
"""
获取最近更新内容
"""
user = get_login_user(request)
recommend = request.POST.get('recommend', 'recommend')
if recommend == 'unrecommend':
articles = Article.objects.raw(get_other_articles_sql)
elif recommend == 'recommend':
articles = Article.ob... | 5,336,754 |
def add_close_export_to_cell(cell):
"""
Adds an HTML comment to close question export for PDF filtering to the top of ``cell``. ``cell``
should be a Markdown cell. This adds ``<!-- END QUESTION-->`` as the first line of the cell.
Args:
cell (``nbformat.NotebookNode``): the cell to add the c... | 5,336,755 |
def get_ram_list_linux():
"""Get RAM list using dmidecode."""
cmd = ['sudo', 'dmidecode', '--type', 'memory']
dimm_list = []
manufacturer = 'Unknown'
size = 0
# Get DMI data
proc = run_program(cmd)
dmi_data = proc.stdout.splitlines()
# Parse data
for line in dmi_data:
line = line.strip()
i... | 5,336,756 |
def test_random_startup_node():
"""
Hard to test reliable for a random
"""
s = [{"1": 1}, {"2": 2}, {"3": 3}],
n = NodeManager(startup_nodes=s)
random_node = n.random_startup_node()
for i in range(0, 5):
assert random_node in s | 5,336,757 |
def get_capability_list(capability=esdl.Producer):
"""Returns a list of all subtypes of the specified capability.
Used to get a list of e.g. all producers in ESDL
The list is automatically generated based on the ESDL meta model"""
subtype_list = list()
for eclassifier in esdl.eClass.eClassifiers:
... | 5,336,758 |
def test_reset_password_bad_token(client: TestClient, session: db.Session):
"""Cannot change password with a bad token"""
bad_token = uuid.uuid4()
password = utils.generate_random_chars(8)
response = client.post(
f"/v2/reset/{bad_token}",
json={"password": password, "password_confirm": p... | 5,336,759 |
def _get_exec_binary(binary, kw):
"""
On win32, the subprocess module can only reliably resolve the
target binary if it's actually a binary; as for a Node.js script
it seems to only work iff shell=True was specified, presenting
a security risk. Resolve the target manually through which will
acc... | 5,336,760 |
def init_SSE_square(Lx, Ly):
"""Initialize a starting configuration on a 2D square lattice."""
n_sites = Lx*Ly
# initialize spins randomly with numbers +1 or -1, but the average magnetization is 0
spins = 2*np.mod(np.random.permutation(n_sites), 2) - 1
op_string = -1 * np.ones(10, np.intp) # initia... | 5,336,761 |
def filter_signal(eeg_df, iqrs, dic_filt_opts):
"""
Filter signal
"""
all_labels = list(eeg_df.columns)
# check the order of labels
label_grouped = False
if all_labels[0].split('.')[-1] == all_labels[1].split('.')[-1]:
label_grouped = True
data_labels = all_pow_nod... | 5,336,762 |
def get_sym_inequiv_components(
components: List[Component], spg_analyzer: SpacegroupAnalyzer
) -> List[Component]:
"""Gets and counts the symmetrically inequivalent components.
Component data has to have been generated with ``inc_site_ids=True``.
Args:
components: A list of structure componen... | 5,336,763 |
def aic(llf, nobs, df_modelwc):
"""
Akaike information criterion
Parameters
----------
llf : {float, array_like}
value of the loglikelihood
nobs : int
number of observations
df_modelwc : int
number of parameters including constant
Returns
-------
aic : f... | 5,336,764 |
def summarize_logs(df, wells, cat, props, sr=0.5):
"""
Function to calculate petrophysical summaries based on well and categorical data. All logs averaged with simple
arithmetic means (maybe supply log permeability to have a better averaged estimation)
Parameters:
logs (pd.DataFrame): datafra... | 5,336,765 |
def run_trap_harvesting(prev_values = [], selected_harvest= 0, radius= default_radius, height= default_height, slope= default_slope, delta= default_delta, constant_population= True):
"""Runs the model for one harvesting cycle. Where a harvesting cycle is period of time ending in the next low tide in which the trap ... | 5,336,766 |
def get_tfpn_mean(targets, predictions):
"""
给定标签和预测,返回对应所有类的 Tp, FN, FP, TN 的平均值
:param targets:
:param predictions:
:return:
"""
cm = confusion_matrix(targets, predictions)
total = np.array(cm).sum()
TP = cm.diagonal().sum()
FN = total - TP
FP = FN
TN = total * len(cm)... | 5,336,767 |
def salad(img_dir_path: str, test_size: float = 0.2, seed: Optional[int] = None,
dir_names: tuple(str, str) = ('train', 'valid')):
"""
Physically split and shuffle the data(copy) in the directory like salad.
default test size is 20%(0.2), seed is optional, default directory names 'train' and 'vali... | 5,336,768 |
def cal_deltaE00_from_LCh(LCh_1, Lab_2):
"""
Calculate the color difference :math:`\Delta E_{00}` between two given colorspace arrays.
:param LCh_1: array-like
:param Lab_2: array-like
:return: numeric or ndarray
"""
Lab_1 = LCh2Lab(LCh_1)
return deltaE00(Lab_1, Lab_2) | 5,336,769 |
def get_var_type_glue(vtype):
"""Get glue module from variable's type.
Parameters
----------
vtype: data type
Returns
-------
Glue Module if glue exists, otherwise None.
"""
global DTYPE_TO_GLUE, PKG_NAME_TO_GLUE_ARGS
glue_mod = DTYPE_TO_GLUE.get(vtype, None)
if glue_mod is... | 5,336,770 |
def sgd(params, lr, batch_size):
"""小批量随机梯度下降。
Defined in :numref:`sec_linear_scratch`"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_() | 5,336,771 |
def contract_TRG(state, svd_option_1st=None, svd_option_rem=None):
"""
Contract the PEPS using Tensor Renormalization Group.
Parameters
----------
svd_option_1st: tensorbackends.interface.Option, optional
Parameters for the first SVD in TRG. Will default to tensorbackends.interface.ReducedS... | 5,336,772 |
def riccati_3(nmax,x):
"""Riccati bessel function of the 3rd kind
returns (r3, r3'), n=0,1,...,nmax"""
x = np.asarray(x)
result = np.zeros((2,nmax) + x.shape, dtype=complex)
for n in range(nmax):
yn = special.spherical_yn(n+1,x)
ynp = special.spherical_yn(n+1,x, derivative=True... | 5,336,773 |
def conv_batch_relu_forward(x, w, b, gamma, beta, conv_param, bn_param):
"""
Convenience layer that performs a convolution, a batch, and a ReLU.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
- gamma, beta, bn_param : batch n... | 5,336,774 |
def hex_layout(npos, width, rotate=None):
"""Compute positions in a hexagon layout.
Place the given number of positions in a hexagonal layout projected on
the sphere and centered at z axis. The width specifies the angular
extent from vertex to vertex along the "X" axis. For example::
Y ^ ... | 5,336,775 |
def copy_sim_files(sim_file_list, sim_dir, param_dict):
"""
Given a list of file paths 'sim_file_list' and simulation directory
'sim_dir', copies the files to the simulation directory and replaces
variables in those files.
"""
print("Copying {} to {} and replacing vars".format(sim_file_list, sim... | 5,336,776 |
def dup_zz_hensel_step(m, f, g, h, s, t, K):
"""
One step in Hensel lifting in `Z[x]`.
Given positive integer `m` and `Z[x]` polynomials `f`, `g`, `h`, `s`
and `t` such that::
f == g*h (mod m)
s*g + t*h == 1 (mod m)
lc(f) is not a zero divisor (mod m)
lc(h) == 1
... | 5,336,777 |
def generate_sobol_index_sample_sets(samplesA, samplesB, index):
"""
Given two sample sets A and B generate the sets :math:`A_B^{I}` from
The rows of A_B^I are all from A except for the rows with non zero entries
in the index I. When A and B are QMC samples it is best to change as few
rows as poss... | 5,336,778 |
def export_gmt_files(files):
"""To convert the output .csv files to gmt:
1. Manually remove the index column and column labels.
2. Save file as .txt
3. Then change the suffix as .gmt """
path = "tfac/data/gsea_libraries/"
for f in files:
translate_gene_sets(pd.read_csv(path ... | 5,336,779 |
def setup_logfile_logger(log_path, log_level=None, log_format=None, date_format=None):
"""
Set up logging to a file.
"""
# Create the handler
handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0)
if log_level:
# Grab and set the level
level = LOG_LEVELS.get... | 5,336,780 |
def pubsub_pub_command():
"""发布频道"""
global r
r.publish("my-first-channel", "my-first-channel-data") | 5,336,781 |
def test_suma(a, gen_b ):
"""Test suma"""
#flexmock(gtw, suma=9 )
s = gtw.suma(a,gen_b)
assert (s == a+gen_b) | 5,336,782 |
def test_tc_train_effectiveness():
"""assert that training decreases the loss"""
happy_tc = HappyTextClassification(
model_type="DISTILBERT",
model_name="distilbert-base-uncased"
)
before_loss = happy_tc.eval("../data/tc/train-eval.csv").loss
happy_tc.train("../data/tc/train-eval.csv... | 5,336,783 |
def fix_encoding_and_explain(text):
"""
Deprecated copy of `ftfy.fix_encoding_and_explain()`.
"""
warnings.warn(
"`fix_encoding_and_explain()` has moved to the main module of ftfy.",
DeprecationWarning,
)
return ftfy.fix_encoding_and_explain(text) | 5,336,784 |
def test_cspad_xy_at_z() :
""" Test cspad geometry table
"""
## 'CxiDs1.0:Cspad.0)' or 'DscCsPad'
basedir = '/reg/g/psdm/detector/alignment/cspad/calib-cxi-camera1-2014-09-24/'
fname_geometry = basedir + '2016-06-03-geometry-cxi06216-r25-camera1-z175mm.txt'
fname_data = basedir + '2016-... | 5,336,785 |
def parse_16bit_color(color16):
"""解析16位的颜色
:param color16: 16位的颜色值
"""
r = int(gamma5[int((color16 >> 11) & 0x1F)])
g = int(gamma6[int((color16 >> 5) & 0x3F)])
b = int(gamma5[int(color16 & 0x1F)])
return (r, g, b) | 5,336,786 |
def remove_default_cube():
"""
Remove the cube that is in the blender default scene to get an empty scene.
"""
bpy.data.objects["Cube"].select = True
bpy.ops.object.delete() | 5,336,787 |
def test_ramp_up_weights():
"""Test TPE adjust observed points correctly"""
weights = ramp_up_weights(25, 15, True)
assert len(weights) == 25
assert numpy.all(weights == 1.0)
weights = ramp_up_weights(25, 15, False)
assert len(weights) == 25
assert numpy.all(weights[:10] == (numpy.linspace(... | 5,336,788 |
def dqc_0008(instance, error_log, suppress_errors, namespaces):
"""DQC_0008 Reversed Calculation"""
dts = instance.dts
ns = get_namespace(namespaces, 'us-gaap')
us_gaap_calc = dqc_0008_calculations.get(ns)
if us_gaap_calc:
for linkrole in dts.calculation_link_roles(arcrole_summation_item):
... | 5,336,789 |
def orders():
"""
List all orders
"""
orders = Order.query.filter_by(user_id=current_user.id).all()
return render_template('customer/orders.html', orders=orders, title="Orders") | 5,336,790 |
def packpeeklist1(n1, n2, n3, n4, n5):
"""
Packs and returns 5 item list
"""
listp = [n1, n2, n3, n4, n5]
return listp | 5,336,791 |
def valid_commands(commands: List[str]) -> List[str]:
"""
Get list of valid commands from list of commands.
:param (list) commands: User-supplied commands.
:return:
"""
return [command for command in commands if command in available_commands()] | 5,336,792 |
def duck_list(request):
""" lists all ducks """
ducks = Duck.objects.all()
return render(request, 'duck/list.html', {'duck_list': ducks}) | 5,336,793 |
def test_scheme_16():
"""SCHEME 16:
Rule 12: Remove Rings First Where the Linker Is Attached to a Ring Hetero-atom at Either End of the Linker
Ring heteroatoms are more easy to functionalise and, therefore, are often functionalised in the later stage
of a chemical library synthesis and thus less chara... | 5,336,794 |
def get_debian_version(file_path):
"""
Get the version of a debian file
:param file_path: the path of the debian file
:return: the version of the debian file
"""
cmd_args = ["dpkg-deb", "-f", file_path, "Version"]
debian_version = run_command(cmd_args)
return debian_version | 5,336,795 |
def hash_type(
draw, hash_type_strategy: Optional[SearchStrategy[HashType]] = None
) -> HashType:
"""Composite strategy for fetching a :class:`~modist.package.hasher.HashType`."""
return draw(HashType_strategy if not hash_type_strategy else hash_type_strategy) | 5,336,796 |
def get_initializer(initializer_name):
"""Get the corresponding initializer function based on the initializer string.
API of an initializer:
init_fn, hparams = get_initializer(init)
new_params, final_l = init_fn(loss, init_params, hps,
num_outputs, input_shape)
Args:
init... | 5,336,797 |
def sh(cmd, grid=False, infile=None, outfile=None, errfile=None,
background=False):
"""
simple wrapper for system calls
"""
if grid:
return 0 # A fake retcode
else:
if infile:
cmd += " < {0} ".format(infile)
if outfile and outfile != "stdout":
... | 5,336,798 |
def clean_kubeflow_repo(
shared_kubeflow_repo: Repository, clean_repo: Repository
) -> Generator[Repository, None, None]:
"""Creates a clean repo with a provisioned local kubeflow stack.
Args:
shared_kubeflow_repo: A repository with a provisioned local kubeflow
stack
clean_repo:... | 5,336,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.