content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_search_best_options_return_type(random_unbounded, maximum):
"""Tests if best options returns a dictionary"""
_, best_options = random_unbounded.search(maximum)
assert isinstance(best_options, dict) | 5,300,600 |
def update_contact(account_id=None, id=None, attributes=None, cursor=None):
"""
Update one contacts entry at database identified by Account ID and ID
:param account_id:
:param id:
:return: Particular dict
"""
if account_id is None:
raise AttributeError("Provide account_id as paramete... | 5,300,601 |
def validate_reserved_alias(_netid: str, client: ShrunkClient, alias: str) -> Any:
"""``GET /api/validate_reserved_alias/<b32:alias>``
Validate an alias. This endpoint is used for form validation in the frontend. Response format:
.. code-block:: json
{ "valid": "boolean", "reason?": "string" }
... | 5,300,602 |
def process_researcher(request, context, form_fields):
"""
Function for processing researcher requests.
:param request: HttpRequest
Http request with session.
:param context: Dict
Existing context.
:param form_fields: Tuple
Fields for saving in context.
"""
alg_set... | 5,300,603 |
def _kl_normal_gp(n, gp, name=None):
"""Calculate the batched KL divergence KL(gp || n).
Args:
n: instance of a Normal distribution object.
gp: instance of a GaussianProcess distribution object.
name: (optional) Name to use for created operations.
default is 'kl_normal_gp'.
Returns:
Batchw... | 5,300,604 |
def mahalanobis(u, v, VI):
"""
:purpose:
Computes the Mahalanobis distance between two 1D arrays
:params:
u, v : input arrays, both of shape (n,)
VI : the inverse of the covariance matrix of u and v
note that some arrays will result in a VI containing
very high v... | 5,300,605 |
def filter_tests(all_tests, arguments):
""" Will figure out which tests are to be run
Arguments:
all_tests (list of Test obj): all processed test objects
arguments (argument object): Contains arguments from argparse
returns:
list: All Test objects that are to be run
"""
pri... | 5,300,606 |
def create_lidarbeam_arr(
sensor_pos: List[float],
sensor_heading: float,
max_range: float,
n_beams: int,
n_pts: int = 600,
resolution: float = None,
) -> Tuple[np.ndarray]:
"""Create all lidar beam points in the WORLD FRAME
:param sensor_pos: Sensor xy position in world frame
:type... | 5,300,607 |
def list_libraries(context,galaxy,path,long_listing,show_id):
"""
List data libraries and contents.
Prints details of the data library and folders
specified by PATH, in GALAXY instance.
PATH should be of the form
'data_library[/folder[/subfolder[...]]]'
"""
# Get a Galaxy instance
... | 5,300,608 |
def build_all():
"""Build the distribution & docs"""
build_dist()
build_docs() | 5,300,609 |
def test_cache_control():
"""Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy"))
app._add_route(
"/test/<string:user>/<name>",
funct,
methods=["GET"],
cors=True,
cache_control="public,max-... | 5,300,610 |
def test_mock_stop_at_4() -> None:
"""Check that stop_at 4 works."""
tc.assertTrue(
is_file_exists(get_absolute_from_current_path(__file__, "0001.png"))
)
copy_file(
get_absolute_from_current_path(__file__, "0001.png"),
get_absolute_from_current_path(__file__, "0001_4.png"),
... | 5,300,611 |
def is_user_blacklisted(user_id: int) -> bool:
"""
CHECK IF A USER IS BLACKLISTED
"""
return bool(
c.execute(
"""
SELECT blacklisted
FROM users
WHERE user_id=?
""",
(user_id,),
).fetchone()[0]
) | 5,300,612 |
def return_pitch_bend_tuple_dict(
tet, origin=0, size_of_semitone=SIZE_OF_SEMITONE
):
"""Returns a dictionary of form
(pitch_number: (12-tet midinum, pitch_bend))
Keyword args:
- origin: the 12 - tet pitch class from which the relevant pitches
will be calculated. (Should pro... | 5,300,613 |
def wrap_up(y, args):
"""Make metatable and print out a divider to indicate the end of
the file processing
"""
y.make_metatable(args.catalog_name)
add_line_in_log() | 5,300,614 |
def third_function(x):
"""Third benchmark function.
Args:
x (int, float): Input.
Returns:
float: Output. :math:`sin(πx)`
"""
return x * np.sin(np.pi * x) | 5,300,615 |
def install_sarge_filter():
"""
Installs Sarge log filter to avoid long 1char debug dumps
:return:
"""
global SARGE_FILTER_INSTALLED
if SARGE_FILTER_INSTALLED:
return
for handler in logging.getLogger().handlers:
handler.addFilter(SargeLogFilter("hnd"))
logging.getLogger(... | 5,300,616 |
def corpus_bleu(list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=None):
"""
:param references: a corpus of lists of reference sentences, w.r.t. hypotheses
:type references: list(list(list(str)))
:param hypotheses: a list of hypothesis sentences
:ty... | 5,300,617 |
def fetch_project(name):
"""Return the loaded JSON data from PyPI for a project."""
url = 'https://pypi.python.org/pypi/{}/json'.format(name)
r = requests.get(url)
try:
return r.json()
except ValueError:
# has to *return* an error instead of raising one,
# cos there seems to ... | 5,300,618 |
def SQuAD1(root: str, split: Union[Tuple[str], str]):
"""SQuAD1 Dataset
For additional details refer to https://rajpurkar.github.io/SQuAD-explorer/
Number of lines per split:
- train: 87599
- dev: 10570
Args:
root: Directory where the datasets are saved. Default: os.path.expan... | 5,300,619 |
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
donggaocun_df = pd.read_feather(f'{input_filepath}/donggaocun_aq_merged_weather.feather')
columns_to_impute = dongg... | 5,300,620 |
def test_channelstate_update_contract_balance():
"""A blockchain event for a new balance must increase the respective
participants balance.
"""
deposit_block_number = 10
block_number = deposit_block_number + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS + 1
our_model1, _ = create_model(70)
partner_... | 5,300,621 |
def a2str(a):
"""
formatting for 1 or 2 dimensional numpy arrays of booleans
"""
if len(a.shape) == 1:
return "".join(map(str, a))
elif len(a.shape) == 2:
return "\n".join(map(lambda row: "".join(map(str, row)), a)) | 5,300,622 |
def walk_dataflow_value(backend: RedunBackendDb, value: Value) -> Iterator[DataflowEdge]:
"""
Iterates through the edges in the upstream dataflow graph of a Value.
"""
# Find upstream CallNodes.
# A value can be produced by many CallNodes and it can be a subvalue of
# a value produced from many... | 5,300,623 |
def find_PFd(A, B, Q, R, beta=.95):
"""
Taking the parameters A, B, Q, R as found in the `setup_matrices`,
we find the value function of the optimal linear regulator problem.
This is steps 2 and 3 in the lecture notes.
Parameters
----------
(A, B, Q, R) : Array(Float, ndim=2)
The ma... | 5,300,624 |
def _should_save_cookies(request):
""" Return True if cookies should be saved for a request """
# based on QNetworkReplyImplPrivate::metaDataChanged() C++ code
attr = request.attribute(
QNetworkRequest.CookieSaveControlAttribute,
QNetworkRequest.Automatic
)
return attr == QNetworkReq... | 5,300,625 |
def generate(data_path, registry):
"""generates templates based on arguments and configurations."""
if not current_folder_has_venv():
logger.warning(Text.no_virtual_environment_remainder)
with open(data_path / "category_tree.json", encoding="UTF-8") as file:
full_tree = json.load(file)
... | 5,300,626 |
def test_metric_held_out_documents_wallach09():
"""
Test with data from original MATLAB implementation by Ian Murray
https://people.cs.umass.edu/~wallach/code/etm/
"""
try:
import gmpy2
except ImportError:
pytest.skip('gmpy2 not installed')
np.random.seed(0)
alpha = np... | 5,300,627 |
def update_chain(graph, loc, du, ud):
"""
Updates the DU chain of the instruction located at loc such that there is
no more reference to it so that we can remove it.
When an instruction is found to be dead (i.e it has no side effect, and the
register defined is not used) we have to update the DU cha... | 5,300,628 |
def get_latest_compatibility_result_by_version(
compatibility_results: Iterable[Optional[CompatibilityResult]]
) -> Optional[CompatibilityResult]:
"""Return the CompatibilityResult with the highest version number.
>>> cr1 = CompatibilityResult(
... packages=[Package('package1')],
...... | 5,300,629 |
def openNewTab(url: str, query: str):
"""Searches in New Tab"""
finalUrl: str = url + query
webbrowser.open_new_tab(finalUrl) | 5,300,630 |
def tapeout(parameters):
"""Copy build artifacts."""
# Nothing here as //base:tapeout will tapeout /usr/local/lib for us
pass | 5,300,631 |
def get_maxima( series, N, start_date = None, stop_date = None, _sorted = True ) :
"""
Summary:
Function that determines the first N maxima of a pandas time series
Arguments:
series - pandas series
N - number of maxima
start_date - start date as DateTime - used to li... | 5,300,632 |
def main():
"""Executes the main program including user-interaction"""
while True:
print("This program calculates sums.")
print(" [0] Exit")
print(" [1] Calculate partial sum of harmonic series")
print(" [2] Calculate Taylor series for e^x")
kind = Console.read_integer... | 5,300,633 |
def ALMASplit(uv, target, err, FQid=1, outClass=" ", logfile = "", \
check=False, debug = False):
"""
Write calibrated data
Returns task error code, 0=OK, else failed
* uv = UV data object to clear
* target = Target source name source name or list of names
* ... | 5,300,634 |
def raw_execute(signer, params, network):
"""Invoke a contract through an Account."""
account_raw_execute_command(signer, params, network) | 5,300,635 |
def get_latest_challenge_from_player_id(player, should_be_completed=False):
"""
Tries to find the latest challenge belonging to a player
param int player: The player ID to search the challenges for
param bool should_be_completed: If the challenge should already be completed or not
returns os3_rll.m... | 5,300,636 |
def get_all_groups():
"""
Get all groups
"""
result = http_request('GET', "/groups")
ec = {'DeepInstinct.Groups(val.id && val.id == obj.id)': result}
return_outputs(
readable_output=tableToMarkdown('Groups', result),
outputs=ec,
raw_response=result
) | 5,300,637 |
def runepisode(env, policy, episodesteps, render, windowlength=4):
"""Runs an episode under the given policy
Returns the episode history: an array of tuples in the form
(observation, processed observation, logprobabilities, action, reward, terminal)
"""
observation = env.reset()
x = prepro(... | 5,300,638 |
def Log(s, verb_level, code=1, extra=None, force_print=False):
"""Write s to stderr if verbosity level low enough"""
global _logger
# controlLine is a terrible hack until duplicity depends on Python 2.5
# and its logging 'extra' keyword that allows a custom record dictionary.
if extra:
_logg... | 5,300,639 |
def test_relation_ways_inserted():
"""Outer ways of multipolygon are inserted. """
park = t.query_row(t.db_conf, 'osm_landusages', -9201)
assert park['type'] == 'park'
assert park['name'] == '9209'
# outer ways of multipolygon stand for their own
road = t.query_row(t.db_conf, 'osm_roads', 9209)... | 5,300,640 |
def process_planet_orders(source_dir, target_dir):
"""Find unique PlanetScope scenes in a directory of Planet order folders
and process newly added scenes into image chips"""
# Get list of all planet orders in source directory
orders = np.array(next(os.walk(source_dir))[1])
# Add full path... | 5,300,641 |
def lookup_linear_velocity(
frame,
reference=None,
represent_in=None,
outlier_thresh=None,
cutoff=None,
as_dataarray=False,
return_timestamps=False,
):
""" Estimate linear velocity of a frame wrt a reference.
Parameters
----------
frame: str or ReferenceFrame
The ref... | 5,300,642 |
def main():
"""
_main_
GitHub plusone tool using status and PR API
"""
opts = build_parser()
gh = GitHubHelper()
if not (opts.id or opts.branch):
print("request id={} branch_name={}".format(opts.id, opts.branch))
msg = "Must supply either pull request ID or branch name"
... | 5,300,643 |
def calculate_u_from_U(state):
"""Make the inverse operation of calculate_U_from_u."""
# TODO: replace these dummy values by the actual ones
idx2, idy2, idz2 = 1., 1., 1.
metric = 'cartesian'
if metric == 'cartesian':
u = state.u['i'].view('k')
v = state.u['j'].view('k')
w =... | 5,300,644 |
def dispatch_slug_path(*views):
"""
Dispatch full path slug in iterating through a set of views.
Http404 exceptions raised by a view lead to trying the next view
in the list.
This allows to plug different slug systems to the same root URL.
Usages::
# in urls.py
path('<slug:slu... | 5,300,645 |
def applyFxToVolumes( ts, vols, fx, **kwargs ):
""" Apply a function on selected volumes of a timeseries.
'ts' is a 4d timeseries. It can be a NiftiImage or a ndarray.
In case of a ndarray one has to make sure that the time is on the
first axis. 'ts' can actually be of any dimensionality, but datasets ... | 5,300,646 |
def log(s):
"""Print a log message to stderr."""
global _last_prog
sys.stdout.flush()
_hard_write(sys.stderr.fileno(), s)
_last_prog = 0 | 5,300,647 |
def getTrack ( tleFile, t_beg, t_end, dt_secs=60):
"""
Given a Two Line Element (TLE) file name, a time interval, returns
tuple with (lon,lat) coordinates of satellite ground track.
"""
dt = t_end-t_beg
n = 1 + int(dt.total_seconds() / dt_secs)
Dt = timedelta(seconds=dt_secs)
nymd =... | 5,300,648 |
def __read_dataset_item(path):
"""Reads data set from path returns a movie dict.
Parameters
----------
path : str
Absolute path of the MovieLens data set(u.data).
Returns
-------
rating_dict : dict
Returns a dict of users, movies and ratings.... | 5,300,649 |
def wait_for_new_checkpoint(checkpoint_dir,
last_checkpoint=None,
seconds_to_sleep=1,
timeout=None):
"""Waits until a new checkpoint file is found.
Args:
checkpoint_dir: The directory in which checkpoints are saved.
last_ch... | 5,300,650 |
def _beta_prior(k, n, r, a0=1, b0=1, plot=False):
"""Compute the posterior distribution of d given the input aggregates
Since the likelihood is given by a binomial distribution, its conjugate prior is a beta distribution.
However, the binomial is defined on the ratio of volumes and so do the beta distributi... | 5,300,651 |
def test_convert(convert_parameters):
"""
It should convert input geojson to 'from-to' json.
"""
test_input = convert_parameters[0]
expected_output = convert_parameters[1]
assert geojson2fromto.convert(test_input) == expected_output | 5,300,652 |
def get_data(data_fn, param):
"""Feed data_fn with param
"""
return data_fn(**merge_dicts(param["data"], param.get("shared", {}))) | 5,300,653 |
def test_get_n_bits_combinations():
"""
Test get_n_bits_combinations by confirming that it generates
appropriate solutions for 1D, 2D, and 3D cases.
"""
# Check n=1 - Pass
assert layer_util.get_n_bits_combinations(1) == [[0], [1]]
# Check n=2 - Pass
assert layer_util.get_n_bits_combinati... | 5,300,654 |
def subscribe_test(client_id=CLIENT_ID, hostname=SERVER, topic=TOPIC,
blocking=True):
"""
Connects to the MQTT server subscribes to a topic and waits for messages
coming from that topic.
:param client_id: Unique identifier for the device connected.
:param hostname: Host name to c... | 5,300,655 |
def get_heat_flow_3(matrix_temp: np.ndarray, param: Parameters) -> float:
"""
各部温度から断熱材+内装材伝導熱量を計算する
:param matrix_temp: 各部温度計算結果 (5,1), degC
:param param: 計算条件パラメータ群
:return: 断熱材+内装材伝導熱量, W/m2
"""
return param.C_2 * (matrix_temp[2] - matrix_temp[3]) | 5,300,656 |
def write_to_waveform_memory(
daq: ziDAQServer,
device_id: str,
channel_index: int,
waveforms: dict,
*,
clear_existing: bool = True,
) -> None:
"""Writes pulses to the waveform memory of a specified generator.
Args:
daq: Instance of a Zurich Instruments API session connected to ... | 5,300,657 |
def create_training_label(center, size, corners, resolution=0.50, scale=4,
x=(0, 90), y=(-50, 50), z=(-4.5, 5.5)):
"""Create training labels which satisfy the range of experiment"""
min_value = np.array([x[0], y[0], z[0]])
xyz_logical = judge_in_voxel_area(center, x, y, z)
center[:, 2] ... | 5,300,658 |
def proxy_list_from_free_proxy_list_net():
"""
will connect to https://free-proxy-list.net/
and will get the proxy list from that page
proxy format : ip address, port
"""
link = 'https://free-proxy-list.net/'
regex = '<td>(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})<\/td><td>(?P<port>... | 5,300,659 |
async def test_flow_fails_user_credentials_faulty(hass, aioclient_mock):
"""Test config flow."""
result = await hass.config_entries.flow.async_init(
UNIFI_DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
a... | 5,300,660 |
def adv_training(sess, inputs, labels):
"""Train and evaluates a model on adversarial examples
"""
adversarial_model = get_model(FLAGS.model_type, 'train_adv')
fgsm2 = FastGradientMethod(adversarial_model, sess=sess)
def attack(inputs):
return fgsm2.generate(inputs, **ADV_CONSTANTS.get_attack_details(FLA... | 5,300,661 |
def unifiable(cls):
""" Register standard unify and reify operations on class
This uses the type and __dict__ or __slots__ attributes to define the
nature of the term
See Also:
>>> class A(object):
... def __init__(self, a, b):
... self.a = a
... self.b = b
... | 5,300,662 |
def generate_LPC_analysis(audio_file, analysis="", wait = True, nb_coefs = 45):
"""
file : file to anlayse
analysis : sdif file to generate, if not defined analysis will be saved in the same path of the audio file, with the same name but with an sdif extension.
"""
if analysis== "":
file_tag = os.path.basename(a... | 5,300,663 |
def test_last_state_attention(batch_size=1,
encoder_num_hidden=2):
"""
EncoderLastStateAttention is a bit different from other attention mechanisms as it doesn't take a query argument
and doesn't return a probability distribution over the inputs (aka alignment).
"""
# s... | 5,300,664 |
def kMeansInitCentroids(X, k):
"""
初始化 cluster centroids
:param X:
:param k:
:return:
"""
m = X.shape[0]
centroids = np.zeros((k, X.shape[1]))
m_arr = np.arange(0, m)
np.random.shuffle(m_arr)
rand_indices = m_arr[:k]
centroids = X[rand_indices, :]
return centroids | 5,300,665 |
def get_metric_rating_max(metric: AnyStr,
start: AnyStr,
end: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the max value for the given period and metric.
:metric (AnyStr) A... | 5,300,666 |
def getContours(frame,frameContour):
""" finds contours of frames"""
global approx
global cnt
global RGBLIST
global RGB_Box
global RGB_value
mode = cv2.RETR_EXTERNAL # Mode for find contours
method = cv2.CHAIN_APPROX_NONE # Metho... | 5,300,667 |
def set_log_level(level, set_logger=None):
"""Sets the root logger level to a given string level (like "INFO")."""
level = "CRITICAL" if level.upper() == "OFF" else level.upper()
set_logger = set_logger if set_logger else root_logger
set_logger.setLevel(level)
# Suppress any random loggers introduc... | 5,300,668 |
def generate_binary_random_number(size=1):
"""Generates a binary random number or array based on an uniform distribution.
Args:
size (int): Size of array.
Returns:
A binary random number or array.
"""
binary_array = np.round(np.random.uniform(0, 1, size))
return binary_array | 5,300,669 |
def make_class(any, base=data.module.YO, *args, **kwargs):
"""check base is correctly resolved to Concrete0"""
class Aaaa(base):
"""dynamic class"""
return Aaaa | 5,300,670 |
def query_select_csv_table_configuration(engine_url: str):
"""
Fixture create a table and drops it after execution
"""
table_name = "test_table_query_select"
query_simple_generic(
additional_parameters=["--engine-name", engine_url],
read_from_stdin=False,
query=f"CREATE FAC... | 5,300,671 |
def save_all_playlists(token):
"""
Use Deezer API to get all user playlists and save each one in its own file as JSON.
The only information saved about each playlist is the name and tracklist (a track is described
by the name of the artist/band, the name of the album and the title.
Args:
to... | 5,300,672 |
def make_caf_foyers_bas_revenus(decoupage_geo=None):
"""
Collects and formats 'allocations foyers bas revenus' data for France by
commune (source INSEE). Reads the information location and outputs in the
`source_config.py` file.
"""
if decoupage_geo is None:
decoupage_geo = 'commune'
... | 5,300,673 |
def log_args(logger: Logger, writer, args, add_git_hash=True, descriptions: dict = None):
""" log argparse args to a given logging.logger and a tensorboard writer (may be None) """
descriptions = descriptions if isinstance(descriptions, dict) else {}
log_headline(logger, 'Args')
others = [('current git ... | 5,300,674 |
def fix_qsl_status (db, qso_id) :
"""Fix stati (qsl_r_status, qsl_s_status, no_qsl_status) for whole db.
can be used after changing the status and qsl_type configuration.
"""
stati = dict (qsl_r_status = 0, qsl_s_status = 0, no_qsl_status = 0)
qsl_ids = db.qsl.filter (None, dict (qso = qso_id))
... | 5,300,675 |
def make_nbh_test(station: str) -> Optional[dict]:
"""Builds NBH test file for station"""
return make_forecast_test(avwx.Nbh, station) | 5,300,676 |
def train(epochs=None, poison_type=None, poison_size=None, poison_loc=None,
display=None):
"""
Train a model on the GTSRB dataset
"""
dataset = gtsrb_dataset.GTSRBDataset(poison_type=poison_type, poison_size=poison_size,
poison_loc=poison_loc)
conv... | 5,300,677 |
def get_manifest_indexes(manifest, channel, column):
"""Get the indices for channel and column in the manifest"""
channel_index = -1
for x in range(len(manifest["channels"])):
if manifest["channels"][x]["channel"] == channel:
channel_index = x
break
if channel_index == -1... | 5,300,678 |
def get_function_call(fn_to_call: ts.FunctionType, argument_names: List[str], fc: context.FunctionContext):
"""
DOES NOT COPY stack symbolic registers!
argument_names should be located in stack symbolic registers [argument_names]
RETURNS a stack symbolic register which the result is saved into or ... | 5,300,679 |
def onconnect(client, userdata, rc):
"""MQTT connect callback."""
if rc == 0:
db = userdata["database"]
cursor = userdata["cursor"]
client.subscribe("#", qos=0)
users = database.userlist(cursor)
for (username, _) in users:
database.setconnected(cursor, username, False)
client.publish(usern... | 5,300,680 |
def _write_checkpoint_metrics(checkpoint_path,
metrics_and_values,
eval_name,
current_metrics='current.metrics'):
"""Writes a JSON of metrics for checkpoint_path in eval_name.
This function writes out metrics to a JSON for a ... | 5,300,681 |
def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER):
"""
Get the IPGrant list for the SMTP virtual server.
:param bool as_wmi_format: Returns the connection IPs as a list in the format WMI expects.
:param str server: The SMTP server name.
:return: A dictionary of the IP and sub... | 5,300,682 |
def parse_training_args(args=None, ignore_unknown=False):
"""parser for training script"""
arg_populate_funcs = [training_args, custom_mlp_args]
arg_check_funcs = [process_training_args]
return parse_various_args(
args, arg_populate_funcs, arg_check_funcs, ignore_unknown
) | 5,300,683 |
def run_task_command(client: ScaleClient, app_name: str, queue_name: str, task: dict):
"""
:param client: A Pcf Client object.
:param app_name: The name of the pcf application to send the task to.
:param queue_name: Name of queue to scale.
:param task:A dict containing the command, memory, and disk ... | 5,300,684 |
def query_ball_point(radius, nsample, xyz, new_xyz):
"""
Input:
radius: local region radius
nsample: max sample number in local region
xyz: all points, [B, N, 3]
new_xyz: query points, [B, S, 3]
Return:
group_idx: grouped points index, [B, S, nsample]
"""
devi... | 5,300,685 |
def _convert_coordinate_dtype(coord, dtype):
"""
Convert a coordinate to the required units and datatype.
Args:
coord (iris.coords.Coord):
Coordinate instance to be modified in place
dtype (type):
Required datatype
"""
if check_precision_loss(dtype, coord.poi... | 5,300,686 |
def calc_response(self):
"""
Calculate the response function
"""
Nelem = self.grid.Nelem
#Inverse volume element
W = spdiags(self.grid.w, 0, Nelem, Nelem)
#Build effective potential operator
Veff = spdiags(W @ self.veff, 0, Nelem, Nelem)
self.chi = np.zeros((Nelem))
H = s... | 5,300,687 |
def test_equal():
"""test if two functions (e1, e2) are equal"""
assert (e1 == e2) == True
"""test if two functions (e1, e3) are equal"""
assert (e1 == e3) == False
"""test if a function and a constant (e1, a) are equal"""
assert (e1 == a) == False | 5,300,688 |
def get_num_blocks(content_length, block_size=DEFAULT_BLOCK_SIZE):
"""
Split file of specified length into blocks
"""
return int(math.ceil(content_length / block_size)) | 5,300,689 |
def generate_models_from_db(model_filepath, config_name=None):
"""
Use sqlacodegen to generate SQLAlchemy models Python module from Postgres
"""
config = _select_config(config_name=config_name)
cmd = (f'sqlacodegen {config.SQLALCHEMY_DATABASE_URI} '
f'--outfile {model_filepath}')
ou... | 5,300,690 |
def is_bounded(coord, shape):
"""
Checks if a coord (x,y) is within bounds.
"""
x, y = coord
g, h = shape
lesser = x < 0 or y < 0
greater = x >= g or y >= h
if lesser or greater:
return False
return True | 5,300,691 |
def save_nd_array_as_image(data, image_name, reference_name = None):
"""
save a 3D or 2D numpy array as medical image or RGB image
inputs:
data: a numpy array with shape [D, H, W] or [C, H, W]
image_name: the output file name
outputs: None
"""
data_dim = len(data.shape)
asse... | 5,300,692 |
def analyze_centroid_area_history(files, num_frames_per_iteration=1800, key_format="from_to"):
"""
Given an array of file names,
get centroid area history iteratively over 30 mins of frames.
Args:
files ([type]): [description]
num_frames (int, optional): [description]. Defaults ... | 5,300,693 |
def archive_results_files(
parentDirectory=config.SOURCE_DIR, subDirectory=config.RESULTS_SCRAPE["ftd"][1]
):
"""Zip/cleardown all source files.
INPUT:
parentDirectory: Parent directory to traverse looking for files to zip/clear
subDirectory: Sub-Directory to traverse looking for files to ... | 5,300,694 |
def perp2coast(X1,X2,Y1,Y2,X0=0,Y0=0,hip=10000,deltahip=1000,units='m',side=1):
"""
INPUT:
X1: Initial point in X for compute slope
X2: Final point in X for compute slope
Y1: Initial point in Y for compute slope
Y2: Final point in Y for compute slope
X0: Point to colocate the slope in X
... | 5,300,695 |
def load_image(url, path):
"""Load image by url to file.
Params
--------------------------------------------
:param url: str
Url with image.
:param path: str
Path, where image will be saved.
--------------------------------------------
"""
response = requests.get(url)
rai... | 5,300,696 |
def patch_request(
module_path: str,
http_method: str,
status_code: int,
text: str = "",
json: Optional[Any] = None) -> Iterator[mock.MagicMock]:
"""Wrapper for mock.patch over a python requests call."""
fn_to_patch = f"{module_path}.requests.{http_method.lower()}"
wi... | 5,300,697 |
def conv2d(input_, W_shape, name, reuse=False):
"""
name - layer name for variable scope W_shape - [height, width, input_layers, output_layers]
"""
# 在名称空间name下添加变量Variable,但最好传递一个reuse参数。
with tf.variable_scope(name, reuse=reuse):
# 对convolution层的权值参数 W 和 b 进行初始化
W_conv = tf.get_var... | 5,300,698 |
def get_one_postalcode(ps='00100', onSale=True):
"""
Perform the query on one postal code.
QUERY TESTED: 13.11.2019
:param ps: the postal code to query.
:param onSale: bool, if true do the query sales, if false do the query on rents
:return: a data frame
"""
ps = re.sub('[^0-9]+', '', ps... | 5,300,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.