content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def createDatabase(s):
"""
Install a _NeedsDelivery and Composer on the given store.
"""
_NeedsDelivery(store=s, composer=Composer(store=s),
message=s, toAddress=u'to@host',
tries=21) | 78,100 |
def process_playbook(item, repo, dest_dir, user, template_name):
"""
Helper function which creates playbook instance from the incoming
case template import
Args:
item (dict): dictionary which has 'scm' and 'playbook' keys
repo (str): The repo in which to impport the
dest_dir (str... | 78,101 |
def analyse(c):
"""
Analyse the document style and wording.
This makes use of the `diction` and `style` packages.
Installation:
Linux:
apt install diction
apt install style
OS X:
brew install diction
brew install style
"""
boo... | 78,102 |
def list_dir(data_dir, allowed_extensions=['.json']):
"""
List files in directory
Args:
data_dir: data directory
allowed_extensions: File extensions were accepted
Returns:
file_paths: list of files
"""
file_paths = []
# anot_paths = []
# List files in data_dir
... | 78,103 |
def weighted_rmsd(x, y, dim=None, weights=None):
""" Compute weighted root mean square deviation between two xarray DataArrays
Parameters
----------
x, y : xarray.DataArray
xarray DataArray for which to compute `weighted_rmsd`.
dim : str or sequence of str, optional
Dimension(s) ove... | 78,104 |
def pretty_color_palette(identifiers, keep_zero_black=True):
"""Return dictionary with pretty colors.
:param identifiers: set of unique identifiers
:param keep_zero_black: whether or not the background should be black
:returns: dictionary
"""
color_dict = {}
for i in identifiers:
i... | 78,105 |
def get_second_derivative_matrix(n):
"""
:param n: The size of the time series
:return: A matrix D such that if x.size == (n,1), D * x is the second derivate of x
"""
m = n - 2
D = spmatrix(list(chain(*[[1, -2, 1]] * m)),
list(chain(*[[i] * 3 for i in range(m)])),
... | 78,106 |
def LastIndexOf(s, substr):
"""Retrieve the last index of substring within a string"""
ctx = None
ctx = _get_ctx2(s, substr, ctx)
s = _coerce_seq(s, ctx)
substr = _coerce_seq(substr, ctx)
return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx) | 78,107 |
def test_init_cpi_openstack_cluster(skuba, kubernetes_version=None):
"""
Initialize the cluster with the openstack cpi
"""
skuba.cluster_init(kubernetes_version, cloud_provider="openstack") | 78,108 |
def _remove_unused_params(params):
"""
Removed unused parameters considering the registries.
For example, if the regularization is None, there is no need for the regularization parameter lambda.
Parameters
----------
params: dict
Dictionary with parameters.
Returns
-------
... | 78,109 |
def multi_batch_apply(f, num_batch_dims, *args, **kwargs):
"""Vectorized application of f on tensors with multiple batch dims.
Batch dims must be the same for every tensor in args/kwargs.
Args:
f: Callable, needs only expect one batch dim in input tensors.
num_batch_dims: Integer, the number of batch di... | 78,110 |
def get_similar_comments(embedder, dataset, corpus, sarcasm_embeddings, query, n):
"""
Returns the most similar comments in terms of cosine similarity of their respective embeddings
Parameters:
embedder (SentenceTransformer): chosen model from HuggingFace
dataset (DataFrame): comment metadata
... | 78,111 |
async def test_reject_presentation(
backchannel: Client,
issue_credential,
issuer_holder_connection,
wait_for_message,
connection,
):
"""Test the presentation rejection message and flows."""
verifier, prover = issuer_holder_connection
verifier = cast(ConnRecord, verifier)
prover = ca... | 78,112 |
def all_registered_modules():
""" Return a generator over the instances of all registered class-based modules """
yield from iterchain(modules.values() for modules in Registry.monomers.values()) | 78,113 |
def build_pr_review_line_comment(context, violation):
"""
Creates a Markdown representation of the comment to be posted to a pull request.
:return: The comment
"""
template = env.get_template("pr_review_line_comment.txt")
return template.render(
violation=violation, context=context, LINT... | 78,114 |
def fetch(table, cols="*", where=(), group=(), order=(), limit=(), **kwargs):
"""
Convenience wrapper for database SELECT and fetch one.
Keyword arguments are added to WHERE.
"""
return init().fetch(table, cols, where, group, order, limit, **kwargs) | 78,115 |
def generate_mesh(level):
"""
Generate a mesh of the North Sea domain using qmesh.
"""
name = "north_sea.{:s}"
# Setup qmesh
qmesh.setLogOutputFile("qmesh.log")
qmesh.initialise()
# Read shapefile describing domain boundaries
boundary = qmesh.vector.Shapes()
boundary.fromFile("... | 78,116 |
def gradient_descent(optfun, x0, iterations=100, tolerance=1e-5):
"""
Given an OptFunction `optfun` and a starting point `x0`, and given
parameters `iterations` and `tolerance`, perform the gradient descent
algorithm using backtracking line search to minimize `optfun`.
This implementation should re... | 78,117 |
def list_files(
*,
storage_bucket_name: str,
prefix: Optional[str] = None,
) -> Set[Blob]:
"""List all files in a given storage bucket."""
client = get_client()
return set(client.list_blobs(storage_bucket_name, prefix=prefix)) | 78,118 |
def focus_next() -> "None":
"""Focus the next control."""
get_app().layout.focus_next() | 78,119 |
def position_list_view(request):
"""
We actually don't want to see PositionForFriends entries in this view
:param request:
:return:
"""
# admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer
authority_required = {'partner_organization', 'verified_vol... | 78,120 |
def _transparent_cmap(cmap, n=255):
"""transparent heat map color map"""
mycmap = cmap
mycmap._init()
mycmap._lut[:, -1] = np.linspace(0, 0.8, n + 4)
return mycmap | 78,121 |
def test_sub_pixel_read_invalid_bounds():
"""Test sub_pixel_read with invalid bounds."""
data = np.zeros((16, 16))
out_size = data.shape
bounds = (0, 0, 0, 0)
with pytest.raises(ValueError, match="Bounds must have non-zero size"):
utils.image.sub_pixel_read(data, bounds, out_size)
boun... | 78,122 |
def get_topo_min(soln_dir: os.PathLike, frame_bg: int, frame_ed: int, level: int):
"""Get the minimum elevation during runtime among the time frames at a specific AMR level.
Arguments
---------
soln_dir : pathlike
Path to where the solution files are.
frame_bg, frame_ed : int
Begini... | 78,123 |
def scrape():
"""Scrape the UD project page for metadata of the treebanks.
"""
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
session.get(URL)
we... | 78,124 |
def test_auto_geofeature_aggregation_creation(composite_resource_with_mi_aggregation_folder, mock_irods):
"""Test that when files that represents a geofeature are uploaded to a folder that
represents a model instance, a geofeature aggregation is created automatically"""
resource, _ = composite_resource_wit... | 78,125 |
def test_mongodb(provider, keyid, secret, token, imageid, subscription, tenant, projectid,
instancetype, user, localpath, region, zone, sriov, kernel):
"""
Run MongoDB YCBS benchmark test on 2 instances.
:param provider Service provider to be used e.g. azure, aws, gce.
:param keyid: use... | 78,126 |
def getProjectsPayload(user_id) -> List[Dict]:
"""
Returns a list of project information accessible to a given user.
:return: list of objects containing project information
"""
global loadedProjects
return [{
'id': p.id,
'name': p.name,
'files': len(p.files),
'pat... | 78,127 |
def QuantileMerge(feature, nan = -1, n_bins = None, q = None ,min_samples = 1):
"""Merge by quantile
Args:
feature (array-like)
nan (number): value will be used to fill nan
n_bins (int): n groups that will be merged into
q (array-like): list of percentage split points
Retur... | 78,128 |
def blog():
"""
The blog section will show the user an infinite cascade of blog posts
that will load based on the user scroll.
"""
return dict(
title="Blog",
year=datetime.now().year
) | 78,129 |
def edge(kube_config_file_path, tc_config_data):
"""
Initializes connection to edge via RaaS or locally (subprocess) based on configuration.
Release connection when not needed anymore
:param kube_config_file_path: Kubernetes konfiguration file path
:param tc_config_data: Test case config
:return... | 78,130 |
def create_refund(order):
"""
全额退款
"""
instance = RefundRecord.create(order, order.user, order.real_amount, order.asset_pay, order.recharge_pay,
refund_desc='拼团失败')
if instance.real_amount > 0 and order.trade_no: # order.real_amount 大于0说明需要微信退款
res =... | 78,131 |
def parse_dhall(content: str, cwd: Optional[Path] = None) -> JSONType:
"""Takes Dhall content and parses it to JSON compatible data."""
cwd = cwd or Path(".")
result = subprocess.run(
["dhall-to-json"], cwd=cwd,
input=content, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, encoding=... | 78,132 |
def getMediaTime(sourceName: str):
"""
Get the current timestamp of media in milliseconds. Supports ffmpeg and vlc media sources (as of OBS v25.0.8)
:param sourceName: String - Source name.
"""
return __createJSON("GetMediaTime", {'sourceName': sourceName}) | 78,133 |
def randbetween(ctx, bottom, top):
"""
Returns a random integer number between the numbers you specify
"""
bottom = conversions.to_integer(bottom, ctx)
top = conversions.to_integer(top, ctx)
return random.randint(bottom, top) | 78,134 |
def read_dependencies(file_path):
"""Reads a json file and creates an iterable of unique dependencies.
Args:
file_path: The path to the runtime dependencies file.
Returns:
An iterable with unique dependencies.
"""
deps = None
with open(file_path) as deps_file:
deps = json.load(deps_file)
dep... | 78,135 |
def iterate_pages(api_obj, class_type, *get_request_path, _limit=30, **query_params):
""" Loads paged entities via GET request.
Yields produced objects of class_type.
Produced object should support field .id
Request should support optional 'lastId'
"""
batch = api_obj.children(class_type, api_obj.api.get(*get_req... | 78,136 |
def is_inactive(
person_data: dict,
keyword: str = COMPANIES_HOUSE_RESIGNATION_KEYWORD,
date_format: str = COMPANIES_HOUSE_DATE_FORMAT,
) -> bool:
"""Tests whether board members (default) or controllers are inactive."""
return (
keyword in person_data
and datetime.strptime(person_dat... | 78,137 |
def test_parse_unexpected_token() -> None:
"""The separator of a merge conflict cannot occur in COMMON state."""
line = "=======\n"
with pytest.raises(parser.UnexpectedTokenError):
parser.parse_line(line, parser.State.COMMON) | 78,138 |
def load_env(state, eid, socket, env_path=DEFAULT_ENV_PATH):
""" load an environment to a client by socket """
env = {}
if eid in state:
env = state.get(eid)
elif env_path is not None:
p = os.path.join(env_path, eid.strip(), '.json')
if os.path.exists(p):
with open(p,... | 78,139 |
def print_progress(step, total, final=False):
"""Print progress in one line
Args:
step: current step; assumed to start at 0
total: total number of steps
final: is this the final step
"""
step += 1
curr_idx = np.int( step * 50 / total)
text = '-'*curr_idx + ' '*(49-... | 78,140 |
def get_day_menu(which, url):
"""Parses the day menu from the given url."""
# Assumptions:
# - The #content-core contains only <li> items belonging to the menu and <h3> elements that indicate a type.
# - All menu items have a price, except vegetables.
# - Priced items are of the form "NAME - € X,XX"... | 78,141 |
def _create_heatmap(image_shape, heatmap_shape,
annotation_points, kernel):
"""
Creates density map.
annotation_points : ndarray Nx2,
annotation_points[:, 0] -> x coordinate
annotation_points[:, 1] -> y coordinate
"""
assert (kernel.... | 78,142 |
def LabelList(ratio=1, root='~/.mxnet/datasets', name='market1501'):
"""Load the Label List for Market 1501 dataset.
Parameters
----------
ratio : float, default 1
Split label into train and test.
root : str, default '~/.mxnet/datasets'
Path to the folder stored the dataset.
nam... | 78,143 |
def generate_docs_manaul():
"""
This Function should be used to create apidoc for different API endpoints.
Returns:
"""
counter = 0
print("Welcome to Swagger.json creation.")
swag_gen = SwaggerDocsGen()
while counter == 0:
method = input('Plese enter the method of API (GET/POST... | 78,144 |
def get_tags_by_month_for_users(data , usernames):
"""
initialize list of months and sets
for each list of data in data
slice out twitter information
if username in username list
for each tag in hashtags in tweet
add hashtag to set in data list
:param data - l... | 78,145 |
def customer_edit(request, cid):
"""
新增客户
:return:
"""
obj = models.Customer.objects.get(id=cid)
if request.method == 'GET':
form = CustomerForm(instance=obj)
return render(request, 'customer_add.html', {'form': form})
form = CustomerForm(data=request.POST, instance=obj)
... | 78,146 |
def dynamic_pricing(tfr_dfs):
"""
Transform the EIA 861 Dynamic Pricing table.
Args:
tfr_dfs (dict): A dictionary of transformed EIA 861 DataFrames, keyed by table
name. It will be mutated by this function.
Returns:
dict: A dictionary of transformed EIA 861 dataframes, keye... | 78,147 |
def get_annotation(annotation_file, annotation_name, sampling_freq=64):
"""
Extract annotation from an EDF file
annotation_file : EDF handle
annotation_name :(str) name of the annoation to get
sampling_freq : (int) sampling freq to use to build the event binary representation
"""
annotation... | 78,148 |
def get_current_theme_assets_dirs():
"""
Returns a path which is the directory root of static assets for a theme.
"""
roots = []
site = get_current_site()
if site is not None:
# ``site`` could be ``None`` when this code is used through
# a manage.py command (ex: collectstatic).
... | 78,149 |
def set_header_path(*args):
"""
set_header_path(path, add) -> bool
Set or append a header path. IDA looks for the include files in the
appended header paths, then in the ida executable directory.
@param path: list of directories to add (separated by ';') may be
NULL, in this case nothing i... | 78,150 |
def plot_acquisition_function_1D(
ax: plt.Axes,
acquisition_function: AcquisitionFunction,
bound: Bound,
n_points: int = 100,
) -> None:
"""Plot a 1D acquisition_function.
Parameters
----------
ax: plt.Axes
matplotlib axes object on which to plot the graph.
acquisition_funct... | 78,151 |
def test_user_config_json_success():
"""Success scenario
"""
class T(CommandLineTool):
"""Test class"""
@arg.user_config_json()
@arg()
def t(self):
"""t"""
valid_json_arg = ["t", "--user-config-json", '{"foo":"bar"}']
test_class = T("avn")
ret = tes... | 78,152 |
def correlate_ica_with_cortical_signal(
participants_file,
ica_pattern,
ctab_pattern,
oc_pattern,
mask_pattern,
):
"""Perform analysis 2.
Correlate each ICA component's time series with the mean cortical signal of the OC dataset.
Divide the components into BOLD and non-BOLD, then record... | 78,153 |
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"
return ''.join(random.choice(letters) for i in range(stringLength)) | 78,154 |
def color_balance (input: Tensor, weight: Tensor) -> Tensor:
"""
Apply color balance adjustment (temperature and tint) on an RGB image.
Parameters:
input (Tensor): Input RGB image with shape (N,3,H,W) in range [-1., 1.].
weight (Tensor): Scalar weight with shape (N,2) in range [-1., 1.].
... | 78,155 |
def register_pump_type(target_class):
"""Called when BasePump is subclassed to add the new pump type to the registry"""
if target_class.__name__ in __PUMP_REGISTRY:
msg = "Trying to register %s but a class with the name %s already exists in the report registry" % (
target_class, target_class... | 78,156 |
def sort_num(request):
""" Sort some numbers from Request """
num_str = request.GET["numbers"]
num_lst = [int(n) for n in num_str.split(",")]
data = {
"num": sorted(num_lst),
"status": "ok",
"msg": "Integer soarted Succesfully!"
}
return HttpResponse(json.dumps(data), con... | 78,157 |
def uwsgi():
"""Entry point for uwsgi"""
config = load_config(os.environ.get("LANAUTH_CONFIG"))
if config is not None:
app = load_app(config)
return app | 78,158 |
async def async_setup(hass: HomeAssistant, config: Dict[str, Any]):
"""Import integration from config."""
if DOMAIN in config:
for entry in config[DOMAIN]:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_I... | 78,159 |
def follow(thefile):
"""Read a new line from the log file
Args:
thefile: log file reference
Returns:
line: a new line
"""
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line | 78,160 |
def get_cephfs_data_pool_name():
"""
Fetches ceph fs datapool name from Ceph
Returns:
str: fs datapool name
"""
ct_pod = pod.get_ceph_tools_pod()
out = ct_pod.exec_ceph_cmd('ceph fs ls')
return out[0]['data_pools'][0] | 78,161 |
def main(args):
"""Run the command line program."""
input_csv = args.infile if args.infile else sys.stdin
df = pd.read_csv(input_csv, header=None, names=('word', 'word frequency'))
df['rank'] = df['word frequency'].rank(ascending=False)
df['inv_rank'] = 1 / df['rank']
df.plot.scatter(x='word f... | 78,162 |
def test_sample_from_manifest():
"""
Test the card lookup function
"""
sample = [1, 99, 100, 101, 121, 200, 201]
d = [{'Tray #': 1, 'Tabulator Number': 17, 'Batch Number': 1, 'Total Ballots': 100, 'VBMCart.Cart number': 1},\
{'Tray #': 2, 'Tabulator Number': 18, 'Batch Number': 2, 'Total Bal... | 78,163 |
def no_identical_digits_in_same_block():
"""Returns a list of clauses, stating that if a digit appears
in a cell, the same digit cannot appear elsewhere in the
same row, column, or 3x3 square."""
bigi = 0
bigj = 0
list = []
for big in range(9):# The 9 big boxes
if (bigj > 2):
... | 78,164 |
def cli(ctx,
language, # type: str
file, # type: str
action, # type: str
vcs # type: bool
):
"""
Get or increment current version in the file
Supported: raw text file, npm package.json
:param ctx
:param language: str
:param file: str
:param action: s... | 78,165 |
def xgb_average_recalln_curve_score(n):
"""evaluate average recall-n curve score for xgb"""
def feval(preds, labels):
labels = labels.get_label()
trials = np.argsort(preds)[::-1]
ranks = get_rank(labels[trials])
curve = recall_curve(ranks)
return "a-recall@%d" % n, np.su... | 78,166 |
def view_organization(organization_id):
"""
Function enables user to view an Organization from the database.
"""
try:
organization_id = int(organization_id)
if not organization_controller.query_organization(organization_id):
return jsonify({
'message': 'Organi... | 78,167 |
def GenerateFieldContent(element_name, field_info, content, lines):
"""Generate the content of a field to be included in the static structure
initializer. If the field's content is not specified, uses the default value
if one exists.
"""
if content is None:
content = field_info.get('default', None)
type... | 78,168 |
def get_face_rectangles(azure_response):
"""
Returns the rectangles corresponding to the faces detected by Azure
:param azure_response: Response from Azure Face request as dictionary.
:return: The rectangles of any detected face with the format: (width, height, left, top)
"""
result = []
for... | 78,169 |
def SchaffersF7(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Weierstrass function."""
dim = len(arr)
arr.shape = (dim, 1)
if dim == 1:
return 0.0
z = np.matmul(_R(dim, seed, b"R"), arr)
z = Tasy(z, 0.5)
z = np.matmul(_R(dim, seed, b"Q"), z)
z = np.matmul(LambdaAlpha(10.0, dim... | 78,170 |
def test_ap_wpa2_eap_peap_crypto_binding_server_oom(dev, apdev):
"""WPA2-Enterprise connection using EAP-PEAPv0/EAP-MSCHAPv2 and crypto binding with server OOM"""
check_eap_capa(dev[0], "MSCHAPV2")
params = int_eap_server_params()
hapd = hostapd.add_ap(apdev[0], params)
with alloc_fail(hapd, 1, "eap... | 78,171 |
def retr_spacegroup_number(xtalstr,ini0):
"""
Retrieve the space group number.
When choosing real space grids some space groups imply restrictions
on the number of points along the different lattice vectors.
To impose the correct restrictions we need to know the space group
number of the curren... | 78,172 |
def GetLocationFlag():
"""Anthos location flag."""
return base.Argument(
'--location',
required=False,
help='Specifies the Google Cloud location to use. If not'
'specified will use the current compute/zone property.') | 78,173 |
def get_user_credentials(env_ctx, upgrades):
"""
Prompt for snaplogic user credentials. If upgrades required then ask for admin user.
"""
credentials = None
print ""
user = 'admin'
password = input_value("Please specify the SnapLogic admin Password:", "", False, True)
env_ctx['SNAPLOGIC_... | 78,174 |
def rmse(y_true, y_pred):
"""
Calculates the RMSE value for forecast Values
Args:
y_true: True time series
type: np.array
y_pred: Predicted time series
type: np.array
Return:
score: RMSE value for forecast values
... | 78,175 |
def test_in_place(example_model):
"""This test checks if in_place parameter works as expected."""
o_weights = example_model.get_weights()
n_model = prune_model(example_model, 0.8, in_place=False)
assert (example_model.get_weights()[0] == o_weights[0]).all(), \
'original model shouldn\'t change'
... | 78,176 |
def build_yolo_augmentation(cfg, is_train):
"""
Train Augmentations:
- YOLOFJitterCrop
- YOLOFResize
- YOLOFRandomDistortion
- RandomFlip
Test:
- YOLOFResize
"""
augmentation = []
if is_train:
if cfg.INPUT.JITTER_CROP.ENABLED:
augmentat... | 78,177 |
def get_mean_expression(fnames, name, sep="\t", gene_set=[]):
"""Get mean expression for replicates of one time point."""
dfs = [get_expression(fname, sep=sep, gene_set=gene_set) for fname in fnames]
joined = pd.concat(dfs, axis=1, join="inner")
return joined.mean(axis=1).rename(name) | 78,178 |
def find_random_monster(min_cr=None, max_cr=None, environment=None):
"""
Find a random monster
"""
filters = [
{'$sample': {'size': 1}}
]
if min_cr:
query = {'$match': {'challenge_rating': {"$gte": float(min_cr)}}}
filters.insert(0, query)
if max_cr:
query ... | 78,179 |
def make_vowelify(words):
"""Chop off consonant ala nautica if second to last letter is a vowel."""
new_arr = []
for word in words:
if re.search(_regexes['all_vowels'], word[:-2]):
new_arr.append(word[:-1])
return new_arr | 78,180 |
def sketch_by_name(sketches: adsk.fusion.Sketches, name: str) -> adsk.fusion.Sketch:
"""
Finds a sketch by name in a list of sketches
Useful for parsing a collection of sketches such as DXF import results.
:param sketches: A list of sketches.
:type sketches: adsk.fusion.Sketches
:param name: Th... | 78,181 |
def LoadFinalCircuit(Parasitics=False,LoopgainMag=True,LoopgainPhs=True):
"""
Returns the Loop Gain symbolic analysis estimation of the final circuit
Select Parasitcs=True for symbolic estimations considering the parasitics after extraction in Cadence.
"""
#Frequency limits to be plot
f_check_... | 78,182 |
def get_conformer(species, name):
"""
Generate a conformer of a species given a new name but with the same
atoms
Arguments:
species (autode.species.Species):
name (str):
Returns:
(autode.conformers.Conformer): Conformer
"""
conformer = Conformer(name=name, atoms=spe... | 78,183 |
def save_tempfile(
text,
filename=None,
encoding='utf-8',
start=True,
browser=False,
): # pylint: disable=too-many-branches, too-many-return-statements
# fmt: on
"""Save text (str) to file (default to tmp.txt) or filepath (Path(str)).
if brwoser set to True/1, attem... | 78,184 |
def is_valid_mixture(mixture):
"""Check if mixture is a 2D array with strings representing the models."""
assert type(mixture) == list and len(mixture) > 0
for inner_comb in mixture:
assert type(inner_comb) == list and len(inner_comb) > 0
for model in inner_comb:
assert model in ... | 78,185 |
def _get_stream_with_params_and_return_list_of_ads(filter_params):
"""
This function handles:
http GET request
check that no http error is returned
converting the bytestring in the response to a list of ads
"""
response = requests.get(url_for_stream, headers=headers, params=filte... | 78,186 |
def add_token_to_certs_request(token):
"""
Add a token to the file holding the nodes we expect a certificate request from
:param token: the token
"""
with open(certs_request_tokens_file, "a+") as fp:
fp.write("{}\n".format(token)) | 78,187 |
def build_logfile_dirpath(gearman_worker):
"""
Build the path for saving the transfer logfile
"""
cruise_dir = os.path.join(gearman_worker.shipboard_data_warehouse_config['shipboardDataWarehouseBaseDir'], gearman_worker.cruise_id)
return os.path.join(cruise_dir, gearman_worker.ovdm.get_required_ext... | 78,188 |
def post_nadlan_sviva_rest(body, only_neighborhoods=True, subject=None,
add_coords=True):
"""take body from request and post to nadlan.gov.il deals REST API,
Sviva=other parameters, demographics, etc,
subject 1: nadlan
subject 2: area services
subject 4: demography
sub... | 78,189 |
def make_export(objects, exportable_objects=None):
"""Make export"""
query_helper = QueryHelper(objects)
ids_by_type = query_helper.get_ids()
converter = ExportConverter(
ids_by_type=ids_by_type,
exportable_queries=exportable_objects,
)
csv_data = converter.export_csv_data()
object_names = "_"... | 78,190 |
def respond(data):
"""Show ballot summary."""
global BASE_PATH
ballotid = os.path.basename(data.getfirst('b')) # get rid of any slashes, etc
ballotfile = os.path.join(BASE_PATH, 'vote2017', '{}.json'.format(ballotid))
try:
with open(ballotfile, 'r', encoding='utf-8') as inf:
da... | 78,191 |
def grad(fld, bnd=True):
"""2nd order centeral diff, 1st order @ boundaries if bnd"""
# vx, vy, vz = fld.component_views()
if bnd:
fld = viscid.extend_boundaries(fld, order=0, crd_order=0)
if fld.iscentered("Cell"):
crdx, crdy, crdz = fld.get_crds_cc(shaped=True)
# divcenter = "... | 78,192 |
def profile(request):
"""displays profile page"""
current_user = request.user
user_id = current_user.id
return render(request, 'profile/profile.html', {
'account': get_object_or_404(Account, acc_id=user_id),
'dj_name': current_user.username
}) | 78,193 |
def positions_join(positions_sequence):
"""Return concatenated positions arrays."""
return numpy.concatenate(positions_sequence) | 78,194 |
def rotate_matrix(matrix, phi, theta, psi):
""" Rotate affine transformation described by the matrix.
The rotation is described by the three euler angles
phi, theta, psi (in degree).
This is untested!
"""
# decompose transformations
t, s, r = decompose_matrix(matrix)
# buil... | 78,195 |
def build_optimizer(model, args):
""" helper to build the optimizer and wrap model
:param model: the model to wrap
:returns: optimizer wrapping model provided
:rtype: nn.Optim
"""
optim_map = {
"rmsprop": optim.RMSprop,
"adam": optim.Adam,
"adadelta": optim.Adadelta,
... | 78,196 |
def common_create_tiff(pixels: np.ndarray, out_path: str, nodata: int = -99, as_float: bool = False,
image_md: dict = None, compress: bool = False,
raster_update_func: Callable[[osgeo.gdal.Dataset], None] = None) -> None:
"""Common tiff file generating function
Argu... | 78,197 |
def test_attrib_xpath_contains():
"""
Test the selection of paths based on a contained keyword
"""
schema_dict = InputSchemaDict.fromVersion('0.34')
with pytest.raises(NoUniquePathFound):
schema_dict.attrib_xpath('l_mperp')
assert schema_dict.attrib_xpath(
'l_mperp', contains=... | 78,198 |
def docs_chm():
""" Build CHM documentation and deploy in export directory """
staging_path = 'export\\staging_docs_chm'
reset_dir(staging_path)
os.rmdir(staging_path) # for shutil.copytree
shutil.copytree('docs', staging_path)
shutil.copytree('export\\final_examples\\unpacked', op.jo... | 78,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.