content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def page_osr_vieworder():
"""Return everything."""
query = f'SELECT DISTINCT orderdate FROM orderlog'
g.cur.execute(query)
rows = g.cur.fetchall()
return render_template('vieworder.html', dates=rows) | 5,305,700 |
def eval_metric_fns():
"""Returns a dict from name to metric functions.
This can be customized as follows. Care must be taken when handling padded
lists. (only takes labels >= 0.
def _auc(labels, predictions, features):
is_label_valid = tf_reshape(tf.greater_equal(labels, 0.), [-1, 1])
clean_l... | 5,305,701 |
async def update_check(
db_session: Session,
check: GitHubCheck,
github_conclusion: str,
github_status: str = "completed",
entry_id: Optional[uuid.UUID] = None,
) -> None:
"""
Updates GitHub conclusion and status and entry_id if provided.
"""
query = db_session.query(GitHubCheck).fil... | 5,305,702 |
def combine_score_weights(
weights: List[Dict[str, float]],
overrides: Dict[str, Optional[Union[float, int]]] = SimpleFrozenDict(),
) -> Dict[str, float]:
"""Combine and normalize score weights defined by components, e.g.
{"ents_r": 0.2, "ents_p": 0.3, "ents_f": 0.5} and {"some_other_score": 1.0}.
... | 5,305,703 |
def handshake(sock, cnxn_id, req_id):
"""Performs the initial handshake operation with the topology server"""
sock.send(utils.encode_delimited(
_handshake_msg(cnxn_id, req_id).SerializeToString()))
response = topology_api_pb2.Response()
try:
response.ParseFromString(utils.get_answer(sock... | 5,305,704 |
def calc_ideal_vel(traj_ref, dt):
"""
Parameters
------------
traj_ref : numpy.ndarray, shape (2, N)
these points should follow subseqently
dt : float
sampling time of system
"""
# end point and start point
diff = traj_ref[:, -1] - traj_ref[:, 0]
distance = np.sqrt(n... | 5,305,705 |
def getImport(accessToken: str, groupId: str, importId: str) -> dict:
"""
:param accessToken
:param groupId
:param importId
"""
url = 'https://api.powerbi.com/v1.0/myorg/groups/{groupId}/imports/{importId}'.format(
groupId=groupId,
importId=importId,
)
headers = {
... | 5,305,706 |
def call(func_name):
""" Marker for call """
if write_log:
write_log("CAL", func_name) | 5,305,707 |
def make_rgba(grid2D, levels, colorlist, mask=None,
mercator=False):
"""
Make an rgba (red, green, blue, alpha) grid out of raw data values and
provide extent and limits needed to save as an image file
Args:
grid2D: Mapio Grid2D object of result to mape
levels (list): list... | 5,305,708 |
def AES_encryption(enc,server=False):
"""
Performs AES encryption using the globablly declared AES key.
"""
enc = str(enc)
enc = enc + ((16 - len(enc) % 16) * ' ')
iv = enc[:16]
aes_cipher = None
if server:
aes_cipher = AES.new(login_server_key, AES.MODE_CBC, iv)
el... | 5,305,709 |
def named_cache_page(cache_timeout):
"""
Decorator for views that tries getting the page from the cache and
populates the cache if the page isn't in the cache yet.
The cache is keyed by view name and arguments.
"""
def wrapper(func):
def foo(*args, **kwargs):
key = func.__na... | 5,305,710 |
def get_product(location, product_id, quantity):
""" Used by the movement route to get a product from a location. """
product_array = []
db = get_db()
b_id = session.get("user_id")
if location == "product_factory":
# Get product from product table, deduct the quantity
ogquan... | 5,305,711 |
def calc_psi_r(qr, r1, r2, r3, r4):
"""
radial geodesic angle
Parameters:
qr (float)
r1 (float): radial root
r2 (float): radial root
r3 (float): radial root
r4 (float): radial root
Returns:
psi_r (float)
"""
kr = ((r1 - r2) * (r3 - r4)) / ((r1 - ... | 5,305,712 |
def mse(tensor_true, tensor_pred):
""" Mean squared error
Parameters
----------
tensor_true : Tensor
tensor_pred : {Tensor, TensorCPD, TensorTKD, TensorTT}
Returns
-------
float
"""
tensor_res = residual_tensor(tensor_true, tensor_pred)
return np.mean(tensor_res.data ** 2) | 5,305,713 |
def covered_cv_skills_from_course(user_id, course_id):
"""This function is used find the relation of a course to a user cv"""
fetch_cv_command = """SELECT DISTINCT id FROM "CVs" WHERE user_id={user_id}""""".format(**{'user_id': user_id})
cv_df = get_table(sql_command=fetch_cv_command)
if len(cv_df) > 0:... | 5,305,714 |
def test_bind_column_parent_class():
"""
Binding to a parent class can optionally recurse through children, adding a
copy of the column when there are no conflicts
"""
class Parent(BaseModel):
class Meta(IMeta):
abstract = True
class Child(Parent):
id = Column(Strin... | 5,305,715 |
def test_collection():
"""
Test collection on 'cf_profile' ensuring output array is correct
"""
with tempfile.TemporaryDirectory() as TEMP_DIR:
init_logger('reV.handlers.collection')
profiles = manual_collect(H5_DIR, 'peregrine_2012', 'cf_profile')
h5_file = os.path.join(TEMP_DIR... | 5,305,716 |
def extract_dtm(dsm_path, ground_dem_path, non_ground_dem_path, radius, terrain_slope):
"""
Generates a ground DEM and non-ground DEM raster from the input DSM raster.
Input:
dsm_path: {string} path to the DSM raster
radius: {int} Search radius of kernel in cells.
terrain_slope: {flo... | 5,305,717 |
def processRHS(rhs):
"""
Depending on the type of the argument, calls the corresponding
function to deal with that type.
:param rhs: portion of JSGF rule
:type rhs: either a JSGF Expression, list, or string
:returns: list of strings
"""
if type(rhs) is list:
return processSequen... | 5,305,718 |
def svn_prop_name_is_valid(prop_name):
"""svn_prop_name_is_valid(char const * prop_name) -> svn_boolean_t"""
return _core.svn_prop_name_is_valid(prop_name) | 5,305,719 |
def factory():
"""
A factory that creates clustering algorithms.
"""
return ClusteringFactory | 5,305,720 |
def subdivision_type(country_code):
"""Returns the name of the most common country subdivision type for
the given country code."""
ensure_definition(country_code)
counts = dict()
for subdivision in pycountry.subdivisions.get(country_code=country_code):
if subdivision.parent_code is not None:... | 5,305,721 |
def event_detected(channel):
"""
Returns True if an edge has occurred on a given GPIO. You need to enable edge detection using add_event_detect() first.
channel - either board pin number or BCM number depending on which mode is set.
"""
logger.info("Waiting for even detection on channel :{}".format... | 5,305,722 |
def get_fans(tp):
""" Get fan_in and fan_out with corresponding slices """
slices_fan_in = {} # fan_in per slice
slices_fan_out = {}
for weight, instr in zip(tp.weight_views(), tp.instructions):
slice_idx = instr[2]
mul_1, mul_2, mul_out = weight.shape
fan_in = mul_1 * mul_2
... | 5,305,723 |
def scroll_text(text, font='default.pil', size=8, foreground=Color('white'),
background=Color('black'), direction='left',
duration=None, fps=15):
"""
Generator function which yields a series of frames depicting *text*
scrolling in *direction* across the display. Each frame wi... | 5,305,724 |
def download_noaa_mbl(
noaa_mbl_url,
download_dest="../data/raw/co2_GHGreference_surface.txt",
target_lat=None,
target_lon=None,
interp_method="linear",
):
"""
Downloads the NOAA marine boundary layer xCO2 and grids it
to a defined grid if target lat and lon provided.
Args:
... | 5,305,725 |
def get_pier_nodes(bridge: Bridge, ctx: BuildContext) -> PierNodes:
"""All the nodes for a bridge's piers.
NOTE: This function assumes that 'get_deck_nodes' has already been called
with the same 'BuildContext'.
"""
pier_nodes = []
for pier_i, pier in enumerate(bridge.supports):
z_min, ... | 5,305,726 |
def secret_token():
"""
Fixture that yields a usable secret token.
"""
return 'super-secret-token-string'.encode() | 5,305,727 |
def gf_from_int_poly(f, p):
"""
Create ``GF(p)[x]`` polynomial from ``Z[x]``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_from_int_poly
>>> gf_from_int_poly([7, -2, 3], 5)
[2, 3, 3]
"""
return gf_trunc(f, p) | 5,305,728 |
def macro_uk_halifax_yearly():
"""
东方财富-经济数据-英国-Halifax 房价指数年率
http://data.eastmoney.com/cjsj/foreign_4_1.html
:return: Halifax房价指数年率
:rtype: pandas.DataFrame
"""
url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx"
params = {
"type": "GJZB",
"sty": "HKZB",
... | 5,305,729 |
def fock_state(state, device_wires, params):
"""Computes the expectation value of the ``qml.FockStateProjector``
observable in Strawberry Fields.
Args:
state (strawberryfields.backends.states.BaseState): the quantum state
device_wires (Wires): the measured mode
params (Sequen... | 5,305,730 |
def datetime_from_filetime(filetime):
"""return a :class:`datetime.datetime` from a ``windows`` FILETIME int"""
# Manual non-approx rounding as filetime will not have a perfect representation as Python float
# We do some sort of "manual rounding cause of py2 vs py3
# PY2: round(0.5) == 1
# PY3: roun... | 5,305,731 |
def forward_one_to_one_with_sr(request):
"""
Return all the publishers with associated owner, using select_related.
53ms overall
1ms on queries
1 queries
SELECT "bookstore_publisher"."id",
"bookstore_publisher"."name",
"bookstore_publisher"."owner_id",
"auth_us... | 5,305,732 |
def is_variable(tup):
""" Takes (name, object) tuple, returns True if it is a variable.
"""
name, item = tup
# callable()
# 函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;
# 但如果返回False,调用对象ojbect绝对不会成功。
# 对于函数, 方法, lambda 函式, 类, 以及实现了 __call__
# 方法的类实例, 它都返回 True。
if callable(item):
... | 5,305,733 |
def show_multi(images, data, pose_ids, problem, p_dir,
thresh_log_conf=Conf.get().path.thresh_log_conf,
first_run=False, n_actors=1):
"""
Args:
images (Dict[int, np.ndarray]):
data (SkeletonPosesWrapper):
pose_ids (Dict[str, Dict[int, int]]):
proble... | 5,305,734 |
def _IsOnDevice(path, st_dev):
"""Checks if a given path belongs to a FS on a given device.
Args:
path: a filesystem path, possibly to a non-existent file or directory.
st_dev: the ID of a device with a filesystem, as in os.stat(...).st_dev.
Returns:
True if the path or (if the path does not exist) ... | 5,305,735 |
def _Solve_Amplitude(data, ufit, error=None) :
""" Compute the amplitude needed to normalise the 1d profile which minimises
the Chi2, given a x array, data and an error array
The calculation follows a simple linear optimisation using
Ioptimal = (dn x dn / dn x fn)
where dn i... | 5,305,736 |
def generate_ethmac(peripheral, shadow_base, **kwargs):
""" Generates definition of 'ethmac' peripheral.
Args:
peripheral (dict): peripheral description
shadow_base (int or None): shadow base address
kwargs (dict): additional parameters, including 'buffer'
Returns:
string: ... | 5,305,737 |
def pix_centers(geoTransform, rows, cols, make_grid=True):
""" provide the pixel coordinate from the axis, or the whole grid
Parameters
----------
geoTransform : tuple, size=(6,1)
georeference transform of an image.
rows : integer
amount of rows in an image.
cols : integer
... | 5,305,738 |
def test_conll2000_dataset_shuffle_global_num_parallel_workers_4():
"""
Feature: CoNLL2000ChunkingDataset.
Description: test param check of CoNLL2000ChunkingDataset.
Expectation: throw correct error and message.
"""
original_num_parallel_workers = config_get_set_num_parallel_workers(4)
origi... | 5,305,739 |
def rhymes(input_val: str_or_list_of_str, sample_size=None) -> List[str]:
"""Return a list of rhymes in randomized order for a given word if at least one can be found using the pronouncing
module (which uses the CMU rhyming dictionary).
:param input_val: the word or words in relation to which this function... | 5,305,740 |
def nifti_resave(input_filepath, output_filepath):
""" Copies a file somewhere else. Effectively only used for compressing nifti files.
Parameters
----------
input_filepath: str
Input filepath.
output_filepath: str
Output filepath to be copied to.
"""
... | 5,305,741 |
async def logout():
"""Clear the current session, including the stored user id."""
logout_user()
return redirect(url_for("index")) | 5,305,742 |
def delete_user_class(user_class_id: int) -> flask.Response:
"""
Create a new user class. Requires the ``userclasses_modify`` permission.
.. :quickref: UserClass; Delete user class.
**Example request**:
.. parsed-literal::
PUT /user_classes HTTP/1.1
{
"name": "user_v2"
... | 5,305,743 |
def cpp_library_external(
name,
link_whole = None,
force_shared = None,
force_static = None,
header_only = None,
include_dir = None,
deps = (),
external_deps = (),
propagated_pp_flags = (),
linker_flags = (),
soname = None,
... | 5,305,744 |
def ajax_form_errors(errors):
""" returns form errors as python list """
errs = [{'key': k, 'msg': unicode(errors[k])} for k in errors.keys()]
#equivalent to
#for k in form.errors.keys():
# errors.append({'key': k, 'msg': unicode(form.errors[k])})
return errs | 5,305,745 |
def load_data_file(name, skip_header=None) -> np.recarray:
"""Load a data file.
Returns
-------
data : :class:`numpy.recarray`
data values
"""
fname = os.path.join(os.path.dirname(__file__), 'data', name)
return np.recfromcsv(
fname, skip_header=skip_header, case_sensitive=T... | 5,305,746 |
def sanitize_html(html, bad_tags=['body']):
"""Removes identified malicious HTML content from the given string."""
if html is None or html == '':
return html
cleaner = Cleaner(style=False, page_structure=True, remove_tags=bad_tags,
safe_attrs_only=False)
return cleaner.clea... | 5,305,747 |
def create_base_map(
move_data: DataFrame,
lat_origin: Optional[float] = None,
lon_origin: Optional[float] = None,
tile: Optional[Text] = TILES[0],
default_zoom_start: Optional[float] = 12,
) -> Map:
"""
Generates a folium map.
Parameters
----------
move_data : DataFrame
... | 5,305,748 |
def ks_plot(pitobj, n_quant=100, savefig=True, figname='default_ksplot.jpg'):
""" KS test illustration.
Ancillary function to be used by class KS."""
#pits = ks._pits
spl_ens, metamets = pitobj.evaluate()
pits = np.array(pitobj._pit_samps)
ksobj = PITKS(pits, spl_ens)
stat_and_pval = ksobj.e... | 5,305,749 |
def test_fetch_project_asciicasts_error():
"""
Testing fetch_project_ascicasts' error handling. Testing on a file
and a non-existent directory.
"""
wrong_type: Path = Path("./tests/examples/no-audio.yaml")
not_exists: Path = Path("./foobar/foo/bar")
if not_exists.exists():
raise Fil... | 5,305,750 |
def delete_stream(StreamARN=None, CurrentVersion=None):
"""
Deletes a Kinesis video stream and the data contained in the stream.
This method marks the stream for deletion, and makes the data in the stream inaccessible immediately.
To ensure that you have the latest version of the stream before deleting ... | 5,305,751 |
def main():
"""Module main function."""
state_file_name = 'monitor_state.json'
parser = argparse.ArgumentParser(description='Monitors observation reception.')
parser.add_argument('--config', type=str, help='configuration file to use')
args = parser.parse_args()
config_file = args.config if arg... | 5,305,752 |
def when(condition: Callable, f_true: Callable) -> Callable:
"""Returns `f_true(args)` if `condition(args)` returns true, else returns args.
>>> f = when(gamla.greater_than(5), lambda i: -i)
>>> f(6)
'-6'
>>> f(3)
'3'
"""
return ternary(condition, f_true, operator.identity) | 5,305,753 |
def check_use_speech_in_inference(tts: AbsTTS, decode_config: Dict) -> bool:
"""Check whether to require speech in inference.
Args:
tts (AbsTTS): TTS model instance.
decode_config (Dict): Decoding config dictionary.
Returns:
bool: True if speech is required else False.
"""
... | 5,305,754 |
def main():
"""
GAE handlers with a 'main' function are cached.
Every request will cause this function to be called.
'run_wsgi_app' converts CGI requests to WSGI requests.
"""
run_wsgi_app(channel_set) | 5,305,755 |
def f56a():
"""Return a unit-distance embedding of the F56A graph.
Note that MathWorld's LCF notation for this is incorrect;
it should be [11, 13, -13, -11]^14."""
t = tan(pi/14)
u = sqrt(polyval([-21, 98, 71], t*t))
z1 = 2*sqrt(14*polyval([31*u, -20, -154*u, 104, 87*u, -68], t))
z2 = 7*t*(t... | 5,305,756 |
def test_driver_score():
""" Test driver_score is calculated correctly """
ndarr = np.array([
[1, 2, 3, 4, 5, 6],
[6, 5, 4, 3, 8, 1],
[1, 1, 9, 1, 1, 1],
[9, 2, 2, 2, 2, 2],
[3, 3, 3, 9, 3, 3],
[1, 2, 2, 9, 1, 4]
])
arr = np.array([1, 2, 3, 4, 5, 6])
exp_driver_... | 5,305,757 |
def verification(model, mode='test', device='a'):
"""
get the equal error rate through verification set.
:param model:
:param mode:
:param device:
:return:
"""
standarizer = TaskbStandarizer(data_manager=Dcase18TaskbData())
mu, sigma = standarizer.load_mu_sigma(mode='train', device='... | 5,305,758 |
def _nova_to_osvif_route(route):
"""Convert Nova route object into os_vif object
:param route: nova.network.model.Route instance
:returns: os_vif.objects.route.Route instance
"""
obj = objects.route.Route(
cidr=route['cidr'])
if route['interface'] is not None:
obj.interface =... | 5,305,759 |
def info_news():
"""新浪财经消息"""
refresh_news() | 5,305,760 |
def transform(params):
"""
Transforms an heterogeneous map of params into a CloudStack
ready mapping of parameter to values.
It handles lists and dicts.
>>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}}
>>> transform(p)
>>> print(p)
{'a': '1', 'b': 'foo', 'c': ... | 5,305,761 |
def main(args):
"""Main example"""
frame_count = 0
with pyvpl.bitstream_file_reader_name(args.input) as source:
with open("raw.out", "wb") as sink:
opts = []
if args.impl == 'sw':
opts.append(
pyvpl.property("mfxImplDescription.Impl",
... | 5,305,762 |
def recall(pred, target):
"""Calculate macro-averaged recall according to the prediction and target
Args:
pred (torch.Tensor | np.array): The model prediction.
target (torch.Tensor | np.array): The target of each prediction.
Returns:
float: The function will return a single float a... | 5,305,763 |
def send_ui_notification(error_message, success_message,
error_event_type=EVENT_TYPE_ERROR,
migrate_op=False, log_exception=False):
"""
Send a notification to the GUI. If the decorated method throws an
exception, an error notification will be sent, else a su... | 5,305,764 |
def test_repeated_dictionary_updates_converge_with_zero_lambda():
"""Test repeated updates converge to fixed point."""
random_seed = 0
random_state = check_random_state(random_seed)
n_features = 13
n_components = 3
n_samples = 50
max_iterations = 100
tolerance = 1e-6
lambda_W = 0... | 5,305,765 |
def fetch_dataset_as_namedtuple(dataset_id: int, target: str,
read_csv_kwargs: dict,
load_dataframe: bool,
) -> Union[DatasetAll, DatasetInfoOnly]:
"""
Takes a dataset identifier, a target column name,
and some a... | 5,305,766 |
def mps_to_kmph(mps):
"""
Transform a value from meters-per-second to kilometers-per-hour
"""
return mps * 3.6 | 5,305,767 |
def test_SIS_logw_computations():
"""
there are at present 3 ways to compute the logw of an ULA SIS proposal...
1. manual calculation
2. compute generalized logw
3. compute ULA logw
i will do a random annealing protocol and assert that the logws are consistent
"""
from scipy.stats import... | 5,305,768 |
def get_comparison_data(data_type: str, similar: List[str]):
"""Screener Overview
Parameters
----------
data_type : str
Data type between: overview, valuation, financial, ownership, performance, technical
Returns
----------
pd.DataFrame
Dataframe with overview, valuation, f... | 5,305,769 |
def common_params(task_instance, task_cls):
"""
Grab all the values in task_instance that are found in task_cls.
"""
if not isinstance(task_cls, task.Register):
raise TypeError("task_cls must be an uninstantiated Task")
task_instance_param_names = dict(task_instance.get_params()).keys()
... | 5,305,770 |
def two_ammonia_fake_print(ammonia_fake) -> (oechem.OEMol, oechem.OEMol):
"""
Returns two fingerprints for ammonia molecules with fake Wiberg bond
orders
"""
fingerprint1 = danceprops.DanceFingerprint(ammonia_fake[1], 0.05)
fingerprint2 = danceprops.DanceFingerprint(ammonia_fake[1], 0.05)
re... | 5,305,771 |
def imread(path, grayscale=False, size=None, interpolate="bilinear",
channel_first=False, as_uint16=False, num_channels=-1, **kwargs):
"""
Read image from ``path``.
If you specify the ``size``, the output array is resized.
Default output shape is (height, width, channel) for RGB image and (he... | 5,305,772 |
def get_client(project_id, cloud_region, registry_id, device_id, private_key_file,
algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port):
"""Create our MQTT client. The client_id is a unique string that identifies
this device. For Google Cloud IoT Core, it must be in the format below."""
log... | 5,305,773 |
def mutAddConn(self, connG, nodeG, innov, gen):
"""Add new connection to genome.
To avoid creating recurrent connections all nodes are first sorted into
layers, connections are then only created from nodes to nodes of the same or
later layers.
Todo: check for preexisting innovations to avoid duplicates in s... | 5,305,774 |
def heat_diffusion(heat, laplacian, start=0, end=0.1):
"""Heat diffusion
Iterative matrix multiplication between the graph laplacian and heat
"""
out_vector=expm_multiply(
-laplacian,
heat,
start=start,
stop=end,
endpoint=True
)[-1]
return out_vect... | 5,305,775 |
def behavior(instance_mode="session", instance_creator=None):
"""
Decorator to specify the server behavior of your Pyro class.
"""
def _behavior(clazz):
if not inspect.isclass(clazz):
raise TypeError("behavior decorator can only be used on a class")
if instance_mode not in ("... | 5,305,776 |
def gt2out(gt_bboxes_list, gt_labels_list, inp_shapes_list, stride, categories):
"""transform ground truth into output format"""
batch_size = len(gt_bboxes_list)
inp_shapes = gt_bboxes_list[0].new_tensor(inp_shapes_list, dtype=torch.int)
output_size = inp_shapes[0] / stride
height_ratio, width_ratio... | 5,305,777 |
def giveup():
"""Action to take if anything bad happens."""
for matrix in xrange(4):
display.set_raw64(LED8x8ICONS['UNKNOWN'],matrix)
print "Error occured."
sys.exit(1) | 5,305,778 |
def lstm_step_forward(x, prev_h, prev_c, Wx, Wh, b):
"""
Forward pass for a single timestep of an LSTM.
The input data has dimension D, the hidden state has dimension H, and we
use a minibatch size of N.
Inputs:
- x: Input data, of shape (N, D)
- prev_h: Previous hidden state, of shape (N,... | 5,305,779 |
def get_wx_js_sdk_config():
"""
获取微信JS-SDK权限验证配置
:return:
"""
url = request.args.get('url')
claim_args(1201, url)
appid = current_app.config['INTERVAL_APPID']
wx_authorizer = WXAuthorizer.query_by_appid(appid)
jsapi_ticket = wx_authorizer.get_jsapi_ticket()
claim_args(1810, jsapi... | 5,305,780 |
def get_reviewer_by_id(reviewerID): # noqa: E501
"""Get a Reviewer by ID
# noqa: E501
:param reviewerID: ID of Reviewer
:type reviewerID: int
:rtype: List[Reviewer]
"""
results = _globals.pgapi.get(
'Reviewers',
clause=f'WHERE reviewerID={reviewerID}'
)
if type... | 5,305,781 |
def get_quats(tpf=None, camera=None, sector=None, time=None, dt=None):
"""Get an array of the quaternions, at the time resolution of the input TPF"""
if (tpf is None) and (camera is None) and (sector is None):
raise ValueError('set either TPF or camera/sector')
if camera is None:
camera = tp... | 5,305,782 |
def create_list_id_title(sheets: list) -> list:
"""
Args:
this function gets a list of all the sheets of a spreadsheet
a sheet is represented as a dict format with the following fields
"sheets" : [
{
"properties": {
... | 5,305,783 |
def inlinequery(bot, update):
"""
Handle inline queries from any conversation where a user writes
@NewsGeneratorBot. Works the same as the write() function above
in principle, but using the inline query args as a prime_str instead.
"""
logger.info(f'New inline request by {update.inline_query.fro... | 5,305,784 |
def qng(qc: qiskit.QuantumCircuit, thetas: np.ndarray, create_circuit_func: types.FunctionType, **kwargs):
"""Calculate G matrix in qng
Args:
- qc (qiskit.QuantumCircuit)
- thetas (np.ndarray): parameters
- create_circuit_func (FunctionType)
- num_layers (int): number of layer o... | 5,305,785 |
def horizontal_projection(img_matrix):
"""
Function that calculate the angle rotation according to the Hough Transform technique
:param img_matrix: A list of ints with the matrix of pixels of the image
:return: rotateAngle: angle of rotation
"""
try:
img_grey = cv2.cvtColor(img_matrix... | 5,305,786 |
def set_minor_tick(ax: Axes, n: int = 2):
"""Set one minor tick between major ticks."""
from matplotlib.ticker import AutoMinorLocator
ax.xaxis.set_minor_locator(AutoMinorLocator(n))
ax.yaxis.set_minor_locator(AutoMinorLocator(n))
return ax | 5,305,787 |
def template_debug_output():
""" Usage:
try:
self.client.get(...)
except:
template_debug_output()
"""
import sys
import html
from django.views.debug import ExceptionReporter
reporter = ExceptionReporter(None, *sys.exc_info())
reporter.get_template_ex... | 5,305,788 |
def fit_lfm_pcfp(x, p, sig2, k_):
"""For details, see here.
Parameters
----------
x : array, shape (t_, n_)
p : array, shape (t_,)
sig2 : array, shape (t_, t_)
k_ : scalar
Returns
-------
alpha_PC : array, shape (n_,)
beta_PC : array, shape (n_, k_)
... | 5,305,789 |
def mock_session_error_status(request, mock_session):
"""Make sessions return a response with error codes"""
response = requests.Response()
response.status_code = request.param
requests.Session.request.return_value = response | 5,305,790 |
def _generate_is_in_range(message):
"""Generate range checks for all signals in given message.
"""
signals = []
for signal in message.signals:
scale = signal.decimal.scale
offset = (signal.decimal.offset / scale)
minimum = signal.decimal.minimum
maximum = signal.decima... | 5,305,791 |
def download_img(img_url, file_path=None, file_name=None):
"""
函数功能:下载图片
参数:
img_url:图片的url链接
file_path:要保存的图片的目录
file_name:保存的图片的名称
返回:无
"""
img_content = get_img_content(img_url)
if file_path is None:
if file_name is None:
file_name = img_url.sp... | 5,305,792 |
def computeRealExpectation(params1, params2, angles, backend):
"""
Computes the real part of the inner product of the
quantum states produced by acting with U(θ)
characterised by two sets of parameters, params1 and
params2.
"""
qreg = QuantumRegister(2)
anc = QuantumRegister(1)
creg ... | 5,305,793 |
def green_on_black(string, *funcs, **additional):
"""Text color - green on background color - black. (see sgr_combiner())."""
return sgr_combiner(string, ansi.GREEN, *funcs, attributes=(ansi.BG_BLACK,)) | 5,305,794 |
async def test_discovery_broken(opp, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
data1 = '{ "name": "Beer", "command_topic": "test_topic#" }'
data2 = '{ "name": "Milk", "command_topic": "test_topic" }'
await help_test_discovery_broken(opp, mqtt_mock, caplog, cover.DOMAIN, data1, da... | 5,305,795 |
def format_params_diff(parameter_diff: List[DictValue[Any, Any]]) -> str:
"""Handle the formatting of differences in parameters.
Args:
parameter_diff: A list of :class:`DictValue` detailing the differences
between two dicts returned by :func:`diff_dictionaries`.
Returns:
A form... | 5,305,796 |
def hashfile(path, hasher=None, blocksize=65536):
"""
A function to hash files.
See: http://stackoverflow.com/questions/3431825
"""
if hasher is None: hasher = hashlib.md5()
try:
try:
f = gzip.open(path, "rb")
buf = f.read(blocksize)
except OSError:
... | 5,305,797 |
def EditFragNeighborIds(fnids: list, bbtps: list) -> list:
"""Remove fragment neighbor ids that are doubly/triply bonded to fragment."""
# not double/triple bonds
n23bonds = [
[
(x != Chem.rdchem.BondType.DOUBLE and x != Chem.rdchem.BondType.TRIPLE)
for x in y
]
... | 5,305,798 |
def db_add_game(game: str, channel: str, set_default_game: bool=False) -> bool:
"""Adds a game to the database for a channel, does not allow duplicates
"""
if not db_check_for_duplicate(game, channel):
return False
else:
if set_default_game:
default = "YES"
else:
... | 5,305,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.