content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def quadratic_bezier(t, p0, p1, p2):
"""
:return: Quadratic bezier formular according to https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B%C3%A9zier_curves
"""
return (1 - t) * ((1 - t) * p0 + t * p1) + t * ((1 - t) * p1 + t * p2) | 45,900 |
def add_musician_genres(musician, genre_list):
"""Add genres to a musician's profile"""
musician_genres = []
found_genres = Genre.query.filter(Genre.genre_name.in_(genre_list)).all()
for genre in found_genres:
musician_genre = MusicianGenre(genre_id=genre.genre_id,
... | 45,901 |
def test_eat_exceptions_normal_case():
"""
If no exceptions, this wrapper should do nothing.
"""
@utils.eat_exceptions
def test_function(x):
return x
assert test_function(1) == 1 | 45,902 |
def delete_system_interface(api_client, interface_id, **kwargs): # noqa: E501
"""delete_system_interface # noqa: E501
Delete System Interface # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> response = awa... | 45,903 |
def IsPlacementGroupCompatible(machine_type):
"""Returns True if VMs of 'machine_type' can be put in a placement group."""
prefix = machine_type.split('.')[0]
return prefix not in NON_PLACEMENT_GROUP_PREFIXES | 45,904 |
def destroy():
"""
Remove the cloud environment and all its PGA contents.
"""
click.echo("cloud destroy") | 45,905 |
def join_paths(new_Folder, file_Name=False):
"""
Requer uma string. Nome da pasta a ser criada.
Por padrão file_Name é False.
Quando file_Name é falso retorna o abspath da
pasta passada em folder.
Quando file_Name é verdadeiro junta o abspath da pasta
passada mais o nome do arquivo ... | 45,906 |
def test_call_after_hooks_in_correct_order(hookregistry, mocker):
"""
Test calling registered hooks in the correct order
"""
# given
data = [] # used to capture ordering
@after.all(order=2)
def second_hook(features):
data.append(2)
@after.all(order=1)
def first_hook(step):... | 45,907 |
def largest_number_in_arrays():
"""
Given an array of arrays of numbers, return the largest.
"""
return | 45,908 |
def create_public_key_from_b64(b64Key: bytes) -> X25519PublicKey:
"""Derive X25519 Private key from b64 ascii string"""
public_bytes = binascii.a2b_base64(b64Key)
loaded_private_key = X25519PublicKey.from_public_bytes(public_bytes)
return loaded_private_key | 45,909 |
def im_detect_bbox(model, images, target_scale, target_max_size, device,
captions=None,
positive_map_label_to_token=None
):
"""
Performs bbox detection on the original image.
"""
if cfg.INPUT.FORMAT is not '':
input_format = cfg.IN... | 45,910 |
async def ignore_error_handler(err: Any) -> None: # pragma: no cover
"""Always ignore error."""
pass | 45,911 |
def jmap(g, H, ae0, be0, af0, bf0, max_iter=1000, tol=1e-4, rcond=None, observer=None):
"""Maximum a posteriori estimator for g = H @ f + e
p(g | f) = normal(H f, ve I)
p(ve) = inverse_gauss(ae0, be0)
p(f | vf) = normal(0, vf I)
p(vf) = inverse_gauss(af0, bf0)
JMAP: maximizes p(f,ve,vf|g) = p(... | 45,912 |
def text_rank_init(graph: Graph, uniform: bool = False, seed: Optional[int] = None) -> Tuple[List[float], List[float]]:
"""Generate the initial scores for each node and pre-compute the outgoing strength.
The sum of the weights for outbound edges for a given node doesn't change as text rank runs because
it ... | 45,913 |
def get_chats(im):
"""This function gets the chatting messages.
Arguments:
im (PIL.Image.Image): Image object
Return:
Image object list (PIL.Image.Image).
[0]: The most latest chatting message. e.g, The most below messages.
"""
return get_chat_msg(im) | 45,914 |
def test_fire_sim_persist(
netlogo_sh, netlogo_args, sess_file, get_beshp_xml, result_field_map
):
"""This is a persistent test of whether the thing works, without persisting the data.
1. Build the NetLogo args vector for invocation
2. Write a setup-file to contain the model arguments
3. Invoke Net... | 45,915 |
def state_field(value):
"""Fetch the pagination state field from flask.request.args.
:returns: list of the state(s)
"""
states = istate.States.all()
value = value.split(',')
invalid_states = [state for state in value if state not in states]
assert not invalid_states, \
_('State(s) "... | 45,916 |
def cal_smoothness_orig(var1_orig, var2_orig, var3_orig, io, args):
"""
Input:
var1_orig, var2_orig, var3_orig: scalar tensors, original variances on the 3 principal orientations
Return: smoothness_orig: scalar, original smoothness of this region (linearity/planarity/scattering,
dependi... | 45,917 |
def format_size(size):
"""Format provided size in bytes in a human-friendly format
:param int size: size to format in bytes
:return: formatted size with an SI prefix ('k', 'M', 'G', 'T') and unit
('B')
:rtype: str
"""
if abs(size) < 1000:
return str(size) + 'B'
for unit in ... | 45,918 |
def get_acl_permission(acl, complete_acl_list):
"""
This uses numpy's vectorized operations to quickly match the acl returned from the API, to
the complete list of acls to get the description.
"""
index = -1
where_arrays = np.where(acl == complete_acl_list[:,0])
try:
index = wher... | 45,919 |
def interface_script(mod_interface, nn_module):
"""
Makes a ScriptModule from an nn.Module, using the interface methods rule for
determining which methods to compile.
Args:
mod_interface: the interface type that the module have
nn_module: The original Python nn.Module that we are creat... | 45,920 |
def create_call_error(message: str) -> str:
"""Create CallError serialized representation based on serialize Call.
Raises ValueError if message is not type Call. CallResult and CallError
don't require response.
"""
call: Call = unpack(message)
if isinstance(call, Call):
call_error: Call... | 45,921 |
def test_discordwebhook_webhook_url():
"""validate that we can query after setting serverid and api key"""
base_url = 'https://discordapp.com/api/webhooks/'
test_serverid = 1234
test_apikey = 'some-key'
test_url_faulty = 'some string'
test_url_correct = base_url + str(test_serverid) + '/' + test... | 45,922 |
def filter_boxes(min_score, boxes, scores, classes):
"""Return boxes with a confidence >= `min_score`"""
n = len(classes)
idxs = []
for i in range(n):
if scores[i] >= min_score:
idxs.append(i)
filtered_boxes = boxes[idxs, ...]
filtered_scores = scores[idxs, ...]
filtered_... | 45,923 |
def test_make_regressor_1():
""" test the generated regressor
"""
condition = ([1, 20, 36.5], [2, 2, 2], [1, 1, 1])
frame_times = np.linspace(0, 69, 70)
hrf_model = 'spm'
reg, reg_names = compute_perfusion_regressors([condition], ['cond'],
hrf_mo... | 45,924 |
def recenter_image(im):
"""
"""
n_height, n_width = im.shape
com = nd.center_of_mass(im)
if any(np.isnan(com)):
return im
im_center = im[(com[0]-n_height/2):(com[0]+n_height/2)]
offset = [(n_height-im_center.shape[0]),(n_width-im_center.shape[1])]
if offset[0]%2 > 0:
h_odd = 1
else:
h_odd = 0
if offse... | 45,925 |
def show_opts():
"""
BG__colors
BG_BLACK, BG_RED, BG_GREEN, BG_YELLOW, BG_BLUE,
BG_MAGENTA, BG_CYAN, BG_WHITE
EFFECTS
RESET, BOLD, FAINT, ITALIC, UNDERLINE
COLORS
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE
"""
__show('BG__colors', __bgColors)
__show('EFFECTS', __ef... | 45,926 |
def test_get_report_type(mocker, input, expected_results):
"""
Given:
- set of parameters from demisto.
When:
- create an instance and on every run.
Then:
- Returns a report type.
"""
report_type: str = feed.get_report_type(input)
assert report_type == expected_res... | 45,927 |
def cal_participate_num(course: Course) -> Counter:
"""
计算该课程对应组织所有成员的参与次数
return {Naturalperson.id:参与次数}
前端使用的时候直接读取字典的值就好了
"""
org = course.organization
activities = Activity.objects.activated().filter(
organization_id=org,
status=Activity.Status.END,
category=Activ... | 45,928 |
def plot(
self,
fig=None,
ax=None,
is_lam_only=False,
sym=1,
alpha=0,
delta=0,
is_edge_only=False,
edgecolor=None,
is_add_arrow=False,
is_display=True,
is_show_fig=True,
):
"""Plot the Lamination with empty Slots in a matplotlib fig
Parameters
----------
... | 45,929 |
def usage_percentage(usage, limit):
"""Usage percentage."""
if limit == 0:
return ""
return "({:.0%})".format(usage / limit) | 45,930 |
def all(numbered=False):
"""
Get all included stanzas.
Takes optional argument numbered.
Returns a dict if numbered=True, else returns a list.
"""
return dict(zip(range(1, 165 + 1), stanzas)) if numbered else stanzas | 45,931 |
def cosine_decay(learning_rate, global_step, maximum_steps,
name=None):
"""
"""
from tensorflow.python.ops import math_ops
from tensorflow.python.framework import ops
if global_step is None:
raise ValueError("global_step is required for cosine_decay.")
with ops.name_scope(name, "Cosine... | 45,932 |
def bake_to_animation(nodes, min_time = None, max_time = None):
"""
bake the animation with nice settings that fix flipping
"""
if not min_time or not max_time:
min_time, max_time = get_min_max_time()
cmds.bakeResults( nodes, simulation = True,
t = (m... | 45,933 |
def parse_file_header_64(bytes):
"""Parse the ELF file header."""
e_ident = {}
e_ident['EI_CLASS'] = get_bytes(bytes, 4)
e_ident['EI_DATA'] = get_bytes(bytes, 5)
endian = get_byte_order(e_ident['EI_DATA'])
e_ident['EI_VERSION'] = get_bytes(bytes, 6)
e_ident['EI_OSABI'] = get_bytes(bytes, 7)
... | 45,934 |
def _or (*args):
"""Helper function to return its parameters or-ed
together and bracketed, ready for a SQL statement.
eg,
_or ("x=1", _and ("a=2", "b=3")) => "(x=1 OR (a=2 AND b=3))"
"""
return " OR ".join (args) | 45,935 |
def strip_empty_values(values: Dict) -> Dict:
"""Remove any dict items with empty or ``None`` values."""
return {k: v for k, v in values.items() if v or v in [False, 0, 0.0]} | 45,936 |
def dispnet(path=None, batch_norm=True):
"""dispNet model architecture.
Args:
path : where to load pretrained network. will create a new one if not set
"""
model = DispNet(batch_norm=batch_norm)
if path is not None:
data = torch.load(path)
if 'state_dict' in data.keys():
... | 45,937 |
def add_model_components(m, d, scenario_directory, subproblem, stage):
"""
The following Pyomo model components are defined in this module:
+-------------------------------------------------------------------------+
| Expressions |
+======... | 45,938 |
def apigw_required(view_func):
"""apigw装饰器
"""
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
request.jwt = JWTClient(request)
if not request.jwt.is_valid:
return jwt_invalid_view(request)
return view_func(request,... | 45,939 |
def set_up_random(salesforce):
"""" This function is used to generate unique set of values for each test.
Every time this function is used, generates a unique RANDOM string to
set up the values used in every test."""
TEST_DATA['STR_15_RANDOM'] = get_random_string(string.ascii_letters, 15)
logger.in... | 45,940 |
def text_analysis(string: str, *, nlp) -> str:
"""Return a text analysed string.
post-analysis sentences are separated by <sent> tags
e.g., 'a sentence<sent>a second sentence<sent>a third.
see https://spacy.io/usage/rule-based-matching#adding-patterns-attributes
"""
sents = []
doc = nlp(s... | 45,941 |
def wtr_tens(P, T):
"""Function to Calculate Gas-Water Interfacial Tension in dynes/cm"""
#P pressure, psia
#T temperature, °F
s74 = 75 - 1.108 * P ** 0.349
s280 = 53 - 0.1048 * P ** 0.637
if (T <= 74):
sw = s74
elif(T >= 280):
sw = s280
else:
sw... | 45,942 |
def _decompose_move(event: MoveElements) -> List[MoveElements]:
"""
Decompose an event moving elements into a list of MoveElements events representing the
same action.
:param event: event to decompose
:return: list of events representing the same action
"""
return [event] | 45,943 |
def _read_housekeeping(fname):
"""Reads housekeeping file (fname; csv-format) returns a pandas data frame instance."""
print('reading %s'%fname)
try:
df = pd.read_csv(fname, error_bad_lines=False)
except ValueError:
return False
# data = df.values
# dateString = fname.split... | 45,944 |
def get_line_equation(segment_point0, segment_point1):
"""
Ax + By + C = 0
:param segment_point0: Point
:param segment_point1:
:return: A, B, C
"""
x0, y0 = segment_point0.px, segment_point0.py
x1, y1 = segment_point1.px, segment_point1.py
a, b, c = y1 - y0, x0 - x1, x1 * y0 - y1 * ... | 45,945 |
def keep_lesser_x0_y0_zbt0_pair_in_dict(p, p1, p2):
"""Defines x0, y0, and zbt0 based on the group associated with the
lowest x0. Thus the new constants represent the point at the left-most
end of the combined plot.
:param p: plot to combine p1 and p2 into
:param p1: 1st plot to combine
:param p... | 45,946 |
def build_csv_from_cellset_dict(
row_dimensions: List[str],
column_dimensions: List[str],
raw_cellset_as_dict: Dict,
top: Optional[int] = None,
line_separator: str = "\r\n",
value_separator: str = ",",
include_attributes: bool = False) -> str:
""" transform ra... | 45,947 |
def get_stages_from_api(**kwargs):
"""
This is the API method, called by the appConfig.instantiate method
"""
resp = utils.request(utils.RETRIEVE, 'stages', kwargs)
return utils.parse(resp) | 45,948 |
def fill_str_array(data, size, push_back=True):
"""
Fill StringArrayType array with given values to reach the size
"""
string_array_size = len(data)
nan_array_size = size - string_array_size
num_chars = sdc.str_arr_ext.num_total_chars(data)
result_data = sdc.str_arr_ext.pre_alloc_string_ar... | 45,949 |
def _visible_fields(user_profile, user, configuration=None):
"""
Return what fields should be visible based on user's preferences
:param user_profile: User profile object
:param user: User object
:param configuration: A visibility configuration dictionary.
:return: whitelist List of fields to b... | 45,950 |
def open_dataframe():
"""
Function to open the dataframe if it exists, or create a new one if it does not
:return: Dataframe
"""
print("Checking for presence of data file......")
try:
datafile = './data/data.csv'
dataframe = pd.read_csv(datafile)
print("File found.... loa... | 45,951 |
def parse_manifest_v3(manif, manifest_info, opts):
"""
parse IIIF V3 manifest for annotations
"""
annotation_info = manifest_info['annotations']
canvas_ids = set()
annolist_idx = 0
if manif.get('type', None) != 'Manifest':
raise ValueError("Manifest not of type Manifest")
... | 45,952 |
def zipglob(sfiles, namelist, path):
"""Returns a subset of filtered namelist"""
files = []
# cycle the sfiles
for sfile in sfiles:
# we will create a list of existing files in the zip filtering them
# by the sfile filename
sfile.zfiles = fnmatch.filter(namelist, join(path, sfile... | 45,953 |
def to_string(result: ValidationResult, name_col_width: int) -> str:
"""Format a validation result for printing."""
name = state_name(result.state)
if result.failed:
msg = ", ".join(result.error_details.strip().split("\n"))
return f"❌ {name} {msg}"
elif result.state.reward is None:
... | 45,954 |
def two_sum_v1(array, target):
"""
For each element, find the complementary value and check if this second value is in the list.
Complexity: O(n²)
"""
for indice, value in enumerate(array):
second_value = target - value
# Complexity of in is O(n). https://stackoverflow.com/questions/... | 45,955 |
def worker_numric_avg(fleet, value, env="mpi"):
"""R
"""
return worker_numric_sum(fleet, value, env) / fleet.worker_num() | 45,956 |
def collection_subscribers():
"""
Collection weekly and monthly subscriber counts.
"""
log.debug('Starting collection subscriber update...')
cursor = connection.cursor()
cursor.execute("""
UPDATE collections SET weekly_subscribers = 0, monthly_subscribers = 0
""")
cursor.execute(... | 45,957 |
def build_graph(
nodes: List[Tuple[str, Dict]], edges: List[Tuple[str, str, Dict]]
) -> nx.DiGraph:
"""Builds the graph using networkx
Arguments
---------
nodes : list
A list of node tuples
edges : list
A list of edge tuples
Returns
-------
networkx.DiGraph
... | 45,958 |
def assert_ndim(arg: Any, ndims: Int) -> None:
"""Raise exception if the argument has a different number of dimensions than `ndims`."""
if np.ndim(arg) != ndims:
raise AssertionError(f"Number of dimensions must be {ndims}, not {np.ndim(arg)}") | 45,959 |
def table_exists_sql(any_schema=False):
"""SQL to check for existence of a table. Note that for temp tables, any_schema should be set to True."""
if not any_schema:
schema_filter_sql = sql.SQL('AND schemaname = current_schema()')
else:
schema_filter_sql = sql.SQL('')
return sql.SQL("""S... | 45,960 |
def _process_json(data):
"""
return a list of GradPetition objects.
"""
requests = []
for item in data:
petition = GradPetition()
petition.description = item.get('description')
petition.submit_date = datetime_from_string(item.get('submitDate'))
if 'decisionDate' in it... | 45,961 |
def PaddingMask(pad=0):
"""Returns a layer that maps integer sequences to padding masks.
The layer expects as input a batch of integer sequences. The layer output is
an N-D array that marks for each sequence position whether the integer (e.g.,
a token ID) in that position represents padding -- value ``pad`` --... | 45,962 |
async def delete_image(image: str) -> None:
"""Deletes the specified image, used for testing"""
try:
async with aiodocker.Docker() as client:
await client.images.delete(image, force=True)
except aiodocker.DockerError as e:
# ignore failures saying the image doesn't exist
... | 45,963 |
def pdf(option_pdf):
"""
Открытие файла для чтения и закрытие в конце работы.
"""
pdf_document = fitz.open(option_pdf)
yield pdf_document
pdf_document.close() | 45,964 |
def python_packages():
"""
Reads input.yml and returns a list of python
related packages
"""
with open(r"tests/input.yml") as file:
inputs = yaml.load(file, Loader=yaml.FullLoader)
return inputs["python_packages"] | 45,965 |
def create_tcp_visonic_connection(address, port, protocol=VisonicProtocol, command_queue = None, event_callback=None, disconnect_callback=None, loop=None, excludes=None):
"""Create Visonic manager class, returns tcp transport coroutine."""
# use default protocol if not specified
protocol = partial(
... | 45,966 |
def test_string_conversion(list_entry_factory):
"""
Converting a list entry to a string should return the entry's text.
"""
entry = list_entry_factory()
assert str(entry) == entry.text | 45,967 |
def metric_wind_dict_to_beaufort(d):
"""
Converts all the wind values in a dict from meters/sec
to the corresponding Beaufort scale level (which is not an exact number but rather
represents a range of wind speeds - see: https://en.wikipedia.org/wiki/Beaufort_scale).
Conversion table: https://www.win... | 45,968 |
def add_favorite_clubs():
"""
POST endpoint that adds favorite club(s) for student user. Ordering is preserved
based on *when* they favorited.
"""
user = get_current_user()
json = g.clean_json
new_fav_clubs_query = NewOfficerUser.objects \
.filter(confirmed=True) \
.filter(... | 45,969 |
def _send_msg_task(sock, cli_addr, cli_cli_msgs_ps):
"""响应定向客户端的消息"""
pipe = cli_cli_msgs_ps[cli_addr][1]
while True:
sock.sendto(pipe.recv(), cli_addr) | 45,970 |
def open_sentinel2_band(scene_path, band_id):
"""Open one Sentinel-2 band image with rasterio"""
with open_sentinel2_bands(scene_path, [band_id]) as bands:
yield bands[0] | 45,971 |
def death_rate_60():
"""
Real Name: b'death rate 60'
Original Eqn: b'Critical Cases 60*fraction of death 60/duration of treatment 60'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return critical_cases_60() * fraction_of_death_60() / duration_of_treatment_60() | 45,972 |
def test_get_query_logging_config():
"""Test valid and invalid get_query_logging_config requests."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Create a query logging config that can then be retrieved.
hosted_zone_test_nam... | 45,973 |
def test_cdpp():
"""Tests the estimate_cdpp() convenience function which wraps
`LightCurve.estimate_cdpp()`"""
flux = np.random.normal(loc=1, scale=100e-6, size=10000)
lc = LightCurve(time=np.arange(10000), flux=flux)
assert_almost_equal(estimate_cdpp(flux), lc.estimate_cdpp()) | 45,974 |
def _find_tracking_gaps(
first_spc_date_string, last_spc_date_string, top_tracking_dir_name,
tracking_scale_metres2, source_name, min_time_diff_seconds):
"""Finds gaps (temporal discontinuities) between storm-tracking files.
:param first_spc_date_string: See documentation at top of file.
:p... | 45,975 |
def get_item(character, command):
"""Parses the get command."""
# first, we sanitize spaces
command = re.sub(r"\s+", " ", command).lower()
# prendre objet:
match = re.match(r"(le |la |les |l')?(\w+)\s*$", command)
if match:
get_item_from_room(character, match.group(2))
return
... | 45,976 |
def cast_vote(uid, target_type, pcid, value):
""" Casts a vote in a post.
`uid` is the id of the user casting the vote
`target_type` is either `post` or `comment`
`pcid` is either the pid or cid of the post/comment
`value` is either `up` or `down`
"""
# XXX: This function returns a... | 45,977 |
def convert_file(ifn: str, ofn: str, opts: Namespace) -> bool:
"""
Convert ifn to ofn
:param ifn: Name of file to convert
:param ofn: Target file to convert to
:param opts: Parameters
:return: True if conversion is successful
"""
if ifn not in opts.converted_files:
out_json = to... | 45,978 |
def target_validation(target_name, action):
"""
Given a Target name and an action, determine if the target_name is a valid
target in target.json and if the target supports the action.
Parameters
----------
target_name : str
Name of the Target.
action : str
Type of action the... | 45,979 |
def _writechecksummanifest(fn: str, prefixlen: int, bac: dict) -> tuple[str, int, int]:
"""Write an AIP "checksum manifest".
This writes an AIP "checksum manifest" to the given ``fn`` PDS filename, stripping ``prefixlen``
characters off paths, and using information from the ``bac``. Return a triple of the... | 45,980 |
def print_analysis(experiment_name, expected_free_energy, obtained_free_energy):
"""Print the results of the analysis.
Parameters
----------
experiment_name : str
The name of the experiment to print.
expected_free_energy : tuple of float
The expected pair (DeltaF, dDeltaF) in kT.
... | 45,981 |
def create_os_instance_yaml(section_name, project_name):
"""
Create yaml from template for OpenStack instances
"""
data_type = "instances"
instance_name = section_name + "_os_instance"
instance_yaml = instance_name + ".yaml"
instance_cleanup_yaml = instance_name + "_cleanup.y... | 45,982 |
def bartletts_formula(acf_array, n):
"""
Computes the Standard Error of an acf with Bartlet's formula
Read more at: https://en.wikipedia.org/wiki/Correlogram
:param acf_array: (array) Containing autocorrelation factors
:param n: (int) Length of original time series sequence.
"""
# The first ... | 45,983 |
def construct_sentences(g, key):
"""
Utility function used to extract a sentence from a frame RDF graph
"""
query = """
PREFIX oflog: <https://yaknema.com/oflog/1.0.0/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?action_name ?resource_name ?reso... | 45,984 |
def AddEnum(idx, name, flag):
"""
Add a new enum type
@param idx: serial number of the new enum.
If another enum with the same serial number
exists, then all enums with serial
numbers >= the specified idx get their
serial numbers incremented (in other words,
... | 45,985 |
def get_turbine_shadow_polygons(blade_length: float,
blade_angle: Optional[float],
azi_ang: float,
elv_ang: float,
wind_dir,
tower_shadow: bool = True
... | 45,986 |
def str_igrep(S, strs):
"""Returns a list of the indices of the strings wherein the substring S
is found."""
return [i for (i,s) in enumerate(strs) if s.find(S) >= 0]
#return [i for (s,i) in zip(strs,xrange(len(strs))) if s.find(S) >= 0] | 45,987 |
def save_lbin_history(ah: AuctionHouse) -> None:
"""
Record the lowest BIN buffer of the given AuctionHouse instance into the
database.
:param ah: The AuctionHouse instance to use.
:return: None.
"""
sql = 'INSERT INTO lbin_history VALUES (?, ?, ?, ?)'
now = datetime.now()
for (item... | 45,988 |
def random_laplace(shape, loc=0.0, scale=1.0, dtype=tf.float32, seed=None):
"""
Helper function to sample from the Laplace distribution, which is not
included in core TensorFlow.
"""
z1 = random_exponential(shape, loc, dtype=dtype, seed=seed)
z2 = random_exponential(shape, scale, dtype=dtype, seed=seed)
r... | 45,989 |
def resample_image(img_in, width_in, height_in, width_out, interpolation_method="bilinear"):
"""
Resample (i.e., interpolate) an image to new dimensions
:return resampled image, new height
"""
img_out = []
scale = float(width_out) / float(width_in)
scale_inv = 1.0 / scale
# print "Resampling scale and scale_i... | 45,990 |
def identify_missing(df=None, na_values=['n/a', 'na', '--', '?']):
"""Detect missing values.
Identify the common missing characters such as 'n/a', 'na', '--'
and '?' as missing. User can also customize the characters to be
identified as missing.
Parameters
----------
df : DataFrame
R... | 45,991 |
def test0():
"""None->None
affiche a, variable non déclarée dans la fonction"""
print("valeur de a dans test0",a) | 45,992 |
def categorize():
"""API de categorização utilizando o modelo Perceptron()"""
# Load input
body = request.json
# Error handling
if not "products" in body:
return { "error": "json field 'products' does not exist"}, 400
products = body["products"]
if type(products) != list:
... | 45,993 |
def test_is_fitted(network=CNNClassifier()):
"""
testing that the networks correctly recognise when they are not fitted
"""
X_train, y_train = load_italy_power_demand(split="train", return_X_y=True)
if isinstance(network, BaseRegressor):
# Create some regression values, taken from test_reg... | 45,994 |
def _TryJobSvnRepo(builder_type):
"""Returns an SVN repo to use for try jobs based on the builder type."""
if builder_type == fetch_build.PERF_BUILDER:
return PERF_SVN_REPO_URL
if builder_type == fetch_build.FULL_BUILDER:
return FULL_SVN_REPO_URL
if builder_type == fetch_build.ANDROID_CHROME_PERF_BUILDE... | 45,995 |
def find_wr5bis_common2(i, n, norm, solution_init, common2b_init):
"""
Find the point when for the scalar product of the solution
equals the scalar product of a guess with 2 consecutive bits in common.
Fct_common2b(w) = fct_solution(w), for which w in [w0_3 , w0_4]
with 0 =< w0_3 < w0_4 < 1 ?
fct_solution(w) =... | 45,996 |
def np_printoptions(*args, **kwargs):
"""Temporary set numpy printoptions
with np_printoptions(precision=3, suppress=True):
http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array
"""
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
yield
np.set_pri... | 45,997 |
def yml_remove_releaseNote_record(file_path, current_server_version):
"""
locate and remove release notes from a yaml file.
:param file_path: path of the file
:param current_server_version: current server GA version
:return: True if file was changed, otherwise False.
"""
with open(file_path,... | 45,998 |
def calculate_z_score(
data: Union[MultimodalData, UnimodalData, anndata.AnnData],
n_bins: int = 50,
) -> np.array:
"""Calculate the standardized z scores of the count matrix.
Parameters
-----------
data: ``MultimodalData``, ``UnimodalData``, or ``anndata.AnnData`` object.
Single cell e... | 45,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.