content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def setParent(q=1,dt="string",m=1,top=1,u=1,ut="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/setParent.html
-----------------------------------------
setParent is undoable, queryable, and NOT editable.
This command changes the default parent to be the specified parent... | 47,900 |
def bmi_stats(merged_df, out=None, include_min=True, include_mean=True, include_max=True,
include_std=True, include_mean_diff=True,
include_count=True, age_range=[2, 20], include_missing=False):
"""
Computes summary statistics for BMI. Clean values are for BMIs computed when both the hei... | 47,901 |
def create_index(connection: psycopg2.extensions.connection, cursor: psycopg2.extensions.cursor):
"""Creates an hash index on the name column
Args:
connection (psycopg2.extensions.connection): [description]
cursor (psycopg2.extensions.cursor): [description]
"""
create_index_query = "CRE... | 47,902 |
async def system_health_info(hass):
"""Get info for the info page."""
remaining_requests = list(hass.data[DOMAIN].values())[0][
COORDINATOR
].accuweather.requests_remaining
return {
"can_reach_server": system_health.async_check_can_reach_url(hass, ENDPOINT),
"remaining_requests"... | 47,903 |
def predict_ankle_model(data):
"""Generate ankle model predictions for data.
Args:
data (dict): all data matrices/lists for a single subject.
Returns:
labels (dict): columns include 'probas' (from model) and 'true'
(ground truth). One row for each fold.
"""
RESULT_DIR ... | 47,904 |
def cholesky_decomp(A):
"""
Function: int gsl_linalg_cholesky_decomp (gsl_matrix * A)
This function factorizes the positive-definite square matrix A into
the Cholesky decomposition A = L L^T. On output the diagonal and
lower triangular part of the input matrix A contain the matrix L.
The upper ... | 47,905 |
def is_block_comment(line):
""" Entering/exiting a block comment """
line = line.strip()
if line == '"""' or (line.startswith('"""') and not line.endswith('"""')):
return True
if line == "'''" or (line.startswith("'''") and not line.endswith("'''")):
return True
return False | 47,906 |
def plot_covariances(Ca, Cb, ax, only_sds=False, corr_coefs=False):
""" scatter plot comparison for two covariance mats """
if corr_coefs:
sda = np.sqrt(np.diag(Ca))
sdb = np.sqrt(np.diag(Ca))
Ca = Ca / np.dot(sda[:,None], sda[None,:])
Cb = Cb / np.dot(sdb[:,None], sdb[None,:])
... | 47,907 |
def test_refit():
"""Regression test for bug in refitting
Simulates re-fitting a broken estimator; this used to break with
sparse SVMs.
"""
X = np.arange(100).reshape(10, 10)
y = np.array([0] * 5 + [1] * 5)
clf = GridSearchCV(BrokenClassifier(), [{'parameter': [0, 1]}],
... | 47,908 |
def generate_keras_segmentation_dual_transform(*layers):
"""Generates a `dual_transform` pipeline from Keras preprocessing layers.
This method takes in Keras preprocessing layers and generates a
transformation pipeline for the `dual_transform` argument in
*semantic segmentation* loaders, which applies ... | 47,909 |
def get_before_deploy_steps():
"""Get pre-deploy steps and their associated model aliases.
Get a map of configuration steps to model aliases. If there are
configuration steps which are not mapped to a model alias then these are
associated with the the DEFAULT_MODEL_ALIAS.
eg if test.yaml contained... | 47,910 |
def pre_ml_preprocessing(df, initial_to_drop, num_cols, target_var = None, num_cols_threshold = 0.9, low_var_threshold = 0.9):
"""Process data for machine learning preprocessing.
Low variance categorical features are high correlated numerical features are dropped from DataFrame. This process helps in dimension... | 47,911 |
def pool_status():
"""Fetch overall pool status."""
d = make_request('getpoolstatus')
return json.loads(d) | 47,912 |
def get_airtable_data(url: str, token: str) -> List[Dict[str, str]]:
"""
Fetch all data from airtable.
Returns a list of records where record is an array like
{'my-key': 'George W. Bush', 'my-value': 'Male'}
"""
response = requests.request("GET", url, headers={"Authorization": f"Bearer {tok... | 47,913 |
def displayname(user):
"""Returns the best display name for the user"""
return user.first_name or user.email | 47,914 |
def format_satoshis_plain(x, decimal_point = 8):
"""Display a satoshi amount scaled. Always uses a '.' as a decimal
point and has no thousands separator"""
scale_factor = pow(10, decimal_point)
return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.') | 47,915 |
def get_aps(dispatcher, apic, tenant):
"""Display Application Profiles configured in Cisco ACI."""
if not apic:
dispatcher.prompt_from_menu("aci get-aps", "Select APIC Cluster", apic_choices)
return False
try:
aci_obj = NautobotPluginChatopsAci(**aci_creds[apic])
except KeyError... | 47,916 |
def delete_dnt(id):
"""
Function deleting specific department by its id
:param id: id of the specific department an admin wants to delete
:return: redirects user to the departments page
"""
if session.get('user') and session.get('user')[0] == ADMIN:
data = f'?login={session["user"][0]}&p... | 47,917 |
def price(listing):
"""Score based on number of bedrooms."""
if listing.price is None:
return -4000
score = 0.0
bedrooms = 1.0 if listing.bedrooms is None else listing.bedrooms
if (bedrooms * 1000.0) > listing.price:
score += -1000 - ((bedrooms * 750.0) / listing.price - 1.0) * 1000
... | 47,918 |
def search_author(complete_name, cursor):
"""
Getting the id of a specific author
:param cursor: Cursor for executing SQL statement
:param name: Name and surname author to search
:return: The Id of the author
"""
try:
# Get the name and surname from name
author_name = complet... | 47,919 |
def entropy_to_mnemonic(entropy: bytes) -> str:
"""Convert entropy bytes to a BIP39 english mnemonic
Entropy can be 16, 20, 24, 28, 32, 36 or 40 bytes"""
try:
return wally.bip39_mnemonic_from_bytes(None, entropy)
except ValueError:
raise InvalidEntropy | 47,920 |
async def read_run(catalog_name: str, run_uid: str):
"""Summarize the run for the given uid."""
summary = databroker.run_summary(catalog_name, run_uid)
if summary is None:
raise HTTPException(status_code=404, detail="Not found")
return summary | 47,921 |
def test_code_spans_342():
"""
Test case 342: The stripping only happens if the space is on both sides of the string:
"""
# Arrange
source_markdown = """` a`"""
expected_tokens = [
"[para(1,1):]",
"[icode-span(1,1): a:`::]",
"[end-para:::True]",
]
expected_gfm =... | 47,922 |
def compute_freqs(count_file, dump_file, power=.75):
"""Compute the frequencies of the counts raised to the given power.
count_file (str): file with the dictionary with words and their counts.
dump_file (str): file where the result should be dumped.
power (float): value to which the counts should be raised be... | 47,923 |
def shell_quote(*args: str) -> str:
"""
Takes command line arguments as positional args, and properly quotes each argument to make it safe to
pass on the command line. Outputs a string containing all passed arguments properly quoted.
Uses :func:`shlex.join` on Python 3.8+, and a for loop of :func:`... | 47,924 |
def is_resources_sufficient(order):
"""Returns True when order can be made, False if ingredients are insufficient."""
check = [
True if MENU[order][key] <= resources[key] else False
for key, value in MENU[order].items()
]
return not False in check[:-1] | 47,925 |
def plot_representation_norms(nnet, xp_path, title_suffix, xlabel, file_prefix):
"""
plot norms of feature representations of train, val, and test set.
"""
ylab = "Feature representation norm"
for which_set in ['train', 'val', 'test']:
if (which_set == 'val') & (nnet.data.n_val == 0):
... | 47,926 |
def test_osi_license(license_mock):
"""
Testing if the repo's license is OSI-approved.
"""
license_mock.return_value.spdx_id = 'MPL-2.0'
assert MetaCollector('TestRepoOwner', 'TestRepoName').osi_license == True
license_mock.return_value.spdx_id = 'Proprietary'
assert MetaCollector('TestRepoO... | 47,927 |
def mode(arr):
"""Return the mode, i.e. most common value, of NumPy array <arr>"""
uniques, counts = np.unique(arr, return_counts=True)
return uniques[np.argmax(counts)] | 47,928 |
def normalized_state_to_tensor(state, building):
"""
Transforms a state dict to a pytorch tensor.
The function ensures the correct ordering of the elements according to the list building.global_state_variables.
It expects a **normalized** state as input.
"""
ten = [[ state[sval] for sval in bui... | 47,929 |
def init(path='/docs'):
"""
Initializes this extension to a swapy module
It registers following routes:
- /docs (default)
- /docs-static (default) (for resources like styles)
:param path: str
URL endpoint path for which will be routed
Default: '/docs'
"""
if not path.st... | 47,930 |
def pdbParserByIndex(pdbFilePaths: List[str]):
"""
Given one or more pdb file paths, retrieve relevant columns based on character positions (indices).
Outputs the data in tab-delimited format to a new file path.
"""
for pdbFilePath in pdbFilePaths:
print("Parsing by index in", os.path.base... | 47,931 |
def get_num_of_lines_in_file(filename):
"""Open the file and get the number of lines to use with tqdm as a progress bar."""
file_to_read = open(filename, "rb")
buffer_generator = takewhile(
lambda x: x, (file_to_read.raw.read(1024 * 1024) for _ in repeat(None))
)
return sum(buf.count(b"\n") ... | 47,932 |
def translate_lat_to_geos5_native(latitude):
"""
The source for this formula is in the MERRA2
Variable Details - File specifications for GEOS pdf file.
The Grid in the documentation has points from 1 to 361 and 1 to 576.
The MERRA-2 Portal uses 0 to 360 and 0 to 575.
latitude: float Needs +/- i... | 47,933 |
def disabled_payments_notice(context, addon=None):
"""
If payments are disabled, we show a friendly message urging the developer
to make his/her app free.
"""
addon = context.get('addon', addon)
return {'request': context.get('request'), 'addon': addon} | 47,934 |
def upload_fastq_collection_single(gi,history_id,fastq_single):
"""
Uploads given fastq files to the Galaxy history and builds a dataset collection.
:param gi: Galaxy instance.
:param history_Id: History id to upload into.
:param fastq_single: Single-end files to upload.
:return: The datase... | 47,935 |
def get_world_size() -> int:
"""
Simple wrapper for correctly getting worldsize in both distributed
/ non-distributed settings
"""
return (
torch.distributed.get_world_size()
if torch.distributed.is_available() and torch.distributed.is_initialized()
else 1
) | 47,936 |
def filtraColunas(df: pd.DataFrame, colunas_interesse: list) -> pd.DataFrame:
"""
Seleciona apenas as colunas de interesse de uma DataFrame
Parameters
----------
DataFrame : pd.DataFrame
DataFrame para filtragem
colunas_interesse : list
lista com os cabeçalhos das col... | 47,937 |
def PatSub(s, op, pat, replace_str):
"""Helper for ${x/pat/replace}."""
#log('PAT %r REPLACE %r', pat, replace_str)
regex, err = glob_.GlobToExtendedRegex(pat)
if err:
e_die("Can't convert glob to regex: %r", pat)
if regex is None: # Simple/fast path for fixed strings
if op.do_all:
return s.r... | 47,938 |
async def check_for_role(self, name):
"""
A function to check for the existence of a role.
"""
name = name.lower()
role = (
await GuildRoles
.query
.where(database.func.lower(GuildRoles.name) == name)
.gino
.scalar()
)
return role | 47,939 |
def construct_futures_symbols(
symbol, start_year=2010, end_year=2014
):
"""
Constructs a list of futures contract codes
for a particular symbol and timeframe.
"""
futures = []
# March, June, September and
# December delivery codes
months = 'HMUZ'
for y in range(start_... | 47,940 |
def UpdateDescription(unused_ref, args, request):
"""Update description.
Args:
unused_ref: unused.
args: The argparse namespace.
request: The request to modify.
Returns:
The updated request.
"""
if args.IsSpecified('clear_description'):
request.group.description = ''
elif args.IsSpecif... | 47,941 |
def _make_example_and_append_to_list(
*,
example_values: List[_Example],
input_code_block_lines: List[str],
expected_output: str) -> None:
"""
Make an example value and append it ot a specified list.
Notes
-----
This function clears a list of input code blo... | 47,942 |
def getAllChannels():
"""
a func to see all valid channels
:return: a list channels
"""
return ["Hoechst", 'ERSyto', 'ERSytoBleed', 'Ph_golgi', 'Mito'] | 47,943 |
def get_virtual_func_address(name, tinfo=None, offset=None):
"""
:param name: method name
:param tinfo: class tinfo
:param offset: virtual table offset
:return: address of the method
"""
address = idc.LocByName(name)
if address != idaapi.BADADDR:
return address
address = C... | 47,944 |
def coupler_netlist(
wg_width: float = 0.5,
gap: float = 0.236,
length: float = 20.007,
coupler_symmetric_factory: Callable = coupler_symmetric,
coupler_straight: Callable = coupler_straight,
layer: Tuple[int, int] = LAYER.WG,
layers_cladding: List[Tuple[int, int]] = [LAYER.WGCLAD],
clad... | 47,945 |
def accuracy(output, target, mask, inc_fix=False):
""" Calculate accuracy from output, target, and mask for the networks """
output = output.astype(cp.float32)
target = target.astype(cp.float32)
mask = mask.astype(cp.float32)
arg_output = cp.argmax(output, -1)
arg_target = cp.argmax(ta... | 47,946 |
def short_demo(cfg, dataset_test):
"""
Test and visualize inference on a test dataset
"""
predictor = DefaultPredictor(cfg)
own_vis = Visualizer()
for d in dataset_test:
img = cv2.imread(d['file_name'])
visualizer = DetectronVisualizer(img[:, :, ::-1], metadata=MetadataCatalog.ge... | 47,947 |
def print_board(state):
"""Given a state of cells print the board"""
bar = '-------------'
cells_tmpl = '| {} | {} | {} |'
cells = []
for i in range(0, 9):
cells.append(i + 1 if state[i] == '-' else state[i])
print('\n'.join([
bar,
cells_tmpl.format(cells[0], cells[1],... | 47,948 |
async def test(message: discord.Message):
"""Simply writes "Test" in channel."""
await message.channel.send("Test") | 47,949 |
def get_filterset_class(filterset_class, **meta):
"""Get the class to be used as the FilterSet"""
if filterset_class:
# If were given a FilterSet class, then set it up and
# return it
return setup_filterset(filterset_class)
return custom_filterset_factory(**meta) | 47,950 |
def first_lower(string):
"""
Return a string with the first character uncapitalized.
Empty strings are supported. The original string is not changed.
"""
return string[:1].lower() + string[1:] | 47,951 |
def read_db() -> list:
"""Читает все данные из базы"""
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USERNAME, password=DB_PASS, host=DB_HOST)
cursor = conn.cursor(cursor_factory=DictCursor)
cursor.execute('SELECT * FROM posts')
res = cursor.fetchall()
conn.close()
return res | 47,952 |
def logit(p):
"""Logit function"""
p = np.atleast_1d(np.asfarray(p))
logit_p = np.zeros_like(p)
valid = (p > 0) & (p < 1)
if np.any(valid):
logit_p[valid] = np.log(p[valid] / (1 - p[valid]))
logit_p[p==0] = np.NINF
logit_p[p==1] = np.PINF
return logit_p | 47,953 |
async def logout(request):
"""
Finish the session with auth, clear the cookie and stop the session being used again.
"""
session_id = request['session'].session_id
await finish_session(request, session_id, 'logout')
session = await get_session(request)
session.pop(str(session_id))
await... | 47,954 |
def create_multiple_new_predictions(monkeypatch):
"""
Mock prediction model method to ensure no duplicate prediction in
predictions table.
"""
@classmethod
async def mockfunc_get_one_by_username(cls, username):
"""Return a user record from the users table."""
hashed_pwd = bcrypt... | 47,955 |
def tidy_split(df, column, sep, keep=False):
"""
Split the values of a column and expand so the new DataFrame has one split
value per row. Filters rows where the column is missing.
Params
------
df : pandas.DataFrame
dataframe with the column to split and expand
column : str
... | 47,956 |
def test_every_edge_has_position(simple_bytecode: str):
"""Test that every edge has a position encoding."""
builder = graph_builder.ProGraMLGraphBuilder()
graph = builder.Build(simple_bytecode)
for src, dst, position in graph.edges(data="position"):
assert isinstance(
position, int
), f'No positio... | 47,957 |
def greedyClustering(v_space, initial_pt_index, k, style):
"""
Generate `k` centers, starting with the `initial_pt_index`.
Parameters:
----------
v_space: 2D array.
The coordinate matrix of the initial geometry.
The column number is the vertex's index.
... | 47,958 |
def s2_matrix(beta, gamma, device=None):
"""
Returns a new tensor corresponding to matrix formulation of the given input tensors representing
SO(3) group elements.
Args:
beta (`torch.FloatTensor`): beta attributes of group elements.
gamma (`torch.FloatTensor`): gamma attributes of group... | 47,959 |
def test_generate_signature():
"""
Using example data from
http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
"""
secret_key = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'
service = 'iam'
date = '20110909'
key = HMAC4SigningKey(secret_key, service, prefix="HMAC4",... | 47,960 |
def cache(func):
"""Thread-safe caching."""
lock = threading.Lock()
results = {}
def wrapper(*args, **kwargs):
identifier = checksum(args, kwargs)
if identifier in results:
return results[identifier]
with lock:
if identifier in results:
re... | 47,961 |
def run(cmd):
""" Run system command, returns exit-code and stdout """
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
txt = p.stdout.read()
return p.wait(), txt | 47,962 |
def hide_console():
"""Startup-info for subprocess.Popen which hides the console on
Windows.
"""
if platform.system() != 'Windows':
return None
si = sp.STARTUPINFO()
si.dwFlags |= sp.STARTF_USESHOWWINDOW
si.wShowWindow = sp.SW_HIDE
return si | 47,963 |
def merge_dicts(dict1: Dict[str, Any],
dict2: Dict[str, Any],
*dicts: Dict[str, Any]) -> Dict[str, Any]:
"""
Merge multiple dictionaries, producing a merged result without modifying
the arguments.
:param dict1: the first dictionary
:param dict2: the second dictio... | 47,964 |
def decode(model, inputs):
"""Decode inputs."""
decoder_inputs = encode_onehot(np.array(['='])).squeeze()
decoder_inputs = jnp.tile(decoder_inputs, (inputs.shape[0], 1))
return model(
inputs, decoder_inputs, train=False, max_output_len=get_max_output_len()) | 47,965 |
def combinations_all(data: Sequence) -> List:
"""
Return all combinations of all length for given sequence
Args:
data: sequence to get combinations of
Returns:
List: all combinations
"""
comb = []
for r in range(1, len(data) + 1):
comb.extend(combinations(data, r=r)... | 47,966 |
def templateSummary():
"""
"""
# Load Model
tablename = "survey_template"
s3db[tablename]
s3db.survey_complete
crud_strings = s3.crud_strings[tablename]
def postp(r, output):
if r.interactive:
if len(get_vars) > 0:
dummy, template_id = get_vars.viewi... | 47,967 |
def suffix_array(text, _step=16):
"""Analyze all common strings in the text.
Short substrings of the length _step a are first pre-sorted. The are the
results repeatedly merged so that the garanteed number of compared
characters bytes is doubled in every iteration until all substrings are
sorted... | 47,968 |
def get_main_image():
"""Rendering the scatter chart"""
yearly_temp = []
yearly_hum = []
for city in data:
yearly_temp.append(sum(get_city_temperature(city))/12)
yearly_hum.append(sum(get_city_humidity(city))/12)
plt.clf()
plt.scatter(yearly_hum, yearly_temp, alpha=0.5)
plt... | 47,969 |
def get_PhotoImage(path, scale=1.0):
"""Generate a TKinter-compatible photo image, given a path, and a scaling
factor.
Parameters
----------
path : str
Path to the image file.
scale : float, default: 1.0
Scaling factor.
Returns
-------
img : `PIL.ImageTk.PhotoImage ... | 47,970 |
def build(ctx):
"""Build distributable python package"""
poetry(ctx, "build -v") | 47,971 |
def MCLA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None):
"""Meta-CLustering Algorithm for a consensus function.
Parameters
----------
hdf5_file_name : file handle or string
cluster_runs : array of shape (n_partitions, n_samples)
verbose : bool, optional (def... | 47,972 |
def parse_sampleids(samplelabel,ids):
"""
Parse the label id according to the given sample labels
Parameter:
samplelabel: a string of labels, like '0,2,3' or 'treat1,treat2,treat3'
ids: a {samplelabel:index} ({string:int})
Return:
(a list of index, a list of index labels)
"""
# labels
idsk=["... | 47,973 |
def create_sample(source, dest, data_dir, n_lines):
"""
Create a text file of name dest from n_lines number of lines
of text file of name source.
"""
if n_lines % 2 == 1:
n_lines -= 1
source_path = path.join(data_dir, source)
dest_path = path.join(data_dir, dest)
with open(source... | 47,974 |
async def test_create_request_params(client, method, signature, kwargs):
"""Test that all every argument supplied to an endpoint goes into the HTTP request"""
endpoint = method.endpoint
arguments = construct_arguments(client, signature, **kwargs)
total_params = []
for location in locations:
... | 47,975 |
def iso_date(iso_string):
""" from iso string YYYY-MM-DD to python datetime.date
Note: if only year is supplied, we assume month=1 and day=1
This function is not longer used, dates from lists always are strings
"""
if len(iso_string) == 4:
iso_string = iso_string + '-01-01'
d = d... | 47,976 |
def summary_dist_xdec(res, df1, df2):
"""
res is dictionary of summary-results DataFrames.
df1 contains results variables for baseline policy.
df2 contains results variables for reform policy.
returns augmented dictionary of summary-results DataFrames.
"""
# create distribution tables groupe... | 47,977 |
def test_functions_and_methods_exist_in_rust():
"""
Check that for each of the functions and methods present in the Python
typestub file, there is a line in `src/lib.rs` containing a matching
definition. Since we're doing a naive grep search, without access to the
Rust AST, there may be false negati... | 47,978 |
def is_app_running(appname):
"""Tries to determine if the application in appname is currently
running"""
display.display_detail('Checking if %s is running...' % appname)
proc_list = get_running_processes()
matching_items = []
if appname.startswith('/'):
# search by exact path
mat... | 47,979 |
def moore_to_basu(moore, rr, lam):
"""Returns the coordinates, speeds, and accelerations in BasuMandal2007's
convention.
Parameters
----------
moore : dictionary
A dictionary containg values for the q's, u's and u dots.
rr : float
Rear wheel radius.
lam : float
Steer... | 47,980 |
def adjust_learning_rate(optimizer, epoch):
"""decrease the learning rate at 100 and 150 epoch"""
lr = args.lr
if epoch >= 50:
lr /= 10
if epoch >= 100:
lr /= 10
if epoch >= 150:
lr /= 10
for param_group in optimizer.param_groups:
param_group['lr'] = lr | 47,981 |
def get_username(sciper):
"""
return username of user
"""
attribute = 'uid'
response = LDAP_search(
pattern_search='(uniqueIdentifier=' + sciper + ')',
attribute=attribute
)
return response[0]['attributes'][attribute][0] | 47,982 |
def number_to_string(s, number):
"""
:param s: word user input
:param number: string of int which represent possible anagram
:return: word of alphabet
"""
word = ''
for i in number:
word += s[int(i)]
return word | 47,983 |
def mean(num_lst):
"""
Calculates the mean of a list of numbers
Parameters
----------
num_lst : list
List of numbers to calculate the average of
Returns
-------
The average/mean of num_lst
Examples
--------
>>> mean([1,2,3,4,5])
3.0
"""
... | 47,984 |
def key_special():
""" keys selected objects with special color """
selected = cmds.ls(sl=True)
for sel in selected:
cmds.setKeyframe(sel, hierarchy="none", shape=False, an=False)
time = cmds.currentTime(q=True)
cmds.keyframe(t=(time, time), e=True, tds=True) | 47,985 |
def development_create_database(df_literature, df_inorganics, df_predictions, inp):
"""
Create mass transition database.
Create mass transition database based on literature, inorganic and prediction data.
Parameters
----------
df_literature : dataframe
Dataframe with parsed literat... | 47,986 |
def _stream_to_file(
r: requests.Response,
file: IO[bytes],
chunk_size: int = 2**14,
progress_bar_min_bytes: int = 2**25,
) -> str:
"""Stream the response to the file, returning the checksum.
:param progress_bar_min_bytes: Minimum number of bytes to display a progress bar for. Default is 32MB
... | 47,987 |
def strip_attributes(soup):
"""Strip class and style attributes."""
for element in soup.find_all():
element.attrs.pop("class", None)
element.attrs.pop("style", None) | 47,988 |
def get_user(key: str, user: int, type_return: str = 'dict', **kwargs):
"""Retrieve general user information."""
params = {
'k': key,
'u': user,
'm': kwargs['mode'] if 'mode' in kwargs else 0,
'type': kwargs['type_'] if 'type_' in kwargs else None,
'event_days': kwargs['event_days'] if 'event_days' in kwargs els... | 47,989 |
def remove_apk_timestamps(filename):
"""Remove the timestamps embedded in an apk archive."""
sys.stdout.write('Processing: %s\n' % os.path.basename(filename))
with zipfile.ZipFile(filename, 'r') as zf:
# Creates a temporary file.
out_file, out_filename = tempfile.mkstemp(prefix='remote_apk_timestamp')
... | 47,990 |
def test_node_request_only_needed_propagates(looper, setup, txnPoolNodeSet,
sdk_wallet_client, sdk_pool_handle, tconf):
"""
One of node lacks sufficient propagates
"""
delay = tconf.PROPAGATE_REQUEST_DELAY
faulty_node = setup
old_count_recv_ppg = get... | 47,991 |
async def test_command(
hass: HomeAssistant,
device: DysonVacuumDevice,
service: str,
service_data: dict,
command: str,
command_args: list,
):
"""Test platform services."""
service_data[ATTR_ENTITY_ID] = ENTITY_ID
await hass.services.async_call(VACUUM_DOMAIN, service, service_data, b... | 47,992 |
def infer_schema(example, binary_features=[]):
"""Given a tf.train.Example, infer the Spark DataFrame schema (StructFields).
Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to
disambiguate these types for Spark DataFrames DTypes (StringType and BinaryType), so we requ... | 47,993 |
def mongo_sync_status(remongo=False, update_all=False, user=None, xform=None):
"""Check the status of records in the mysql db versus mongodb. At a
minimum, return a report (string) of the results.
Optionally, take action to correct the differences, based on these
parameters, if present and defined:
... | 47,994 |
def replay_gain_mode(context, mode):
"""
*musicpd.org, playback section:*
``replay_gain_mode {MODE}``
Sets the replay gain mode. One of ``off``, ``track``, ``album``.
Changing the mode during playback may take several seconds, because
the new settings does not affect the buffe... | 47,995 |
def create_batches_of_sentence_ids(sentences, batch_equal_size, max_batch_size):
"""
Groups together sentences into batches
If max_batch_size is positive, this value determines the maximum number of sentences in each batch.
If max_batch_size has a negative value, the function dynamically creates the batches such th... | 47,996 |
def _run_download_data_IB_loop() -> None:
"""
Run loading by chunks different symbol sequentially.
"""
symbols = ["DA", "ES", "NQ"]
_LOG.info("Running sequential downloading of %s", symbols)
timer = htimer.Timer()
for symbol in symbols:
_run_download_data_IB_loop_by_symbol(500, symbo... | 47,997 |
def com_com_distances_axis(universe, mda_selection_pairs, fstart=0, fend=-1, fstep=1, axis='z'):
"""Center of mass to Center of mass distance in one dimension (along an axis).
This function computes the distance between the centers of mass between pairs of MDAnalysis atoms selections
across the the MD traje... | 47,998 |
def min_vertex_cover(G, sampler=None, **sampler_args):
"""Returns an approximate minimum vertex cover.
Defines a QUBO with ground states corresponding to a minimum
vertex cover and uses the sampler to sample from it.
A vertex cover is a set of vertices such that each edge of the graph
is incident ... | 47,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.