content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import chardet
import os
def get_folder_status(dirname, with_message=False):
"""获取目录状态
Args:
dirname(str): 目录路径
with_message(bool): 是否需要返回状态文件内的信息
"""
status = None
closest_time = 0
message = ''
for status_type in [
DatasetStatus, TaskStatus, PredictStatus, Pru... | f07ea80cc517c9653b675484c5ab645ea5f22198 | 3,657,100 |
def handle_session_event(event: EventData) -> core_pb2.SessionEvent:
"""
Handle session event when there is a session event
:param event: event data
:return: session event
"""
event_time = event.time
if event_time is not None:
event_time = float(event_time)
return core_pb2.Sessi... | ddaa78a889c23326f52595d4a7fb71c1813eb971 | 3,657,101 |
import sys
import os
import json
import re
def job_builder(meta, valid_meta, workflow, job_dir, out_dir, coprocess=None, other_args="", writeimg=False):
"""Build a list of image processing jobs.
Args:
meta: Dictionary of processed image metadata.
valid_meta: Dictionary of valid meta... | e64cb50f1ecd01217fc5308e5de0d99dd384e67e | 3,657,102 |
def bump_patch(version):
"""Raise the patch part of the version
:param: version string
:return: the raised version string
:rtype: str
"""
verinfo = parse(version)
return format_version(verinfo['major'], verinfo['minor'],
verinfo['patch'] + 1) | 350e53788b0851138eb0d0248250bebd7e357e10 | 3,657,103 |
def _extract_bike_location(bike, lon_abbrev='lon'):
"""
Standardize the bike location data from GBFS. Some have extra fields,
and some are missing fields.
Arguments:
bike (dict[str, str]): A GBFS bike object as it appears in free_bike_status.json
lon_abbrev (str): The abbreviation used for `longitude`
... | a20929a85c993a59b82b552fcfee81b1f818648d | 3,657,104 |
def clean_word(word):
"""Return word in lowercase stripped of whitespace"""
return word.strip().lower() | ce57fa95ec111ee18c8a00c2076c686bc0abfe5c | 3,657,105 |
def get_batch_size(tracks):
"""
If tracks is a track-major list of possibly None tracks, get the batch size
"""
return get_shape(tracks)[0] | 677f26a0f42d4e745d77ff6abc1867ce857ea208 | 3,657,106 |
def find_edges_from_wires(body: TopoDS_Shape) -> set[TopoDS_Edge]:
"""Return set of edges from Wires."""
edge_set = set()
for wire in TopologyExplorer(body, ignore_orientation=False).wires():
for edge in WireExplorer(wire).ordered_edges():
edge_set.add(edge)
return edge_set | 89d8d848d98c32e925f955da623a3e1018245f75 | 3,657,107 |
import geopandas as gpd
import contextily as ctx
import seaborn as sns
import cartopy.crs as ccrs
def plot_israel_map(gis_path=gis_path, rc=rc, ticklabelsize=12, ax=None):
"""general nice map for israel, need that to plot stations,
and temperature field on top of it"""
sns.set_style("ticks", rc=rc)
is... | 09c801bf48756e9c118222747ce49dcd8187df90 | 3,657,108 |
def getSentB(text2: str, offsetB: int, nextPoint: int, sentLength: int):
"""
alignSentences auxiliar function to get the sentences of the original text.
"""
posB = text2[offsetB+sentLength:].find('.')
sentLength += posB+1
sentB = text2[offsetB:offsetB+sentLength]
nextPoint = offsetB + sentLe... | 54914a3c1d85464c0e5a4267538a73693e3df238 | 3,657,109 |
def get_mapping_fcost_local(interface, bus_def):
"""
coarse cost function to cheaply estimate local (subset of ports)
interface match to bus_def
"""
cost = _get_mapping_fcost_base(interface, bus_def, penalize_umap=False)
name_cost = _get_name_fcost2(interface, bus_def)
cost.nc = name_cost
... | c945e89174fea0c131f35ad4688c5539a55c3eda | 3,657,110 |
import base64
def base64_image(image: bytes, mime_type: str) -> str:
"""Encode the image for an URL using base64
Args:
image: the image
mime_type: the mime type
Returns:
A string starting with "data:{mime_type};base64,"
"""
base64_data = base64.b64encode(image)
image_... | 3079c73137959fea1d16ceb64251870500ae30a5 | 3,657,111 |
import math
import six
import numpy
def multi_box_head(inputs,
image,
base_size,
num_classes,
aspect_ratios,
min_ratio=None,
max_ratio=None,
min_sizes=None,
max_sizes... | e3fabec0dd64fec9caea929e0bf4c04848d22df6 | 3,657,112 |
from operator import invert
import numpy
def expandMask(img, shrink = False, step = 1):
"""Grow or shrink a mask by a pixel."""
if shrink:
img = invert(img)
img = jitterSum(img.data, step) > 0
img = Image(data = img.astype(numpy.uint8)*255)
if shrink:
img = invert(img)
return i... | 4853a0c42856cc34a5b9b58533d335c0ac858345 | 3,657,113 |
def isHeader(line):
"""
tests to see if 'line' is in the event file
header
"""
if containsAny(line, 'EVF Filename:', 'Generation Time:', 'Start_time:',
'End_time:', 'events in list)', '#', 'Include:',
'Init_value:'):
return True
elif len(line... | 548d0273b174c16e7ab874fe8a94d4ec7e87703b | 3,657,114 |
import requests
def redirect_page(source_url, destination_url):
"""returns False is current page is not 200"""
def _check_redirect(full_url):
print('Getting ' + full_url)
response = requests.get(full_url, allow_redirects=False)
if response.status_code == 200:
print("Was 20... | 8caa9db41948f44cc015ca51f179ff318eb22ada | 3,657,115 |
def semantic_analysis(program, print_results=True):
"""
TODO
:param program: TODO
:param print_results: TODO
:return: TODO
"""
semanter = make_semantic_analyser()
program_ir = semanter.transform(program)
if print_results:
print_readable_ast(program_ir)
return program_ir | 5921e93c8d60a367a13e8154cffaf9e630a7f4ba | 3,657,116 |
def WrapWithQuotes(text, quote='"'):
""" Wrap the supplied text with quotes
Args:
text: Input text to wrap
quote: Quote character to use for wrapping (default = "")
Returns:
Supplied text wrapped in quote char
"""
if not text.startswith(quote):
text = quote + text
... | f4f7b83d60e3ea928e3502b9d19ca4c8d52914b9 | 3,657,117 |
import os
def get_fastsync_bin(venv_dir, tap_type, target_type):
"""
Get the absolute path of a fastsync executable
"""
source = tap_type.replace('tap-', '')
target = target_type.replace('target-', '')
fastsync_name = f'{source}-to-{target}'
return os.path.join(venv_dir, 'pipelinewise', '... | 113835e7620bd378d87cdd162b842e1f7c3a86dc | 3,657,118 |
def login_aws_via_idp(session, username, password, entity_id):
""" Get a SAML assertion and set of AWS roles which can be assumed with the SAML assertion. """
logger.info("Looking up your IdP")
idp_url, idp_form = get_idp_login_form(
session, username, password, entity_id)
logger.info("Logging ... | 586250b66771275b5282ae0e22d40298550164e2 | 3,657,119 |
def fit_linreg(x, y, intercept=True):
"""Simple linear regression: y = kx + b.
Arguments
---------
x: :class:`~numpy.ndarray`
A vector of independent variables.
y: :class:`~numpy.ndarray`
A vector of dependent variables.
intercept: bool
If using steady state assumption f... | 18248eb0ece96dfda5fbc2d94a591f98570feddd | 3,657,120 |
import torch
def entropy(x, input_as_probabilities):
"""
Helper function to compute the entropy over the batch
input: batch w/ shape [b, num_classes]
output: entropy value [is ideally -log(num_classes)]
"""
if input_as_probabilities:
x_ = torch.clamp(x, min = 1e-8)
b = x_ ... | 9cf9f5ecd59ffe068bbf8f25da62ac3c5c2eedb6 | 3,657,121 |
from typing import Callable
def find_function_in_object(o: object, function_name: str) -> Callable:
"""Finds a callable object matching given function name in given object.
Args:
o: Any object.
function_name: Name of attribute within o.
Returns:
Callable object with name <functio... | c3b6ad12f42d005f643bc8a657f728613bd0e93c | 3,657,122 |
async def refresh(db: AsyncSession, schema: RefreshToken):
"""
Refresh token
:param db: DB
:type db: AsyncSession
:param schema: Refresh token
:type schema: RefreshToken
:return: Access token
:rtype: dict
:raise HTTPException 400: User not found
""... | f20cde1c44ef515c18318c45af9df4bb360c85e6 | 3,657,123 |
def gumbel_softmax(logits, temperature, hard=False):
"""Sample from the Gumbel-Softmax distribution and optionally discretize.
Args:
logits: [batch_size, n_class] unnormalized log-probs
temperature: non-negative scalar
hard: if True, take argmax, but differentiate w.r.t. soft sample y
Returns:
[... | 7612ef322acf77f8c2fdf1963b6d15934f84b416 | 3,657,124 |
import copy
def dqn_learn(t, agent, env, env_state, history, args):
"""Learning loop for DeepQAgent"""
step_type, reward, discount, state = env_state
state = copy.deepcopy(state)
# Act
action = agent.act_explore(state)
step_type, reward, discount, successor = env.step(action)
# Learn
... | 1ff3333ef9f2492866a1b32540c5440d3683d600 | 3,657,125 |
def build_custom_Theta(
data,
data_description=[],
add_constant_term=True,
):
"""
builds a matrix Theta(U) from a predefined set of terms
This is used when we subsample and take all the derivatives point by point or if there is an
extra input to put in.
input:
data: column 0 is... | 451c306124e94d5f04d436c98ede6af232a6458e | 3,657,126 |
import pathlib
from typing import Optional
import importlib
def load(plugin: pathlib.Path) -> Optional[ModuleType]:
"""Load a specific cemu plugin
Args:
plugin (pathlib.Path): the path of the plugin to load
Returns:
Optional[ModuleType]: the loaded plugin module on success, None if there... | eac265743ba9a58842cf7e97a1b961234ea3b17b | 3,657,127 |
from datetime import datetime
import logging
import os
def get_standard_logger(name, log_dir=None):
"""Function to return an instance of type logger."""
if log_dir is None:
log_dir = '/Users/teaton/dev/fantasyAM/logs'
time_stamp = datetime.now().strftime('%Y%m%d_%H%M%S')
logging.basicConfig(l... | 1e0c4d6ea3ee74d7f5c88f2861369fd3a37f7750 | 3,657,128 |
import traceback
def getDatabaseConnection(databaseString):
"""Attempt connection to the database"""
sqlsession = None
try:
sqlengine = sqlalchemy.create_engine(databaseString)
SQLSession = sessionmaker(bind=sqlengine)
sqlsession = SQLSession()
print("Connection to " + databaseString + " successfull")
... | 8199838e24c6828977d5fe6a7f2af20f755f25f6 | 3,657,129 |
def prepare_multiple_configs(conf):
""" This function uses workload_1 as a base, and then duplicates its configuration for all
other workloads 2,3... while leaving properties already defined in subsequent workloads (2,3..)
unchanged.
"""
keys_starting_with_workload = []
for k, _ in conf.iterite... | 760adf50bbca9dd160375ed8d506a33618d39a94 | 3,657,130 |
def undo_coefficient_scaling(clf = None, coefficients = None, intercept = 0.0, scaler = None):
"""
given coefficients and data for scaled data, returns coefficients and intercept for unnormalized data
w = w_scaled / sigma
b = b_scaled - (w_scaled / sigma).dot(mu) = b_scaled - w.dot(mu)
:param skle... | cee60338386bdc87cb50e4b54af43517135fba46 | 3,657,131 |
import copy
def reduce(snail_nr):
"""Returns a fully reduced version of the given snail number."""
new_snail_nr = copy.deepcopy(snail_nr)
# print("Start:")
# print(snail_nr)
while True:
# print("\nNew reduction phase...")
if explode_in_place(new_snail_nr):
# print("Exp... | 1facd7a7bbc73794ff2519ef0894ec9536c18690 | 3,657,132 |
def load_image_embedding_model(input_repr, content_type, embedding_size):
"""
Returns a model with the given characteristics. Loads the model
if the model has not been loaded yet.
Parameters
----------
input_repr : "linear", "mel128", or "mel256"
Spectrogram representation used for audi... | f78d458e2cd000206d3fcc35c166ede43e84e8fd | 3,657,133 |
def prepare_alm(alm=None, ainfo=None, lmax=None, pre=(), dtype=np.float64):
"""Set up alm and ainfo based on which ones of them are available."""
if alm is None:
if ainfo is None:
if lmax is None:
raise ValueError("prepare_alm needs either alm, ainfo or lmax to be specified")
ainfo = sharp.alm_info(lmax)
... | 21406a6b3df7e63eeb05998c8940e525021b62ce | 3,657,134 |
from typing import Any
def increment_occurance_dict(d: dict, k: Any) -> None:
"""
Increment occurance dict, updates in-place so nothing is returned.
"""
try:
d[k] += 1
except KeyError:
d[k] = 1
return None | 725b437494f4c647848c54a3d13b4e974fa7f0e8 | 3,657,135 |
import sys
import os
import pathlib
def package_versions(modules=None, builtins=False, standard_lib=None):
"""Retrieve package version information.
When builtins or standard_lib are None, they will be included only
if a version was found in the package.
@param modules: Modules to inspect
@type m... | 3962c29740c8b7ee9214a3d343a5774973344563 | 3,657,136 |
import scipy
def closest_line(query_lines, metric='cosine'):
"""Compute the distance to, and parameters for, the closest line to each
line in query_lines.
Args:
- query_lines: Array of lines to compute closest matches for, shape
(n_lines, width, height, 1)
- metric: String to ... | 187cb6f8266ddf7bd0347fb233fb02a7ea4cbad3 | 3,657,137 |
def deref_vtk(obj):
"""Dereferences the VTK object from the object if possible."""
if isinstance(obj, TVTKBase):
return obj._vtk_obj
else:
return obj | 1ba46f83a389983df3c35f011c94836f12fdd905 | 3,657,138 |
def order_assignee_factory(team):
"""
Creates a :class:`datahub.omis.order.models.OrderAssignee` instance related to ``team``
"""
adviser = Advisor.objects.create(
first_name='John',
last_name='Doe',
email=f'{uuid4()}@example.com',
)
order_assignee = OrderAssignee.objects... | fe39d16a105ff01be63614e76dcf001b5ca4171f | 3,657,139 |
def is_bool(space, w_obj):
""" Finds out whether a variable is a boolean"""
return space.wrap(w_obj.tp == space.tp_bool) | 39b62ec08ebbdd4d7505e558ad4901ca67afc12d | 3,657,140 |
from typing import Tuple
from typing import Dict
from typing import List
from typing import Callable
from typing import Any
def _compile_for_uhfqa(
device: zhinst.Device,
cached_schedule: schedule_helpers.CachedSchedule,
settings_builder: zi_settings.ZISettingsBuilder,
) -> Tuple[zi_settings.ZISettingsBui... | ba01201bac5bb40101009145e7cf4a0fca5684aa | 3,657,141 |
import os
import yaml
import logging
def read_config():
"""Parses config and returns config values
:returns: config as dict
"""
dirname = os.path.dirname(__file__)
config_path = os.path.join(dirname, 'config.yaml')
try:
stream = open(config_path, "r")
except FileNotFoundError:
... | d8584727983880591675fcb99dbcc4b9a3a75626 | 3,657,142 |
def air_density(t_f, elevation):
"""Eq 20, page 25"""
return (1.293 - 1.525e-4 * elevation + 6.379e-9 * elevation ** 2) / (
1 + 0.00367 * t_f
) | d5677c755fc52e1ae8cc5293d4ed5c9a4debb71d | 3,657,143 |
def _strip_after_new_lines(s):
"""Removes leading and trailing whitespaces in all but first line."""
lines = s.splitlines()
if len(lines) > 1:
lines = [lines[0]] + [l.lstrip() for l in lines[1:]]
return '\n'.join(lines) | 247cee0f34ab1e742069e05c8c00095cd24d80bc | 3,657,144 |
def make_connection(request):
"""
Create a StreamSplitRoutine from a MockConnection and a container, return topics 'A' and 'B' as well as the routine
"""
def generate(*, max_items_send: int):
return MockConnection(max_items_send=max_items_send)
yield generate | a0a4adbdf6fb7487d27f9e81c8f4bb5af49fae58 | 3,657,145 |
import copy
def my_browse(*args, **kwargs):
""" Creates and starts an ObjectBrowser with modified summary column.
"""
attribute_columns = copy.deepcopy(DEFAULT_ATTR_COLS)
summary_column = [col for col in attribute_columns if col.name == 'summary'][0]
summary_column.data_fn = my_summary
return ... | 3f5e681112bf5dd7a56a3259e188a1c5773f2cf5 | 3,657,146 |
import psutil
def cpu_min_frequency():
"""
Returns the processor minimum frequency, in Mhz (> int)
"""
return psutil.cpu_freq().min | de4312ccd95e46d6d157bdb1a08d48fe5924942f | 3,657,147 |
def log_error(message: str) -> str:
"""error log"""
return message | dbd86c39bc504dbac8d308e124c73310df21f372 | 3,657,148 |
from datetime import datetime
from operator import or_
from operator import and_
def exclude_preservation_pending(q):
"""
Transform query to exclude MuseumObject entries which are pending
preservation
"""
now = datetime.datetime.now(datetime.timezone.utc)
preservation_boundary = now - PRESERVA... | a43eefeaaac16ac872ae02bd522873966e5f21e2 | 3,657,149 |
from datetime import datetime
def naturalday(value, format=None):
"""
For date values that are tomorrow, today or yesterday compared to
present day returns representing string. Otherwise, returns a string
formatted according to settings.DATE_FORMAT.
"""
value = localtime(value)
try:
... | fbc1fe32f5735f57c989488989aabd427a59c160 | 3,657,150 |
import tensorflow as tf
from torch.utils.data import DataLoader
def test_adaptors(adaptor: str, shuffle_buffer_size: int):
"""
Test if framework-specific generator adpators yield batches.
"""
idx = np.arange(0, 10)
def map_fn(x_, obs_):
"""
Note: Need to convert to numpy in output... | 088bd70f50b63a07f7392f1712de0d6aab9515a2 | 3,657,151 |
def qg8_graph_write(filename: str, graph: qg8_graph):
"""
Wrapper function which prepares a collection of chunks (graph) and writes it to a file
"""
if not isinstance(graph, qg8_graph):
raise TypeError("Second argument is not a qg8_graph")
try:
qg8f = qg8_file_open(filename, QG8_MOD... | a26891c86df5541cb1ffa3d3eb463bea5472d3d7 | 3,657,152 |
def valid_post_author(user, post):
"""This function checks whether the post was created by the user"""
if str(user.key().id()) == str(post.user.key().id()):
return True | 94ca2f23aa66f79be997080c61fc2f265e868e5f | 3,657,153 |
import json
import time
import collections
from datetime import datetime
def listing(request, **kwargs):
"""view for processing and applying listings"""
context = {
'view': 'listing',
'all_channels': CHANNELS,
'all_towns': TOWNS,
'method': request.method,
'actions': ['l... | c4938dc4db4526ca93558305ea702660956e77fa | 3,657,154 |
def get_rise_or_fall(U, V, Im, demo=0):
"""
Get increase or decrease of intensity in flow direction: This finds us
the front and the wake regions of each wave.
"""
rr, cc = np.shape(Im)
ax_x, ax_y = np.linspace(1, cc, cc), np.linspace(1, rr, rr)
XX, YY = np.meshgrid(ax_x, ax_y)
Velo_mag ... | a2d86bd986f576054ccd2686af7d9da4ffd3a1f0 | 3,657,155 |
import functools
def has_vanity_name(func):
"""Decorator checking whether a command has been provided a vanity_name value"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
vanity_name = args[1]
if vanity_name is None:
ctx = args[0]
await ctx.send("Please... | 5da3cc410822f0e112a2be1b3cdfc66fb4d79b0c | 3,657,156 |
from typing import List
import logging
def get_data_providers(
data_providers_configs: List[dict], data_providers_input: List[str]
) -> List[data.DataProvider]:
"""
Determines which data provider and in which order should be used.
:param data_providers_configs: A list of data provider configurations
... | 076659d2bf619808f5cb0ac124839e569af0c74a | 3,657,157 |
def _PredatorForFracas(config=None):
"""A helper to pass in the standard pipeline class."""
return PredatorForFracas(MOCK_GET_REPOSITORY, config or {}) | c7e1e3c771a8b8afa921a291198adc084f75d186 | 3,657,158 |
def py_SurfStatSmooth(Y, surf, FWHM):
"""Smooths surface data by repeatedly averaging over edges.
Parameters
----------
Y : numpy array of shape (n,v) or (n,v,k)
surface data, v=#vertices, n=#observations, k=#variates.
surf : a dictionary with key 'tri' or 'lat', or a BSPolyData object.
... | 6b537e33174459cee6364dbd145181c66156830d | 3,657,159 |
from typing import Tuple
def arm_name_to_sort_key(arm_name: str) -> Tuple[str, int, int]:
"""Parses arm name into tuple suitable for reverse sorting by key
Example:
arm_names = ["0_0", "1_10", "1_2", "10_0", "control"]
sorted(arm_names, key=arm_name_to_sort_key, reverse=True)
["contro... | c29958bb541a9754e7b4defc6ad953030a364d2f | 3,657,160 |
from typing import Optional
from typing import Mapping
from typing import Any
def run_query_row(cur: Cursor, sql: str, params: Optional[Mapping[str, Any]] = None, **kwargs: Any
) -> Optional[skytools.dbdict]:
""" Helper function if everything you need is just paramertisized execute to
fe... | 0ba46ba0666d0cbefeda5b3fe62ac5ed883a190f | 3,657,161 |
def vortex_indicator(high_arr, low_arr, close_arr, n):
"""Calculate the Vortex Indicator for given data.
Vortex Indicator described here:
http://www.vortexindicator.com/VFX_VORTEX.PDF
:param high_arr: high price of the bar, expect series from cudf
:param low_arr: low price of the bar, expect s... | 8b34ca26f7cc52361eb95ff1ad17c010fd270759 | 3,657,162 |
from typing import Dict
def getServiceById(serviceId: str, **kwargs) -> Dict:
"""Retrieve service by its identifier.
Args:
serviceId: Identifier of service to be retrieved.
Returns:
Service object.
"""
db_collection_service = (
current_app.config['FOCA'].db.dbs['serviceSt... | fc568b337495873263f9a7ea85d46ac4bcd55819 | 3,657,163 |
from typing import Dict
from typing import Any
def replace_module_prefix(
state_dict: Dict[str, Any], prefix: str, replace_with: str = "", ignore_prefix: str = ""
):
"""
Remove prefixes in a state_dict needed when loading models that are not VISSL
trained models.
Specify the prefix in the keys th... | b8499c818053e7798e9549fbe546bab7d5fbfa84 | 3,657,164 |
import os
import glob
def create_csv(parent_dir, tsv_folder, export_csv = True):
"""
The function reads all .tsv files, combine them into a csv file, and export .csv file into parent directory
Args:
parent_dir (string) : The working directory you are working with
tsv_folder (st... | a5efd653bbb23dc5b0135b03961521019e183c85 | 3,657,165 |
def crop(img, left, top, right, bottom):
"""
Crop rectangle from image.
Inputs:
img - The image to crop.
left - The leftmost index to crop the image.
top - The topmost index.
right - The rightmost index.
bottom - The bottommost index.
Outputs:
img - The c... | 1507a55bba07dc656f51f873d2328b69f70682c9 | 3,657,166 |
import os
def cl_file_with_height(tmp_path):
"""Create netcdf file for ``cl`` with hybrid height coordinate."""
nc_path = os.path.join(tmp_path, 'cl_hybrid_height.nc')
dataset = Dataset(nc_path, mode='w')
create_hybrid_height_file(dataset, 'cl')
dataset.close()
return nc_path | ff66c7adb505135a115d7b2ded2b80e2fea942ee | 3,657,167 |
import ipaddress
def get_hosts(network):
"""get_hosts() will return all the hosts within a provided network, range"""
network = ipaddress.IPv4Network(network, strict=False)
hosts_obj = network.hosts()
hosts = []
for i in hosts_obj:
hosts.append(str(i))
return hosts | 097fa3abbf1cda1c3c0ddc0c2fec4a06d1d44fa9 | 3,657,168 |
def select_organization(cursor):
"""organization情報取得(全取得)
Args:
cursor (mysql.connector.cursor): カーソル
Returns:
dict: select結果
"""
# select実行
cursor.execute('SELECT * FROM organization ORDER BY organization_id')
rows = cursor.fetchall()
return rows | 6e5c1a2f90d41223ba09fe3278353370515c0430 | 3,657,169 |
def _GetInstDisk(index, cb):
"""Build function for calling another function with an instance Disk.
@type index: int
@param index: Disk index
@type cb: callable
@param cb: Callback
"""
def fn(ctx, inst):
"""Call helper function with instance Disk.
@type ctx: L{InstanceQueryData}
@type inst: ... | 4dc83bb5c7ac3556750f9e3a70f77c9325893fb4 | 3,657,170 |
def Jphii_cal(L, W, q, xi_local):
"""タスク写像のヤコビ行列"""
return np.array([[1, 0, -sin(q[2, 0]) * xi_local[0, 0] - cos(q[2, 0]) * xi_local[1, 0]],
[0, 1, cos(q[2, 0]) * xi_local[0, 0] - sin(q[2, 0]) * xi_local[1, 0]]], dtype = np.float32)
#return np.array([[1, 0, -xi_local[1, 0]],
# ... | 300a3724829d8ce2df15801b6ae02e78e8e2e6b7 | 3,657,171 |
def model_evalution(test_data):
""" function to test the loss and accuracy on validation data """
for X_test, y_test in val_data:
y_pred = model(X_test, training=False)
val_acc_metrics.update_state(y_test, y_pred)
accuracy = val_acc_metrics.result()
return float(accuracy) | d581013f50560082f8f6854f201cfd791be6e876 | 3,657,172 |
import inspect
import numpy
def make_python_script_from_list(list_optical_elements1,script_file=""):
"""
program to build automatically a python script to run shadow3
the system is read from a list of instances of Shadow.Source and Shadow.OE
:argument list of optical_elements A python list with inta... | 85eb57955badaa4a2748be8ca6f2bf0f370b422d | 3,657,173 |
def flax_tag(arr):
"""Wraps a value in a flax module, to inspect intermediate values."""
return arr | be2fbef6117c859b7fc9dd7274815df4e70df17e | 3,657,174 |
def toEpoch( dateTimeObject = None ):
"""
Get seconds since epoch
"""
if dateTimeObject == None:
dateTimeObject = dateTime()
return nativetime.mktime( dateTimeObject.timetuple() ) | f679f75e9d416c471491b0b933505fc6bbb6eb7d | 3,657,175 |
import requests
import json
def sendNotification(token, title, message, extraData=None, channelID=None):
"""
send Notification to Devices
:param token:
:param title:
:param message:
:return:
"""
url = 'https://exp.host/--/api/v2/push/send'
headers = {
"Content-Type": "app... | 1038dfd3872221a0d447b7708d58d95e931c59e5 | 3,657,176 |
def make_phsfct_kernel(size_px, dpx, g_fac):
"""
Make a kernel for phase function convolution
:param size_px:
:param dpx: [deg/px]
:param g_fac:
:return: ph_ker [deg]
"""
ke = np.mgrid[:size_px, :size_px]
half = (size_px - 1) / 2
ke[0] -= half
ke[1] -= half
dist = np.sqrt... | 0f214d19f7418385f3db9155e8cabb06779fdf83 | 3,657,177 |
def sample_pts_ellipsoid_surface(mu, Q, NB_pts, random=True):
"""
Uniformly samples points on the surface of an ellipsoid, specified as
(xi-mu)^T Q^{-1} (xi-mu) == 1
arguments: mu - mean [dim]
Q - Q [dim x dim]
NB_pts - nb of points
random - True... | 89fa8383d32b74e8c92a52792fe2de4d35816acc | 3,657,178 |
def load_mzml_path():
"""Return the path to the mzML toy file.
Parameters
----------
None
Returns
-------
path_data : str
The path to the mzML data.
Examples
--------
>>> from specio.datasets import load_mzml_path
>>> load_mzml_path() # doctest: +ELLIPSIS
'...s... | b0548589a209b14ef336a28eeca74782f3550186 | 3,657,179 |
def _czce_df_read(url, skip_rows, encoding='utf-8', header=0):
"""
郑州商品交易所的网页数据
:param header:
:type header:
:param url: 网站 string
:param skip_rows: 去掉前几行 int
:param encoding: utf-8 or gbk or gb2312
:return: pd.DataFrame
"""
headers = {
"Accept": "text/html,application/xh... | 1491e312f1548141294d20b6ebe2fb4517cd3e07 | 3,657,180 |
import random
def select(weights):
"""
select a node with probability proportional to its "weight"
"""
r = random.random() * sum(weights)
s = 0.0
for k,w in enumerate(weights):
s += w
if r <= s:
return k
raise RuntimeError("select WTF from %s" % weights) | fed92de65cfae6f3532754215f5b88a564365ac7 | 3,657,181 |
def kexo(spacecraft_id, sensor_id, band_id):
"""Sun exo-atmospheric irridiance [W/m2/sr]
This is used for processing surface reflectance.
Spacecraft_id: Landsat7
Sensor_id: ETM+
band_id: band1, band2, band3, band4, band5, band7, band8
Spacecraft_id: Terra
Sensor_id: Aster
band_id: band1, band2, band3, ban... | 0e11a1b0b6ea8a43bef954273ed3a32a1d39c842 | 3,657,182 |
def gen_profile_id(profile_id):
"""
Generates the Elasticsearch document id for a profile
Args:
profile_id (str): The username of a Profile object
Returns:
str: The Elasticsearch document id for this object
"""
return "u_{}".format(profile_id) | 003586fe87d2936d9054aaa35963ae0241a5e594 | 3,657,183 |
import pathlib
import os
import sys
import re
def check_config():
"""
Check required fields are present in config.
"""
sections = [{'name': 'assembly',
'keys': ['accession', 'prefix', 'alias', 'span'],
'defaults': {'accession': 'draft', 'alias': '==prefix'}},
... | 2fa8d8768144a9c84fe20394ac572b63349a28cd | 3,657,184 |
async def get_self_info(credential: Credential):
"""
获取自己的信息
Args:
credential (Credential): Credential
"""
api = API["info"]["my_info"]
credential.raise_for_no_sessdata()
return await request("GET", api["url"], credential=credential) | 74cc7f5e43c555de45c382db27cd314bb2b5794e | 3,657,185 |
import os
def app(request):
"""Testable flask application"""
_app.config.from_mapping(
TESTING=True,
SECRET_KEY=os.environ.get('SECRET_KEY'),
SQLALCHEMY_DATABASE_URI=os.getenv('TEST_DATABASE_URL'),
SQLALCHEMY_TRACK_MODIFICATIONS=False,
WTF_CSRF_ENABLED=False
)
... | 5c6837abda4cf3e58e1df63f67742e9b6bafcd48 | 3,657,186 |
def mpl_event_handler(event_type: MplEvent):
"""Marks the decorated method as given matplotlib event handler
.. note::
This decorator should be used only for methods of classes that
inherited from :class:`MplEventDispatcher` class.
This decorator can be used for reassignment event handlers... | 7cec2aad7f50daf832657bc01ac710159d1161a0 | 3,657,187 |
def get_date_pairs(in_dates, step):
"""
入场点出场点数据
:param in_dates: 所有入场日期
:param step: 步长
:return:
"""
DatePair = namedtuple('DatePair', ['in_date', 'out_date'])
date_pairs = []
for in_date in in_dates:
out_date = date_utility.date_cal(in_date, step)
date_pairs.append(... | a2da0f3a48296de6c9f70b0e7535c8a2dd8e3d0b | 3,657,188 |
import random
def new_jitters(jitter):
"""
update jitter vector every 100 frames by setting ~half of noise vector units to lower sensitivity
"""
jitters=np.zeros(128)
for j in range(128):
if random.uniform(0,1)<0.5:
jitters[j]=1
else:
jitters[j]=1-jitter ... | cab660f8b8c6cfb21e745479cae95e964dc412b9 | 3,657,189 |
import logging
import os
import subprocess
import re
def reduce_jscs(file_line_mapping, **extra):
"""
Runs JSHCS on the project with the default configured rules. The output
is reduced to only contain entries from the Git change set.
:param file_line_mapping: Mapping of files with changed lines (obta... | 2b4014a44fbb1db1671f436a81f41a72b15188cf | 3,657,190 |
def add_manuscript_urls_to_ci_params(ci_params):
"""
Return and edit in-place the ci_params dictionary to include 'manuscript_url'.
This function assumes Travis CI is used to deploy to GitHub Pages, while
AppVeyor is used for storing manuscript artifacts for pull request builds.
"""
if not ci_pa... | 7d45c4fe8060d387d0238788e4b7566e09abc499 | 3,657,191 |
def count_sites(vcfpath):
"""Extract number of sites in VCF from its tabix index."""
cmd = ["bcftools","index","--nrecords", vcfpath]
so, se, code = slurp_command(cmd)
return int(so) | 4f340827bbfc279e3b2601bd84ef68669ce1d829 | 3,657,192 |
import torch
from typing import Callable
def model_contrast_score(overlays: torch.Tensor, masks: torch.Tensor, object_labels: torch.Tensor,
scene_labels: torch.Tensor, object_model: Callable, scene_model: Callable,
object_method: Callable, scene_method: Callable, devi... | b44b0a958a79a1ad7a84de15817cdbc32160c13b | 3,657,193 |
from typing import Optional
def get_network_insights_access_scope_analysis(network_insights_access_scope_analysis_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNetworkInsightsAccessScopeAnalysisResult:
"""
Resource schema f... | cbd65230cf553b438f4a78ad34f6faa9eafb119f | 3,657,194 |
import torch
import logging
import os
def learnable_eval(
cfg: OmegaConf, classifier, encoder: ContrastiveModel, training_data_loader: DataLoader,
val_data_loader: DataLoader, top_k: int,
) -> tuple:
"""
:param cfg: Hydra's config instance.
:param classifier: Instance of classifier with le... | 612639e490830d67cb333ba48954df8eddc83079 | 3,657,195 |
def wavenumber(src, rec, depth, res, freq, wavenumber, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, verb=2):
"""Return the electromagnetic wavenumber-domain field.
Calculate the electromagnetic wavenumber-domain field due to infinitesimal
small electric or magnetic ... | c108f3343936a62b0d49a3807d2d25b4f3fc1eda | 3,657,196 |
def gumbel_softmax(logits, temperature, dtype=tf.float32, seed=0):
"""Gumbel Softmax Layer."""
log_alpha = tf.nn.log_softmax(logits)
eps = 1e-7
gumbel = -tf.log(-tf.log(
tf.random_uniform(
tf.shape(logits), minval=0, maxval=1 - eps, dtype=dtype, seed=seed) +
eps))
prob = tf.nn.softmax((log_alpha + gumbe... | 3889105f39e6f81c35e1a3ca94685b6e6d7e3f37 | 3,657,197 |
def divide(num1, num2=1):
"""
除法
:param num1: int
:param num2: int
:return: float
"""
# 增加判断操作,抛出自定义异常
if num2 == 0:
raise InvalidOpreation()
val = num1 / num2
return val | 6bcc9631ebba74a15f16f8da0a9dc7f76e372725 | 3,657,198 |
def convert2int(image):
""" Transfrom from float tensor ([-1.,1.]) to int image ([-1024,6500])
"""
return tf.image.convert_image_dtype((image + 1) * 2036 - 1000, tf.float32) | 1697e6bb6911e936e9ff4bbb0ab37ddfc8115340 | 3,657,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.