content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gen_mapping_tuples():
"""Retrieve intersphinx gist and yield mapping tuples."""
data = get_gist_data()
yield from gen_tuples_from_data(data) | 46,100 |
def particle_movement_x(time):
"""
Generates a random movement in the X label
Parameter:
time (int): Time step
Return:
x (int): X position
"""
x = 0
directions = [1, -1]
for i in range(time):
x = x + random.choice(directions)
return x | 46,101 |
def plot_two_series(A, B, variable, title):
"""
Plots two series using the same `date` index.
Parameters
----------
A, B: pd.DataFrame
Dataframe with a `date` key and a variable
passed in the `variable` parameter. Parameter A
represents the "Observed" series and B the "... | 46,102 |
def find_match_characters(string, pattern):
"""Find match match pattern string.
Args:
params: string
pattern
Returns:
Raises:
"""
matched = []
last_index = 0
if not string or not pattern:
return matched
if string[0] != pattern[0]:
return matc... | 46,103 |
def cross_product_configs(**configs):
"""
Given configs from users, we want to generate different combinations of
those configs
For example, given M = ((1, 2), N = (4, 5)),
we will generate (({'M': 1}, {'N' : 4}),
({'M': 1}, {'N' : 5}),
({'M': 2}, {'N' : 4... | 46,104 |
def columnwise_normalize(X: np.ndarray) -> Union[None, np.ndarray]:
"""normalize per column"""
if X is None:
return None
return (X - np.mean(X, 0)) / np.std(X, 0) | 46,105 |
def test_fieldset_sample_eval(fieldset, xdim=60, ydim=60):
""" Sample the fieldset using the explicit eval function. """
lon = np.linspace(-170, 170, xdim, dtype=np.float32)
lat = np.linspace(-80, 80, ydim, dtype=np.float32)
v_s = np.array([fieldset.V.eval(0, x, 70., 0.) for x in lon])
u_s = np.arra... | 46,106 |
def fchdir(fd):
"""Change the current working directory to the directory represented by the
file descriptor fd.
:type fd: int
:rtype: None
"""
pass | 46,107 |
def add_long_reads(bam_file, read, long_reads, min_event_size, get_hp=True):
"""Adds a (primary, non-supplementary, long) read to the long_reads list
Read added to long_reads if within the inteval defined by ranges
Alignments belonging to the LongRead instance combined if within the
min_event_size dist... | 46,108 |
def test_spin_adapted_t1():
"""
Description: Test spin adapted t1
Expectation:
"""
t1_20 = spin_adapted_t1(2, 0)[0]
assert str(t1_20) == '1.0 [4^ 0] +\n1.0 [5^ 1] '
t1_00 = spin_adapted_t1(0, 0)[0]
assert str(t1_00) == '1.0 [0^ 0] +\n1.0 [1^ 1] ' | 46,109 |
def my_print(*args, filepath="~/my_stdout.txt"):
"""Modified print statement that prints to terminal/scree AND to a given file (or default).
Note: import it as follows:
from utils.utils import my_print as print
to overwrite builtin print function
Keyword Arguments:
filepath {str} -- wher... | 46,110 |
def fq_classification(fqclass, verbose=False):
"""
Read the fastq classification file
:param fqclass: the classification file that has the file name and then arbitrary classifications separated by tabs
:param verbose: more output
:return: a dict of the classification. Guaranteed that all have the sa... | 46,111 |
def line_intersect(a1, da, b1, db):
"""
compute intersection of infinetly long lines
"""
dba = np.array(a1) - np.array(b1)
da_perpendicular = perp(da)
num = np.dot(da_perpendicular, dba)
denom = np.dot(da_perpendicular, db)
dist_b = (num / denom)
return dist_b*db + b1 | 46,112 |
def sequence_(t : r(e(a))) -> e(Unit):
"""
sequence_ :: (Foldable r, Monad e) => r (e a) -> e ()
Evaluate each monadic action in the structure from left to right, and
ignore the results. For a version that doesn't ignore the results see
sequence.
As of base 4.8.0.0, sequence_ is just sequenceA... | 46,113 |
def param_validated(param, val):
"""Return True if matches validation pattern, False otherwise"""
if param in validation_dict:
pattern = validation_dict[param]
if re.match(rf'{pattern}', val) is None:
log.error("Validation failed for param='%s', "
"val='%s'. Val... | 46,114 |
def bitcoinde(filename="", output_file = ""):
"""
timeseries aren't included in bitfinex or crypto.wat.ch,
have to be downloaded and adjusted to fit.
https://www.bitcoin.de/json/chart/stats_hourly_btcusd_statistics_60month.json
:return:
"""
output_dicct = {}
output_dicct['exchange'] = "b... | 46,115 |
def remove_keys_from_array(array, keys):
"""
This function...
:param array:
:param keys:
:return:
"""
for key in keys:
array.remove(key)
return array | 46,116 |
def create_tree_data(codepage, options, target_node, pos):
"""Create structure needed for Dijit Tree widget """
tree_nodes = []
for opt in options:
code = opt['code']
cp = codepage + code
add_tree_node(tree_nodes, cp, code+"-"+opt['label'], cp)
tree_data = {
... | 46,117 |
def detect_octavia():
"""
Determine whether the underlying OpenStack is using Octavia or not.
Returns True if Octavia is found in the region, and False otherwise.
"""
try:
creds = _load_creds()
region = creds['region']
for catalog in _openstack('catalog', 'list'):
... | 46,118 |
def add_cache_control_header(response):
"""Disable caching for non-static endpoints
"""
if "Cache-Control" not in response.headers:
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
return response | 46,119 |
def clean_new_import_aliases(
import_aliases: List[ImportAlias],
) -> List[ImportAlias]:
"""Clean up a list of import aliases."""
# Sort them
cleaned_import_aliases = sorted(import_aliases, key=lambda n: n.evaluated_name)
# Remove any trailing commas
last_name = cleaned_import_aliases[-1]
if... | 46,120 |
def _format_td(timedelt):
"""Format a timedelta object as hh:mm:ss"""
if timedelt is None:
return ''
s = int(round(timedelt.total_seconds()))
hours = s // 3600
minutes = (s % 3600) // 60
seconds = (s % 60)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) | 46,121 |
def test_75_gpload_merge_chinese_standard_conforming_str_on():
"""75 gpload merge data with different quotations '"col"'(support) "\"col\""(support) "'col'" and "col"
with standard_conforming_strings on"""
runfile(mkpath('setup.sql'))
copy_data("external_file_19.txt", "data_file.txt")
# '"Col"' ... | 46,122 |
def main() -> None:
"""
Calculate and output the solutions based on the real puzzle input.
"""
data = aocd.get_data(year=2019, day=2)
program = read_program(data)
patched = program[0:1] + (12, 2) + program[3:]
print(f"Part 1: {run_program(patched)[0]}")
noun, verb = find_input_values(p... | 46,123 |
def add_quad_reaction_node(graph, rxn):
"""
Adds a "Quad Reaction Node" (QRN) group of nodes to a graph, and connects
them to the correct compound nodes.
The QRN consists of two nodes constituting the intended forward direction
of the reaction and two nodes constituting the reverse direction. Each ... | 46,124 |
def test_load_module_recursive_complex_module_dependencies(local_module_package_index: str, snippetcompiler) -> None:
"""
Test whether the load_module_recursive() method works correctly when complex, circular dependencies exist between modules.
Dependency graph:
complex_module_dependencies_mod1 -----... | 46,125 |
def delete_accounts(account):
"""
Function to delete account
"""
account.delete_account() | 46,126 |
def clearSnapshotSectors(date):
"""Removes sector-specific spreadsheets from the snapshot with the given
date
"""
sectorTable = getSectorTable(date)
snapshotPath = getSnapshotPath(date)
for sector in sectorTable:
sectorPath = snapshotPath + "/%s.xls" % sector["Code"]
if os.pat... | 46,127 |
def api_dataset(dataset):
"""
Return a list of available years
"""
path = os.path.join(geodata_dir, dataset)
if os.path.exists(path):
return jsonify(find_maps(path))
else:
return 'error: cannot find dataset: %s' % dataset | 46,128 |
def matrixFilter(np_image_2D, np_mask):
"""
Processing filtering with given matrix
Keyword argument:
np_image_2D -- two dimensional image(grayscale or single color channel)
np_mask -- mask matrix as numpy array
Return:
np_image_fil -- image as numpy 2D array, after specified filtering
... | 46,129 |
def model1():
"""
This model is composed of one Sersic profile
""" | 46,130 |
def batch_split_axis(batch, n_split):
"""Reshapes batch to have first axes size equal n_split."""
x, y = batch
n = x.shape[0]
n_new = n / n_split
assert n_new == int(n_new), (
"First axis cannot be split: batch dimension was {} when "
"n_split was {}.".format(x.shape[0], n_split))
n_new = int(n_... | 46,131 |
def right_align(value, length):
"""
:param value: string to right align
:param length: the number of characters to output (spaces added to left)
:return:
"""
if length <= 0:
return u""
value = text(value)
if len(value) < length:
return (" " * (length - len(value))) + va... | 46,132 |
def test_disable_functions_as_notebooks(backup_spec_with_functions):
"""
Tests a typical workflow with a pieline where some tasks are functions
"""
with open('pipeline.yaml') as f:
spec = yaml.safe_load(f)
spec['meta']['jupyter_functions_as_notebooks'] = False
Path('pipeline.yaml').writ... | 46,133 |
def proxy_gettext(*args, **kwargs):
"""Proxy calls this function to the real built-in gettext() function.
This is not required for normal operation of the application, could be not imported at all,
but will help development.
"""
### this would load gettext in case it wasn't done before use, but cou... | 46,134 |
def plot_fundamental_diagram(tabled_density_values, deduced_flow_rates, mean_densities, mean_flow_rates) :
""" Рисує фундаментальну діаграму транспортних потоків """
# Підписуємо графік
plt.figure("Фундаментальна діаграма транспортних потоків")
plt.title("Фундаментальна діаграма транспортних потоків")
plt.xla... | 46,135 |
def generate_users_data(users):
"""
Generate users' rows (assuming the user's password is the defualt one)
:param users:
:return:
"""
headers = ['שם משתמש', 'סיסמה']
rows = [[user.username, DEFAULT_TEAM_USER_PASSWORD] for user in users]
rows.insert(0, headers)
return rows | 46,136 |
def ListToMatrix(lv):
""" Convert a list of 3 or 4 ``c4d.Vector`` to ``c4d.Matrix``. """
if not isinstance(lv, list):
raise TypeError("E: expected list of vectors, got %r" % type(lv))
m = len(lv)
if not isinstance(lv[0], c4d.Vector):
raise TypeError("E: expected list elements of type c4... | 46,137 |
def loadEpithelium(name):
"""Returns an epithelium from a CSV file with the given name.
Precondition: name exists and it's in CSV format"""
assert type(name) == str, "name isn't a string"
recs = []
text = open(name)
i = 0
for line in text:
if i > 0:
recs.append(l... | 46,138 |
def focal_attention(query, context, use_sigmoid=False, scope=None):
"""Focal attention layer.
Args:
query : [N, dim1]
context: [N, num_channel, T, dim2]
use_sigmoid: use sigmoid instead of softmax
scope: variable scope
Returns:
Tensor
"""
with tf.variable_scope(scope or "attention", reus... | 46,139 |
def _on_add_trace_event(zk2fs_sync, zkpath):
"""Invoked when trace event is added."""
fpath = zk2fs_sync.fpath(zkpath)
# Extract timestamp.
_name, timestamp, _rest = os.path.basename(fpath).split(',', 2)
utime = float(timestamp)
zksync_utils.write_data(
fpath, None, utime, raise_err=Fa... | 46,140 |
def test_sub_state_output_unifier_result_converted_to_true():
"""
Test for output is unified so the result is converted to True
:return:
"""
data = {
"sub_state_run": [
{
"comment": ["data", "in", "the", "list"],
"changes": {},
"nam... | 46,141 |
def format_float(x):
""" Pretty formatting for floats
"""
if pd.isnull(x):
return " ."
else:
return "{0:10.2f}".format(x) | 46,142 |
def random_points_and_attrs(count, srs_id):
"""
Generate Random Points and attrs (Use some UTM Zone)
"""
points = generate_utm_points(count, srs_id)
rows = []
for p in points:
rand_str = ''.join(choice(ascii_uppercase + digits) for _ in range(10))
rand_bool = bool(randint(0, 1))
... | 46,143 |
def trimap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in TriMap basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
... | 46,144 |
def quantile(arg, quantile, interpolation='linear'):
"""
Return value at the given quantile, a la numpy.percentile.
Parameters
----------
quantile : float/int or array-like
0 <= quantile <= 1, the quantile(s) to compute
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'... | 46,145 |
def random_new(algo=RNG_CMWC):
"""Return a new Random instance. Using ``algo``.
Args:
algo (int): The random number algorithm to use.
Returns:
Random: A new Random instance using the given algorithm.
"""
return tcod.random.Random(algo) | 46,146 |
def get_kth_value(unsorted, k, axis=-1):
"""
Args:
unsorted: numpy.ndarray of any dimensionality.
k: int
Returns:
kth values along the designated axis.
"""
indices = np.argpartition(unsorted, k, axis=axis)[..., :k]
k_smallests = np.take_along_axis(unsorted, indic... | 46,147 |
def rdc_transformer(
local_data,
meta_types,
domains,
k=None,
s=1.0 / 6.0,
non_linearity=np.sin,
return_matrix=False,
ohe=True,
rand_gen=None,
):
# logger.info('rdc transformer', k, s, non_linearity)
"""
Given a data_slice,
return a transformation of the features data... | 46,148 |
def trim(docstring):
"""Trims the leading spaces from docstring comments.
From http://www.python.org/dev/peps/pep-0257/
"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().spli... | 46,149 |
def test_get_tip_drop_location(
decoy: Decoy,
tip_rack_def: LabwareDefinition,
labware_view: LabwareView,
subject: GeometryView,
) -> None:
"""It should get relative drop tip location for a pipette/labware combo."""
pipette_config: PipetteDict = cast(PipetteDict, {"return_tip_height": 0.7})
... | 46,150 |
async def get_layer_version(compatible_runtime=None,layer_name=None,version=None,opts=None):
"""
Provides information about a Lambda Layer Version.
"""
__args__ = dict()
__args__['compatibleRuntime'] = compatible_runtime
__args__['layerName'] = layer_name
__args__['version'] = version
_... | 46,151 |
def get_header_names(header_annotation_names: Optional[List[str]],
doc: Optional[str] = None,
docs: Optional[List[str]] = None):
"""Get a list of header annotations and a dictionary for renamed annotations."""
# Get source_header_names from headers file if it exists
... | 46,152 |
def data_index(data, key):
"""Indexing data for key or a list of keys."""
def idx(data, i):
if isinstance(i, int):
return data[i]
assert isinstance(data, dict)
if i in data:
return data[i]
for k, v in data.items():
if str(k) == str(i):
... | 46,153 |
def calculate_misfit(da):
""" For each force orientation, extracts minimum misfit
"""
misfit = da.min(dim=('origin_idx', 'F0'))
return misfit.assign_attrs({
'best_force': _min_force(da)
}) | 46,154 |
def filter_calendar(
input_file, re_pattern, start_date, end_date, output_format, output_file
):
"""
Filter ics-format calendar
"""
from calh.filter import CalendarFilter
with click_spinner.spinner():
CalendarFilter.filter(
input_file=input_file,
re_pattern=re_pa... | 46,155 |
def f_score_one_hot(labels,predictions,beta=1.0,average=None):
"""compute f score, =(1+beta*beta)precision*recall/(beta*beta*precision+recall)
the labels must be one_hot.
the predictions is prediction results.
Args:
labels: A np.array whose shape matches `predictions` and must be one_ho... | 46,156 |
def articles():
"""Show a list of article titles"""
the_titles = [[a[0], a[1]] for a in articles]
return render_template('articles.html', titles = the_titles) | 46,157 |
def create_montage_for_background(montage_folder_path: str, im_b_path: str, f_path: str, only_face: bool) -> str:
"""
Creates and saves the montage from a designed background. If a folder is provided for faces, it will create a file
'faces.json' inside the folder for faster loading if used repeatedly. If ne... | 46,158 |
def preprocesses_split_lines3():
"""Preprocess the text by selecting only max n-grams
Alternative split.
"""
LOGGER.info("Reading filtered data:")
answers = set()
for encoded_line in open(NEWS_FILE_NAME_FILTERED):
line = encoded_line #.decode('utf-8')
if line.count(" ") < 5:
... | 46,159 |
def test_view(app):
"""Test view."""
with app.app_context():
login_url = url_for_security('login')
with app.test_client() as client:
res = client.get(login_url)
assert res.status_code == 200 | 46,160 |
def deserialize_question(
question: QuestionDict
) -> Question:
"""Convert a dict into Question object."""
return Question(
title=question['title'],
content=question.get('content'),
choices=[
Choice(
title=title,
goto=goto
)
... | 46,161 |
def cmd_stop_all():
"""Stop all apps"""
echo("Stopping all apps", fg="green")
for app in listdir(APP_ROOT):
if not app.startswith((".", "_")):
app = sanitize_app_name(app)
remove_nginx_conf(app)
cleanup_uwsgi_enabled_ini(app)
write_deployinfo(app, {"de... | 46,162 |
def ensure_utc_datetime(value):
"""
Given a datetime, date, or Wayback-style timestamp string, return an
equivalent datetime in UTC.
Parameters
----------
value : str or datetime.datetime or datetime.date
Returns
-------
datetime.datetime
"""
if isinstance(value, str):
... | 46,163 |
def get_pod_status(pod_name: str) -> GetPodEntry:
"""Returns the current pod status for a given pod name"""
oc_get_pods_args = ["get", "pods"]
oc_get_pods_result = execute_oc_command(oc_get_pods_args, capture_output=True).stdout
line = ""
for line in oc_get_pods_result.splitlines():
if po... | 46,164 |
def helix_evaluate(t, a, b):
"""Evalutes an helix at a parameter.
Parameters
----------
t: float
Parameter
a: float
Constant
b: float
Constant
c: float
Constant
Returns
-------
list
The (x, y, z) coordinates.
Notes
-----
An i... | 46,165 |
def sst_bf_repo_path(host, ansible_vars):
""" Get supporting script and return file path as string """
remote_location = "https://github.com/intel/CommsPowerManagement"
commit = "05509e90fc082538609198c05179a52971bb5897"
# Attempt to get repository from GitHub
_, file_location = mkstemp()
cmd ... | 46,166 |
def get_pfb_window(num_taps, num_branches, window_fn='hamming'):
"""
Get windowing function to multiply to time series data
according to a finite impulse response (FIR) filter.
Parameters
----------
num_taps : int
Number of PFB taps
num_branches : int
Number of PFB branches.... | 46,167 |
def retrieve_bluffs_by_id(panelist_id: int,
database_connection: mysql.connector.connect,
pre_validated_id: bool = False) -> Dict:
"""Returns an OrderedDict containing Bluff the Listener information
for the requested panelist ID
Arguments:
panelis... | 46,168 |
def test__neighbors_fixed_radius():
""" Returns the list of neighbor column indices if within the fixed radius """
result = _neighbors_fixed_radius(pwmat = tr.pw_beta, radius = 20)
assert isinstance(result, list) | 46,169 |
def apply_function_to_members(cls, fn):
"""
Apply a function to all the members of a class.
Used for decorators that is applied in a class and want all the members
to use it
:param cls: class
:param fn: function
:return:
"""
for name, method in _get_interesting_members(Assembly, cls... | 46,170 |
def extract_protein_from_record(record):
"""
Grab the protein sequence as a string from a SwissProt record
:param record: A Bio.SwissProt.SeqRecord instance
:return:
"""
return str(record.sequence) | 46,171 |
def _diff_coord(coord):
"""Returns the difference as a `xarray.DataArray`."""
v0 = coord.values[0]
calendar = getattr(v0, "calendar", None)
if calendar:
import cftime
ref_units = "seconds since 1800-01-01 00:00:00"
decoded_time = cftime.date2num(coord, ref_units, calendar)
... | 46,172 |
def test_get_markings_smoke(data):
"""Test get_markings does not fail."""
assert len(markings.get_markings(data, "a")) >= 1
assert markings.get_markings(data, "a") == ["1"] | 46,173 |
def checkDependencies():
"""
Sees which outside dependencies are missing.
"""
missing = []
try:
import _tkinter
del _tkinter
except:
missing.append("WARNING: _tkinter is necessary for NetworKit.\n"
"Please install _tkinter \n"
"Root privileges are necessary for this. \n"
"If you have these, t... | 46,174 |
def game():
""" A guessing game """
# Use 'raw_input' to read standard input
value = input("Please enter your guess (between 1 and 10): ")
try:
# str オブジェクトを int オブジェクトに変換する
value = int(value)
except ValueError:
print('Wrong type entered, try again', value)
return
... | 46,175 |
def test_case_not_found(client, django_assert_num_queries, elasticsearch):
""" Test /series/volume/case/ not found """
with django_assert_num_queries(select=1):
response = client.get(reverse('citation', args=['fake', '123', '456'], host='cite'))
check_response(response, content_includes='Search for ... | 46,176 |
def get_user_groups_sta_command(client: Client, args: Dict[str, Any]) -> CommandResults:
""" Function for sta-get-user-groups command. Get all the groups associated with a specific user. """
response, output_data = client.user_groups_data(userName=args.get('userName'), limit=args.get('limit'))
if not respo... | 46,177 |
def _not_implemented_tensor_from_file(_, __, ___=None):
"""Used to make sure TensorMap is never used to load data"""
raise NotImplementedError('This TensorMap cannot load data.') | 46,178 |
def test_service(host):
"""
Test service state
"""
service = host.service('vsftpd')
assert service.is_enabled
# if host.system_info.codename in ['jessie', 'xenial']:
if host.file('/etc/init.d/vsftpd').exists:
assert 'is running' in host.check_output('/etc/init.d/vsftpd status')
... | 46,179 |
def get_capital_flow(order_book_ids, start_date=None, end_date=None, frequency="1d", market="cn"):
"""获取资金流入流出数据
:param order_book_ids: 股票代码or股票代码列表, 如'000001.XSHE'
:param start_date: 开始日期
:param end_date: 结束日期
:param frequency: 默认为日线。日线使用 '1d', 分钟线 '1m' 快照 'tick' (Default value = "1d"),
:param... | 46,180 |
def process_message(data):
"""
@keyword *channel bomb:* `^kevin.*channel bomb.*`
@summary send a channel bomb to really get peoples attention.
@see *channel bomb:* _*kevin* send a giant *channel bomb* right now_
"""
# IF ALL CHECKS PASS SEND JOB TO DB
if 'text' in data:
text = data['... | 46,181 |
def split_quoted(s):
"""Split a string with quotes, some possibly escaped, into a list of
alternating quoted and unquoted segments. Raises a ValueError if there are
unmatched quotes.
Both the first and last entry are unquoted, but might be empty, and
therefore the length of the resulting list must... | 46,182 |
def calc_IOU(seg_omg1: torch.BoolTensor, seg_omg2: torch.BoolTensor, eps: float = 1.e-6) -> float:
"""
calculate intersection over union between 2 boolean segmentation masks
:param seg_omg1: first segmentation mask
:param seg_omg2: second segmentation mask
:param eps: eps for numerical stability
... | 46,183 |
def _call_list(urls, method, payload=None, headers=None, auth=None,
proxies=None, timeout=None, stream=None, verify=True,
payload_to_json=True, allow_redirects=True):
"""Call list of supplied URLs, return on first success."""
_LOGGER.debug('Call %s on %r', method, urls)
attempt... | 46,184 |
def td_path_join(*argv):
"""Construct TD path from args."""
assert len(argv) >= 2, "Requires at least 2 tdpath arguments"
return "/".join([str(arg_) for arg_ in argv]) | 46,185 |
def calculate_segmentation_statistics(outputs: torch.Tensor, targets: torch.Tensor, class_dim: int = 1, threshold=None):
"""Compute calculate segmentation statistics.
Args:
outputs: torch.Tensor.
targets: torch.Tensor.
threshold: threshold for binarization of predictions.
class_... | 46,186 |
def sample_from_cov(mean_list, cov_list, Nsamples):
"""
Sample from the multivariate Gaussian of Gaia astrometric data.
Args:
mean_list (list): A list of arrays of astrometric data.
[ra, dec, plx, pmra, pmdec]
cov_list (array): A list of all the uncertainties and covariances:
... | 46,187 |
def get_finger_distal_angle(x,m):
"""Gets the finger angle th3 from a hybrid state"""
return x[2] | 46,188 |
def get_karma(**kwargs):
"""Get your current karma score"""
user_id = kwargs.get("user_id").strip("<>@")
session = db_session.create_session()
kama_user = session.query(KarmaUser).get(user_id)
try:
if not kama_user:
return "User not found"
if kama_user.karma_points == ... | 46,189 |
def medical_charges_nominal(dataset_dir: Path) -> bool:
"""
medical_charges_nominal x train dataset (130452, 11)
medical_charges_nominal y train dataset (130452, 1)
medical_charges_nominal x test dataset (32613, 11)
medical_charges_nominal y train dataset (32613, 1)
"""
dataset_name = 'me... | 46,190 |
def plotly_shap_violin_plot(X, shap_values, col_name, color_col=None, points=False, interaction=False):
"""
Returns a violin plot for categorical values.
if points=True or color_col is not None, a scatterplot of points is plotted next to the violin plots.
If color_col is given, scatter is colored... | 46,191 |
def animation():
"""
This function gives access to the animation tools factory - allowing you
to access all the tools available.
Note: This will not re-instance the factory on each call, the factory
is instanced only on the first called and cached thereafter.
:return: factories.Factor... | 46,192 |
def platonic_solids(basedir=".\\"):
"""
@MoneyShot
Draws out an Icosahedron and Dodecahedron.
args:
basedir:The directory where the images are to be saved.
In the main pyray repo, basedir is ..\\images\\RotatingCube\\
"""
for i in range(0, 31):
im = Image.new("RGB", (... | 46,193 |
def sync_pip_libraries():
"""
This task is used by Celery beat in order to periodically
schedule available PIP libraries synchronization.
"""
schedule_sync() | 46,194 |
def merge(pinyin_d_list):
"""
:rtype: dict
"""
final_d = {}
for overwrite_d in pinyin_d_list:
final_d.update(overwrite_d)
return final_d | 46,195 |
def HttpPostRequest(url, post_dict):
"""Proceed an HTTP POST request, and returns an HTTP response body.
Args:
url: a URL string of an HTTP server.
post_dict: a dictionary of a body to be posted.
Returns:
a response from the server.
"""
body = urlencode(post_dict)
cmd = [GOMA_FETCH, '--noauth'... | 46,196 |
def nn_avg_pool2d(expr: Expr,
params: Dict[str, np.ndarray],
schedule: Schedule,
net: Dict[Expr, Expr],
op_idx: Dict[str, int],
RELAY_2_XLAYER: Dict[str, Callable],
**kwargs) -> XLayer:
"""
TVM Avg Pool2d... | 46,197 |
def load(*args):
"""Load one or more environment modules
Raises an exception if the module cannot be loaded.
"""
for arg in args:
if arg:
print("Loading environment module: %s" % arg)
module('load',arg)
if arg not in loaded():
raise Exception... | 46,198 |
def dprnn_tasnet(name_url_or_file=None, *args, **kwargs):
""" Load (pretrained) DPRNNTasNet model
Args:
name_url_or_file (str): Model name (we'll find the URL),
model URL to download model, path to model file.
If None (default), DPRNNTasNet is instantiated but no pretrained
... | 46,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.