content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sg(P):
""" Specific entropy [kJ / kg K]
of saturated vapor"""
return region4.sg(P) | a1600840f8fc70444e883cfcf2538b1a501a35c4 | 45,360 |
def example(request):
""" Returns a finished home page to the user """
return render(request, 'page_gen/example.html') | aa1772e31c39d6d68ce8919b86b69db841f2d603 | 45,361 |
import re
def initial_data_processor(Irwin_FP, pretraining=True, from_disk=True):
"""
"Simple" utility function to clean the Irwin fire data
"""
if from_disk:
file = gpd.GeoDataFrame(
pd.read_pickle(
"/home/connor/Desktop/MassCrop/OutputFolder/tabular/tabular_fix... | 620166ff4f8453ebcb508df3b4c21d7b532938fa | 45,362 |
def cached(method=None, name=None, ignore_args=False):
"""A decorator allowing for specifying the name of a cache, allowing it to be modified elsewhere."""
if ignore_args:
return _cached_ignore_args(method=method, name=name)
else:
return _cached(method=method, name=name) | de0757f446d492ccadff024b68fe0c4b52049e16 | 45,363 |
def bias_reduced_delta(Y, Ygrid, X, m, num_resamples, conf_level, fy=None, xr=None):
"""Plischke et al. 2013 bias reduction technique (eqn 30)"""
d_hat = calc_delta(Y, Ygrid, X, m, fy=fy, xr=xr)
if num_resamples > 0:
d = np.zeros(num_resamples)
N = len(Y)
r = np.random.randint(N, s... | 7e32bf57b6e1ba8b343b5e8e66343d2603ff781e | 45,365 |
def _CreateRecipe(messages, agent_rule, os_type, prev_recipes):
"""Create a recipe for one agent rule in guest policy.
Args:
messages: os config guest policy api messages.
agent_rule: ops agent policy agent rule.
os_type: ops agent policy os type.
prev_recipes: a list of original SoftwareRecipe.
... | ddd70f25e86d9d77178c99bdbb3f7a0a6dc8d942 | 45,366 |
def fixture_extended():
"""Return a /forecast/extended/pollen/<ZIP> response."""
return {
"Type": "pollen",
"ForecastDate": "2018-06-12T00:00:00-04:00",
"Location": {
"ZIP": "80238",
"City": "DENVER",
"State": "CO",
"periods": [
... | eff02c6271bc985473c86203cb7a69f4e673c827 | 45,367 |
def is_sequencing(lane_info):
"""
Determine if we are just sequencing and not doing any follow-up analysis
"""
if lane_info['experiment_type'] in ('De Novo','Whole Genome'):
return True
else:
return False | 822125f8603969a4624e07188874aae40f8752d3 | 45,368 |
def frame_data_to_non_herm_hoff(fname, channel, start=None, stop=None, TDlen=0,
window_shape=0., verbose=True,deltaT=None):
"""
Function to read in data in the frame format
and convert it to a COMPLEX16FrequencySeries
h(f) = FFT[ h(t) ]
Create complex FD data that does not assume Hermitiani... | 6d71f3aa0f10eeb4779bea470299426149c470af | 45,370 |
import random
def get_session_data(transaction, session_id):
""" Looks up (or creates) the session with the given session_id.
Creates a random session_id if none is provided. Increments
the number of views in this session. Updates are done in a
transaction to make sure no saved increments ... | e19423c6ab360ce3ed135227fe18452621ece0d4 | 45,372 |
import string
def _split_punc(source):
"""Split leading or trailing punctuation."""
tokens = source.split(" ")
new_tokens = []
for token in tokens:
if all(char in string.punctuation for char in token):
new_tokens.append(token)
continue
leading_punc = None
for punc in string.punctuatio... | 79f49cdfe0663b19f634c749c4bb5d515568fc05 | 45,375 |
import six
def _ValidateDurationUs(arg_internal_name, arg_value):
"""Validates an argument which should have Duration value in microseconds."""
try:
if isinstance(arg_value, six.string_types):
return TIMEOUT_PARSER_US(arg_value)
elif isinstance(arg_value, int):
return TIMEOUT_PARSER_US(str(arg... | 82c938c3957653c983f8dba9a1beef740d72a2e8 | 45,376 |
def get_saved_cities(uid):
"""
Gets the weather information for all the locations listed in the Places
List of the user's database record.
Args:
uid (string) -- the user's key
Returns:
None if the user doesn't exist in the database.
List of weather information (see get_weather())
... | 675c0e3203aa35a49ee189a8f623aa20540b5247 | 45,377 |
def shr2shc(omega_real):
"""
Convert from real to complex spherical harmonics.
(See https://en.wikipedia.org/wiki/Spherical_harmonics#Real_form)
Parameters
----------
omega_real: ndarray(shape=(N**2,), dtype=float)
Returns
-------
omega_complex: ndarray(shape=(N**2,), dtype=complex... | cc7f60a3b6559a856d38676b48d7778f16a3860b | 45,378 |
def get_cluster_name(tags):
"""
Get the cluster name from the list of specified tags
:param tags: tags
:type tags: [str]
:returns: cluster name
:rtype: str
"""
for tag in tags:
if tag.startswith("storm.cluster.name:"):
return tag.replace("storm.cluster.name:", "")
... | 2b811f32d5c61bb093d6a68fcaecddbdce3be057 | 45,379 |
from typing import BinaryIO
import io
import wave
import struct
def fixture_two_chunk_plain_wav() -> BinaryIO:
"""Creates a fixture WAVE file with two distinct sections.
The audio is 100Hz mono. Each section 10 samples long. Samples in the first
alternate between +/-(1 << 5) and in the second between +/-(1 << ... | 3c6d06409b40228348c3e5697b8fdc1b9bc73c90 | 45,380 |
def convert_hash(fp, hash_func=md5_hash):
""" into metadata [byte-read][bytes] format.
Args:
fp: str filepath
hash_func: function for calculating hash of file
Returns:
tuple (int, hash)
int: byte length of the hash
"""
fn_hash = hash_func(fp)
return util.byte_l... | 48933b2c5ca19bc6c767adb36589c2f30a8aaaed | 45,381 |
def staircase(A, B, C, compute_T=False, form='c', invert=False,
block_indices=False):
"""
Given a state model data A, B, C, Returns the so-called staircase form
State realization to assess the controllability/observability properties.
If observer-form is requested, internally the system i... | 19b5f76100f3548fe8e5a92416dc1c944a487cfa | 45,382 |
def adjacency_dict(graph):
"""
Returns the adjacency list representation
of the graph.
"""
adj = {node: [] for node in graph.nodes}
for edge in graph.edges:
node1, node2 = edge[0], edge[1]
adj[node1].append(node2)
if not graph.is_directed:
adj[node2].append(no... | d7ce44b6106b2b6a6e88f4ced23ec0faa722d80f | 45,383 |
def _detailed_parse_choice(choice):
"""Return Selected Choice's Full Name string as per its codename. Choices are based as per our server.
:param choice: str
The code name of the choice
:return: str
Return Selected Choice's Full Name string as per its codename
"""
... | 3b7fe18c322426e478b5243ec75e3881d1bd690e | 45,384 |
def np_exponential_moving_average(source: np.ndarray, window_size: int):
"""
Compute an exponential moving average from a source list.
Arguments:
source: The source list of data from which to compute the moving average.
window_size: The size of the moving average to compute.
Ret... | 24add1b9e0eceffa7850b914d3bdf0064c2f5690 | 45,385 |
def get_body(content_dict):
"""
Get the content item body or caption, whatever it's called
"""
content_item = find_content_item(content_dict)
if content_item.get('body', False):
body = content_item['body'] or ''
elif content_item.get('caption', False):
body = content_item['capti... | 31d128c002eb43cb83bdbef0d6bbaceff52a9313 | 45,386 |
def compute_mass_list(dialog_idx, sen_idx):
"""
Most confusing step...
dialog_idx = [41, 81, 134, ...]
means the first dialogue of the subtitle is plain_text[0:41]
the second dialogue of the subtitle is plain_text[41:81]
the third dialogue of the subtitle is plain_text[81:134]
... | 9745fbebde8302a1fa3b4fb4d94cc19eb3316458 | 45,387 |
def svn_node_kind_from_word(*args):
"""svn_node_kind_from_word(char word) -> svn_node_kind_t"""
return _core.svn_node_kind_from_word(*args) | 6c52da476e7801a55392dcfcb82f1a738d98ad79 | 45,388 |
def rotate(th):
"""Return the matrix to rotate a 2-D point about the origin by ``angle``.
The angle is measured in radians. To Point a point about a point other
then the origin, translate the Point, do the rotation, and
translate it back:
>>> from sympy.geometry.entity import rotate, translate
... | ad30c797f739bfe6b91354b5802e9aaaede9d8e4 | 45,389 |
def autocor(y):
"""Autocorrelation of array y""" #Formula from: https://www.itl.nist.gov/div898/handbook/eda/section3/eda35c.htm
autocorarr = []
counter = 0
denom = sumdenomeq(y)
for i in range (len(y)-1):
autocorarr.append((sumnomeq(y,i)/denom))
counter += 1
print(f"Progress... | ecf2715cc0786ba29bf1a3414bb69d936efaf0b6 | 45,391 |
import numpy as np
import astropy.io.fits as pyfits
import astropy.wcs as pywcs
def wfc3ir_header(ra=53.1592277508136, dec=-27.782056346146, pa_aper=128.589,
flt='ibhj34h6q_flt.fits', filter='G141'):
"""Make HST/WFC3-IR image header
Parameters
----------
ra, dec: float, float
... | e5b4bfe866e14b294baf84acf63b8fd02941b5b4 | 45,394 |
def get_base_graph() -> GeNeG:
""" Retrieves the base graph created from the news dataset. """
utils.get_logger().info('GeNeG: Loading base knowledge graph into memory..')
global __BASE_GRAPH__
if '__BASE_GRAPH__' not in globals():
initializer = lambda: GeNeG.build_base_graph()
__BASE_GR... | c56d40dbb053d22317e055f084de4d9e190ae9a6 | 45,395 |
import re
def do_parse_pod_name(text):
"""Find the pod name from the failure and return the pod name."""
p = re.search(r' pod (\S+)', text)
if p:
return re.sub(r'[\'"\\:]', '', p.group(1))
else:
return "" | 01c5999a4b735973ef25fc9c0e563cfbd5e70610 | 45,396 |
def needle_statistics_alignio(infile):
"""Reads in a needle alignment file and returns an AlignIO object with annotations
Args:
infile (str): Alignment file name
Returns:
AlignIO: annotated AlignIO object
"""
alignments = list(AlignIO.parse(infile, "emboss"))
if len(alignmen... | 07eabb4cfae4db60101830dac73c2ccc4c6cb7eb | 45,397 |
def _testProduct_to_dict(product_obj, ctx):
"""
Returns testProduct instance in dict format.
Args:
product_obj (_TestProduct): testProduct instance.
ctx (SerializationContext): Metadata pertaining to the serialization
operation.
Returns:
dict: product_obj as a ... | 7db80ae68cb6966273e53a4f0fb2d9aad52fa119 | 45,398 |
def get_phi(struct,obser='ones',rmax=15,delta=0.05,sigma=0.075,kernsize=10,tol=0.1):
"""
Get the fingerprint phi for a given structure
:param struct: The pymatgen structure you want to use
:param rmax: The maximum r in Angstroms you want to create the fingerprint for
:param obser: The observable yo... | 619fba4ac5ea9a0754e32095e2eb566d0f78022e | 45,399 |
def generate_new_model_for_dataset():
"""Return a feed forward model from scratch
https://www.kaggle.com/kabure/titanic-eda-model-pipeline-keras-nn"""
model = Sequential()
model.add(Dense(64, activation='relu', input_dim=26))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.50))
... | d1e39366537f3c00e15c65661840548db0b55bc3 | 45,400 |
def loss(params, batch, model_predict):
"""Calculate loss."""
inputs, targets = batch
preds = model_predict(params, inputs)
return -np.mean(preds * one_hot(targets, preds.shape[-1])) | aa33dbba5939a54a4b18395f33497680dc13399c | 45,401 |
def Action(name):
""" Registers any function with this decorator onto the ACTIONS dict
under the key of it's name; this decorator also registers the
parameters that the function takes, sorting them under
static params (those passed in from the database configuration) and/or
dymanic p... | fe556e767525e2f450566f5368252a31babdb2f2 | 45,402 |
def get_anime_class(url):
"""
Get anime class corresposing to url or name.
See :py:data:`anime_downloader.sites.ALL_ANIME_SITES` to get the possible anime sites.
Parameters
----------
url: string
URL of the anime.
Returns
-------
:py:class:`anime_downloader.sites.anime.Anim... | df785074caef15ca2796e8b496faf04c04fa0098 | 45,403 |
from typing import cast
def create_cross_chain_payment(payment: Payment, dest_account: str) -> Payment:
"""
Creates a cross-chain payment transaction.
Args:
payment: The initial payment transaction. If the transaction is signed, then
it will need to be re-signed. There must be no more... | aefa751e1c8d4169a0cf5836e2f3f1ce7c9f30b5 | 45,404 |
def initialize_schur_ksp_obj(matrix_A, schur_approx):
"""
Creates a right-hand-side and solution PETSc4Py vector for
testing ksp solves.
Parameters
----------
matrix_A: :class:`PETSc.Mat`
Global matrix object.
schur_approx: :class:`LS.SchurPrecon`
Returns
-------
ksp_ob... | a4c3e6c8c7e2fe3f45999171738a0f3aeaa0edcc | 45,405 |
from typing import Mapping
from typing import Collection
import base64
import json
def build_response(
*,
request: reviews.Request,
outcomes: Mapping[ids.HandlerId, execution.Outcome],
warnings: Collection[str],
jsonpatch: patches.JSONPatch,
) -> reviews.Response:
"""
C... | 3cbf25b1a00800de83d7a25312bdbf07a674f6fd | 45,406 |
from operator import and_
def _get_fields_translation_data(session=DBSession):
"""
Obtaining Field table with all translations(TranslationAtom)
of it's name from DB session and returning it as:
dict {
(client_id, object_id): dict {
'field': models.F... | 0262182e7e9a0359ad3c00b0219f36c7c83651cd | 45,407 |
def hxltm_hastag_de_csvhxlated(csv_caput: list) -> list:
"""hxltm_hastag_de_csvhxlated [summary]
Make this type of conversion:
- 'item__conceptum__codicem' => '#item+conceptum+codicem'
- 'item__rem__i_ara__is_arab' => '#item+rem+i_ara+is_arab'
- '' => ''
Args:
csv_caput (list): Array o... | 1ab1503c26c86c969e699236f97842ae74ae0ae5 | 45,409 |
def add_payload_parameters(env_params):
"""
Adds the common parameters to be used by the extension scripts
:param dict[str, str] env_params: Dictionary to be added
:return: Dictionary with updated parameters
:rtype: dict[str, str]
"""
env_params["STRATOS_APPLICATION_PATH"] = cartridge_agent_... | 5a74ad9700682d3a865d0d0a080acfc5d322baab | 45,410 |
def sphere(p: np.array, radius: np.float) -> np.float:
"""
Sphere SDF
:param p: vec3 position
:param radius: radius
:return: signed distance
"""
return euclidean_length(p) - radius | 108b3b1a69504f1e29e94b16c670bc1dc42a0c60 | 45,411 |
import math
def conv_node(nodes, children, feature_size, output_size):
"""Perform convolutions over every batch sample."""
with tf.name_scope('conv_node'):
std = 1.0 / math.sqrt(feature_size)
w_t, w_l, w_r = (
tf.Variable(tf.random.truncated_normal([feature_size, output_size], stdd... | f52c84c3e53b55f78a722b63ca37c1f9e984755d | 45,412 |
def response_service_unavailable():
"""Returns a 503 error based on a static template"""
return HttpResponse(loader.render_to_string('503.html'), status=HTTP_SERVICE_UNAVAILABLE) | 919ecbfad29c42e5db9b66bc6b4156f5625df924 | 45,413 |
def little_endian_decode(array, word_size):
"""Transform array of words to one integer."""
return big_endian_decode(reversed(array), word_size) | 53d08792571650d54c1e04777d66e893f81a11d4 | 45,414 |
def plot(var_item, off_screen=False, full_screen=False, screenshot=None,
interactive=True, cpos=None, window_size=None,
show_bounds=False, show_axes=True, notebook=None, background=None,
text='', return_img=False, eye_dome_lighting=False, **kwargs):
"""
Convenience plotting function f... | 965aa70c3d1181ed99c9891c8d52cad4ad27ef4e | 45,415 |
import random
def gen_color():
"""
generate random color for WordCloud
"""
return "rgb(%s,%s,%s)" % (
random.randint(0, 160),
random.randint(0, 160),
random.randint(0, 160),
) | d0dfa4424293e68057c45376f0ccbc028020c66c | 45,416 |
def test_freeze():
"""
Frozen classes are completely immutable.
Users should not be able to mutate or add any
existing properties.
:return:
:rtype:
"""
# Initialize props and set properties to
# 1 and 2, respectively
frozen_class = fd.freeze(Props)(1, 2)
with pytest.raises(I... | 55fe15ff92053ee58e4a596b99533e41686fe18d | 45,417 |
def cmyk_to_rgb(color_values: tp.List[float]) -> tp.List[float]:
"""Converts list of CMYK values to RGB.
:param color_values: (list) 4-member CMYK color value list
:return: (list) 3-member RGB color value list
"""
return [round(1.0 - min(1.0, x + color_values[3]), 3) for x in color_values[:3]] | 09c144acbe83a8d871c8f50949810042cc9772bb | 45,418 |
def cancel_all():
"""Handles SocketIO request to cancel all goals"""
logger.info('Client requests to cancel all goals!')
return vtr_mission_planning.remote_client().cancel_all() | f6058f17cadee09c68706976e2de5b5d6e496a7a | 45,419 |
def group_iou_across_classes(gt_boxes: BoundingBoxGroup, pt_boxes: BoundingBoxGroup, as_iou=False):
"""
Compute the IoU between two boxes group set. For each class in each round, iteratively select a box from gt_boxes
and pick corresponding maximum IoU box in pt_boxes as pairs. After finished, compute I... | 871907abeb82aef4435b8605bcf878aa49adf789 | 45,420 |
def makeAnyJournal(items=3, attrib=None): # noqa
"""
Retorna uma lista de objetos ``Journal`` com atributos ``jid``,
``is_public`` e ``acronym`` limitando a quantidade pelo param ``items``.
Param attrib para adicionar atributo aos objecto do tipo Journal
"""
journals = []
for _ in range(it... | 29863d359a5c612cae0d47e172ba0a722557aa72 | 45,421 |
import urllib
import tempfile
def image_from_url(url):
"""
Read an image from a URL. Returns a numpy array with the pixel data.
Arguments:
url: urls for images for display
Outputs:
img: numpy array for the image
"""
try:
f = urllib.request.urlopen(url)
_, fname ... | e8a9365309bf1c76a9fe236fa99ca48da9ea3ca5 | 45,422 |
def humanify(code):
"""
Tries to interpret a Jpl object or site code as a human readable celestial
object name.
Args:
code (str): the code to be translated.
Returns:
str: the corresponding human readable name.
"""
if code.isdigit():
id_ = int(code)
elif code.sta... | d94d5a4809d3eb5899117a9e67fb3acbf0e116f9 | 45,423 |
def stateToQd(x):
"""
Converts qd struct used in hardware to x vector used in simulation
x is 1 x 13 vector of state variables [pos vel quat omega]
qd is a struct including the fields pos, vel, euler, and omega
"""
qd = qd_object()
# current state
qd.pos = x[0:3]
qd.vel = x[3:6]
... | 8623592cf6a1703cd9b10eac46e69fde7babab9f | 45,425 |
def get_symbol_size(version, scale=1, border=None):
"""\
Returns the symbol size (width x height) with the provided border and
scaling factor.
:param int version: A version constant.
:param scale: Indicates the size of a single module (default: 1).
The size of a module depends on the us... | f26fb15b4b2bcec934ec2d0455bd04ba33480e82 | 45,426 |
def convert():
""" Writes the convert.inp file.
:return convert_inp_str: String for input file
:rtype: string
"""
convert_inp_str = 'MultiInputFile tst.inp'
return convert_inp_str | 698194568af4a35d4167f5ead7f5ead8f5379e1b | 45,427 |
def showVecMatrix(xvec, yvec, vals, full=False, **kwargs):
"""Plot three vectors as matrix.
Parameters
----------
xvec, yvec : iterable (e.g. list, np.array, pg.Vector) of identical length
vectors defining the indices into the matrix
vals : iterable of same length as xvec/yvec
vecto... | 2abcc12ca00ab0c6780af1be341fa3b3a984088d | 45,429 |
def infected_critical_case_rate_30():
"""
Real Name: b'infected critical case rate 30'
Original Eqn: b'Infected symptomatic 30*fraction of critical cases 30/symptomatic duration 30'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return infected_symptomatic_30() * ... | bc9ae461df93d070d6063310b2eaa9273192f956 | 45,430 |
def recover_public_key(message, signature, hasher=None):
"""
Recovers public key from signed message
:param message: message
:param signature: signature
:param hasher: hash function to use on message (usually sha256 or keccak_hash)
:return: public key
"""
if len(signature) != eth_common... | b3f9649ffa0d929a4fb7e92b4c5ea0d0fffae44f | 45,431 |
def descriptive_statistics(
master_path,
SG_tabs,
avl_recs_SG,
missing_recs_SG,
all_charts_num_1_,
all_charts_cat_1_,
print_report=False,
):
"""
:param master_path: Path containing the input files.
:param SG_tabs: 'measures_of_counts','measures_of_centralTendency','measures_of_ca... | f86317f3f229dad075aaeb4817bb172822b19545 | 45,432 |
def mocked_operations_create(monkeypatch):
"""Monkeypatch operations.create."""
mock_create = mock.MagicMock()
monkeypatch.setattr(operations, "create", mock_create)
return mock_create | 1732fbd7ba5f4a045d8f020fed1bbef138e0dd6b | 45,433 |
def preprocessing(df, attribute):
"""
This is the base preprocessing for french.
It scapes \ char and replace all ocurrence of -
:df: pandas data frame.
:attribute: atribute of df.
"""
return getattr(df, attribute).map(lambda sent: sent.lower().replace('\'', '\\\' ').replace('-', ' ')) | 6ca98d434ba5a43667b2dfc1501bf152f151c209 | 45,435 |
def ident_snapshot_test(arg):
"""
Used to build identification string for each autogenerated test (for easy recognition of failed tests).
:param arg: dict with information about rules.
:return: identification string with snapshot_id.
"""
if isinstance(arg, bool):
return "remediated" if ... | 2fc320d084294f4963cb60452ee577cc18c45763 | 45,436 |
def gcj2wgs_rough(gcjLat, gcjLon):
"""
GCJ-02 转 WGS-84 粗略版
"""
if outOfChina(gcjLat, gcjLon):
print("The latitude or longitude is out of China!")
return gcjLat, gcjLon
lat, lng = delta(gcjLat, gcjLon)
return gcjLat - lat, gcjLon - lng | f3c1652685f012f1199a3ef487224b4444ed80da | 45,438 |
import re
def target_expression(environment_file):
"""
Get the target expression from given file.
Parameters
----------
environment_file : str
Path and name of the environment file (giving the target relative
expression levels)
Returns
-------
target_expresstion :... | a8b351c2d57b4e19dcc505dcbcbeb532f2ab5f4d | 45,439 |
from typing import Optional
from typing import Dict
from typing import List
def extract_features(
self,
prev_output_tokens,
encoder_out: Optional[EncoderOut] = None,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
full_context_alignment: bool = False,
alignment_laye... | 4ef9ae35ecdc2120feffa91925cd4ab973485c3f | 45,440 |
from typing import Tuple
import io
def sanitize_screenshot(raw_png: bytes, real_size: Tuple[int, int]) -> Image.Image:
"""Processing screenshots taken by the browser."""
with io.BytesIO(raw_png) as f:
image = Image.open(f).convert("RGB")
return image.resize(real_size) | c9902cb1db35b17175a4f662b0ea369a6298e392 | 45,441 |
def read_h5_event_components(hdf_path):
"""
Read events from HDF5 file (Monash style).
@param hdf_path Path to HDF5 file
@returns Events as four np arrays with the event components
"""
f = h5py.File(hdf_path, 'r')
if 'events/x' in f:
#legacy
return (f['events/x'][:], f['event... | b13c623fcd208b878b1f7565958aa25a224782f8 | 45,442 |
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero | 2d7a6489517bf731e263be2a7a9a3a5f5ec9973f | 45,443 |
import operator
def product_upper_triangle(values, include_diagonal=False):
"""
Return an iterator over pairs, (v0, v1), drawn from values.
If `include_diagonal` is True, returns all pairs such that v0 <= v1.
If `include_diagonal` is False, returns all pairs such that v0 < v1.
"""
return all_... | 8741a1a12b38012f7e624116591ff77eb29d74a2 | 45,444 |
def current_filtered_positive_identifier() -> FilteredPositiveIdentifier:
"""Returns the current filtered positive identifier.
Returns:
{FilteredPositiveIdentifier} -- the current filtered positive identifier
"""
return FilteredPositiveIdentifierV3() | 349670a0614f5133776d593d2c01661eb06feb55 | 45,445 |
from typing import Optional
from typing import Dict
async def _create(pea: 'PeaModel', envs: Optional[Dict] = {}):
"""
.. #noqa: DAR101
.. #noqa: DAR201"""
try:
args = ArgNamespace.kwargs2namespace(pea.dict(), set_pea_parser())
return store.add(args, envs)
except Exception as ex:
... | 00ecda8032bed916d14dd418b2e52f442c939f76 | 45,446 |
import re
def non_numeric():
"""\\D: Non-numerical characters."""
return "{}dom is comming, tomorrow".format(
re.search(r'\D+', "4free").group()) | 0de9f4fc01c968bdbff534573071cbf8708842b6 | 45,447 |
def whataremyips():
"""
Get the machine's ip addresses
:returns: list of Strings of ip addresses
"""
addresses = []
for interface in netifaces.interfaces():
try:
iface_data = netifaces.ifaddresses(interface)
for family in iface_data:
if family not... | d4461b90607964362ad86e732221b9a9b496878e | 45,448 |
def update_book(sql: Session, book_id: int, book: BooksUpdate):
"""
Update a specific book
"""
old_data = sql.query(Books).filter(Books.BookId == book_id).first()
if old_data is not None:
new_data = book.dict()
old_data.Title = new_data["Title"]
old_data.AuthorId = new_data[... | 21d1673a1669e7c08fb13b3e60d5d327a820d561 | 45,449 |
def IsJsFile(ref):
"""Returns true if the provided reference is a JavaScript file."""
return ref.endswith('.js') | ad58dd41544c5b92ec629787d674cec34a1126c3 | 45,450 |
def calc_topk_accuracy(output, target, topk=(1,)):
"""
Modified from: https://gist.github.com/agermanidis/275b23ad7a10ee89adccf021536bb97e
Given predicted and ground truth labels,
calculate top-k accuracies.
"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1... | aedd1f4ca1b2b6be411d500ee8f82aef731e8913 | 45,451 |
import json
def read_anno_Traff_mcl(anno_info):
"""Read the annotation.
if the dataset in ['Trafficlight_mcl'], this function will be used.
:return: boxes, klass, is_crowd
:rtype: tuple
"""
(anno_path, set_ignore, set_fake, label_map, tl_color_map, vehicle_person_id, boxes, klass, is_crowd) =... | 670f19df29de0818af2e57d52b2e9e863faf6f69 | 45,454 |
import asyncio
def get_delayed_hash(delay):
"""
Returns a delayed version for testing hash_func.
"""
async def delayed_hash(left, right):
await asyncio.sleep(delay)
return await hash_func(left, right)
return delayed_hash | b9441c45b51a35a6cbb923cee7f34f9a431e8696 | 45,455 |
def seek_revised(request):
"""Getting the investigations, studies and assays based on the
information given by the user in the upload form. The user selects
the project, investigation, study and assay. After selecting the assay
the user enter a title and description an can upload a data file to the
... | 6a35c3718f477cb1d80ef6d142757aa66b097580 | 45,456 |
def discriminative_instance_loss(y_true, y_pred,
delta_v=0.5,
delta_d=1.5,
gamma=1e-3):
"""Discriminative loss between an output tensor and a target tensor.
Args:
y_true: A tensor of the same shape as `y_... | 9c5b35e395117a7e495cf9cdcac96f7fec4f1caa | 45,457 |
def get_from_konrad(variable,exps):
"""Extracts a variable from the output files of several `konrad` experiments.
Parameters
----------
variable : str
Variable name in the output file.
exps : list
List of strings describing the paths to the output files.
Returns
-------
p,t ... | 5fd5389e1ce79f96632f013c983a371a57a91b20 | 45,458 |
def fence_vegalite(source, language, class_name, options, md, **kwargs):
"""
Inspired by https://github.com/facelessuser/pymdown-extensions/blob/8ee5b5caec8f9373e025f50064585fb9d9b71f86/pymdownx/superfences.py#L146
""" # noqa
if not _validateJSON(source):
raise SuperFencesException from Plugin... | 2194fb7aeb10b255462533dd128c3d116d9c1487 | 45,459 |
def ExportKeypointsToCOCO(image_ids,
detection_keypoints,
detection_scores,
detection_classes,
categories,
output_path=None):
"""Exports keypoints in numpy arrays to COCO API.
This func... | 8ef6a789296c095e6c5e2e2ead5d3f73b7ca0ce0 | 45,460 |
def to_monochrome(source, fmt):
""" Convert an image to monochrome """
img = Image.open(source)
img.convert(mode='1')
img.save(source, format=fmt.replace('jpg', 'jpeg') if fmt else None)
return source | 0eced011d204c362468bb72461a03bd4ba633a1b | 45,461 |
def dark_correct_arimg(
img: arimage.ARImage,
dark: arimage.ARImage) -> arimage.ARImage:
""" Dark corrects image """
logger.info("Dark correcting image: " + img.getFullPath())
logger.info(" with dark: " + dark.getFullPath())
# Load image data into memory if it is not already ... | d646b97473f694043487b6da2efd5779b20cfb09 | 45,462 |
def isPathPolyIntersect(path, poly):
"""Given a path in the form of np.ndarray, return if it intersects with a given polygon.
:param path: ndarray, (\*, 2) a path represented by N by 2 matrice
"""
line = LineString(path)
intersect = line.intersects(poly)
print(intersect)
if isinstance(inter... | fc1d60a3fbaba2fd0e0b2d61c3e7408c0950f742 | 45,464 |
def convertMDSToCreateObjectExpression(mds, path, allowPrivate, name, pathToCodeDefinitionStrings):
"""given an MDS and a path, return an expression
that creates a module member and the type of module member."""
tree = convertMDSToSourceCodeTree(mds, name)
parser = ForaNative.ModuleParser()
resul... | 2ff722674ca00f06098c6a5a2a766137022750f3 | 45,465 |
import pickle
def load_pickle(file, decompress=True):
"""
Load a .pickle file.
:param file: file .pickle to load.
:param decompress: the compress or not the file
:return: loaded data.
"""
with open(file, "rb") as f:
if decompress:
data = pickle.load(f)
else:
... | ce86a034c87ddd3a74de40465d60cb2f55d1089c | 45,466 |
def latex(df):
"""Converte o DF fornecido para tabela LaTeX"""
return print(df.to_latex()) | 6ab524733ac1f9040699f349564cf4321ae6e909 | 45,468 |
def generate_king_attack_bb_from_square(from_square: int) -> np.uint64:
"""
Returns the king attack bitboard on an otherwise empty board from the provided square
:param from_square: starting square from which to generate king attacks
:return: np.uint64 bitboard representation of king attacks on an other... | 4f7d556c67e7897d1502afa82783e811b9739919 | 45,469 |
def get_review_by_product(request, id):
"""get reviews of certain product and return render"""
prod = get_object_or_404(Product, pk=id) # get product
related = Review_Connector.objects.all().select_related().filter(product_id=id)
context = {'review_connected': related,
"product_id": ... | f18b1491c8a81226fc266cf3e9a4df25674d9c7d | 45,470 |
def normalise_operator_input(*args):
"""Input to Operator may contain products of epsilons which are sympy TensMul
objects. This causes problems since I don't want to define products of
epsilons or deltas to be operators.
This function normalises the input to the Operator constructor to avoid
probl... | e1b6df90db1f948f40ceae648111c1b07caf5599 | 45,471 |
from typing import Sequence
from typing import Callable
def make_button(
name: str = '',
parent: QObject|None = None,
slots: Sequence[Callable, ...] = (),
hint: str = ''
):
"""Make a simple, default Qt push button.\n
Slots will be connected to the `clicked` signal.
"""
... | 17aa577acf3820daa263fb7a3ab76b4ac62a7704 | 45,472 |
def _fontValidator(font):
"""Check if font value is valid, regex is too slow.
Checks everything before ``,`` on basic font value. Everything after should
be a valid font-family value.
"""
if u',' in font:
# split off until 1st family
font1, families2 = font.split(u',', 1)
else:
... | 515742f57d630c08d8562baedc90d7b4e55744b0 | 45,473 |
import json
from datetime import datetime
async def edit_event(ctx, client):
"""
Function:
edit_event
Description:
A existing event is edited from the user's schedule file
Input:
ctx: the current context
client: the instance of the bot
Output:
- A reply sayi... | 5a69b88efd37979b3c8618d042e748932c9a0327 | 45,474 |
def plot_country(country, yvals, y2vals):
"""Makes 3-panel plot from country data"""
# Log values
yvals_log = get_log(yvals)
y2vals_log = get_log(y2vals)
# Per-day change
yvals_perday = get_change_per_day(yvals)
y2vals_perday = get_change_per_day(y2vals)
fig = make_subplots(
r... | 37a994efb72647c7c8d047a68c5c31c71d826579 | 45,475 |
def get_accountinfo(msg: dict) -> str:
"""
Returns a dictionary containing the
account id and an array of prowler group checks.
"""
if msg == "":
raise IndexError
else:
try:
account_id = msg['Id']
return account_id
except KeyError as err:
... | 496c3c1f0c64ecb8627f51bce69e6d5672406344 | 45,476 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.