content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def host_list(request):
"""List all code hosts
:rtype: json
"""
hosts = Host.objects.all()
serializer = host_serializer(hosts, many=True)
return JsonResponse(serializer.data, safe=False) | 0f41acd02beef4e656e13da9bf7401b5c24c138c | 791 |
def columns_not_changed(df, col_to_keep):
"""
insert the clean columns as features without changing the columns
:param df: dataframe
:param col_to_keep: columns that are clean and should not be changed
:return unchanged columns plus SK_ID_CURR
"""
df = df.loc[:, ['SK_ID_CURR'] + col_to_ke... | 138a21dc6b84dc03678d68c9ce279accac3b853a | 792 |
def removeRestaurantFromList(update: Update, context: CallbackContext) -> int:
"""Removes the current restaurant from the current preferred list."""
query = update.callback_query
query.answer()
# Removing the restaurant from the list in the database
removeRestaurantFromListDb(
context.chat_... | 7150744f16c53d43c8ba789df90afd98bba7c16d | 793 |
def _process_null(_):
"""
Placeholder for an efficient replacement for when no columns of a
`WaveformReducer` are activated.
"""
return dict() | 377b355104a01d93916e8a5e91934f0be79d1b13 | 794 |
import torch
def make_padded_batch(items):
"""
Pads sequences in a batch, so they are all the same length as the longest.
"""
max_len = max(len(d["input_ids"]) for d in items)
if max_len == 0:
return {k: torch.zeros((0, 0), dtype=torch.long) for k in items[0]}
return {
k: pad_s... | 8f11f83a4070845259c9549307f6d8eccee92545 | 796 |
import ctypes
def hlmlEventSetCreate() -> hlml_t.HLML_EVENT_SET.TYPE:
""" Create an empty set of events
Parameters: None.
Returns:
st (HLML_EVENT_SET) - An empty set of events.
"""
global _hlmlOBJ
st = hlml_t.HLML_EVENT_SET.TYPE
fn = _hlmlOBJ.get_func_ptr("hlml_event_s... | b5e05c9a0acdb580db2e80e46978857cbd869feb | 797 |
def is_ip_addr(value):
"""
Check that the supplied value is an Internet Protocol address, v.4,
represented by a dotted-quad string, i.e. '1.2.3.4'.
>>> vtor.check('ip_addr', '1 ')
'1'
>>> vtor.check('ip_addr', ' 1.2')
'1.2'
>>> vtor.check('ip_addr', ' 1.2.3 ')
'1.2.3'
>>> vt... | ba4a8ead84ee43ea76d14b24838ef83dca651691 | 798 |
def batchEuclid (features, patterns, knowledge):
"""
Classifies whole dataset via euclidean distance. Returns score.
"""
dists = euclidean_distances (knowledge, features)
preds = np.array (dists).argmin (axis = 0)
truthVector = (preds.T.astype (float) == patterns)
pos = truthVector.sum ()
... | 76ebcda00b28b4456454d5d1e1b5fe7aeb4e8314 | 799 |
def upload_plans_for_template(request):
"""
Allow user to upload a csv file to create plans based on a previously selected template
"""
ctxd = {}
context = RequestContext(request, ctxd)
return render_to_response("rundb/plan/modal_batch_planning_upload.html", context_instance=context) | 7ec7930bcaf755b8325ea691e8d8181aca4f0feb | 800 |
def calculate_total_correlativity(coefficient_array):
""" Returns the total correlativity of the coefficient_array. The total
correlativity is the sum of the absolute values and a measure of how
correlated to timeseries are. The greater the value the more correlated."""
return sum(map(abs, coefficient... | 84acdd15a47cb95285eec30a3ab9dc33e3044493 | 801 |
from datetime import datetime
def hide_topic(topic_id: TopicID, moderator_id: UserID) -> BoardTopicHidden:
"""Hide the topic."""
topic = _get_topic(topic_id)
moderator = _get_user(moderator_id)
now = datetime.utcnow()
topic.hidden = True
topic.hidden_at = now
topic.hidden_by_id = moderat... | ee1c4fff752c81b31f1adec06ed03090cd0c0a99 | 802 |
def argmax(a, axis=None, out=None):
""" Returns the indices of the maximum values along an axis.
Parameters
----------
a: array_like
axis: int, optional
By default, the index is into the flattened array, otherwise along the specified axis.
out: ... | 29e8e718e9d6c6455217fac614e53c642ff8cbb1 | 803 |
def FlowBalance_rule(model, node):
"""Ensures that flows into and out of a node are equal
"""
return model.Supply[node] \
+ sum(model.Flow[i, node] for i in model.NodesIn[node]) \
- model.Demand[node] \
- sum(model.Flow[node, j] for j in model.NodesOut[node]) \
== 0 | 628e8e2bb6967c9114dfcb8ea449d760180ab206 | 804 |
def abcd(actual, predicted, distribution, as_percent=True):
"""
Confusion Matrix:
|`````````````|`````````````|
| TN[0][0] | FP[0][1] |
| | |
|`````````````|`````````````|
| FN[1][0] | TP[1][1] |
| | |
````````````````````... | 8e4923ef72b3cb74bc5563083d223d3e8a92e982 | 805 |
def get_gene_name(protein_id, web_fallback=True):
"""Return the gene name for the given UniProt ID.
This is an alternative to get_hgnc_name and is useful when
HGNC name is not availabe (for instance, when the organism
is not homo sapiens).
Parameters
----------
protein_id : str
Uni... | 3319bd94a2933e03459ec586f76e105e9e3c64ed | 806 |
def summarize():
""" Returns summary of articles """
if request.method == 'POST':
url = request.form['pageurl']
parser = HtmlParser.from_url(url, Tokenizer(LANGUAGE))
stemmer = Stemmer(LANGUAGE)
summarizer = Summarizer(stemmer)
summarizer.stop_words = get_stop_words(LANG... | 4bfa483961609967657544049fa0495f173262e5 | 807 |
def version(include_copyright=False):
"""Get the version number of ``ssocr``.
Equivalent of running: ``ssocr --version``
Parameters
----------
include_copyright : :class:`bool`, optional
Whether to include the copyright information.
Returns
-------
:class:`str`
The ver... | 189634e1a6fd00df5c71e8d671f28ad0858a1027 | 809 |
from typing import List
import itertools
def intersection(n: np.ndarray,
d: float,
A: np.ndarray,
b: np.ndarray) -> List[np.ndarray]:
"""Return the intersection of the plane and convex ployhedron.
Returns a list of points which define the intersection betwee... | d3f653ae5f67dbe7be8b2f92de65031299e3b360 | 810 |
def create_session(checkpoint_path, target_device):
"""Create ONNX runtime session"""
if target_device == 'GPU':
providers = ['CUDAExecutionProvider']
elif target_device == 'CPU':
providers = ['CPUExecutionProvider']
else:
raise ValueError(
f'Unsupported target device... | bbd900a7e454e499010c8503f95c15aedd8f8a5c | 811 |
def V_eN_int(cgf_1, cgf_2, mol):
"""
Compute electron-nuclear integral between two contracted gaussian functions.
"""
v = 0
for i, _ in enumerate(cgf_1.alpha):
for j, _ in enumerate(cgf_2.alpha):
for k in range(mol.num_atoms):
v += cgf_1.co[i] * cgf_2.co[j] * pote... | b13b26048e5a419d507e03f29387f84422ff2035 | 812 |
def create_subword_vocab(input_data,
subword_size):
"""create subword vocab from input data"""
def generate_subword(word,
subword_size):
"""generate subword for word"""
subwords = []
chars = list(word)
char_length = len(chars)
... | 651f9da1e1df0f8b78168870bbdec6b4aff65425 | 813 |
import requests
import json
def request_json(input_data):
"""Request JSON data from full node, given request data input.
More info: http://docs.python-requests.org/en/master/"""
requested_data = None # Prevent no state if all servers fail!
for full_node_url in full_node_list_http:
try:
requested_data = r... | b26d022d28c186d6ad6d793d18c3eebb8056d9e8 | 814 |
def rrange(x, y = 0):
""" Creates a reversed range (from x - 1 down to y).
Example:
>>> rrange(10, 0) # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
"""
return range(x - 1, y - 1, -1) | 37c41673dab3fca797f4f6f0ab2f8160e7650248 | 815 |
def einsum_outshape(subscripts, *operants):
"""Compute the shape of output from `numpy.einsum`.
Does not support ellipses.
"""
if "." in subscripts:
raise ValueError(f"Ellipses are not supported: {subscripts}")
insubs, outsubs = subscripts.replace(",", "").split("->")
if outsubs == ""... | fb67dd428bda133548c8eb84293faf2013fe0ef1 | 816 |
def random_points(region, color="00FFFF", points=100, seed=0):
"""Generates a specified number of random points inside a given area.
Args: region(feature): region to generate points
color(color code): default is red, I think
points(numeric): how many points do you want? Default is 100
... | 9fc82d74a7d65bd7869f79b0e6050199f4368b3e | 817 |
import tqdm
def GridSearch(X_train_df, Y_train_df, hps_NaN_dict, features_l,
hps_models_dict, cv=5, n_jobs=-1, randomise=True):
"""Launch a grid search over different value of the hps."""
# Compute all the possible combinations of hps
tuples_hp = BuildHpTuples(X_train_df, hps_NaN_dict,
... | 8aa5a89e011e47c46ba809792787eb5793f6b0ec | 818 |
def atm():
"""Fixture to compute atmospheric properties just once before tests.
Returns:
Atmosphere object
"""
return Atmosphere(h_geom_truth_arr) | eea29ad064920d71e00fc5f8dd3f4bef75776b87 | 819 |
def get_key(my_dict: dict, val):
"""Get key value form dictionary using key value.
Args:
collection_name: dict: collection in dictionary format
val: Value in dictionary
Returns:
Key from dictionary.
"""
for key, value in my_dict.items():
if val == value:
ret... | 99bb74468b4dd5bb02c6f642a86c345365d8d616 | 820 |
def closest(point, points):
"""works, but @@DEPRECATED!!
return index into points of closest-to-point
"""
da = dist_array(point, points)
return N.argmin(da) | 70f30f98dfb2aed9d6f485d17c113469005946ea | 821 |
def generate_provenance_json(script="unknown", params={}):
"""Generate the provenance in a format which can later be output as valid json.
Inputs:
string: The name of the script used to trigger the data generation/deidentification/synthesis process
dict: The parameters used to tune the data gen... | f18712b8652da832f3271bcfb8098b7e0b029dd0 | 822 |
def dot(v, w):
"""v_1 * w_1 + ... + v_n * w_n"""
return sum(v_i * w_i for v_i, w_i in zip(v, w)) | 29f6551f44459ad6c7856500019a1c551aaa3cbe | 823 |
def get_users():
"""Query for user accounts."""
return JsonResponse(queryFor(UserAccount)) | 47cf0dcf2874ce89d1e394aa5e80c026e036cc0a | 824 |
from typing import Dict
def get_added_and_removed_pitches(
chord_root_tpc: int,
chord_type: ChordType,
changes: str,
key_tonic_tpc: int,
key_mode: KeyMode,
) -> Dict[str, str]:
"""
Get a mapping of pitch alterations from the given chord. Pitches are given
and returned with PitchType TP... | 857c581af61457450e89574ee94839131da94382 | 825 |
def get_n_random_points_in_region(region_mesh, N, s=None):
"""
Gets N random points inside (or on the surface) of a mes
"""
region_bounds = region_mesh.bounds()
if s is None:
s = int(N * 2)
X = np.random.randint(region_bounds[0], region_bounds[1], size=s)
Y = np.random.randint(regio... | ead32d58612f6ceddd495218efd8aac3d4cb3ca3 | 826 |
import numpy
def make_octad_tables(basis):
"""Return tables for encoding an decoding octads.
Octads are numbered in the lexicographical order as given by the
numbers of the corresponding Golay codewords in 'gcode'
representation.
The function returns a triple
(oct_enc_table, oct_dec_... | 8db61ea0e3a2aa4792aefe0eb0cee9b77aa76d91 | 827 |
def fetch_profile(request):
""" attaches the user.profile object into the request object"""
context = {}
if request.user.is_authenticated():
profile_module_name = get_my_profile_module_name()
profile = getattr(request, profile_module_name, None)
if profile != None:
conte... | ac86e9aa47d316b0a66aadafc2f55fad24a150fe | 828 |
def to_local_op(input):
"""Returns the local tensor of a consistent tensor.
Args:
input (Tensor): the input tensor.
For example:
.. code-block:: python
>>> import oneflow as flow
>>> import numpy as np
>>> np_arr = np.array([0.5, 0.6, 0.7]).astype(np.float32)
... | 3aa9797e21c8eaa566825df7e099f14064e64b73 | 830 |
import math
def col_round(x):
"""
As Python 3 rounds 0.5 fraction to closest even,
floor and cell round methods used here to round 0.5
up to next digit and 0.4 down back to previos.
"""
frac = x - math.floor(x)
if frac < 0.5:
return math.floor(x)
return math.ceil(x) | 3f21a6dcc525daebf78c9adfd6afee9ba865399b | 831 |
def _create_notebook(client, headers: dict[str, str]) -> str:
"""Create a notebook.
:param client: Test API client.
:param headers: Headers with the access token.
:return: Notebook ID.
"""
n = {"name": "Test Notebook"}
r = client.post("/notebooks/notebook", headers=headers, json=n)
ret... | c112fdb16e858a83265518e50257888d587f59be | 832 |
def plot_range_range_rate(x_sat_orbdyn_stm:np.ndarray, x_obs_multiple:np.ndarray, t_sec: np.array):
""" Plots range and range relative to the station
Args:
x_sat_orbdyn_stm (np.ndarray): satellite trajectory array.
x_obs_multiple (np.ndarray): observer positions.
t_sec (np.ndarray): arr... | dafa57d5bf8347c19d02216c5cff6aa77392dfed | 833 |
def _make_tag(tagname: str, content: str = "", **attrs) -> str:
"""Creates a tag."""
tag = f"<{tagname} "
for key, value in attrs.items():
if key == "raw":
tag += " " + value
continue
if key == "cls":
key = "class"
if isinstance(value, float):
... | cf6dba281a63c90e0ff3ae8bf64c6adb3f936d4c | 835 |
def action_functions(action_id: str):
"""Determines which function needs to be run."""
action_mappings = {
NewIncidentSubmission.form_slack_view: [report_incident_from_submitted_form],
UpdateParticipantCallbacks.submit_form: [update_participant_from_submitted_form],
UpdateParticipantCall... | 132e847d63606db0e4d234befe6c313113f6bcaf | 837 |
def setup_function(function):
"""
Make sure there are no adapters defined before start of test
"""
clear_adapters()
# Setup a basic int adapter for all tests
@adapter((str, float, int), (int, str))
def to_int(obj, to_cls):
return to_cls(obj) | a72d7a4fc31fe88f155df9f01a79a4c08a38188a | 839 |
def get_best_response_actions_as_string(best_response_actions):
"""Turns a dict<bytes, int> into a bytestring compatible with C++.
i.e. the bytestring can be copy-pasted as the brace initialization for a
{std::unordered_,std::,absl::flat_hash_}map<std::string, int>.
Args:
best_response_actions: A dict map... | cf2b475d6bb76d262c17dc7753f1624e38cc69f4 | 840 |
def rank_velocity_genes(adata, vkey="velocity_S", prefix_store="rank", **kwargs):
"""Rank genes based on their raw and absolute velocities for each cell group.
Parameters
----------
adata: :class:`~anndata.AnnData`
AnnData object that contains the gene-wise velocities.
vkey: str... | 214a788813782f4f9706357e7139758f78b04dfd | 841 |
def build_genome(tree, genome):
"""
Goes through a tree and builds a genome from all codons in the subtree.
:param tree: An individual's derivation tree.
:param genome: The list of all codons in a subtree.
:return: The fully built genome of a subtree.
"""
if tree.codon:
# If th... | 67fd7a23a9ca812717bde5d3e35affc5cc7474f4 | 842 |
from typing import Tuple
def fixture_yaml_formatting_fixtures(fixture_filename: str) -> Tuple[str, str, str]:
"""Get the contents for the formatting fixture files.
To regenerate these fixtures, please run ``test/fixtures/test_regenerate_formatting_fixtures.py``.
Ideally, prettier should not have to chan... | 0eb4b1d6716b4b925cec0201354893cadd704945 | 843 |
def conv_bboxinfo_bboxXYHW_to_centerscale(bbox_xyhw, bLooseBox = False):
"""
from (bbox_xyhw) -> (center, scale)
Args:
bbox_xyhw: [minX,minY,W,H]
bLooseBox: if true, draw less tight box with sufficient margin (SPIN's default setting)
Output:
center: bbox center
scale: sca... | 1d85f9ee0ee6db00877eeb091729d2748fec08cf | 845 |
def add_video(db: Session, video: schemas.Video):
"""
Adds video to table video_library
model used is Video.
Attributes:
- video_user_id: int, non-nullable, foreign_key
- video_link: string, non-nullable, unique
- video_name: string, non-nullable,
- video_height: int, non... | ff192b8b286ae5e143ff3a9671e74be630a1a557 | 846 |
def compute_principal_axes(xyz_centered, weights=None, twodim=True):
"""
:param xyz_centered: [list_of_xs, lst_of_ys, list_of_zs]
:param weights: weights of each pixel
:param twodim: whether to compute two main axes in xy plane, or three axes in 3D image.
:return: ax1, ax2, (ax3 if not twodim else ... | fcee28353676dd2955e12ff134f31a353f8849cb | 847 |
import time
def stream_http_get(S, dest):
"""Get contents of http://dest/ via HTTP/1.0 and
samclasses.StreamSession S."""
C = S.connect(dest)
C.send('GET / HTTP/1.0\r\n\r\n')
while True:
line = stream_readline(C).strip()
if line.find('Content-Length: ') == 0:
clen = int(line.split()[1])
... | e13e0ec701985b9fdabb33842e1233a8fee04fd8 | 848 |
import re
def get_definition(division_id, path=None):
"""
Returns the expected contents of a definition file.
"""
config = {}
division = Division.get(division_id, from_csv=ocd_division_csv)
# Determine slug, domain and authority.
name = division.name
if not name:
print('%-60s... | 5dd1b67729c7ddc6ca6287e3a5931a751751da2c | 849 |
def api_last_blog_update(request):
"""Return the date of the last blog update.
This is a PRIVATE API.
Format: __lastblogupdate.json
JSON return:
{'lastupdate': '2019-01-31'}
or if none available:
{'lastupdate': None}
"""
api_code = enter_api_call('api_last_blog_update', ... | f22413dc6a202fb15cdb0f94ede5eefc4477c21b | 850 |
def pearson(arr1, arr2):
"""
calculate pearson correlation between two numpy arrays.
:param arr1: one array, the feature is a column. the shape is `m * n`
:param arr2: the other array, the feature is a column. the shape is `m * k`
:return: a pearson score np.array , the shape is `k * n`
"""
... | 5de328cec314c7d320928e12cb634d13a60fa504 | 851 |
def exact_match_filter(query_set, field, values):
"""Check if a field exactly matches a value."""
return field_filter(lambda x, y: Q(**{x: y}), query_set, field, values) | 8b25770c74140921d3ef61283b37c67ab98e1e01 | 852 |
def get_move_descriptions(get_moved_ids, initial_state, current_state, obj_stuff, sort_attributes, obj_attributes):
"""
Get all 'move' descriptions from the current state (if any).
Parameters
----------
get_moved_ids: function
Function that extracts the id of objects that are being moved.
... | 0b423d41b24a60611ae33048afe4ddf60d15a558 | 853 |
def reliability_diagram(labels,
probs,
class_conditional=False,
y_axis='accuracy',
img=False):
"""Reliability Diagram plotting confidence against accuracy.
Note that this reliability diagram is created by looking at the... | 2653321e0199ea4b067d4e2ea2d169b2c1d872bf | 854 |
def GuessSlugFromPath(path):
"""Returns the slug."""
if path.endswith('index.md'):
# If it ends with index, get the second last path component.
return path.split('/')[-2]
else:
# Otherwise, just get the filename.
return path.split('/')[-1].split('.')[0] | ff0c8f4f12fdc1ddf684393408a725a0d4c3ce0e | 855 |
import torch
def _onenorm_matrix_power_nnm(A, p):
"""
Compute the 1-norm of a non-negative integer power of a non-negative matrix.
Parameters
----------
A : a square ndarray or matrix or sparse matrix
Input matrix with non-negative entries.
p : non-negative integer
The power t... | 55ae02857418ca6b70a6532a27621e81e3ac3373 | 858 |
def _stiff_terms_null(states, *args, **kwargs):
"""Dummy function"""
return states | a77a23a8b6d480ab0bf92313cbb8a04ebd9770a8 | 859 |
def _compute_non_batch_kl(mu_a, sigma_a, mu_b, sigma_b):
"""Non-batch KL for N(mu_a, sigma_a), N(mu_b, sigma_b)."""
# Check using numpy operations
# This mostly repeats the tensorflow code _kl_mvn_mvn(), but in numpy.
# So it is important to also check that KL(mvn, mvn) = 0.
sigma_b_inv = np.linalg.inv(sigma_... | af1fef041ef10f72365ec5e2d7335a6c930ea54a | 861 |
import time
def wait_until(fn, timeout, period, message):
"""
:param fn: callable function
:param timeout:
:param period:
:param message:
:return: bool
"""
mustend = time() + timeout
while time() < mustend:
if fn():
return True
sleep(period)
raise Ti... | b73d2711f877754257fe65b607f3f2d261fa7f47 | 862 |
import torch
def single_test(model, testdata, max_seq_len=20):
"""Get accuracy for a single model and dataloader.
Args:
model (nn.Module): MCTN2 Model
testdata (torch.utils.data.DataLoader): Test Dataloader
max_seq_len (int, optional): Maximum sequence length. Defaults to 20.
Ret... | 39c7fc2aae7512565abbf1483bb9d93661307654 | 863 |
import itertools
def allocate_memory_addresses(instructions: list[Instruction], reserved_memory_names: set[str]):
"""
Allocate memory addresses for SharedName and Slice, and replace AddressOf and MemoryOf with PrimitiveValue.
"""
allocated_before: tuple[int, int] | None = None # (bank_id, address)
... | 6dfd65caca014398e116e30c9c15970d48afe3a2 | 864 |
def find_blobs(B):
"""find and return all blobs in the image, using
eight-connectivity. returns a labeled image, the
bounding boxes of the blobs, and the blob masks cropped
to those bounding boxes"""
B = np.array(B).astype(bool)
labeled, objects = label_blobs(B)
blobs = [labeled[obj] == ix +... | 9cb7b66353e9534bc43aa7a84e30b62d4411d06f | 865 |
def star_dist(a, n_rays=32, mode='cpp'):
"""'a' assumbed to be a label image with integer values that encode object ids. id 0 denotes background."""
n_rays >= 3 or _raise(ValueError("need 'n_rays' >= 3"))
if mode == 'python':
return _py_star_dist(a, n_rays)
elif mode == 'cpp':
return _... | d19b031bfb6e9ad07537a0ff36037792f78a257b | 866 |
def get_bond_enthalpy(element1: str, element2: str, bond='single bond') -> int:
"""Utility function that retrieves the bond enthalpy between element1 and element2 (regardless or order)
An optional argument, bond, describing the bond (single, double, triple) could be specified
If not specified, bond defaults... | 5349b3b752b25d0e844d6bb8d46fbb1ad8cec085 | 867 |
def approx_sample(num_items: int, num_samples: int) -> np.array:
"""Fast approximate downsampling."""
if num_items <= num_samples:
return np.ones(num_items, dtype=np.bool8)
np.random.seed(125)
# Select each xy with probability (downsample_to / len(x)) to yield
# approximately downsample_to selections.
f... | 051447c311ed392f288c4eb0491df6f0b981883b | 868 |
def extract_out_cos(transmat, cos, state):
""" Helper function for building HMMs from matrices: Used for
transition matrices with 'cos' transition classes.
Extract outgoing transitions for 'state' from the complete list
of transition matrices
Allocates: .out_id vector and .out_a array (of size cos... | 4f60290ca960fa1b714313b8bdfc0cc35f54ac90 | 869 |
import csv
def import_statistics(sourcefile,starttime):
"""
Forms a dictionary for MarkovModel from the source csv file
input
--------
sourcefile: Source csv file for Markov Model
starttime : For which hour the optimization is run
Returns a dictionary statistics2
keys ar... | d349559e389f08f77cda46a1d40c1cb7914ef0ce | 870 |
import click
def image_repository_validation(func):
"""
Wrapper Validation function that will run last after the all cli parmaters have been loaded
to check for conditions surrounding `--image-repository`, `--image-repositories`, and `--resolve-image-repos`. The
reason they are done last instead of in... | ab72b2233353f50833e80f662d945702dd20b173 | 871 |
import inspect
def create_source_location_str(frame, key):
"""Return string to use as source location key
Keyword arguments:
frame -- List of frame records
key -- Key of the frame with method call
Takes frame and key (usually 1, since 0 is the frame in which getcurrentframe() was... | 4bf3a7d68e5b5c667261710dfcb3e2f1cb613533 | 873 |
def uv_lines(reglist, uv='uv', sty={}, npoints=1001, inf=50., eps=1e-24):
"""
"""
for reg in reglist:
for b in reg.blocks:
smin, smax, ds = -5., 25., 1.
vals = np.arange(smin, smax, ds)
cm = plt.cm.gist_rainbow
cv = np.linspace(0,1,len(vals))
for i in range(len(vals)):
style1 = dict(c=cm(cv[i]),... | f80f4551707564cf979377bb17908c4151ea61f3 | 874 |
def rand_initialisation(X, n_clusters, seed, cste):
""" Initialize vector centers from X randomly """
index = [];
repeat = n_clusters;
# Take one index
if seed is None:
idx = np.random.RandomState().randint(X.shape[0]);
else:
idx = np.random.RandomState(seed+cste).randint(X... | e1d4d58018596c2ed3955b8d8d82d040def7b3e1 | 875 |
def l2_hinge_loss(X, Y, W, C, N):
"""
Computes the L2 regularized Hinge Loss function, and its gradient over a mini-batch of data.
:param X: The feature matrix of size (F+1, N).
:param Y: The label vector of size (N, 1).
:param W: The weight vector of size (F+1, 1).
:param C: A hyperparameter of... | 1de1cf7881466a039e6882161bbea3836dc4bf2f | 876 |
from numpy.core import around, number, float_
from numpy.core.numerictypes import issubdtype
from numpy.core.fromnumeric import any as npany
def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
"""
Raise an assertion if two objects are not equal up to desired precision.
The test veri... | 95005d6f8782d5b5c4221343be035a905db2c255 | 878 |
def train_val_test_split(dataframe, val_ratio=.2, test_ratio=.2):
"""
Takes a dataframe and returns a random train/validate/test split
param test_ratio: the percentage of data to put into the test portion
- must be between 0.0 and 1.0
param val_ratio: the percentage of data to put into the val... | 2b3cf8a656c0d66a8481ad50ea6123bab31aaf9d | 879 |
def diff_pf_potential(phi):
""" Derivative of the phase field potential. """
return phi**3-phi | c22af096d27cf817ffee683453ecafb4e5c61cdc | 880 |
def process_image(image, label, height=224, width=224):
""" Resize the images to a fixes input size,
and rescale the input channels to a range of [-1,1].
Args:
image: "tensor, float32", image input.
label: "tensor, int64", image label.
height: "int64", (224, 224, 3) -> (height, 224, 3).
wid... | 98fa8332603c7fdcc973f38711b982648b1f13f0 | 881 |
def astz(data):
"""
[X] ASTZ - Request actual status
STBY (dyno stopping) or
SSIM (road load) or
SMTR (constant speed) or
SRPM (constant RPM) or
SKZK (constant motor force)
"""
responds = data.split(" ")
if len(responds) > 2:
if responds... | da36efc3d6b477f8e7de96148c9890aa1cf9c560 | 882 |
def get_peer_snappi_chassis(conn_data, dut_hostname):
"""
Get the Snappi chassis connected to the DUT
Note that a DUT can only be connected to a Snappi chassis
Args:
conn_data (dict): the dictionary returned by conn_graph_fact.
Example format of the conn_data is given below:
{u... | 96bfa8d2189b2dea041754fd4daa2a39a96dd687 | 883 |
def gen_hwpc_report():
"""
Return a well formated HWPCReport
"""
cpua = create_core_report('1', 'e0', '0')
cpub = create_core_report('2', 'e0', '1')
cpuc = create_core_report('1', 'e0', '2')
cpud = create_core_report('2', 'e0', '3')
cpue = create_core_report('1', 'e1', '0')
cpuf = cr... | 1380ef25281f9dde7626f0df9c4bb59c7a0eff29 | 884 |
def special_crossentropy(y_true, y_pred):
"""特殊的交叉熵
"""
task = K.cast(y_true < 1.5, K.floatx())
mask = K.constant([[0, 0, 1, 1, 1]])
y_pred_1 = y_pred - mask * 1e12
y_pred_2 = y_pred - (1 - mask) * 1e12
y_pred = task * y_pred_1 + (1 - task) * y_pred_2
y_true = K.cast(y_true, 'int32')
... | 7cd14e5bc788175ed7022ead942853260a4b2679 | 885 |
def nonensembled_map_fns(data_config):
"""Input pipeline functions which are not ensembled."""
common_cfg = data_config.common
map_fns = [
data_transforms.correct_msa_restypes,
data_transforms.add_distillation_flag(False),
data_transforms.cast_64bit_ints,
data_transforms.squ... | 223f85312503941a6e90bdc027f3f522e70aaacc | 886 |
import re
def _getMark(text):
"""
Return the mark or text entry on a line. Praat escapes double-quotes
by doubling them, so doubled double-quotes are read as single
double-quotes. Newlines within an entry are allowed.
"""
line = text.readline()
# check that the line begins with a valid e... | 3f6de6246069a9f1d9cdb127fdcde40de16106d6 | 887 |
def get_screen_resolution_str():
"""
Get a regexp like string with your current screen resolution.
:return: String with your current screen resolution.
"""
sizes = [
[800, [600]],
[1024, [768]],
[1280, [720, 768]],
[1366, [768]],
[1920, [1080, 1200]],
]
... | 7de1c15d92dd3582598740a7062d9ef1c5c2adba | 888 |
def page_body_id(context):
"""
Get the CSS class for a given page.
"""
path = slugify_url(context.request.path)
if not path:
path = "home"
return "page-{}".format(path) | 2d4c709111a510c29e5bfa48016f59f65d45f2c4 | 889 |
def load_centers(network, name, eps):
"""Load values of centers from the specified network by name.
:param network: Network to load center values
:param name: Name of parameter with centers
:return: Normalized centers
"""
assert name in network.params.keys(), 'Cannot find name: {} in params'.f... | cf677d4ca387f5095500077f9d704ae3a884c0c9 | 890 |
def naive_sort_w_matrix(array):
"""
:param array: array to be sorted
:return: a sorted version of the array, greatest to least, with the appropriate permutation matrix
"""
size = len(array)
def make_transposition(i, j):
mat = np.identity(size)
mat[i, i] = 0
mat[j, j] ... | aedcf7c39c633b1e958997038d905bed0bc4958d | 891 |
def plot_route(cities, route, name='diagram.png', ax=None):
"""Отрисовка маршрута"""
mpl.rcParams['agg.path.chunksize'] = 10000
if not ax:
fig = plt.figure(figsize=(5, 5), frameon=False)
axis = fig.add_axes([0, 0, 1, 1])
axis.set_aspect('equal', adjustable='datalim')
plt.ax... | 748fff61c00c3a186eefa577b3785a400acf0eff | 892 |
def aes_cbc_mac(
key: bytes, b: bytes, iv: bytes=None,
pad=False
) -> bytes:
"""
AES CBC-MAC.
:param key: The verification key.
:param b: The buffer to be authenticated.
:param iv: The initial vector.
:param pad: Whether to apply PKCS-7 padding to the buffer.
:return: A vali... | 0b15c5270a29c814b02fcc9502c080e0f507eaad | 893 |
import json
def seamus():
"""
Preview for Seamus page
"""
context = make_context()
# Read the books JSON into the page.
with open('www/static-data/books.json', 'rb') as readfile:
books_data = json.load(readfile)
books = sorted(books_data, key=lambda k: k['title'])
# Harve... | 4252f5abd7c2d8927395e5f036bf4899b12d555e | 894 |
def resolve_alias(term: str) -> str:
"""
Resolves search term aliases (e.g., 'loc' for 'locations').
"""
if term in ("loc", "location"):
return "locations"
elif term == "kw":
return "keywords"
elif term == "setting":
return "setting"
elif term == "character":
... | 8080d6ffb73457fd61aeca610b30b18695ec01bd | 896 |
from typing import Union
from typing import Any
from typing import Iterable
from typing import List
import math
def to_number(value: Union[Any, Iterable[Any]], default: Any = math.nan) -> Union[NumberType, List[NumberType]]:
""" Attempts to convert the passed object to a number.
Returns
-------
value: Scalar
... | d7e4e85fb3ea056a3188b9dce98f5e806beb0a5b | 897 |
def secretValue(value=None, bits=64):
"""
A single secret value
bits: how many bits long the value is
value: if not None, then a specific (concrete or symbolic) value which this value takes on
"""
return AbstractNonPointer(bits=bits, value=value, secret=True) | 55672dbc78a8393a2cb3c39c3165c89180df3bfe | 898 |
def year_frac(d_end, d_start=0,
dates_string=False, trading_calendar=True):
""" :returns year fraction between 2 (business) dates
:params dates are datetimes, if string then insert dates_string=True
"""
delta_days = days_between(d_end, d_start, dates_string, trading_calendar)
year... | cd5916e54b969476c335adce3aa9138ce4be68b2 | 899 |
def _indent(s):
# type: (str) -> int
"""
Compute the indentation of s, or None of an empty line.
Example:
>>> _indent("foo")
0
>>> _indent(" bar")
4
>>> _indent(" ")
>>> _indent("")
"""
t = s.lstrip()
return len(s) - len(t) if t else None | c523704bf4ff75f132c9e021a4db0d0ac5482f0b | 900 |
import re
def normalize_middle_high_german(
text: str,
to_lower_all: bool = True,
to_lower_beginning: bool = False,
alpha_conv: bool = True,
punct: bool = True,
):
"""Normalize input string.
to_lower_all: convert whole text to lowercase
alpha_conv: convert alphabet to canonical form
... | 543a69175cd78bf2678bd0b173e1112e96d75fd8 | 901 |
def _convert_format(input_format, reverse=0):
"""Convert FITS format spec to record format spec. Do the opposite
if reverse = 1.
"""
fmt = input_format
(repeat, dtype, option) = _parse_tformat(fmt)
if reverse == 0:
if dtype in _fits2rec.keys(): # FITS form... | 2861a74752328bf6e654f5f4ea31238f6b672f54 | 902 |
from pathlib import Path
def clean_elec_demands_dirpath(tmp_path: Path) -> Path:
"""Create a temporary, empty directory called 'processed'.
Args:
tmp_path (Path): see https://docs.pytest.org/en/stable/tmpdir.html
Returns:
Path: Path to a temporary, empty directory called 'processed'.
... | 4d5a528a7e24b80678b41374deac2ac4580da50a | 904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.