content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from . import graphics
def merge_all_mods(list_of_mods, gfx=None):
"""Merges the specified list of mods, starting with graphics if set to
pre-merge (or if a pack is specified explicitly).
Params:
list_of_mods
a list of the names of mods to merge
gfx
a graphics pack... | c0b6ed6df7116a0abcb0c2674c8bddabd4a52f82 | 3,650,600 |
def pearson_r_p_value(a, b, dim):
"""
2-tailed p-value associated with pearson's correlation coefficient.
Parameters
----------
a : Dataset, DataArray, GroupBy, Variable, numpy/dask arrays or scalars
Mix of labeled and/or unlabeled arrays to which to apply the function.
b : Dataset, Dat... | d9236eaf1d7315fd61eba35bdd4cdc4f27cb9890 | 3,650,601 |
from datetime import datetime
import time
def get_ceilometer_usages(date, connection_string):
"""
Function which talks with openstack
"""
today = datetime.datetime.combine(date, datetime.datetime.min.time())
yesterday = today - datetime.timedelta(days=1)
engine = create_engine(connection_stri... | b05e7f2024ebf2e2eb23a914da71b834debb66cc | 3,650,602 |
def fit_kij(kij_bounds, eos, mix, datavle=None, datalle=None, datavlle=None,
weights_vle=[1., 1.], weights_lle=[1., 1.],
weights_vlle=[1., 1., 1., 1.], minimize_options={}):
"""
fit_kij: attemps to fit kij to VLE, LLE, VLLE
Parameters
----------
kij_bounds : tuple
bo... | 0f2e05a64599b49f70b327e8a69a66647b4c344f | 3,650,603 |
import os
def pickle_photospheres(photosphere_filenames, kind, meta=None):
"""
Load all model photospheres, parse the points and photospheric structures.
"""
if meta is None:
meta = {
"kind": kind,
"source_directory": os.path.dirname(photosphere_filenames[0])
}... | 5c8417899766e2f450cafaad142d9ceb55a9dd29 | 3,650,604 |
import os
import platform
def get_pid_and_server():
"""Find process id and name of server the analysis is running on
Use the platform.uname to find servername instead of os.uname because the latter is not supported on Windows.
"""
pid = os.getpid()
server = platform.uname().node
return f"{pid... | 433d1493674e2355554d9bc6e189658e155560de | 3,650,605 |
def calc_ac_score(labels_true, labels_pred):
"""calculate unsupervised accuracy score
Parameters
----------
labels_true: labels from ground truth
labels_pred: labels form clustering
Return
-------
ac: accuracy score
"""
nclass = len(np.unique(labels_true))
labels_size =... | 39ca30d3cdcf683dda04d429146775cffd7c0134 | 3,650,606 |
def wave_ode_gamma_neq0(t, X, *f_args):
"""
Right hand side of the wave equation ODE when gamma > 0
"""
C = f_args[0]
D = f_args[1]
CD = C*D
x, y, z = X
return np.array([-(1./(1.+y) + CD)*x + C*(1+D*CD)*(z-y), x, CD*(z-y)]) | 4b2f5f7b5b4e1c932e0758e9be10fcbc5d9fbbb7 | 3,650,607 |
from typing import Dict
def run_workflow(
config: Dict,
form_data: ImmutableMultiDict,
*args,
**kwargs
) -> Dict:
"""Executes workflow and save info to database; returns unique run id."""
# Validate data and prepare run environment
form_data_dict = __immutable_multi_dict_to_nested_dict(
... | bfa732ceaef6fbd6865e015b9c28da68932fa2db | 3,650,608 |
from typing import List
def insertion_stack(nums: List[int]) -> List[int]:
""" A helper function that sort the data in an ascending order
Args:
nums: The original data
Returns:
a sorted list in ascending order
"""
left = []
right = []
for num in nums:
while left and le... | 045e28d763ece3dac9e1f60d50a0d51c43b75664 | 3,650,609 |
def svn_wc_get_pristine_contents(*args):
"""svn_wc_get_pristine_contents(char const * path, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t"""
return _wc.svn_wc_get_pristine_contents(*args) | 5a26e358bbd2a4341bdb1c572f98d419f676a725 | 3,650,610 |
import os
def _FindAllPossibleBrowsers(finder_options, android_platform):
"""Testable version of FindAllAvailableBrowsers."""
if not android_platform:
return []
possible_browsers = []
if finder_options.webview_embedder_apk and not os.path.exists(
finder_options.webview_embedder_apk):
raise exce... | 50b3be887e940bb3f313d18348969dac49732dd8 | 3,650,611 |
import os
import yaml
def getLanguageSpecification(lang):
"""
Return a dictionary which contains the specification of a language.
Specifically, return the key-value pairs defined in the 'lang.yaml' file as
a dictionary, i.e. for the language cpp return the contents of
'plugins/cpp/lang.yaml'.
... | 65954b85cb88b998053141c60b7c184916163b84 | 3,650,612 |
import os
def _is_valid_file(file):
"""Returns whether a file is valid.
This means that it is a file and not a directory, but also that
it isn't an unnecessary dummy file like `.DS_Store` on MacOS.
"""
if os.path.isfile(file):
if not file.startswith('.git') and file not in ['.DS_Store']:
... | 48f3b2171b6aa2acb93cbcab6eba74f0772fe888 | 3,650,613 |
def create_cache_key(func, key_dict=None, self=None):
"""Get a cache namespace and key used by the beaker_cache decorator.
Example::
from tg import cache
from tg.caching import create_cache_key
namespace, key = create_cache_key(MyController.some_method)
cache.get_cache(namespace... | 461fc998a7345d646fdaa61fd36f91c3c250d331 | 3,650,614 |
def longest_common_substring(s, t):
"""
Find the longest common substring between the given two strings
:param s: source string
:type s: str
:param t: target string
:type t: str
:return: the length of the longest common substring
:rtype: int
"""
if s == '' or t == '':
r... | 66aef17a117c6cc96205664f4c603594ca496092 | 3,650,615 |
def correct_predictions(output_probabilities, targets):
"""
Compute the number of predictions that match some target classes in the
output of a model.
Args:
output_probabilities: A tensor of probabilities for different output
classes.
targets: The indices of the actual targe... | 1bff085d95da7b37bb2232b6ac03b034e2bdb6b9 | 3,650,616 |
def resolve_all(anno, task):
"""Resolve all pending annotations."""
return (x for x in (_first_match(anno, task), _first_match_any(anno)) if x) | ca127999972644ad25741bc48c78d67aaa4adeec | 3,650,617 |
import socket
def get_free_port():
""" Find and returns free port number. """
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(("", 0))
free_port = soc.getsockname()[1]
soc.close()
return free_port | d1a514a47a906c946fa3a8cb4312e71bc4f7570e | 3,650,618 |
def get_diff_list(small_list, big_list):
"""
Get the difference set of the two list.
:param small_list: The small data list.
:param big_list: The bigger data list.
:return: diff_list: The difference set list of the two list.
"""
# big_list有而small_list没有的元素
diff_list = list(set(big_list).... | f92d20e6edd1f11ca6436a3ada4a6ba71da37457 | 3,650,619 |
def blend_weight_arrays(n_weightsA, n_weightsB, value=1.0, weights_pp=None):
"""
Blend two 2d weight arrays with a global mult factor, and per point weight values.
The incoming weights_pp should be a 1d array, as it's reshaped for the number of influences.
Args:
n_weightsA (np.array): Weight ar... | f5167730773718952f48a67970d62a197bd92944 | 3,650,620 |
def weight_kabsch_dist(x1, x2, weights):
"""
Compute the Mahalabonis distance between positions x1 and x2 given Kabsch weights (inverse variance)
x1 (required) : float64 array with dimensions (n_atoms,3) of one molecular configuration
x2 (required) : float64 a... | e03c86875873af3b890fc3cfa799f037c808196e | 3,650,621 |
def calc_color_rarity(color_frequencies: dict) -> float:
"""
Return rarity value normalized to 64.
Value ascending from 0 (most rare) to 64 (most common).
"""
percentages = calc_pixel_percentages(color_frequencies)
weighted_rarity = [PERCENTAGES_NORMALIZED.get(k) * v * 64 for k,v in percentages.... | 54dd3dde36dc02101b5536630e79d3d39fe18aa8 | 3,650,622 |
def exp_map(x, r, tangent_point=None):
"""
Let \(\mathcal{M}\) be a CCM of radius `r`, and \(T_{p}\mathcal{M}\) the
tangent plane of the CCM at point \(p\) (`tangent_point`).
This function maps a point `x` on the tangent plane to the CCM, using the
Riemannian exponential map.
:param x: np.array,... | 2544e6f6054c602d5eae438b405b55dc995d190a | 3,650,623 |
import sys
def get_python_msvcrt_version():
"""Return the Visual C runtime version Python is linked to, as an int"""
python_version = sys.version_info[0:2]
if python_version < (2.4):
return 60
if python_version < (2.6):
return 71
return 90 | dcedf8bdfafd21087c8ef60aa2a2ecd0593c453d | 3,650,624 |
def _get_data_column_label_in_name(item_name):
"""
:param item_name: Name of a group or dataset
:return: Data column label or ``None``
:rtype: str on None
"""
# /1.1/measurement/mca_0 should not be interpreted as the label of a
# data column (let's hope no-one ever uses mca_0 as a label)
... | 58a50f9b28a8dd3c30eb609bbf61eeaf1b821238 | 3,650,625 |
def _auto_backward(loss,
startup_program=None,
parameter_list=None,
no_grad_set=None,
callbacks=None,
distop_context=None):
"""
modification is inplaced
"""
act_no_grad_set = _get_no_grad_set(loss, no_grad_set... | f7c08e9677768faf125ccc2a273016312004c225 | 3,650,626 |
import re
def strip_from_ansi_esc_sequences(text):
"""
find ANSI escape sequences in text and remove them
:param text: str
:return: list, should be passed to ListBox
"""
# esc[ + values + control character
# h, l, p commands are complicated, let's ignore them
seq_regex = r"\x1b\[[0-9;... | 8597654defffbdde33b844a34e95bf7893a36855 | 3,650,627 |
def _concat_columns(args: list):
"""Dispatch function to concatenate DataFrames with axis=1"""
if len(args) == 1:
return args[0]
else:
_lib = cudf if HAS_GPU and isinstance(args[0], cudf.DataFrame) else pd
return _lib.concat(
[a.reset_index(drop=True) for a in args],
... | e60a3d5120e50dbd2d1be5632042e702e5780bc6 | 3,650,628 |
import re
def applyRegexToList(list, regex, separator=' '):
"""Apply a list of regex to list and return result"""
if type(regex) != type(list):
regex = [regex]
regexList = [re.compile(r) for r in regex]
for r in regexList:
list = [l for l in list if r.match(l)]
list = [l.split(separator) for l in... | eee1edebf361f9516e7b40ba793b0d13ea3070f3 | 3,650,629 |
import os
def pathsplit(path):
""" This version, in contrast to the original version, permits trailing
slashes in the pathname (in the event that it is a directory).
It also uses no recursion """
return path.split(os.path.sep) | 1a89994c8ee9bb1b9ef2b9c90575ea2b0ab21c50 | 3,650,630 |
def GetFileName(path: str) -> str:
"""Get the name of the file from the path
:type path: str
:rtype: str
"""
return splitext(basename(path))[0] | 4aa3a8b75a1ed926c173f9d978504ca2ed653e20 | 3,650,631 |
import re
from functools import reduce
def collapse(individual_refs):
"""Collapse references like [C1,C2,C3,C7,C10,C11,C12,C13] into 'C1-C3, C7, C10-C13'.
Args:
individual_refs (string): Uncollapsed references.
Returns:
string: Collapsed references.
"""
parts = []
for ref in... | f4225586d30960cae74123806b8d44ff6f007584 | 3,650,632 |
import os
def get_parent_directory(path):
"""
Get parent directory of the path
"""
return os.path.abspath(os.path.join(path, os.pardir)) | a46ecb9f370076ec975a1823d04b7f2efb0d564d | 3,650,633 |
def generate_fig_univariate_categorical(
df_all: pd.DataFrame,
col: str,
hue: str,
nb_cat_max: int = 7,
) -> plt.Figure:
"""
Returns a matplotlib figure containing the distribution of a categorical feature.
If the feature is categorical and contains too many categories, the ... | 9e6f9b8739b1907f67c864ceaf177f9f1007d35b | 3,650,634 |
def pt_sharp(x, Ps, Ts, window_half, method='diff'):
"""
Calculate the sharpness of extrema
Parameters
----------
x : array-like 1d
voltage time series
Ps : array-like 1d
time points of oscillatory peaks
Ts : array-like 1d
time points of oscillatory troughs
w... | 6d06b9343c71115fc660a298569794933267bd51 | 3,650,635 |
def associate_by_email(strategy, details, user=None, *args, **kwargs):
"""Deny duplicate email addresses for new users except in specific cases
If the incoming email is associated with existing user, authentication
is denied. Exceptions are:
* the existing user does not have associated social login
... | 53eb25acac22317e697b8a3e1e8f0633502ba326 | 3,650,636 |
from datetime import datetime
def convert_date(string, report_date, bad_dates_rep, bad_dates_for):
"""
Converts date string in format dd/mm/yyyy
to format dd-Mmm-yyyy
"""
x = string.split('/')
try:
date = datetime.datetime(int(x[2]),int(x[1]),int(x[0]))
date_str = date.strftime... | f84db7bc2edc070a4c6b9c475458081701bca1eb | 3,650,637 |
def render_raw(request, paste, data):
"""Renders RAW content."""
return HttpResponse(paste.content, content_type="text/plain") | 2ec6fdb719e831988a4384e3690d2bec0faad405 | 3,650,638 |
def node_avg():
"""get the avg of the node stats"""
node_raw = ["average", 0, 0, 0]
for node in node_stats():
node_raw[1] += float(node[1])
node_raw[2] += float(node[2])
node_raw[3] += float(node[3])
num = len(node_stats())
node_avg = ["average",
"{:.2f}".format(... | 985e1f848945d8952ec224a0dd56a02e84b2ea57 | 3,650,639 |
from typing import Union
def decrypt_vault_password(key: bytes, password: Union[str, bytes]) -> Union[str, bool]:
"""Decrypt and return the given vault password.
:param key: The key to be used during the decryption
:param password: The password to decrypt
"""
if isinstance(password, str):
... | 3311b6dc7a9fba4152545ff3ca89881e9ceebb94 | 3,650,640 |
from datetime import datetime
import os
def readData(op,filetype,config):
"""
Reads data from Hive or CSV
"""
try:
if filetype=='csv':
print('csv')
csvU=optimusCsvUtils(config)
hr=datetime.now().hour
today=str(datetime.now().date())
p... | 2bd0086c0ec137a296533ce062169279c565a82e | 3,650,641 |
from typing import Optional
def get_gv_rng_if_none(rng: Optional[rnd.Generator]) -> rnd.Generator:
"""get gym-gridverse module rng if input is None"""
return get_gv_rng() if rng is None else rng | 008bf9d22fb6c9f07816e62c2174c60839a5353f | 3,650,642 |
def fill_name(f):
"""
Attempts to generate an unique id and a parent from a BioPython SeqRecord.
Mutates the feature dictionary passed in as parameter.
"""
global UNIQUE
# Get the type
ftype = f['type']
# Get gene name
gene_name = first(f, "gene")
# Will attempt to fill in the... | d2351eb509d72b6b2ef34b7c0b01c339acd52677 | 3,650,643 |
def run_single_softmax_experiment(beta, alpha):
"""Run experiment with agent using softmax update rule."""
print('Running a contextual bandit experiment')
cb = ContextualBandit()
ca = ContextualAgent(cb, beta=beta, alpha=alpha)
trials = 360
for _ in range(trials):
ca.run()
df = Data... | 953c07ae1cdc25782f24206a0ce02bf4fc15202b | 3,650,644 |
def available(name):
"""
Returns ``True`` if the specified service is available, otherwise returns
``False``.
We look up the name with the svcs command to get back the FMRI
This allows users to use simpler service names
CLI Example:
.. code-block:: bash
salt '*' service.available... | 371980f44a348faf83ab32b9d50583fc8e9bae41 | 3,650,645 |
def coincidence_rate(text):
""" Return the coincidence rate of the given text
Args:
text (string): the text to get measured
Returns:
the coincidence rate
"""
ko = 0
# measure the frequency of each letter in the cipher text
for letter in _VOCAB:
count = text.count(letter)
ko = ko + (count *... | ca1ca3d8b746ea40ba07af1cb96a194bf14c1d98 | 3,650,646 |
import numpy
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
dt = numpy.dtype('>i' + str(num)... | 38b97fb9d5ecc5b55caf7c9409e4ab4a406a21d7 | 3,650,647 |
def search_spec(spec, search_key, recurse_key):
"""
Recursively scans spec structure and returns a list of values
keyed with 'search_key' or and empty list. Assumes values
are either list or str.
"""
value = []
if search_key in spec and spec[search_key]:
if isinstance(spec[search_ke... | 9d89aacc200e205b0e6cbe49592abfd37158836a | 3,650,648 |
import test
def before_class(home=None, **kwargs):
"""Like @test but indicates this should run before other class methods.
All of the arguments sent to @test work with this decorator as well.
"""
kwargs.update({'run_before_class':True})
return test(home=home, **kwargs) | 3b36e448ec76a2c513a1f87dd29b8027b0693780 | 3,650,649 |
import os
import time
import csv
def get_airports(force_download=False):
"""
Gets or downloads the airports.csv in ~/.config/mss and returns all airports within
"""
global _airports, _airports_mtime
file_exists = os.path.exists(os.path.join(MSS_CONFIG_PATH, "airports.csv"))
if _airports and f... | 345532e2eeef226c6f1883ea234ed3ede03323a2 | 3,650,650 |
import math
def hellinger_distance_poisson_variants(a_means, b_means, n_samples, sample_distances):
"""
a - The coverage vec for a variant over n_samples
b - The coverage vec for a variant over n_samples
returns average hellinger distance of multiple poisson distributions
"""
# generate dist... | 555365ea295ef2ff1e18e5c26b6b56b1c939035a | 3,650,651 |
def min_threshold(x, thresh, fallback):
"""Returns x or `fallback` if it doesn't meet the threshold. Note, if you want to turn a hyper "off" below,
set it to "outside the threshold", rather than 0.
"""
return x if (x and x > thresh) else fallback | e92c17aafb8a7c102152d9f31d0a317b285a0ae6 | 3,650,652 |
def get_command(command, meta):
"""Construct the command."""
bits = []
# command to run
bits.append(command)
# connection params
bits.extend(connect_bits(meta))
# database name
if command == 'mysqladmin':
# these commands shouldn't take a database name
return bits
if ... | 0c80072fa70e7943bb7693ad5eb2d24d7078b1cc | 3,650,653 |
def get_common_count(list1, list2):
"""
Get count of common between two lists
:param list1: list
:param list2: list
:return: number
"""
return len(list(set(list1).intersection(list2))) | c149b49e36e81237b775b0de0f19153b5bcf2f99 | 3,650,654 |
def text_present(nbwidget, text="Test"):
"""Check if a text is present in the notebook."""
if WEBENGINE:
def callback(data):
global html
html = data
nbwidget.dom.toHtml(callback)
try:
return text in html
except NameError:
return Fal... | f61f90c6fbbe5251c4839cc3ef82ed1298640345 | 3,650,655 |
def multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams=defaultXtraParams):
"""multiFilm(layers, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams={})... | ae586a6860ece7e21f46e221398a462619d16acd | 3,650,656 |
def value_iteration(R, P, gamma, epsilon=1e-6):
"""
Value iteration for discounted problems.
Parameters
----------
R : numpy.ndarray
array of shape (S, A) contaning the rewards, where S is the number
of states and A is the number of actions
P : numpy.ndarray
array of sha... | 4f8286d7519577f77f86b239c14e948eed513a6a | 3,650,657 |
def mock_api_response(response_config={}):
"""Create a mock response from the Github API."""
headers = {
'ETag': 'W/"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"',
'Cache-Control': 'public, max-age=60, s-maxage=60',
'Content-Type': 'application/json; charset=utf-8'
}
api_response = MagicMoc... | f79af84cb51ffa063c1db2b70dce99ae61da871a | 3,650,658 |
from os import listdir
def files_with_extension(path: str,extension: str):
"""
Gives a list of the files in the given directory that have the given extension
Parameters
----------
path: str
The full path to the folder where the files are stored
extension: str
The extension... | 18d06303e9b2a734f5fe801847908e2e21b48eae | 3,650,659 |
import argparse
import getpass
def get_inputs_repl_cluster_or_vol():
"""
This input is for clusters that have replication
"""
parser = argparse.ArgumentParser()
parser.add_argument('-m', type=str,
required=True,
metavar='mvip',
... | 0723fabb4c55d85471fbbfa9f5a300ca9b35ac61 | 3,650,660 |
import tqdm
import json
def load_jsonl(file_path):
""" Load file.jsonl ."""
data_list = []
with open(file_path, mode='r', encoding='utf-8') as fi:
for idx, line in enumerate(tqdm(fi)):
jsonl = json.loads(line)
data_list.append(jsonl)
return data_list | 58bd0dbfa59d08036aa83e62aab47acd2c40ba6e | 3,650,661 |
from io import StringIO
from datetime import datetime
def aurora_forecast():
"""
Get the latest Aurora Forecast from http://swpc.noaa.gov.
Returns
-------
img : numpy array
The pixels of the image in a numpy array.
img_proj : cartopy CRS
The rectangular coordinate system of th... | 04ee88aee75f7ac86063c9a57f4e5155378f9085 | 3,650,662 |
def get_number_trips(grouped_counts):
"""
Gets the frequency of number of trips the customers make
Args:
grouped_counts (Pandas.DataFrame): The grouped dataframe returned from
a get_trips method call
Returns:
Pandas.DataFrame: the dataframe co... | 4045f10e95fe597e626883c586cc832aa34157c3 | 3,650,663 |
import re
def process_text(text, max_features=200, stopwords=None):
"""Splits a long text into words, eliminates the stopwords and returns
(words, counts) which is necessary for make_wordcloud().
Parameters
----------
text : string
The text to be processed.
max_features : number ... | 531c8eea539136701289eea5cd462476ba7fefac | 3,650,664 |
def update_graph_map(n):
"""Update the graph rail network mapbox map.
Returns:
go.Figure: Scattermapbox of rail network graph
"""
return get_graph_map() | 826b12616e9c08b05cecef8d44017a1599ed8f98 | 3,650,665 |
def get_party_leads_sql_string_for_state(party_id, state_id):
"""
:type party_id: integer
"""
str = """ select
lr.candidate_id,
c.fullname as winning_candidate,
lr.constituency_id,
cons.name as constituency,
lr.party_id,
lr.max_votes,
(lr.max_votes-sr.votes) ... | de1e200cf8651626fff04c2011b3ada12b8b08a7 | 3,650,666 |
import requests
import json
import math
import time
def goods_images(goods_url):
"""
获得商品晒图
Parameters:
goods_url - str 商品链接
Returns:
image_urls - list 图片链接
"""
image_urls = []
productId = goods_url.split('/')[-1].split('.')[0]
# 评论url
comment_url = 'https://sclub.jd.com/comment/productPageComments.acti... | 8ed59e295ebd08788f0083be9941ecd8b09f1d84 | 3,650,667 |
def delete_index_list(base_list, index_list):
"""
根据index_list删除base_list中指定元素
:param base_list:
:param index_list:
:return:
"""
if base_list and index_list:
return [base_list[i] for i in range(len(base_list)) if (i not in index_list)] | 0dd8960d0efc168df42cabb92147f078da362e5e | 3,650,668 |
def not_found():
"""Page not found."""
return make_response(
render_template("404.html"),
404
) | 3bc56677f760937f1767e0465e4dbd0a11eb41d0 | 3,650,669 |
def _traverseAgg(e, visitor=lambda n, v: None):
"""
Traverse a parse-tree, visit each node
if visit functions return a value, replace current node
"""
res = []
if isinstance(e, (list, ParseResults, tuple)):
res = [_traverseAgg(x, visitor) for x in e]
elif isinstance(e, CompValue)... | c436dbb548c6a1b7bc6ddc8ea8770cb953e76a72 | 3,650,670 |
def roll(image, delta):
"""Roll an image sideways
(A more detailed explanation goes here.)
"""
xsize, ysize = image.size
delta = delta % xsize
if delta == 0:
print("the delta was 0!")
return image
part1 = image.crop((0, 0, delta, ysize))
part2 = image.crop((delta... | b9ccd9659eedfefa5002f064a23c768d36dfdc0a | 3,650,671 |
def make_long_format(path_list, args):
"""Output list of strings in informative line-by-line format like ls -l
Args:
path_list (list of (str, zipfile.Zipinfo)): tuples, one per file
component of zipfile, with relative file path and zipinfo
args (argparse.Namespace): user arguments to... | 68a30c16409c98e92a31b21a911cbca7ca9ef7c4 | 3,650,672 |
import unicodedata
import re
def is_name_a_title(name, content):
"""Determine whether the name property represents an explicit title.
Typically when parsing an h-entry, we check whether p-name ==
e-content (value). If they are non-equal, then p-name likely
represents a title.
However, occasional... | 2a8d3191920fba0d92670a3d520bfdf6836dbe69 | 3,650,673 |
from datetime import datetime
import traceback
def insertTweet(details, insertDuplicates=True):
""" Adds tweet to database
@param details {Dict} contains tweet details
@param insertDuplicates {Boolean} optional, if true it
will insert even if alread... | e11aba2fecd3d2e0a8f21f25ea1f920512949bdc | 3,650,674 |
import os
import yaml
def dump_yaml(file_path, data):
"""Dump data to a file.
:param file_path: File path to dump data to
:type file_path: String
:param data: Dictionary|List data to dump
:type data: Dictionary|List
"""
with open(os.path.abspath(os.path.expanduser(file_path)), "w") as f:... | f1210295f5f947c51df6ef80fc479723e157a84c | 3,650,675 |
from typing import OrderedDict
def return_embeddings(embedding: str, vocabulary_size: int, embedding_dim: int,
worddicts: OrderedDict) -> np.ndarray:
"""Create array of word embeddings."""
word_embeddings = np.zeros((vocabulary_size, dim_word))
with open(embedding, 'r') as f:
... | 86379e2cc9c343733464bea207dc3f41b4dd7601 | 3,650,676 |
import sympy
def symLink(twist, dist, angle, offset):
"""
Transform matrix of this link with DH parameters.
(Use symbols)
"""
twist = twist * sympy.pi / 180
T1 = sympy.Matrix([
[1, 0, 0, dist],
[0, sympy.cos(twist), -sympy.sin(twist), 0],
[0, sympy.sin(twist), sympy.co... | a6e2ac09866f2b54ffb33da681ba9d19e74e57f0 | 3,650,677 |
import aiohttp
from typing import Tuple
from typing import Dict
from typing import Any
from typing import Sequence
async def _parse_action_body(service: UpnpServerService, request: aiohttp.web.Request) -> Tuple[str, Dict[str, Any]]:
"""Parse action body."""
# Parse call.
soap = request.headers.get("SOAPAc... | d5f390d956d726ffca0d37891815b8ccf488a826 | 3,650,678 |
import json
def get_tc_json():
"""Get the json for this testcase."""
try:
with open(GLOBAL_INPUT_JSON_PATH) as json_file:
tc = json.load(json_file)
except Exception:
return_error('Could not custom_validator_input.json')
return tc | de19278f5edb415d40e383d2ad08dfc6e968cb81 | 3,650,679 |
def dualgauss(x, x1, x2, w1, w2, a1, a2, c=0):
"""
Sum of two Gaussian distributions. For curve fitting.
Parameters
----------
x: np.array
Axis
x1: float
Center of 1st Gaussian curve
x2: float
Center of 2nd Gaussian curve
w1: float
... | d60d63ad0776aa6d5babfe5e963503f18dca0c3e | 3,650,680 |
def pdg_format3( value , error1 , error2 , error3 , latex = False , mode = 'total' ) :
"""Round value/error accoridng to PDG prescription and format it for print
@see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf
@see section 5.3 of doi:10.1088/0954-3899/33/1/001
Quote:
The b... | 9d75007e19d60caac14a2a830800e7db215c0de6 | 3,650,681 |
from datetime import datetime
def getChinaHoliday(t):
"""找出距离输入日期最近的中国节日,输出距离的天数"""
date_time = datetime.datetime.strptime(t, '%d %B %Y')
y = date_time.year
# 中国阳历节日
sh = [
(y, 1, 1), # 元旦
(y, 4, 5), # 清明
(y, 5, 1), # 五一劳动节
(y, 10, 1) # 国庆节
... | bc9520f56135d86cf196bfe30bde0ea645377f45 | 3,650,682 |
def parse_mimetype(mimetype):
"""Parses a MIME type into its components.
:param str mimetype: MIME type
:returns: 4 element tuple for MIME type, subtype, suffix and parameters
:rtype: tuple
Example:
>>> parse_mimetype('text/html; charset=utf-8')
('text', 'html', '', {'charset': 'utf-8'})... | a9abfde73528e6f76cca633efe3d4c881dccef82 | 3,650,683 |
def terraform_state_bucket(config):
"""Get the bucket name to be used for the remote Terraform state
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
string: The bucket name to be used for the remote Terraform state
"""
# If a bucket name is specified for ... | 443ae393896d180f3e419db7a6b7e346dca0655c | 3,650,684 |
def get_binary_matrix(gene_expr, libraries):
"""
Get binary matrix with genes as rows and pathways as columns.
If a gene is found in a given pathway, it is given a value of
1. Else, 0. Only the list of genes in common between that found
in the gene set libraries and the current dataset are used.
... | 53f39909efc1dfb083cba734a01f77d181f4c36c | 3,650,685 |
def get_tip_downvotes(tips_id):
"""
GET function for retrieving all User objects that have downvoted a tip
"""
tip = Tips.objects.get(id=tips_id)
tips_downvotes = (tip.to_mongo())["downvotes"]
tips_downvotes_list = [
User.objects.get(id=str(user)).to_mongo() for user in tips_downvotes
... | b528be2bd74169a4baff14ecb473ef12d8554be9 | 3,650,686 |
from typing import List
from typing import Dict
def get_placements(
big_graph: nx.Graph, small_graph: nx.Graph, max_placements=100_000
) -> List[Dict]:
"""Get 'placements' mapping small_graph nodes onto those of `big_graph`.
This function considers monomorphisms with a restriction: we restrict only to un... | fad71c888639ba29c0b0d2d61ddeff2a2c1d8653 | 3,650,687 |
import subprocess
def make_static_server_url_stop(root, host=HOST, port=PORT):
"""start a tornado static file server"""
server_args = [
"python",
str(PA11Y / "serve.py"),
f"--host={host}",
f"--port={port}",
f"--path={root}",
]
url = f"http://{host}:{port}/"
... | 9c6e465467b283d8bb27b7308e6271e728c9f491 | 3,650,688 |
import requests
import urllib
import http
def request_url(url):
"""
get the resource associated with a url.
"""
try:
# -- todo; eliminate pesky assignment so can be put into chain of Ok then's.
user_agent = 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.3... | 0d7df45e038c65b8b2760bd0304c242d4af294c5 | 3,650,689 |
import inspect
import six
def _filter_baseanalysis_kwargs(function, kwargs):
"""
create two dictionaries with kwargs separated for function and AnalysisBase
Parameters
----------
function : callable
function to be called
kwargs : dict
keyword argument dictionary
Returns
... | a674c640618ebba3d2c29fec0458773344c84be6 | 3,650,690 |
def torch_to_flax(torch_params, get_flax_keys):
"""Convert PyTorch parameters to nested dictionaries"""
def add_to_params(params_dict, nested_keys, param, is_conv=False):
if len(nested_keys) == 1:
key, = nested_keys
params_dict[key] = np.transpose(param, (2, 3, 1, 0)) if is_conv else np.transpose(p... | fd87617e3e0db491ff313218883961a1c2aa9d0f | 3,650,691 |
from typing import Union
from pathlib import Path
from typing import Optional
def subset_shape(
ds: Union[xarray.DataArray, xarray.Dataset],
shape: Union[str, Path, gpd.GeoDataFrame],
raster_crs: Optional[Union[str, int]] = None,
shape_crs: Optional[Union[str, int]] = None,
buffer: Optional[Union[... | 2d751cd4a9300645cb9bc7b1b353dc29da388f96 | 3,650,692 |
def plot_record_static(
record,
save=True,
scale=1000,
select_kw={},
x_prop='wavenumber',
**kwargs
):
"""Figure of Static data from a record.
High level function.
record: Record to get data from
save: Boolean, Save figure
scale: Scale y axis.
sel... | 4a25068f7df9450870af81fb2507f6262db61b42 | 3,650,693 |
def logmelspectrogram(wave: np.ndarray, conf: ConfMelspec) -> np.ndarray:
"""Convert a waveform to a scaled mel-frequency log-amplitude spectrogram.
Args:
wave::ndarray[Time,] - waveform
conf - Configuration
Returns::(Time, Mel_freq) - mel-frequency log(Bel)-amplitude spectrogram
"""
... | d4849092495b097b8efb292826eb020c8775157c | 3,650,694 |
def get_trainer_config(env_config, train_policies, num_workers=9, framework="tf2"):
"""Build configuration for 1 run."""
# trainer config
config = {
"env": env_name, "env_config": env_config, "num_workers": num_workers,
# "multiagent": {"policy_mapping_fn": lambda x: x, "policies": policies... | 4452d0e037b4bc49a5b027d4f0f6dd2993eceac2 | 3,650,695 |
def SamAng(Tth,Gangls,Sangl,IFCoup):
"""Compute sample orientation angles vs laboratory coord. system
:param Tth: Signed theta
:param Gangls: Sample goniometer angles phi,chi,omega,azmuth
:param Sangl: Sample angle zeros om-0, chi-0, phi-0
... | 7b7efb995e9a3a2c659e5392c5c2b5b836b2750f | 3,650,696 |
def debye_C_V(T,thetaD,natoms):
"""
Returns the heat capacity at constant volume, C_V, of the Debeye model at a
given temperature, T, in meV/atom/K.
"""
C_V = 4*debye_func(thetaD/T)-3*(thetaD/T)/(sp.exp(thetaD/T)-1.)
C_V = 3*natoms*BOLTZCONST*C_V
return C_V | 08e708f9c9ce16ed5c54e6f1bc920dd4be81e31e | 3,650,697 |
def setup(clip=True, flip=True):
"""
Project specific data import and setup function
:param clip: bool - use clipping
:param flip: bool - use flipping
:return: data as pandas dataframe, List[LAICPMSData obj]
"""
# calibration
# Zn: y = 0.0395 kcps/(µg/g)* x + 1.308 kcps
# use invers... | 2f62f124512daff76b59e3e93a2b50de6d5ca0be | 3,650,698 |
import array
def choi_to_kraus(q_oper):
"""
Takes a Choi matrix and returns a list of Kraus operators.
TODO: Create a new class structure for quantum channels, perhaps as a
strict sub-class of Qobj.
"""
vals, vecs = eig(q_oper.data.todense())
vecs = list(map(array, zip(*vecs)))
return ... | 850465f98442ce8c8fa329a293a9b519e4a7202e | 3,650,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.