content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_rawfile_unique_values(
file: str
) -> list:
"""Extract the unique raw file names from "R.FileName" (Spectronaut output), "Raw file" (MaxQuant output),
"shortname" (AlphaPept output) or "Run" (DIA-NN output) column or from the "Spectral Count" column from the
combined_peptide.tsv file without... | 5,355,000 |
def _fetch_from_s3(bucket_name, path):
"""Fetch the contents of an S3 object
Args:
bucket_name (str): The S3 bucket name
path (str): The path to the S3 object
Returns:
str: The content of the S3 object in string format
"""
s3 = boto3.resource('s3')
bucket = s3.Bucket(bu... | 5,355,001 |
def deterministic(seed):
"""
Make the experiment reproducible
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
cudnn.deterministic = True | 5,355,002 |
def vrv_getatttype(schema, module, gp, aname, includes_dir = ""):
""" returns the attribut type for element name, or string if not detectable."""
# Look up if there is an override for this type in the current module, and return it
# Note that we do not honor pseudo-hungarian notation
attype, hun... | 5,355,003 |
def test_create_splits_mid_year():
"""
Make sure that year splits are properly generated when not using first day of year
as start of time series
"""
swe = np.zeros((3000, 50, 50))
a = analysis.Analysis(datetime.date(1993, 5, 1), swe)
years = a.create_year_splits()
assert years[0] == 121 | 5,355,004 |
def _tf1_setpar_ ( func , par , value ) :
"""Set parameter of TF1
>>> fun = ... ## function
>>> fun.setPar(1,1) ## set parameter #1 to be 1
>>> fun.setPar('m',2) ## set parameter 'm' to be 2
"""
if not par in func : raise IndexError("Invalid parameter index %s" % par )
#
... | 5,355,005 |
def inc_date(date_obj, num, date_fmt):
"""Increment the date by a certain number and return date object.
as the specific string format.
"""
return (date_obj + timedelta(days=num)).strftime(date_fmt) | 5,355,006 |
def recombine_edges(output_edges):
"""
Recombine a list of edges based on their rules.
Recombines identical Xe isotopes. Remove isotopes.
:param output_edges:
:return:
"""
mol = Chem.MolFromSmiles(".".join(output_edges))
# Dictionary of atom's to bond together and delete if they come in ... | 5,355,007 |
def parse_comments(content: str) -> List[str]:
"""Parses comments in LDF files
:param content: LDF file content as string
:type content: str
:returns: a list of all comments in the LDF file
:rtype: List[str]
"""
comment = os.path.join(os.path.dirname(__file__), 'lark', 'comment.lark')
p... | 5,355,008 |
def excludevars(vdict, filters):
"""
Remove dictionary items by filter
"""
vdict_remove = dict()
for filtr in filters:
a = filtervars_sub(vdict, filtr)
vdict_remove.update(a)
vdict_filtered = vdict.copy()
for key in vdict_remove.keys():
del vdict_filtered[key]
re... | 5,355,009 |
def __updateEntityAttributes(fc, fldList, dom, logFile):
"""For each attribute (field) in fldList,
adds attribute definition and definition source,
classifies as range domain, unrepresentable-value domain or enumerated-value domain, and
for range domains, adds rangemin, rangemax, and un... | 5,355,010 |
def make_laplace_pyramid(x, levels):
"""
Make Laplacian Pyramid
"""
pyramid = []
current = x
for i in range(levels):
pyramid.append(laplacian(current))
current = tensor_resample(
current,
(max(current.shape[2] // 2, 1), max(current.shape[3] // 2, 1)))
... | 5,355,011 |
def create_component(ctx: NVPContext):
"""Create an instance of the component"""
return ToolsManager(ctx) | 5,355,012 |
def _load_csv_key(symbol_key):
"""
针对csv存储模式,通过symbol_key字符串找到对应的csv具体文件名称,
如从usTSLA->找到usTSLA_2014-7-26_2016_7_26这个具体csv文件路径
:param symbol_key: str对象,eg. usTSLA
"""
# noinspection PyProtectedMember
csv_dir = ABuEnv.g_project_kl_df_data_example if ABuEnv._g_enable_example_env_ipython \
... | 5,355,013 |
def test_create_simple_gantt(tmpdir):
"""test_create_simple_gantt."""
c1 = Component("c1")
c1.state_record_list = [
BaseComponentState.WORKING,
BaseComponentState.FINISHED,
BaseComponentState.FINISHED,
BaseComponentState.FINISHED,
BaseComponentState.FINISHED,
]
... | 5,355,014 |
def generate_metadata(year, files, datatype = 'inventory'):
"""
Gets metadata and writes to .json
"""
if datatype == 'source':
source_path = [rcra_external_dir + p for p in files]
source_path = [os.path.realpath(p) for p in source_path]
source_meta = compile_source_metadata(sourc... | 5,355,015 |
def get_routing_table() -> RouteCommandResult:
"""
Execute route command via subprocess. Blocks while waiting for output.
Returns the routing table in the form of a list of routes.
"""
return list(subprocess_workflow.exec_and_parse_subprocesses(
[RouteCommandParams()],
_get_route_com... | 5,355,016 |
def xor_arrays(arr1, arr2):
""" Does a XOR on 2 arrays, very slow"""
retarr = array('B')
for i in range(len(arr1)):
retarr.append(arr1[i] ^ arr2[i])
return retarr | 5,355,017 |
def delete_category():
"""Delete category specified by id from database"""
category = Category.query.get(request.form['id'])
db.session.delete(category)
db.session.commit()
return '' | 5,355,018 |
def gen_dd(acc, amt):
"""Generate a DD (low-level)"""
read()
dd_num = dd_no()
while dd_num in dds.keys():
dd_num = dd_no()
dd = {
'ac_no': acc,
'amount': amt
}
return dd_num, dd | 5,355,019 |
def coranking_matrix(high_data, low_data):
"""Generate a co-ranking matrix from two data frames of high and low
dimensional data.
:param high_data: DataFrame containing the higher dimensional data.
:param low_data: DataFrame containing the lower dimensional data.
:returns: the co-ranking matrix of ... | 5,355,020 |
def gaussian_dist_xmu1xmu2_product_x(mu1,Sigma1,mu2,Sigma2):
"""Compute distribution of N(x|mu1,Sigma1)N(x|mu2,Sigma2)"""
InvSigmaHat = np.linalg.inv(Sigma1) + np.linalg.inv(Sigma2)
SigmaHat = np.linalg.inv(InvSigmaHat)
muHat = np.dot(SigmaHat,np.linalg.solve(Sigma1, mu1) + np.linalg.solve(Sigma2,mu2))
... | 5,355,021 |
def default_marker_size(fmt):
""" Find a default matplotlib marker size such that different marker types
look roughly the same size.
"""
temp = fmt.replace('.-', '')
if '.' in temp:
ms = 10
elif 'D' in temp:
ms = 7
elif set(temp).intersection('<>^vd'):
ms = 9
else... | 5,355,022 |
def vote_smart_candidate_rating_filter(rating):
"""
Filter down the complete dict from Vote Smart to just the fields we use locally
:param rating:
:return:
"""
rating_filtered = {
'ratingId': rating.ratingId,
'rating': rating.rating,
'timeSpan': rating.times... | 5,355,023 |
def write_network_file(path, conf):
"""
Write the key=val string to a file.
It's not possible to use native file output because these files must
be written with euid=0. Of course, there is no way to elevate this
process. Instead, shell out so that sudo can be applied.
Parameters
--------... | 5,355,024 |
def get_syntax(view):
""" get_syntax(view : sublime.View) -> str
>>> get_syntax(view)
'newLISP'
>>> get_syntax(view)
'Lisp'
Retuns current file syntax/language
"""
syntax = view.settings().get('syntax')
syntax = syntax.split('/')[-1].replace('.tmLanguage', '')
return syntax | 5,355,025 |
def test_field_nested_resource_provided(db_session):
"""Test providing a resource to a Relationship works."""
resource = AlbumResource(session=db_session)
field = Relationship(nested=resource)
assert field.resource == resource | 5,355,026 |
def undoInfo(*args, **kwargs):
"""
This command controls the undo/redo parameters.
Flags:
- chunkName : cn (unicode) [create]
Sets the name used to identify a chunk for undo/redo purposes when opening a chunk.
- closeChunk : cck (bool) ... | 5,355,027 |
def run(cmd_str,cwd='.'):
""" an OS agnostic function to execute command
Parameters
----------
cmd_str : str
the str to execute with os.system()
cwd : str
the directory to execute the command in
Note
----
uses platform to detect OS and adds .exe or ./ as appropriate
... | 5,355,028 |
def random_otp():
"""
:return: OTP for Event
:return type: string
"""
try:
all_events = Events.query.all() # Here Error if no Event
all_holded_events = HoldedEvents.query.all()
used_otps = set()
for otp_ in all_events:
used_otps.add(str(otp_.otp))
... | 5,355,029 |
def resume_training(out: ModelDir, notes: str = None, dry_run=False, start_eval=False):
""" Resume training an existing model """
train_params = out.get_last_train_params()
model = out.get_model()
train_data = train_params["data"]
evaluators = train_params["evaluators"]
params = train_params[... | 5,355,030 |
def read_config(path):
"""Read the complete INI file and check its version number
if OK, pass values to config-database
"""
return _read_config(path) | 5,355,031 |
def getProbaForAllMeasures():
"""
Algorithm for calculating conditional probabilities for all categories in all measures
"""
logging.info( "Calculate all conditionnal probabilities" )
istats = 0
measures = getAllMeasures()
measures = measures[:,1:]
measures = np.array([list... | 5,355,032 |
def LinkAndroidDeviceID(request, callback, customData = None, extraHeaders = None):
"""
Links the Android device identifier to the user's PlayFab account
https://docs.microsoft.com/rest/api/playfab/client/account-management/linkandroiddeviceid
"""
if not PlayFabSettings._internalSettings.ClientSessi... | 5,355,033 |
def getPath(file):
"""Get the path of a source file.
Use this to extract the path of a file/directory when the file
could be specified either as a FileTarget, DirectoryTarget or string.
@param file: The object representing the file.
@type file: L{FileTarget}, L{DirectoryTarget} or C{basestring}
"""
asse... | 5,355,034 |
def optical_flow_to_rgb(flows):
"""
Args:
A tensor with a batch of flow fields of shape [b*num_src, 2, h, w]
"""
flows = flows.cpu().numpy()
_, h, w = flows[0].shape
rgbs = []
for i in range(len(flows)):
mag, ang = cv2.cartToPolar(flows[i, 0, ...], flows[i, 1, ...])
... | 5,355,035 |
def get_motes_from_simulation(simfile, as_dictionary=True):
"""
This function retrieves motes data from a simulation file (.csc).
:param simfile: path to the simulation file
:param as_dictionary: flag to indicate that the output has to be formatted as a dictionary
:return: the list of motes formatt... | 5,355,036 |
def menu_bar():
"""each mini-game has a menu bar that allows direct access to
the main menu. This allows story mode to be bypassed after
starting war, but the game state will not be saved"""
pygame.draw.rect(SCREEN, TEAL, (0, 460, 640, 40))
menu_font = pygame.font.Font('freesansbold.ttf', 15)
m... | 5,355,037 |
def merge_sort(a, p, r):
""" merge sort
:param a: a array to sort, a[p:r+1] need to be sorted
:param p: index of array, p < r, if p >= r , the length of a is 1, return
:param r: index of array, p < r, if p >= r , the length of a is 1, return
"""
if p < r:
q = int((p + r) / 2)
# ... | 5,355,038 |
def uint8_to_binary(folder, out_folder):
"""
Convert a folder of mask in 0 255 format to binary format
:param folder: folder to examine
:param out_folder: folder
"""
try:
os.mkdir(out_folder)
except:
pass
if is_mask(folder, 255):
list_mask_path = os.... | 5,355,039 |
def green_foreground(greentext):
"""Green foreground for notice messages.
Green foreground for error messages.
Arguments:
greentext {str} -- text, which will be colored in green.
"""
LOG.notice(pyfancy().green().bold(greentext)) | 5,355,040 |
def get_flow_graph(limit, period):
"""
:type limit int
:type period int
:rtype: list[dict]
"""
rows = ElasticsearchQuery(
es_host=ELASTICSEARCH_HOST,
period=period,
index_prefix='logstash-other'
).query_by_string(
query='kubernetes.labels.job-name:* AND '
... | 5,355,041 |
def upload(server_ip, share, username, password, domain, remote_path, local_path, verbose=True):
""" Get file and folder on the remote file server.
server_ip (str): This value is the ip smb server's ip.
share (str): This value is the share file name.
username (str): This value i... | 5,355,042 |
def list_directory_command(api_client: CBCloudAPI, device_id: str, directory_path: str, limit: Union[int, str]):
"""
Get list of directory entries in the remote device
:param api_client: The API client
:param device_id: The device id
:param directory_path: Directory to list. This para... | 5,355,043 |
def _hparams(network, random_seed):
"""
Global registry of hyperparams. Each entry is a (default, random) tuple.
New algorithms / networks / etc. should add entries here.
"""
hparams = {}
def _hparam(name, default_val, random_val_fn):
"""Define a hyperparameter. random_val_fn takes a Ra... | 5,355,044 |
def bidding_search(request):
"""
"""
query = ''
form = BiddingSearchForm(shop=request.shop, data=request.GET)
if form.is_valid():
query = form.get_query()
results = form.search()
else:
results = form.all_results()
pager = Paginator(results, PAGE_SEARCH)
... | 5,355,045 |
def clean_code(code, code_type):
""" Returns the provided code string as a List of lines """
if code_type.startswith(BOOTSTRAP):
if code_type.endswith(CLEAN):
return code.split("\n")
code = code.replace("\\", "\\\\")
if code_type.startswith(PERMUTATION):
if code_type.end... | 5,355,046 |
def main():
"""Parse the arguments."""
tic = datetime.datetime.now()
parser = argparse.ArgumentParser(
description=('Examine a balance_data.py output file and '
'look for taxids with data sizes that are too large.'))
parser.add_argument("file",
type=s... | 5,355,047 |
def level(arr, l, ax=2, t=None, rounding=False):
"""
As level 1D but accepts general arrays and level is taken is some
specified axis.
"""
return np.apply_along_axis(level1D, ax, arr, l, t, rounding) | 5,355,048 |
def updateStore(request, storeId):
""" view for updating store """
if canViewThisStore(storeId, request.user.id):
# get the corresponding store
store = Store.objects.get(id=storeId)
metadata = getFBEOnboardingDetails(store.id)
if request.method == "POST":
# Create a ... | 5,355,049 |
def i(t, T, r, a, b, c):
"""Chicago design storm equation - intensity. Uses ia and ib functions.
Args:
t: time in minutes from storm eginning
T: total storm duration in minutes
r: time to peak ratio (peak time divided by total duration)
a: IDF A parameter - can be calculated fro... | 5,355,050 |
def get_primary_id_from_equivalent_ids(equivalent_ids, _type):
"""find primary id from equivalent id dict
params
------
equivalent_ids: a dictionary containing all equivalent ids of a bio-entity
_type: the type of the bio-entity
"""
if not equivalent_ids:
return None
id_rank... | 5,355,051 |
def _set_coverage_build():
"""Set the right environment variables for a coverage build."""
os.environ['SANITIZER'] = 'coverage'
os.environ['ENGINE'] = 'libfuzzer'
os.environ['ARCHITECTURE'] = 'x86_64' | 5,355,052 |
def get_L_max_C(L_CS_x_t_i, L_CL_x_t_i):
"""1日当たりの冷房全熱負荷の年間最大値(MJ/d)(20c)
Args:
L_CS_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房顕熱負荷 (MJ/h)
L_CL_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房潜熱負荷 (MJ/h)
Returns:
float: 1日当たりの冷房全熱負荷の年間最大値(MJ/d)
"""
# 暖冷房区画軸合算(暖冷房区画の次元をなくす)
L_CS_x_t = np.sum(L... | 5,355,053 |
def complete_session(session: namedtuple, speeches: list) -> dict:
"""
This will result in loss of data bc content will be reduced to speeches.
HTML_classes, speaker_flow, speaker_role etc. will not be given any longer
since it's assumed that speakers are either members of parliament or
ministers.
... | 5,355,054 |
def replace_text_in_file(file_path, replace_this, for_that, case_insensitive=False, is_regex=False, keep_copy=False,
number_of_subs=0):
""" replace a string or regex (if is_regex is set) from a file given in file_path, with another string.
This is a replacement for sed if needed.
... | 5,355,055 |
def load_annotations(ann_file):
"""Load the annotation according to ann_file into video_infos."""
video_infos = []
anno_database = mmcv.load(ann_file)
for video_name in anno_database:
video_info = anno_database[video_name]
video_info['video_name'] = video_name
video_infos.append(... | 5,355,056 |
def commandline(args):
"""
Settings for the commandline arguments.
Returns the parsed arguments.
"""
parser = argparse.ArgumentParser(description='Checks the timestamps for files in a directory.')
parser.add_argument("-p", "--path", required=True,
help="Path to offline ... | 5,355,057 |
def seq_hist(seq_lens: List[int]) -> Dict[int, int]:
"""Returns a dict of sequence_length/count key/val pairs.
For each entry in the list of sequence lengths, tabulates
the frequency of appearance in the list and returns the
data as a dict. Useful for histogram operations on sequence
length.
"""
seq_cou... | 5,355,058 |
def turn_south():
"""
Karel will turn to South side.
"""
while not facing_south():
turn_left() | 5,355,059 |
def test_ostfullness_serializer():
"""lfshealth.LfsOstFullness: can serialize and deserialize circularly
"""
# Read from a cache file
ostfullness = tokio.connectors.lfshealth.LfsOstFullness(cache_file=tokiotest.SAMPLE_LFS_DF_FILE)
print(ostfullness)
# Serialize the object, then re-read it and ve... | 5,355,060 |
def load_staging_tables(cur, conn):
"""
Load data from files stored in S3 to the staging tables.
"""
print("Loading data from JSON files stored in S3 buckets into staging tables")
for query in copy_table_queries:
cur.execute(query)
conn.commit()
print("Complete.\n"... | 5,355,061 |
def make_ms_url( syndicate_host, syndicate_port, no_tls, urlpath="" ):
"""
Make a URL to the MS.
Return the URL.
"""
scheme = "https://"
default_port = 80
if no_tls:
default_port = 443
scheme = "http://"
if syndicate_port != default_port:
return scheme + os.path.join... | 5,355,062 |
def display(ip=None, port=5555, device_id=None, debug=False):
"""
获取屏幕显示信息
:param ip: 地址
:param port: 端口(默认值5555)
:param device_id: 设备ID
:param debug: 调试开关(默认关闭)
:return: 不涉及
"""
adb_core.shell('dumpsys display | grep DisplayDeviceInfo', ip=ip, port=port, device_id=de... | 5,355,063 |
def clifford_canonical_F(
pauli_layer: List[int], gamma: np.ndarray, delta: np.ndarray
) -> Circuit:
"""
Returns a Hadamard free Clifford circuit using the canonical form of elements of the Borel group
introduced in https://arxiv.org/abs/2003.09412. The canonical form has the structure O P CZ CX where
... | 5,355,064 |
def calculate_second_moment_nondegenerate(
mu1: float, mu2: float, sigma1: float, sigma2: float, a: float, alpha: float
) -> float:
"""The second (raw) moment of a random variable :math:`\\min(Y_1, Y_2)`.
Args:
mu1: mean of the first Gaussian random variable :math:`Y_1`
mu2: mean of the sec... | 5,355,065 |
def game_loop():
"""
The core game loop, handling input, rendering and logic.
"""
while not state.get_current() == GameState.EXIT_GAME:
# progress frame
delta_time = state.update_clock()
# get info to support UI updates and handling events
current_state = state.get_curr... | 5,355,066 |
def q_make( x, y, z, angle):
"""q_make: make a quaternion given an axis and an angle (in radians)
notes:
- rotation is counter-clockwise when rotation axis vector is
pointing at you
- if angle or vector are 0, the identity quaternion is returned.
double x, y, z : axis of rotation
... | 5,355,067 |
def follow(file):
"""generator function that yields new lines in a file
"""
# seek the end of the file
file.seek(0, os.SEEK_END)
# start infinite loop
while True:
# read last line of file
line = file.readline()
# sleep if file hasn't been updated
if not line:
... | 5,355,068 |
def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pymssql.
"""
return create_engine(
_create_mssql_pymssql(username, password, host, port, database),
**kwargs
) | 5,355,069 |
def get_right_list_elements(result):
"""Some of the results are empty - therefore, the try-except.
Others are lists with more than one element and only specific
elements are relevant.
Args:
result (dict of lists): result of the xpath elements.
Returns:
dict of strs
"""
for... | 5,355,070 |
async def test_get_display(aresponses: ResponsesMockServer) -> None:
"""Test getting display information."""
aresponses.add(
"127.0.0.2:4343",
"/api/v2/device/display",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
... | 5,355,071 |
def test_short_file_name_with_ALWAYS():
"""Tests how Boost Jam handles the case when a Windows short file name is
passed to the builtin ALWAYS rule.
"""
if ( not BoostBuild.windows ):
return
t = BoostBuild.Tester(pass_toolset=0)
long_file_name1 = "1__target that should be rebu... | 5,355,072 |
def gen_pixloc(frame_shape, xgap=0, ygap=0, ysize=1., gen=True):
"""
Generate an array of physical pixel coordinates
Parameters
----------
frame : ndarray
uniformly illuminated and normalized flat field frame
xgap : int (optional)
ygap : int (optional)
ysize : float (optional)
... | 5,355,073 |
def select(df: pd.DataFrame, time_key,
from_time='00-00-00 00', to_time='99-01-01 00'):
"""
:param df:
:param time_key:
:param from_time:
:param to_time:
:return:
:rtype: pandas.DataFrame
"""
select_index = (df[time_key] >= from_time) & (df[time_key] < to_time)
... | 5,355,074 |
def load_apogee_distances(dr=None, unit='distance', cuts=True, extinction=True, keepdims=False):
"""
Load apogee distances (absolute magnitude from stellar model)
:param dr: Apogee DR
:type dr: int
:param unit: which unit you want to get back
- "absmag" for absolute magnitude
... | 5,355,075 |
def userstudy(config, data_train):
"""
Update the model based on feedback from user study.
- [config]: hyperparameters for model fine-tuning
- [data_train]: data pool to sample from
"""
def preprocess_data(doc, queries):
"""
Create a new field in [doc] called [antecedent_map] whi... | 5,355,076 |
def clique_create(request):
"""
Creates a new grouping in the database (this integration must be stored in the db to be useful)
Arguments: /group-create "groupname" "@user1 @user2"
"""
requesting_user_id = request.POST.get('user_id')
args = re.findall(DOUBLE_QUOTE_ARG_REGEX, request.POST.get("te... | 5,355,077 |
def cg_atoms(atoms, units, sites, scale, scaleValue, siteMap, keepSingleAtoms,
package):
"""
Get positions for atoms in the coarse-grained structure and the final
bond description. Returns a dictionary of the lattice, fractional
coordinates, and bonds. Also provides the option to scale t... | 5,355,078 |
def read_tickers(video, ocr = None, debug = False, **kwargs):
"""
Reads news stories from sliding tickers on video.
Returns lists of dictionaries which contain:
text: news story text
start time: time when news story shows up
end time: time when news story disappears
Each list co... | 5,355,079 |
def compute_msa_weights(msa, threshold=.8):
"""
msa (Bio.Align.MultipleSeqAlignment): alignment for which sequence frequency based weights are to be computed
threshold (float): sequence identity threshold for reweighting
NOTE that columns where both sequences have a gap will not be taken into account w... | 5,355,080 |
def do_CreateRedis(client, args):
""" Create redis """
val = client.CreateRedis(args.mem,
duration=args.duration,
name=args.name,
zone=args.zone)
utils.print_dict(val) | 5,355,081 |
def search_storefront(client, phrase):
"""Execute storefront search on client matching phrase."""
resp = client.get(reverse("search:search"), {"q": phrase})
return [prod for prod, _ in resp.context["results"].object_list] | 5,355,082 |
def is_repo_in_config(config, repo, rev, hook_id):
"""Get if a repository is defined in a pre-commit configuration.
Parameters
----------
config : dict
Pre-commit configuration dictionary.
repo : str
Repository to search.
rev : str
Repository tag revision.
hook_id : Ho... | 5,355,083 |
def mat33_to_quat(mat):
"""
Convert matrix to quaternion.
:param mat: 3x3 matrix
:return: list, quaternion [x, y, z, w]
"""
wxyz = transforms3d.quaternions.mat2quat(mat)
return [wxyz[1], wxyz[2], wxyz[3], wxyz[0]] | 5,355,084 |
def reshape(x, new_shape):
"""
Reshapes a tensor without changing its data.
Args:
x (Tensor): A tensor to be reshaped.
new_shape (Union[int, list(int), tuple(int)]): The new shape should be
compatible with the original shape. If the tuple has only one element,
the re... | 5,355,085 |
def update_depth(depth_grid, elapsed_ts, depth_factor):
"""Just in time Update Depth for lake to pond
Parameters
----------
depth_grid: np.array like (float)
grid of current lake depths
elapsed_ts: float
number timesteps since start year
depth_factor: float
Returns
----... | 5,355,086 |
def get_submissions(config, event_name, state='new'):
"""
Retrieve a list of submissions and their associated files
depending on their current status
Parameters
----------
config : dict
configuration
event_name : str
name of the RAMP event
state : str, optional
s... | 5,355,087 |
def split_dataframe(df, size=10*1024*1024):
"""Splits huge dataframes(CSVs) into smaller segments of given size in bytes"""
# size of each row
row_size = df.memory_usage().sum() / len(df)
# maximum number of rows in each segment
row_limit = int(size // row_size)
# number of segments
seg... | 5,355,088 |
def convert_table_codes(input_filename: Path, output_filename: Path = None, column: str = 'countryCode',
namespace: Optional[str] = None, fuzzy:int = 0) -> Path:
"""
Adds a 'regionCode' column to the given table containing iso-3 country codes.
Parameters
----------
input_filename: Path
output_filename: Path
co... | 5,355,089 |
def add_message(exception, message):
"""
Embeds an error message into an exception that can be retrieved by
try_get_error_message().
Parameters
----------
exception : Exception
message : str
"""
exception.args += (_Message(message),) | 5,355,090 |
def allow_view(user):
"""Is the current user allowed to view the user account?
Yes, if current user is admin, staff or self.
"""
if not flask.g.current_user: return False
if flask.g.am_admin: return True
if flask.g.am_staff: return True
if flask.g.current_user['username'] == user['username']... | 5,355,091 |
def httptimestamp(inhttpdate):
"""
Return timestamp from RFC1123 (HTTP/1.1).
"""
dat = datetime.datetime(*eut.parsedate(inhttpdate)[:5])
return int(time.mktime(dat.timetuple())) | 5,355,092 |
def main():
"""Read a theme list file, and moves file and create a fixed theme list."""
tml = read(
r"c:\tmp\xxx\AKR Theme List.tml"
) # r"X:\GIS\ThemeMgr\AKR Theme List.tml")
path_maps = build_file_mapping(
"data/tmpaths.txt", "data/moves_extra.csv"
) # data/PDS Moves - inpakrovm... | 5,355,093 |
def calculate_duration(start_date, end_date=None):
""" Calculate how many years and months have passed between start and end dates """
# If end date not defined, use current date
if not end_date:
end_date = datetime.date.today()
years = end_date.year - start_date.year
months = end_date.month... | 5,355,094 |
def write(path, *content):
"""
写出文件
:param path:位置
:param content:内容
:return:
"""
# 防止有些使用`/`有些用`\\`
_sep_path = []
s = path.split('/')
[_sep_path.extend(item.split('\\')) for item in s]
_path = ''
for i in _sep_path:
_end = _sep_path[len(_sep_path) - 1]
i... | 5,355,095 |
def GetSourceRoot(filename):
"""Try to determine the root of the package which contains |filename|.
The current heuristic attempts to determine the root of the Chromium source
tree by searching up the directory hierarchy until we find a directory
containing src/.gn.
"""
# If filename is not absolute, then... | 5,355,096 |
def actives(apikey: str) -> typing.List[typing.Dict]:
"""
Query FMP /actives/ API
:param apikey: Your API key.
:return: A list of dictionaries.
"""
path = f"actives"
query_vars = {"apikey": apikey}
return __return_json_v3(path=path, query_vars=query_vars) | 5,355,097 |
def write_json_file(data: dict, filename: str) -> None:
"""
Write a JSON file.
Example:
{'a': 1, 'b': {'c': 3, 'd': 4}}
{
"a": 1,
"b": {
"c": 3,
"d": 4
}
}
:type data: dict
:param data: data to write
:type filename: str
:param filename: name ... | 5,355,098 |
def find_sue_de_coq(board: Board):
"""we look at each intersection (3 cells) of a block and a row/col:
- we need either two cells containing (together) 4 distinct candidates or
three cells containing (together) 5 distinct candidates
- now we need to find two bi-value cells:
a. one in the row... | 5,355,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.