content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_project_name() -> str:
"""Find project name, which is prefix for info distributions.
Returns:
str: the name of package specified in pyproject.toml
Raises:
EnvironmentError: if file pyproject.toml is not found.
"""
pyproject_path = search_upwards_for_file("pyproject.toml")
... | 62,900 |
def WrtAsUtf(input_str):
"""
Depending if the stream is a socket, a file or standard output,
if Python 2 or 3, Windows or Linux, some complicated tests or conversions are needed.
This writes to:
- Apache socket.
- WSGI stream.
- lib_client stream.
- CGI output.
"""
# FIXME: Shou... | 62,901 |
def print_stats_table(ingestion_stats: dict):
"""
Print import data stats in table.
Args:
ingestion_stats (dict): basic import statistics. {"fault_type": [], "total_faults": []}
"""
rows = []
rows.append(["Type", "Total Files"])
print("\n\n" + "=" * 47)
print("*" * 13, "IMPORTE... | 62,902 |
def print_parser(parser):
"""Prints input parameters"""
popts, pargs = parser.parse_args()
args = pargs
opts = vars(popts)
defs = vars(parser.get_default_values())
print('Arguments: %s\nOptional parameters:\n' % str(args)+\
'<key> <value> <default>')
for k,v in opts.... | 62,903 |
def _lsusbv_on_device(bus_id, dev_id):
"""Calls lsusb -v on device."""
_, raw_output = cmd_helper.GetCmdStatusAndOutputWithTimeout(
['lsusb', '-v', '-s', '%s:%s' % (bus_id, dev_id)], timeout=10)
device = {'bus': bus_id, 'device': dev_id}
depth_stack = [device]
# TODO(jbudorick): Add documentation for ... | 62,904 |
def gcj02_to_wgs84(lng, lat):
"""
GCJ02(火星坐标系)转GPS84
:param lng:火星坐标系的经度
:param lat:火星坐标系纬度
:return:
"""
if not in_hz(lng, lat):
return lng, lat
dlat = transformlat(lng - 105.0, lat - 35.0)
dlng = transformlng(lng - 105.0, lat - 35.0)
radlat = lat / 180.0 * pi
magic =... | 62,905 |
def get_related_sets(node):
"""Return objectSets that are relationships for a look for `node`.
Filters out based on:
- id attribute is NOT `pyblish.avalon.container`
- shapes and deformer shapes (alembic creates meshShapeDeformed)
- set name ends with any from a predefined list
- set in not in ... | 62,906 |
def generate_tox_func(env: toxini.Env) -> t.List[str]:
"""Given a tox env dictionary, returns bash code to run."""
envdir = pathlib.Path(env.settings["envdir"])
if not envdir.exists():
raise RuntimeError(
f"Can't generate env: path {envdir} does not exist."
"Make sure tox has... | 62,907 |
def get_geoinfo(location: str) -> dict:
"""
Infer geographical ISO information from location
:param location: geo location of the person
:return: dictionary with ISO geo-information
"""
mapping = get_country_mapping()
if location:
search = re.search(r'\((.*?)\)', location)
if... | 62,908 |
def Hl_operator(omega):
"""
implements Hl operator in eq 20
"""
omega_norm = np.linalg.norm(omega)
term1 = (1/2)*np.eye(3)
if (omega_norm < 1.0e-5):
return term1
term2 = np.nan_to_num((omega_norm - np.sin(omega_norm)) / (omega_norm**3)) * skew(omega)
term3 = n... | 62,909 |
def get_world_inverse_matrix(mobj):
"""
Returns world inverts matrix of the given Maya object
:param mobj: MObject, Maya object we want to retrieve world inverse matrix of
:return: MMatrix
"""
inverse_matrix_plug = api.DependencyNode(mobj).find_plug('worldInverseMatrix', want_networked_plug=Fal... | 62,910 |
def sum_of_even_valued_fibonacci_numbers() -> int:
"""Sum of even valued Fibonacci numbers.
The values of the Fibonacci sequence should not exceed four millions.
Returns:
int: returned sum.
"""
return sum(get_even_fibonacci_sequence()) | 62,911 |
def get_event_dict(event: Event) -> Dict[str, Any]:
"""Get event dict."""
final_event_dict = {}
event_dict = event.__dict__.copy()
final_event_dict["point"] = event.point.__dict__.copy()
final_event_dict["is_site"] = event.is_site
final_event_dict["name"] = event.name
final_event_dict["event... | 62,912 |
def print_command_output_per_instance(invocations, show_output=False):
"""Print results from ssm.list_command_invocations()"""
for i in invocations:
click.echo(
' ' * lpad + ' '.join(['***', i['Status'], i['InstanceId'], i['InstanceName']]))
if show_output:
for cp in i['C... | 62,913 |
def get_customer_lifetime(df_cust, ref_date, start_date):
"""
Takes in a customer dataframe and
returns the customer lifetime based
on a reference date.
Parameters:
-----------
df_cust : dataframe
Customer dataframe
ref_date : str
Reference date to calcul... | 62,914 |
def helicsFederateIsAsyncOperationCompleted(fed: 'helics_federate') -> "helics_bool":
"""
check if the current Asynchronous operation has completed
Parameters
----------
* `fed` :
the federate to operate on
Returns
-------
0 if not completed, 1 if completed
"""
retur... | 62,915 |
def svn_fs_change_node_prop(*args):
"""
svn_fs_change_node_prop(svn_fs_root_t root, char path, char name, svn_string_t value,
apr_pool_t pool) -> svn_error_t
"""
return _fs.svn_fs_change_node_prop(*args) | 62,916 |
def macaulay_duration(cashflows, discount_rate):
"""
Computes the Macaulay Duration of a sequence of cash flows
"""
discounted_flows = discount(cashflows.index, discount_rate)*cashflows
weights = discounted_flows/discounted_flows.sum()
return np.average(cashflows.index, weights=weights.squ... | 62,917 |
def test_stack_init_list_len_3(short_stack):
"""Initialize list with iterable and test length."""
assert len(Stack([1, 2, 3])) == 3 | 62,918 |
def init_master_table():
"""构建模型主表"""
from datamanage.pro.datamodel.models.datamodel import (
DmmModelFieldStage,
)
master_table_field_list = json.loads(
'''
[
{
"field_name": "price",
"field_alias": "道具价格",
"field_index": 1,
"... | 62,919 |
def precheck(context):
"""
calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_'
(e.g. "precheck_ami_id")
Checking function should return True if OK, or raise RuntimeError w/ message if not
Args:
context: a populated EFVersionContext object
Returns:
True if the p... | 62,920 |
async def print_text(req: Request, request: PrintTextRequest) -> ResponsePayload:
"""Print a text"""
config = Config()
database = Database()
print_id = database.generate_print_id()
username = req.state.user_info["username"]
printer = Printer()
_print_header(config, printer, print_id, userna... | 62,921 |
def catch_index_error(what, otherwise):
"""
runs callable 'what' and catches IndexErrors, returning 'otherwise' if one occurred
:param what: callable
:param otherwise: alternate result in case of IndexError
:return: result of 'what' or 'otherwise' in case of IndexError
"""
try:
retur... | 62,922 |
def alert(alertID=1):
"""
Serves an individual alert investigation report for the given alert ID.
"""
pageState = "{ type: 'alert', dataID: '" + alertID + "' }"
return render_template(
'technical/index.html',
content=g.config['TECHNICAL_CONFIG'],
page=pageState,
langa... | 62,923 |
def decode_data_sequence(data):
"""Read encapsulated data and return a list of strings.
Parameters
----------
data : str
String of encapsulated data, typically dataset.PixelData
Returns
-------
list of bytes
All fragments in a list of byte strings
"""
# Convert data... | 62,924 |
def LF_CG_DISTANCE_SHORT(c):
"""
This LF is designed to make sure that the compound mention
and the gene mention aren't right next to each other.
"""
return -1 if len(list(get_between_tokens(c))) <= 2 else 0 | 62,925 |
def test_set_deposit_limit_crash(raiden_network, token_amount, contract_manager, retry_timeout):
"""The development contracts as of 10/12/2018 were crashing if more than an amount was given
Regression test for https://github.com/raiden-network/raiden/issues/3135
"""
app1 = raiden_network[0]
registr... | 62,926 |
def add_timeframed_query_manager(sender, **kwargs):
"""
Add a QueryManager for a specific timeframe.
"""
if not issubclass(sender, TimeFramedModel):
return
try:
sender._meta.get_field('timeframed')
raise ImproperlyConfigured("Model '%s' has a field named "
... | 62,927 |
def compare_values(fo, v, w, ignored_keys=set(['indexstamp', '_version_', 'body'])):
"""Purpose of this funciton is to compare results from two solr responses, value by value
and print differences into the log file."""
vkeyed = _bibcodify(v.get('response'))
wkeyed = _bibcodify(w.get('response'... | 62,928 |
def generate_motions(p, u, a, d, plane_center, bbox, radius=500, n=32):
"""Generate random robot motions that point sensor at plane
Generate n motions that keep the sensor at position p and orientation u
pointing at the plane given by a[0] + a[1] + a[2] + d = 0
Args:
p: 3D position of sensor o... | 62,929 |
def timesince(dt, default="just now"):
"""
Returns string representing "time since" e.g.
3 days ago, 5 hours ago etc.
"""
now = datetime.utcnow()
diff = now - dt
periods = (
(diff.days / 365, "year", "years"),
(diff.days / 30, "month", "months"),
(diff.days / 7,... | 62,930 |
def testnn(dmname, datarowsfname):
"""Tests NN speeds.
May 30, on arnold (1 core), 128-byte sift descriptors
n data | n test | time
------------------------
50000 | 1000 | 8.5s
100000 | 1000 | 17 s
100000 | 500 | 9.8s
200000 | 500 | 19.8s
300000 | 500 | 30.8s
300... | 62,931 |
def hasAWSEnviornmentalVariables():
"""Checks the presence of AWS Credentials in OS envoirnmental variables and returns a bool if True or False."""
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
if access_key and secret_key:
return True
... | 62,932 |
def cli(ctx):
"""Simple git user environment management tools"""
pass | 62,933 |
def group_zero_one_loss(y_true, y_pred, group_membership, *,
normalize=True,
sample_weight=None):
"""A wrapper around the :any:`sklearn.metrics.zero_one_loss` routine.
The arguments remain the same, with `group_membership` added.
However, the only positional a... | 62,934 |
def list_extracted_7z_files(stdout):
"""
List all files extracted by 7zip based on the stdout analysis.
Based on 7zip Client7z.cpp:
static const char *kExtractingString = "Extracting ";
"""
# FIXME: handle Unicode paths with 7zip command line flags
get_file_list = re.compile('Extractin... | 62,935 |
def test_flatten_dict_without_core_metadata():
"""
An exception should be raised if the core_metadata_collections field does not contain any data.
"""
input1 = {'data': {'data_type_test': [{'core_metadata_collections': [], "file_name_test": "file_name", "object_id": "object_id_test"}]}}
output = fla... | 62,936 |
def build_from_dataframe(data: pd.DataFrame,
tz: Union[str, list]=None,
unit: Union[str, list]=None,
name: Union[str, list]=None,
type: Union[str, list]=None
) -> list:
"""
Returns a list... | 62,937 |
def test_list_hex_binary_max_length_nistxml_sv_iv_list_hex_binary_max_length_1_2(mode, save_output, output_format):
"""
Type list/hexBinary is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/hexBinary/Schema+Instance/NISTSchema-SV-IV-list-hexBinary-maxLengt... | 62,938 |
def resizeColumnWidth(sheet: Worksheet):
"""Resize columns to max width of cell per column."""
headerFilterArrowPadding = 5
dims = {}
for row in sheet.rows:
for cell in row:
if cell.value:
dims[cell.column_letter] = max((dims.get(cell.column_letter, 0), len(str(cell.v... | 62,939 |
def unauthorized():
"""Redirect unauthorized users to Login page."""
flash("You must be logged in to view that page.")
return redirect(url_for("auth.login")) | 62,940 |
def shape(parameter):
"""
Get the shape of a ``Parameter``.
Parameters
----------
parameter: Parameter
``Parameter`` object to get the shape of
Returns
-------
tuple:
shape of the ``Parameter`` object
"""
return parameter.shape | 62,941 |
def test_get_decks_filter_title(client: TestClient, session, snapshot1):
"""Filtering by snapshot title must work"""
response = client.get(f"/v2/decks?q={urllib.parse.quote(snapshot1.title)}")
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["count"] == 1, data
... | 62,942 |
def readFlatWFS(fn,interp=None):
"""
Load in data from WFS measurement of flat mirror.
Assumes that data was processed using processHAS, and loaded into
a .fits file.
Scale to microns, strip NaNs.
If rotate is set to an array of angles, the rotation angle
which minimizes the number of NaNs i... | 62,943 |
def filter_specials(letter):
"""Filter based on dict SPECIAL"""
return SPECIAL[letter] if letter in SPECIAL else letter | 62,944 |
def print_config(config, tuning_options, runner):
"""print the configuration string with tunable parameters and benchmark results"""
print_config_output(tuning_options.tune_params, config, runner.quiet, tuning_options.metrics, runner.units) | 62,945 |
def mape_score(
y_true: Union[Sequence[float], np.ndarray, pd.Series],
y_pred: Union[Sequence[float], np.ndarray, pd.Series],
) -> float:
"""Calculates the Mean Absolute Percentage Error, a common metric used for Time Series Problems
Parameters
----------
y_true: list or array like
The ... | 62,946 |
def movement_windows_construction(tr, periods, group_arr, reftime, halfwidth=3,
debug=False):
"""
Apply movement windows based on eauqtion described in Huajian Yao, 2004
# movement window construction
# | 1 # tgi(Tc) - nTc < t < tgi(Tc) + nTc
... | 62,947 |
def EKOI(x,n=INFO, small=True,dir=tempDir, sz=500., label=""):
"""
output x variable name, create an image based on x value and output a string which cause emacs to display the image
"""
r = ""
frame = inspect.currentframe()
ff = inspect.getouterframes(frame)[1]
fn = tempfile.NamedTemporaryF... | 62,948 |
def get_fusion_major_courses(fusion_major_soup):
"""
:param related_major_soup:
SoupParser.soup_jar['융합전공']
:return:
["빅데이터융합", ...]
"""
lecture_dropdown = fusion_major_soup.find_all('div', {'style': 'height:10em;overflow-y:scroll;'})[1]
ret = []
for i in lecture_dropdown.find_all(... | 62,949 |
def setup(hass, base_config):
"""Start Tentalux platform."""
config = base_config.get(DOMAIN)
host = config[CONF_HOST]
port = config[CONF_PORT]
name = 'tentalux'
controller = TentaluxController(host, port)
controller.connect()
devs = {'light': [], 'scene': [], 'camera': []}
# One l... | 62,950 |
async def download_extensions_json(
json_data: typing.Union[typing.Dict[str, str], Path],
save_path: Path,
*,
real_name: typing.Optional[bool] = None,
versionize: typing.Optional[bool] = None,
) -> None:
"""
Parse the given json data and download the given VSCode extensions into the save pat... | 62,951 |
def voiced_unvoiced(X, window_size=256, window_step=128, copy=True):
"""
Voiced unvoiced detection from a raw signal
Based on code from:
https://www.clear.rice.edu/elec532/PROJECTS96/lpc/code.html
Other references:
http://www.seas.ucla.edu/spapl/code/harmfreq_MOLRT_VAD.m
Parameter... | 62,952 |
def position_split(position_source, position_cible):
"""Prend les arguments positions_sources et position_cible et sépare la lettre et le chiffre. Les chiffres sont
transformé en entier dans l'objectif d'appliquer des opérations mathématiques. La lettre est transformé en
index dans l'objectif d'apli... | 62,953 |
def read_waze(*, file: TextIO = sys.stdin) -> Waze:
"""leitura do mapa do Waze"""
max_speed = float(file.readline().strip())
waze = Waze(max_speed)
try:
while True:
from_, to, *vals = file.readline().split()
waze.new_street(from_, to, *map(float, vals))
# quando a li... | 62,954 |
def shannon_entropy(mag, magerr):
"""Shannon entropy (Shannon et al. 1949) is used as a metric to quantify the amount of
information carried by a signal. The procedure employed here follows that outlined by
(D. Mislis et al. 2015). The probability of each point is given by a Cumulative Distribution
Fun... | 62,955 |
def enrolled_users(context: SolidExecutionContext, edx_course_ids: List[String]) -> DagsterPath: # type: ignore # noqa: WPS210
"""Generate a table showing which students are currently enrolled in which courses.
:param context: Dagster execution context for propagaint configuration data
:type context: Soli... | 62,956 |
def end_work(workers):
"""
Kills all work subprocesses specified.
Parameters
----------
workers : list(int)
List with the subprocesses PIDs.
"""
for pid in workers:
os.kill(pid, signal.SIGKILL) | 62,957 |
def check_well_known_ea_policies():
"""Check the consistency of WELL_KNOWN_EA_POLICIES"""
computed = {}
computed['PolicyAuthValue()'] = policy_auth_value()
computed['PolicyCommandCode(TPM2_CC_NV_UndefineSpaceSpecial)'] = policy_command_code(
Tpm20CommandCode.TPM2_CC_NV_UndefineSpaceSpecial)
... | 62,958 |
def load_judgement(ljson):
""" Load the raw dump of judgement in format of ljson
:ljson: Judgement raw dump filename
:returns: @todo
"""
with open(ljson) as fin:
df = pd.DataFrame.from_records([json.loads(l) for l in fin])
df = expand_field(df, 'scores', 'topic_id', 'score')
... | 62,959 |
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item):
# type: (CryptoConfig, Dict, Dict) -> Bool
"""Determines whether the unencrypted values in the plaintext items attributes are the same as those in the
encrypted item. Essentially this uses brute force to cover when we don't know the ... | 62,960 |
def gettempdir():
"""
Returns:
`fsnative`
Like :func:`python3:tempfile.gettempdir`, but always returns a `fsnative`
path
"""
# FIXME: I don't want to reimplement all that logic, reading env vars etc.
# At least for the default it works.
return path2fsn(tempfile.gettempdir()) | 62,961 |
def get_all_years():
""" All years report """
return json.dumps(query_for_date(4)) | 62,962 |
def test_get_cortx_s3_endpoint_success():
"""Test endpoint configuration in cortxs3."""
config = CORTXS3Config()
config._config['cortx_s3']['endpoint'] = "http://127.0.0.1:7081"
s3_endpoint = config.get_cortx_s3_endpoint()
assert s3_endpoint == "http://127.0.0.1:7081" | 62,963 |
def test_login(mocker):
"""Ensure it calls the expected method"""
mock_cmd_login = mocker.patch('nexuscli.cli.root_commands.cmd_login')
cli.main(argv=['login'])
mock_cmd_login.assert_called_once() | 62,964 |
def generate_title_label_pred(tweets_dict):
"""Generate predicted cluster labels for data points based on title similarity"""
global tfidf_titles
# Get the list of sample_num number of titles from the dict corpus
title_list = corpus_list(tweets_dict, 0, sample_num)
# Taking stems and synonyms into account for stri... | 62,965 |
def underline_code(
source: str,
location: SourceLocation,
end_location: SourceLocation,
padding: int = 1,
) -> str:
"""Underline code."""
pos, lineno, colno = location
end_pos, end_lineno, end_colno = end_location
view_begin = pos
view_end = end_pos
for _ in range(padding + 1)... | 62,966 |
def generateTruth(samples):
"""
generates truth data is sample infected
:param samples: samples to generate truth for
:return: truth
"""
truth = [{'SampleID': sample['SampleID'],
'Truth': decision(sample['CurrentProb'])} for sample in samples]
re... | 62,967 |
def aggregate_single_eval( # noqa: C901
result_dict: dict, all_seeds_for_run: list, eval_name: str
) -> dict:
"""Mean over seeds of single config run."""
new_results_dict = {}
data_temp = result_dict[all_seeds_for_run[0]]
# Get all main data source keys ("meta", "stats", "time")
data_sources = ... | 62,968 |
def information(file_name):
""" adds information extension, if missing
:param file_name: name of file
:type file_name: str
:returns: file with extension added
:rtype: str
"""
return _add_extension(file_name, Extension.INFORMATION) | 62,969 |
def restrict_chat_member(token: str,
chat_id: Union[int, str],
user_id: int,
permissions: ChatPermissions,
until_date: Optional[int] = None
) -> bool:
"""Use this method to restrict a user in... | 62,970 |
def draw_key_base(ctx, shape, base_color, width=60, height=100):
"""
Draw a key shape at 0,0 with the given base color, width, and
height.
"""
# Dark border on outside
ctx.set_source_rgb(*blend((0,0,0), 0.7, base_color))
shape(ctx, 0, width, height)
hilight = cairo.RadialGradient(0,heigh... | 62,971 |
def test_process_capture_both(capsys):
"""
Check that all is captured while running a process.
Arguments:
capsys: Pytest fixture to capture output.
"""
msg_stdout = "out"
msg_stderr = "err"
run(
["bash", "-c", f"echo {msg_stdout}; echo {msg_stderr} >&2"],
capture=Tru... | 62,972 |
def assert_array_equal(x: skimage.util._map_array.ArrayMap, y: numpy.ndarray):
"""
usage.skimage: 8
"""
... | 62,973 |
def access_message(user_profile, message_id):
# type: (UserProfile, int) -> Tuple[Message, UserMessage]
"""You can access a message by ID in our APIs that either:
(1) You received or have previously accessed via starring
(aka have a UserMessage row for).
(2) Was sent to a public stream in your r... | 62,974 |
def log1p(ds: ListDataset):
"""In-place log transformation."""
for data_entry in ds.list_data:
data_entry["target"] = np.log1p(data_entry["target"]) | 62,975 |
def transfer_continue_pinyin_to_hanzi(param, model='dag'):
"""
全拼音按音节切分后转汉字
:param param:
:param model:
:return:
"""
try:
if param.strip() == '':
raise Exception('invalid param')
if is_chinese(param):
return param
else:
pinyin = con... | 62,976 |
def get_mem_usage():
""" Get memory usage for current process """
import os, subprocess
pid = os.getpid()
process = subprocess.Popen("ps -orss= %s" % pid, shell=True, stdout=subprocess.PIPE)
out, _err = process.communicate()
return int(out) | 62,977 |
def del_clipboard():
"""Delete a clipboard entry"""
id = int(request.form.get("id"))
cb.delete(id)
return "" | 62,978 |
def to_list(
mapping: Optional[Dict[Key, Val]],
key_transform: Callable[[Key], Any] = str_if_bytes,
val_transform: Callable[[Val], Any] = to_redis_type,
) -> List:
"""Flattens a Dict to a list consisting of the of keys and values altertnating.
This is useful generating the arguments for Redis comman... | 62,979 |
def check_down_diagonal(board):
"""
Checks to see if one of the players got all the spaces in the diagonal
going from top-left corner to bottom-right corner. If so,
it returns the symbol for that player. If not, it returns None.
"""
symbol = board[0][0]
for row in range(1, SIZE):
if board[... | 62,980 |
def test_invalid_assignment():
"""Invalid assignments to `spec` throw a TypeError."""
with pytest.raises(TypeError):
ProcessRun("name", spec=[ProcessSpec("spec")]) | 62,981 |
def get_bbf_file(data_file_name):
"""Return information from file in bbf/bbf/data/...
Do NOT call on import time --
that would make flamedisx unusable to non-XENON folks!
"""
ensure_repo('XENON1T/bbf.git', BBF_PATH)
return fd.get_resource(f'{BBF_PATH}/bbf/data/{data_file_name}') | 62,982 |
def load(
phonopy_yaml=None, # phonopy.yaml-like must be the first argument.
supercell_matrix=None,
primitive_matrix=None,
is_nac=True,
calculator=None,
unitcell=None,
supercell=None,
nac_params=None,
unitcell_filename=None,
supercell_filename=None,
born_filename=None,
f... | 62,983 |
def get_last_modified(dirs):
"""Get the last modified time.
This method recursively goes through `dirs` and returns the most
recent modification time time found.
Parameters
----------
dirs : list[str]
list of directories to search
Returns
-------
int
most recent mo... | 62,984 |
def vote():
"""
allows the governance contract to approve or deny a new value
if governance approves, the num_votes counter increases by 1
if governance rejects, the reporter's ALGO stake is sent to
the governance contract
solidity equivalent: slashMiner()
Args:
0) will always be equal... | 62,985 |
def load_w2v_instance(file_path):
"""
Load a word2vec instance given its file path.
:param file_path: File path where the instance is located.
:return: Word2vec instance.
"""
return w2v.Word2Vec.load(file_path) | 62,986 |
def set_shot_end_frame(shot_node, end_frame):
"""
Sets the end frame of the given shot
:param shot_node: str
:param end_frame: int
:return: int
"""
raise NotImplementedError() | 62,987 |
def get_streets_with_postal_codes_by_city(city_name, way_type=None):
"""
:param city_name: name of city in English
:return:
"""
query_template_path = core_path() / 'osm' / 'templates' / 'get_streets_with_postal_codes_by_city_name.txt'
with query_template_path.open(mode='r') as f:
... | 62,988 |
def store_person(db):
"""
Query user fro data and store it
in the shelf object
"""
pid = input("Enter unique ID number: ")
person = {}
person['name'] = input("Enter name: ")
person['age'] = input('Enter age: ')
person['phone'] = input('Enter the phone number: ')
db[pid] = person | 62,989 |
def get_maj_answer(votes_per_answer):
"""
:param votes_per_answer: dictionary with {'1': int, '2': int}, where the ints add up to NBR_ANNOTATORS
:return: the majority answers, i.e., number of votes at least half that of the number of annotators;
raises error if the answers are tied
"""
if (len(... | 62,990 |
def find_subsequence(sequence, query):
"""
Find a subsequence in a sequence.
Parameters
----------
sequence : Sequence
The sequence to find the subsequence in.
query : Sequence
The potential subsequence. Its alphabet must extend the
`sequence` alphabet.
Retu... | 62,991 |
def get_retention_period(instance):
"""
Finds "Backup" tag in list of tags or returns default period (7 days)
:param instance: dict Dictionary output with instance details from describe_instances call
:return: Retention period for that instance
"""
for tag in instance["Tags"]:
if tag["Ke... | 62,992 |
def change_password(request, password_change_form=PasswordChangeForm, template_name='woodstock/registration/change_password.html'):
"""
Displays the change password form
"""
user = request.user
if request.method == 'POST':
form = password_change_form(user, request.POST)
if form.is_va... | 62,993 |
def validate_schema(configuration_dict: dict) -> bool:
"""
Validate pipeline file schema
"""
logger.debug("Validating yml schema")
# Pipeline
pipeline_keys_valid(configuration_dict)
version_is_string_type(configuration_dict)
# Workflow
validate_workflow_definition(configuration_dic... | 62,994 |
def compute_average_passengers_per_stop(instance, passengerData, tram_tour, tram_time_arrival, tram_time_departure):
"""
INFO
function to compute the average number of passengers per stop
"""
waitPas = compute_waiting_passenger(instance, passengerData, tram_tour, tram_time_arrival, tram_ti... | 62,995 |
def _add_event_labels(ax, tmin, tmax, with_ribbons=True, textbox=False, bottom=True,
flagmatch='RGraph'):
"""Add event labels and ribbons to axis (with date on x-axis).
- ax: axis object
- tmin, tmax: time range to assume for x axis.
- textbox: whether to draw text in a semi... | 62,996 |
def ShowZTraces(cmd_args=None):
""" Prints all traces with size > 0
"""
ShowZTracesAbove([0]) | 62,997 |
def import_data(filepath, use_pickle = False):
""" Imports a KinDA object as exported in the format specified by export_data()
Imports:
- domains, strands, complexes, reactions, resting-sets, resting-set reactions
- resting-set stats:
=> similarity-threshold
=> c_max (concentration maximu... | 62,998 |
def prepare_gpf4(receptor_filename=None,
ligand_filename = None,
list_filename = None,
gpf_filename = None,
output_gpf_filename = None,
flexres_filename = None,
directory = None,
parameters = [],
... | 62,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.