content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sanitize_option(option):
"""
Format the given string by stripping the trailing parentheses
eg. Auckland City (123) -> Auckland City
:param option: String to be formatted
:return: Substring without the trailing parentheses
"""
return ' '.join(option.split(' ')[:-1]).strip() | ece0a78599e428ae8826b82d7d00ffc39495d27f | 21,577 |
def node_values_for_tests():
"""Creates a list of possible node values for parameters
Returns:
List[Any]: possible node values
"""
return [1, 3, 5, 7, "hello"] | b919efc5e59a5827b3b27e4f0a4cd070ceb9a5a4 | 21,578 |
import torch
def computeGramMatrix(A, B):
"""
Constructs a linear kernel matrix between A and B.
We assume that each row in A and B represents a d-dimensional feature vector.
Parameters:
A: a (n_batch, n, d) Tensor.
B: a (n_batch, m, d) Tensor.
Returns: a (n_batch, n, m) Tensor.... | c9b221b3d6a8c7a16337178a1f148873b27ec04a | 21,579 |
def parse_config(config):
"""Backwards compatible parsing.
:param config: ConfigParser object initilized with nvp.ini.
:returns: A tuple consisting of a control cluster object and a
plugin_config variable.
raises: In general, system exceptions are not caught but are propagated
up to the... | 74689d11c1d610a9211dc5895ff42a8b8e2389ae | 21,580 |
def deletable_proxy_user(request, onefs_client):
"""Get the name of an existing proxy user that it is ok to delete."""
return _deletable_proxy_user(request, onefs_client) | c7440099fe4435cf9b5b557253f7fb9563dc600c | 21,581 |
import six
def get_from_module(identifier, module_params, module_name,
instantiate=False, kwargs=None):
"""The function is stolen from keras.utils.generic_utils.
"""
if isinstance(identifier, six.string_types):
res = module_params.get(identifier)
if not res:
... | 406a1da5843feb8556bbd1802426b57e7a33b20d | 21,582 |
def color_lerp(c1, c2, a):
"""Return the linear interpolation between two colors.
``a`` is the interpolation value, with 0 returing ``c1``,
1 returning ``c2``, and 0.5 returing a color halfway between both.
Args:
c1 (Union[Tuple[int, int, int], Sequence[int]]):
The first color. At... | 96c950c447994a729c9eb4c18bdcc60976dbb675 | 21,583 |
def get_equations(points):
""" Calculate affine equations of inputted points
Input : 1
points : list of list
ex : [[[x1, y1], [x2, y2]], [[xx1, yy1], [xx2, yy2]]] for 2 identified
elements
Contains coordinates of separation lines i.e.
[[[start poin... | 4eea43aee8b5f9c63793daae0b28e3c8b4ce0929 | 21,584 |
def Temple_Loc(player, num):
"""temple location function"""
player.coins -= num
player.score += num
player.donation += num
# player = temple_bonus_check(player) for acheivements
return (player) | dced7b9f23f63c0c51787291ab12701bd7021152 | 21,585 |
def indexGenomeFile(input, output):
"""Index STAR genome index file
`input`: Input probes fasta file
`output`: SAindex file to check the completion of STAR genome index
"""
#print input
#print output
base = splitext(input)[0]
base = base + ".gtf"
#print base
gtfFile = base
o... | 2ebd981ebad97f68adb1043e9c06fd01dc270c10 | 21,586 |
import math
def performance(origin_labels, predict_labels, deci_value, bi_or_multi=False, res=False):
"""evaluations used to evaluate the performance of the model.
:param deci_value: decision values used for ROC and AUC.
:param bi_or_multi: binary or multiple classification
:param origin_labels: true ... | aac87e0bdc02b61ccb5136e04e1ac8b09e01ce65 | 21,587 |
def rotkehlchen_instance(
uninitialized_rotkehlchen,
database,
blockchain,
accountant,
start_with_logged_in_user,
start_with_valid_premium,
function_scope_messages_aggregator,
db_password,
rotki_premium_credentials,
accounting_data_dir,
... | 144585d62c04f97aa7bcb7a355bd90f8ff001022 | 21,588 |
def store_inspection_outputs_df(backend, annotation_iterators, code_reference, return_value, operator_context):
"""
Stores the inspection annotations for the rows in the dataframe and the
inspection annotations for the DAG operators in a map
"""
dag_node_identifier = DagNodeIdentifier(operator_conte... | 228a24a4d59162382b5a3ae7d8204e396b8c76dd | 21,589 |
def switched (decorator):
"""decorator transform for switched decorations.
adds start_fun and stop_fun methods to class to control fun"""
@simple_decorator
def new_decorator (fun):
event = new_event()
def inner_fun (self, *args):
if args:
event.wait()
if threads_alive():
retu... | 1996274fcaba2095b43f7d0da134abb59b2f7a56 | 21,590 |
def logistic_embedding0(k=1, dataset='epinions'):
"""using random embedding to train logistic
Keyword Arguments:
k {int} -- [folder] (default: {1})
dataset {str} -- [dataset] (default: {'epinions'})
Returns:
[type] -- [pos_ratio, accuracy, f1_score0, f1_score1, f1_score2, auc_score... | 69b198c6a5f8a44681ccfee67b532b3d38d2ee44 | 21,591 |
def process_plus_glosses(word):
"""
Find all glosses with a plus inside. They correspond
to one-phoneme affix sequences that are expressed by
the same letter due to orthographic requirements.
Replace the glosses and the morphemes.
"""
return rxPartsGloss.sub(process_plus_glosses_ana, word) | 0678efc61d1af0ec75b8d0566866b305b6312448 | 21,592 |
from datetime import datetime
def check_in_the_past(value: datetime) -> datetime:
"""
Validate that a timestamp is in the past.
"""
assert value.tzinfo == timezone.utc, "date must be an explicit UTC timestamp"
assert value < datetime.now(timezone.utc), "date must be in the past"
return value | a439295190bfa2b6d2d6de79c7dc074df562e9ed | 21,593 |
from typing import Dict
def character_count_helper(results: Dict) -> int:
"""
Helper Function that computes
character count for ocr results on a single image
Parameters
----------
results: Dict
(OCR results from a clapperboard instance)
Returns
-------
Int
Number... | b5bcba9d39b7b09a1a123fec034ab1f27b31d1eb | 21,595 |
import pickle
def from_pickle(input_path):
"""Read from pickle file."""
with open(input_path, 'rb') as f:
unpickler = pickle.Unpickler(f)
return unpickler.load() | 4e537fcde38e612e22004007122130c545246afb | 21,596 |
def PromptForRegion(available_regions=constants.SUPPORTED_REGION):
"""Prompt for region from list of available regions.
This method is referenced by the declaritive iam commands as a fallthrough
for getting the region.
Args:
available_regions: list of the available regions to choose from
Returns:
T... | 2298fde743219f59b5a36844d85e14929d1e2a1e | 21,597 |
def update(x, new_x):
"""Update the value of `x` to `new_x`.
# Arguments
x: A `Variable`.
new_x: A tensor of same shape as `x`.
# Returns
The variable `x` updated.
"""
return tf.assign(x, new_x) | 363cd3232a57d4c2c946813874a5a3c613f9a8c9 | 21,598 |
def r1r2_to_bp(r1,r2,pl=0.01, pu=0.25):
"""
Convert uniform samling of r1 and r2 to impact parameter b and and radius ratio p
following Espinoza 2018, https://iopscience.iop.org/article/10.3847/2515-5172/aaef38/meta
Paramters:
-----------
r1, r2: float;
uniform parameters in from u(... | 0c7f69f3f7960792e8d0ecd75fde028eda9feefa | 21,599 |
from datetime import datetime
def is_utc_today(utc):
"""
Returns true if the UTC is today
:param utc:
:return:
"""
current_time = datetime.datetime.utcnow()
day_start = current_time - datetime.timedelta(hours=current_time.hour, minutes=current_time.minute,
... | f707b44ce9a741a4d126e1e55a33c7e78cb1159e | 21,600 |
def test_run_completed(mock_job, mock_queue, mock_driver):
"""Test run function for a successful run."""
# Setup
def mock_render(*args, **kwargs):
return
class MockStorage:
def __init__(self):
pass
def load(self, *args, **kwargs):
return 'blah'
... | bd4660738e952cf5da24dbd2bc22cd0876716b66 | 21,601 |
async def get_telegram_id(phone_number, user_mode=False):
"""
Tries to get a telegram ID for the passed in phone number.
"""
async with start_bot_client() as bot:
if user_mode:
# just leaving this code here in case it proves useful.
# It only works if you use a user, not ... | e0a0c8d4bcd305b23f831297880b0ead30eeb94a | 21,602 |
def QuadRemesh(thisMesh, parameters, multiple=False):
"""
Quad remesh this mesh.
"""
url = "rhino/geometry/mesh/quadremesh-mesh_quadremeshparameters"
if multiple: url += "?multiple=true"
args = [thisMesh, parameters]
if multiple: args = list(zip(thisMesh, parameters))
response = Util.Com... | f3068768ea62b8960fe11b736a6fcaea722d105d | 21,603 |
def part_2_helper():
"""PART TWO
This simply runs the script multiple times and multiplies the results together
"""
slope_1 = sled_down_hill(1, 1)
slope_2 = sled_down_hill(1, 3)
slope_3 = sled_down_hill(1, 5)
slope_4 = sled_down_hill(1, 7)
slope_5 = sled_down_hill(2, 1)
return slope... | 2a62fa6acde73a8a5c1e59a0403cf6c067baf57a | 21,604 |
def read_and_download_profile_information(id):
"""
linke: https://developer.apple.com/documentation/appstoreconnectapi/read_and_download_profile_information
:param id: bundle_id
:return: 请求结果
"""
data = {
"fields[certificates]": "certificateType",
"fields[devices]": "platform",
... | 01ba704a352df28d20d944baecf108fc0fb44ad1 | 21,605 |
def get_config(node):
"""Get the BIOS configuration.
The BIOS settings look like::
{'EnumAttrib': {'name': 'EnumAttrib',
'current_value': 'Value',
'pending_value': 'New Value', # could also be None
'read_only': False,
... | ca9467800fae3939f83e964c29d564cc306d4b1e | 21,606 |
def get_only_metrics(results):
"""Turn dictionary of results into a list of metrics"""
metrics_names = ["test/f1", "test/precision", "test/recall", "test/loss"]
metrics = [results[name] for name in metrics_names]
return metrics | 1b0e5bb8771fdc44dcd22ff9cdb174f77205eadd | 21,608 |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: ?
Space Complexity: ?
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
pass | 0575524e2e38a215867ce51c08828fd47a230e97 | 21,609 |
import re
def find_tags_containing(project, commit):
"""Find all tags containing the given commit. Returns the full list and a condensed list (excluding tags 'after' other tags in the list)."""
tags = run_list_command(['git', 'tag', '--contains', commit], project)
# The packaging projects had a different... | 792bfd8c6972e818d36343723345ee1152cb66ec | 21,610 |
def setup_nupack_input(**kargs):
""" Returns the list of tokens specifying the command to be run in the pipe, and
the command-line input to be given to NUPACK.
Note that individual functions below may modify args or cmd_input depending on their
specific usage specification. """
# Set up terms of command-line ... | 6dc26413bb2eab4b94c343770e6110ba2d012a41 | 21,611 |
from typing import List
from typing import Union
from typing import Literal
def rebuild_current_distribution(
fields: np.ndarray,
ics: np.ndarray,
jj_size: float,
current_pattern: List[Union[Literal["f"], str]],
sweep_invariants: List[Union[Literal["offset"], Literal["field_to_k"]]] = [
"o... | 66e81639e3ff3995c4a6b6bbe2f361071a6b51b1 | 21,612 |
def get_LCA(index, item1, item2):
"""Get lowest commmon ancestor (including themselves)"""
# get parent list from
if item1 == item2:
return item1
try:
return LCA_CACHE[index][item1 + item2]
except KeyError:
pass
parent1 = ATT_TREES[index][item1].parent[:]
parent2 = AT... | 22e65163cd1c32ac8bd20dadc3aa69c208adb540 | 21,613 |
def select_workspace_access(cursor, workspace_id):
"""ワークスペースアクセス情報取得
Args:
cursor (mysql.connector.cursor): カーソル
workspace_id (int): ワークスペースID
Returns:
dict: select結果
"""
# select実行
cursor.execute('SELECT * FROM workspace_access WHERE workspace_id = %(workspace_id)s',
... | 4cf1e0dd4a1232bd5a00d49d952e3bfb98e189c5 | 21,614 |
def pkcs7_unpad(data):
"""
Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
... | 4b43b80220e195aa51c129b6cbe1f216a94360cd | 21,615 |
def leveinshtein_distance(source,target):
"""
Implement leveintein distance algorithm as described in the reference
"""
#Step 1
s_len=len(source)
t_len=len(target)
cost=0
if(s_len==0):
return t_len
if(t_len==0):
return s_len
print("Dimensions:\n\tN:%d\n\tM:%d"%(s_len,t_len))
#Step 2
matrix=[[0 for _ in ... | cb8e35f491463469c68f5dbc3e3af4cff7e34441 | 21,616 |
def minus (s):
""" заменить последний минус на равенство """
q = s.rsplit ('-', 1)
return q[0] + '=' + q[1] | 8d4ae538d866a930603b71ccdba0b18145af9988 | 21,617 |
def _chk_y_path(tile):
"""
Check to make sure tile is among left most possible tiles
"""
if tile[0] == 0:
return True
return False | cf733c778b647654652ae5c651c7586c8c3567b8 | 21,618 |
def json_project_activities(request):
"""docstring for json_project_activities"""
timestamp = int(request.GET['dt'])
pid = int(request.GET['id'])
project = get_object_or_404(Project, id=pid)
items = project.items(timestamp)
objs = []
for item in items:
... | cde499b9279194cb42df66989849d8beb2de1376 | 21,619 |
from typing import List
def to_complex_matrix(matrix: np.ndarray) -> List:
"""
Convert regular matrix to matrix of ComplexVals.
:param matrix: any matrix.
:return: Complex matrix.
"""
output: List[List] = matrix.tolist()
for i in range(len(matrix)):
for j in range(len(matrix[i])):... | ea21f0993452b4d2b540de4b92f64579e9aeee00 | 21,620 |
def skipIfDarwin(func):
"""Decorate the item to skip tests that should be skipped on Darwin."""
return skipIfPlatform(
lldbplatform.translate(
lldbplatform.darwin_all))(func) | ddca10a60e9d12f7e556192f922bbeaee0bc3a85 | 21,621 |
from typing import Tuple
from pathlib import Path
def load_dataframe(csv_path: PathLike) -> Tuple[str, pd.DataFrame]:
"""Returns a tuple (name, data frame). Used to construct a data set by `load_dataframes_from_directory`.
See:
load_dataframes_from_directory
Dataset
"""
return Path(cs... | dbbb5f36cb767d39f01bc9c57ea27e7edfb2fb35 | 21,622 |
def VerifyReleaseChannel(options):
"""Verify that release image channel is correct.
ChromeOS has four channels: canary, dev, beta and stable.
The last three channels support image auto-updates, checks
that release image channel is one of them.
"""
return GetGooftool(options).VerifyReleaseChannel(
opt... | 2be7073c9aceb2eaef111b73204d4ef4c71cc6df | 21,623 |
def make_start_script(cmd, repo, anaconda_path, env,
install_pip=(), add_swap_file=False):
""" My basic startup template formatter
Parameters
----------
cmd : str
The actual command to run.
repo : str
The repository
anaconda_path : str
The anaconda ... | 0749f257a511526bb220c3fc4c9f34bc00a0fa32 | 21,624 |
import healpy
def radius_hpmap(glon, glat,
R_truncation, Rmin,
Npt_per_decade_integ,
nside=2048, maplonlat=None):
"""
Compute a radius map in healpix
Parameters
----------
- glon/glat (deg): galactic longitude and latitude in degrees
- R_... | 1daafe536ba673213a1ff3b05d0b38f8f6c48abb | 21,625 |
def convert_grayscale_image_to_pil(image):
"""Converts a 2D grayscale image into a PIL image.
Args:
image (numpy.ndarray[uint8]): The image to convert.
Returns:
PIL.Image: The converted image.
"""
image = np.repeat(image[:, :, None], 3, 2)
image_pil = Image.fromarray(image).co... | 01382037d7f08de0e66a47c2be7fbaf158443a00 | 21,626 |
def delete_group(group_id, tasks=False, cached=Conf.CACHED):
"""
Delete a group.
:param str group_id: the group id
:param bool tasks: If set to True this will also delete the group tasks.
Otherwise just the group label is removed.
:param bool cached: run this against the cache backend
:retu... | 6bad912ecb265b512fecb131d9a6f567f90edc52 | 21,627 |
import re
def alphanum_key(string):
"""Return a comparable tuple with extracted number segments.
Adapted from: http://stackoverflow.com/a/2669120/176978
"""
convert = lambda text: int(text) if text.isdigit() else text
return [convert(segment) for segment in re.split('([0-9]+)', string)] | 0e5e3f1d6aa43d393e1fb970f64e5910e7dc53fc | 21,628 |
def merge_data(attribute_column, geography, chloropleth, pickle_dir):
"""
Merges geometry geodataframe with chloropleth attribute data.
Inputs: dataframe or csv file name for data desired to be choropleth
Outputs: dataframe
"""
gdf = load_pickle(pickle_dir, geography)
chloropleth = load_pick... | 70ce82667a974311bb3cda8785e0f6211a86dfd1 | 21,629 |
def get_ls8_image_collection(begin_date, end_date, aoi=None):
"""
Calls the GEE API to collect scenes from the Landsat 7 Tier 1 Surface Reflectance Libraries
:param begin_date: Begin date for time period for scene selection
:param end_date: End date for time period for scene selection
... | d74370a85dedd102ebe99fa41da1a69fdbb313d2 | 21,630 |
def multi_halo(n_halo):
"""
This routine will repeat the halo generator as many times
as the input number to get equivalent amount of haloes.
"""
r_halo = []
phi_halo = []
theta_halo = []
for i in range(n_halo):
r, theta,phi = one_halo(100)
r_halo.append(r)
theta... | 3b46e21f983dfaa44192b7977ca2f4858818ffc1 | 21,631 |
def allocation_proportion_of_shimenwpp():
"""
Real Name: Allocation Proportion of ShiMenWPP
Original Eqn: Allocation ShiMen WPP/Total WPP Allocation
Units: m3/m3
Limits: (None, None)
Type: component
Subs: None
"""
return allocation_shimen_wpp() / total_wpp_allocation() | e476e9472132bb81feccceef7f56c7e2eaa4b6f2 | 21,632 |
import copy
def update_cfg(base_cfg, update_cfg):
"""used for mmcv.Config or other dict-like configs."""
res_cfg = copy.deepcopy(base_cfg)
res_cfg.update(update_cfg)
return res_cfg | c03dcfa7ac6d2f5c6745f69028f7cdb2ebe35eec | 21,633 |
import traceback
def check(conn, command, exit=False, timeout=None, **kw):
"""
Execute a remote command with ``subprocess.Popen`` but report back the
results in a tuple with three items: stdout, stderr, and exit status.
This helper function *does not* provide any logging as it is the caller's
res... | f3ada320c245d0660f5f820e08131fed010a9fd4 | 21,634 |
import functools
def domains_configured(f):
"""Wraps API calls to lazy load domain configs after init.
This is required since the assignment manager needs to be initialized
before this manager, and yet this manager's init wants to be
able to make assignment calls (to build the domain configs). So
... | b336912d9abc80b2f3f5899be7fbf6ae384ae248 | 21,635 |
def add_modified_tags(original_db, scenarios):
"""
Add a `modified` label to any activity that is new
Also add a `modified` label to any exchange that has been added
or that has a different value than the source database.
:return:
"""
# Class `Export` to which the original database is passe... | b1e18f8871e7d9430e5c4eaff41128c72359ce1c | 21,636 |
def import_tep_sets(lagged_samples: int = 2) -> tuple:
"""
Imports the normal operation training set and 4 of the commonly used test
sets [IDV(0), IDV(4), IDV(5), and IDV(10)] with only the first 22 measured
variables and first 11 manipulated variables
"""
normal_operation = import_sets(0)
t... | d9affb48e182f4bb79cdb86e70ca90dadd461d51 | 21,638 |
def to_fgdc(obj):
"""
This is the priamry function to call in the module. This function takes a UnifiedMetadata object
and creates a serialized FGDC metadata record.
Parameters
----------
obj : obj
A amg.UnifiedMetadata class instance
Returns
-------
: str
A strin... | 762f77c45f2e40fd9135b3821e91b9c1c7a30bd9 | 21,639 |
def compute_iqms(settings, name='ComputeIQMs'):
"""
Workflow that actually computes the IQMs
.. workflow::
from mriqc.workflows.functional import compute_iqms
wf = compute_iqms(settings={'output_dir': 'out'})
"""
workflow = pe.Workflow(name=name)
inputnode = pe.Node(niu.IdentityI... | 90ce62cd50ed2818e01c55eabde437b84a10dc70 | 21,640 |
def GetDepthFromIndicesMapping(list_indices):
"""
GetDepthFromIndicesMapping
==========================
Gives the depth of the nested list from the index mapping
@param list_indices: a nested list representing the indexes of the nested lists by depth
@return: depth
"""
retur... | c2318b3c6a398289c2cbf012af4c562d3d8bc2da | 21,642 |
import signal
def lowpassIter(wp, ws, fs, f, atten=90, n_max=400):
"""Design a lowpass filter using f by iterating to minimize the number
of taps needed.
Args:
wp: Passband frequency
ws: Stopband frequency
fs: Sample rate
f: Function to design filter
atten: desired... | c9733a8d7c225dfbf76a4a11441ce75bd8f9042f | 21,643 |
from typing import Union
from typing import Dict
import numpy
def evaluate_themes(
ref_measurement: Measurement,
test_measurement: Measurement,
themes: Union[FmaskThemes, ContiguityThemes, TerrainShadowThemes],
) -> Dict[str, float]:
"""
A generic tool for evaluating thematic datasets.
"""
... | d6f56d54e19b35d6ab3d716d7a231fb27bc3db9a | 21,644 |
def test_global_averaging():
"""Test that `T==N` and `F==pow2(N_frs_max)` doesn't error, and outputs
close to `T==N-1` and `F==pow2(N_frs_max)-1`
"""
if skip_all:
return None if run_without_pytest else pytest.skip()
np.random.seed(0)
N = 512
params = dict(shape=N, J=9, Q=4, J_fr=5, Q... | d8a7c08754c403a2a3450be6ee5856a57f686003 | 21,645 |
def poly_coefficients(df: np.ndarray,z: np.ndarray,cov: np.ndarray) -> np.ndarray:
"""
Calculate the coefficients in the free energy polynomial
Parameters
----------
df : [2,iphase]
Difference between next and current integration points
z: np.ndarray [2,iphase]
Conjugate v... | 67270bbb03a8f9d006e4d22d22f114ec6deab057 | 21,646 |
def NoneInSet(s):
"""Inverse of CharSet (parse as long as character is not in set). Result is string."""
return ConcatenateResults(Repeat(NoneOf(s), -1)) | 00bb27c434b630926eb8d2012ebed6bb1bf368d4 | 21,647 |
import re
def _read_part(f, verbose):
"""Reads the part name and creates a mesh with that name.
:param f: The file from where to read the nodes from.
:type f: file object at the nodes
:param verbose: Determines what level of print out to the console.
:type verbose: 0, 1 or 2
:return: Nothing,... | d6546e39dc0998e979c3cb03b60f149e2a474518 | 21,648 |
async def get_prefix(bot, message):
"""Checks if the bot has a configuration tag for the prefix. Otherwise, gets the default."""
default_prefix = await get_default_prefix(bot)
if isinstance(message.channel, discord.DMChannel):
return default_prefix
my_roles = [role.name for role in message.guild... | 15d44e0a976858b5217b68740485dddd4b4bf0ef | 21,649 |
def HA19(request):
"""
Returns the render for the sdg graph
"""
data = dataFrameHA()
figure = px.bar(data, x = "Faculty", y = "HA 19", labels = {"Faculty":"Faculties",
"HA19":"Number of Modules Corresponding to HA 19"})
figure.write_image("core/static/HA19.png")
return render(re... | 6cdeb6589fffd910b981c583213e268e2ae0f1e2 | 21,651 |
def beta(data, market, periods, normalize = False):
"""
.. Beta
Parameters
----------
data : `ndarray`
An array containing values.
market : `ndarray`
An array containing market values to be used as the comparison
when calculating beta.
periods : `int`
Number ... | 23071387d52d9a715dcb286cc74779d83438d453 | 21,653 |
import math
def heading_from_to(p1: Vector, p2: Vector) -> float:
"""
Returns the heading in degrees from point 1 to point 2
"""
x1 = p1[0]
y1 = p1[1]
x2 = p2[0]
y2 = p2[1]
angle = math.atan2(y2 - y1, x2 - x1) * (180 / math.pi)
angle = (-angle) % 360
return abs(angle) | a9fe4fe79fdff0c390e5870fb05d4e9f0c371185 | 21,654 |
import math
def selSPEA2Diverse(individuals, k):
"""Apply SPEA-II selection operator on the *individuals*. Usually, the
size of *individuals* will be larger than *n* because any individual
present in *individuals* will appear in the returned list at most once.
Having the size of *individuals* equals t... | d5b651844c3dc8ad96e04f9a93e264d368b066a3 | 21,655 |
def utilization_to_states(state_config, utilization):
""" Get the state history corresponding to the utilization history.
Adds the 0 state to the beginning to simulate the first transition.
(map (partial utilization-to-state state-config) utilization))
:param state_config: The state configuration.
... | 1eaaff399dfd6981feb8de56eb5dc4b4baa8fd3f | 21,656 |
from typing import Dict
def generate_person(results: Dict):
"""
Create a dictionary from sql that queried a person
:param results:
:return:
"""
person = None
if len(results) > 0:
person = {
"id": results[0],
"name": results[1].decode("utf-8"),
... | 21c2f2c8fa43c43eabf06785203556ccae708d45 | 21,658 |
def paliindrome_sentence(sentence: str) -> bool:
"""
`int`
"""
string = ''
for char in sentence:
if char.isalnum():
string += char
return string[::-1].casefold() == string.casefold() | 4559f9f823f748f137bbe1eb96070dba8e7d867d | 21,659 |
def get_default_pool_set():
"""Return the names of supported pooling operators
Returns:
a tuple of pooling operator names
"""
output = ['sum', 'correlation1', 'correlation2', 'maximum']
return output | 32d28fdb80ecdacab8494251edd87b566128fd79 | 21,660 |
def virtual_networks_list_all(**kwargs):
"""
.. versionadded:: 2019.2.0
List all virtual networks within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.virtual_networks_list_all
"""
result = {}
netconn = __utils__["azurearm.get_client"]("network... | 52b9d655a2459d1b2f2904fc216b5ccc8ad12b04 | 21,661 |
def generate_state_matrix(Hprime, gamma):
"""Full combinatorics of Hprime-dim binary vectors with at most gamma ones.
:param Hprime: Vector length
:type Hprime: int
:param gamma: Maximum number of ones
:param gamma: int
"""
sl = []
for g in range(2,gamma+1):
for s in combinatio... | 165a6bfe742569780939783dc7f1b086245c747e | 21,662 |
def playfair_decipher(message, keyword, padding_letter='x',
padding_replaces_repeat=False, letters_to_merge=None,
wrap_alphabet=KeywordWrapAlphabet.from_a):
"""Decipher a message using the Playfair cipher."""
column_order = list(range(5))
row_order = list(range(5... | d66afe1447be6b5453a5271f80e678d5e1664c95 | 21,664 |
import json
def create_role(role_name):
"""Create a role."""
role_dict = {
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Principal" : {
"Service" : "lambda.amazonaws.com"
},
"Acti... | 743a88c5e071d1ed2e968f7ec3a7421eaab4d69e | 21,665 |
def evaluate_field(record, field_spec):
"""
Evaluate a field of a record using the type of the field_spec as a guide.
"""
if type(field_spec) is int:
return str(record[field_spec])
elif type(field_spec) is str:
return str(getattr(record, field_spec))
else:
return str(fiel... | 66fdc96aa774a27c225fb273040acdbbf4ff9979 | 21,666 |
def project_points(X, K, R, T, distortion_params=None):
"""
Project points from 3d world coordinates to 2d image coordinates
"""
x_2d = np.dot(K, (np.dot(R, X) + T))
x_2d = x_2d[:-1, :] / x_2d[-1, :]
if distortion_params is not None:
x_2d_norm = np.concatenate((x_2d, np.ones((1, x_2d.sha... | e7f2c3f864e7beb798194eca3425cd9342b2c881 | 21,667 |
import numpy as np
def rate_multipressure(qD, delta_p, B, mu, perm, h):
"""Calculate Rate as Sum of Constant Flowing Pressures"""
return ((.007082 * perm * h) / (B * mu)) * (np.sum(qD * delta_p)) | a8621613abb63bb6f15c71ab3ba02d65ab160e6b | 21,669 |
def osculating_elements_of(position, reference_frame=None, gm_km3_s2=None):
"""Produce the osculating orbital elements for a position.
`position` is an instance of :class:`~skyfield.positionlib.ICRF`.
These are commonly returned by the ``at()`` method of any
Solar System body. ``reference_frame`` is an... | cf6096ed0eeaeccaa013e052ad1a2fe7e63940f5 | 21,670 |
import copy
def rename_actions(P: NestedDicts, policy: DetPolicy) -> NestedDicts:
""" Renames actions in P so that the policy action is always 0."""
out: NestedDicts = {}
for start_state, actions in P.items():
new_actions = copy.copy(actions)
policy_action = policy(start_state)
new... | 433433ded44f118ec05ddbf9fde17825b0fd4e62 | 21,671 |
import csv
from datetime import datetime
async def get_category(category):
"""
Retrieves the data for the provided category. The data is cached for 1 hour.
:returns: The data for category.
:rtype: dict
"""
# Adhere to category naming standard.
category = category.lower()
# URL to re... | a40ba9ec753b8d7a0b2a464675a1bb541be193f0 | 21,672 |
def plot_ellipses_area(
params, depth="None", imin=0, imax=398, jmin=0, jmax=898, figsize=(10, 10)
):
"""Plot ellipses on a map in the Salish Sea.
:arg params: a array containing the parameters (possibly at different
depths and or locations).
:type param: np.array
:arg depth: The depth at w... | b1f96ae602b6e4b1db725ac4efd2be193c23c29c | 21,673 |
from typing import Dict
def populate_workflow_request_body(manifest_data: Dict):
"""
Populate workflow request body with the passed data according API specification
:param data: item data from manifest files
:return: populated request
:rtype: dict
"""
request = {
"runId": ... | f0ec863d835907402a9a5fa3ce3c61ea1e9a4b69 | 21,676 |
def is_leap_year(year):
"""
Is the current year a leap year?
Args:
y (int): The year you wish to check.
Returns:
bool: Whether the year is a leap year (True) or not (False).
"""
if year % 4 == 0 and (year % 100 > 0 or year % 400 == 0): return True
return False | 16e4c83adc9d42dae2396186f980755b33af9188 | 21,678 |
def blank_dog():
"""Set up (16, 3) array of dog with initial joint positions"""
length = 0.5
width = 0.2
ankle_length = 0.1
ankle_to_knee = 0.2
knee_to_shoulder = 0.05
O = Vector(0,0,0) # origin
out = []
for lengthwise in [-1, +1]:
for widthwise in [+1, -1]:
foot = O + length * Vector(lengthwise/2,0,0) ... | af53bd94e273b79b44ff25fff32245ea0dcae280 | 21,680 |
def random_majority_link_clf():
"""
for link classification we do not select labels from a fixed distribution
but instead we set labels to the number of possible segments in a sample.
I.e. we only predict a random link out of all the possible link paths in a sample.
"""
def clf(labels, k:int... | f53f2fee85914e25d5e407808dcfbee623b0782a | 21,682 |
def db_to_df(db_table):
"""Reads in a table from the board games database as pandas DataFrame"""
query = f"SELECT * FROM {db_table};"
pd_table = pd.read_sql(query, DB)
return pd_table | d20f876c7a7e8da891dc949e85eb35932c6ae5fa | 21,683 |
def player_input_choice() -> int:
"""Function that takes the player input as the position for his|her marker"""
marker_position = 0
while marker_position not in range(1, 10) or not tic_tac_toe.check_the_cell(marker_position):
marker_position = int(input("Choose the position for your marker from 1 to... | b717068f4e1aa36251b1ee1503034a3f60b193c7 | 21,685 |
def increment_datetime_by_string(mydate, increment, mult=1):
"""Return a new datetime object incremented with the provided
relative dates specified as string.
Additional a multiplier can be specified to multiply the increment
before adding to the provided datetime object.
Usage:
... | 7651ccb9c4b5b881c5d1389dcdfd015dfabb0a3b | 21,686 |
def get_regularization_loss(scope=None, name="total_regularization_loss"):
"""Gets the total regularization loss.
Args:
scope: An optional scope name for filtering the losses to return.
name: The name of the returned tensor.
Returns:
A scalar regularization loss.
"""
losses = get_regularization_... | dd65e13111b0927c197b38e4500d5194a7bd5453 | 21,687 |
def storage_backend_get_all(context, inactive=False, filters=None):
"""Get all storage backends"""
return IMPL.storage_backend_get_all(context, inactive, filters) | 9f67dab8e6576ee30185a36e59cfb8e0d45569cb | 21,689 |
from datetime import datetime
import requests
def get_date_opm_status_response(intent, session):
""" Gets the current status of opm for the day
"""
card_title = "OPM Status Result"
session_attributes = {}
speech_output = "I'm not sure which o. p. m. status you requested. " \
"P... | 29d1517f87495751a604c209768d6750a0ab960e | 21,690 |
def oauth_api_request(method, url, **kwargs):
"""
when network error, fallback to use rss proxy
"""
options = _proxy_helper.get_proxy_options()
client = RSSProxyClient(**options, proxy_strategy=_proxy_strategy)
return client.request(method, url, **kwargs) | 07438100ea75ae144567001832986f03cd72c3a8 | 21,691 |
def validate_cached(cached_calcs):
"""
Check that the calculations with created with caching are indeed cached.
"""
valid = True
for calc in cached_calcs:
if not calc.is_finished_ok:
print('Cached calculation<{}> not finished ok: process_state<{}> exit_status<{}>'
... | 3406c584dada7d24a46cbb565d0cdbab98a1d303 | 21,692 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.