content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def timeago(seconds=0, accuracy=4, format=0, lang="en", short_name=False):
"""Translate seconds into human-readable.
:param seconds: seconds (float/int).
:param accuracy: 4 by default (units[:accuracy]), determine the length of elements.
:param format: index of [led, literal, dict].
... | 11,300 |
def copy_intervention_to_study(study, intervention):
"""
Copies the given Intervention to the given Study
"""
setting = intervention.setting.all()
i = intervention
i.pk = None
i.version = 2 # Auto upgrade old versions
i.study = study
i.save()
i.setting.set(setting)
i.save(... | 11,301 |
def test_raise_from_itself(
assert_errors,
parse_ast_tree,
default_options,
code,
):
"""Testing that are not allowed to raise an exception from itself."""
tree = parse_ast_tree(code)
visitor = WrongRaiseVisitor(default_options, tree)
visitor.run()
assert_errors(visitor, [RaiseFromI... | 11,302 |
def generate_headline(ids=None):
"""Generate and return an awesome headline.
Args:
ids:
Iterable of five IDs (intro, adjective, prefix, suffix, action).
Optional. If this is ``None``, random values are fetched from the
database.
Returns:
Tuple of parts a... | 11,303 |
def test_directory_exists(value, fails, allow_empty):
"""Test the bytesIO validator."""
if not fails:
validated = validators.directory_exists(value, allow_empty = allow_empty)
if value:
assert validated is not None
else:
assert validated is None
else:
... | 11,304 |
def check_param_or_command_type_recursive(ctxt: IDLCompatibilityContext,
field_pair: FieldCompatibilityPair,
is_command_parameter: bool):
# pylint: disable=too-many-branches,too-many-locals
"""
Check compatibility between ol... | 11,305 |
def open_in_browser(path):
"""
Open directory in web browser.
"""
import webbrowser
return webbrowser.open(path) | 11,306 |
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
Implement a single forward step of the LSTM-cell as described in Figure (4)
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
c_prev ... | 11,307 |
def encode_letter(letter):
"""
This will encode a tetromino letter as a small integer
"""
value = None
if letter == 'i':
value = 0
elif letter == 'j':
value = 1
elif letter == 'l':
value = 2
elif letter == 'o':
value = 3
elif letter ==... | 11,308 |
def test_eval_hparams(composer_trainer_hparams: TrainerHparams):
"""Test that `eval_interval` and `eval_subset_num_batches` work when specified via hparams."""
# Create the trainer from hparams
composer_trainer_hparams.eval_interval = "2ep"
composer_trainer_hparams.eval_subset_num_batches = 2
compos... | 11,309 |
def test_events_api(mock_search_with_activitystream, authed_client, settings):
"""We mock the call to ActivityStream"""
document = {
"content": "The Independent Hotel Show is the only industry event ... in 2012 to support.",
"currency": "Sterling",
"enddate": "2020-03-18",
"folde... | 11,310 |
async def register_log_event(
registration: LogEventRegistration, db: Session = Depends(get_db)
):
"""
Log event registration handler.
:param db:
:param registration: Registration object
:return: None
"""
reg_id = str(uuid4())
# Generate message for registration topic
msg = Log... | 11,311 |
def set_math_mode(math_mode):
"""Set the math mode used by SUSPECT.
Parameters
----------
math_mode: MathMode
the math mode to use
"""
if math_mode == MathMode.ARBITRARY_PRECISION:
from suspect.math import arbitrary_precision as arb
for member in _COMMON_MEMBERS:
... | 11,312 |
def cvAbsDiffS(*args):
"""cvAbsDiffS(CvArr src, CvArr dst, CvScalar value)"""
return _cv.cvAbsDiffS(*args) | 11,313 |
def do_host_evacuate_live(cs, args):
"""Live migrate all instances of the specified host
to other available hosts.
"""
hypervisors = cs.hypervisors.search(args.host, servers=True)
response = []
migrating = 0
for hyper in hypervisors:
for server in getattr(hyper, 'servers', []):
... | 11,314 |
def tps_word_embeddings_correlation_plot(
tps_scores: np.ndarray,
y_values: np.ndarray,
y_label: str,
tps_vs_y_correlation: float,
output_plot_filepath: str,
neighbourhood_size: int,
) -> None:
"""
Saves a correlation plot between TPS scores and some y values.
Parameters
-------... | 11,315 |
def create_template_app(**kwargs):
"""Create a template Flask app"""
app = create_app(**kwargs)
from . import views # this must be placed here, after the app is created
app.register_blueprints()
return app | 11,316 |
def mse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mse(predict,actual),decimals = 2)
1.33
>>> actual = [1,1,1];predict = [1,1,1]
>>> mse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np... | 11,317 |
def train_generator(wav_list, feat_list, receptive_field,
batch_length=None,
batch_size=1,
feature_type="world",
wav_transform=None,
feat_transform=None,
pulse_transform=p_trans_binary_multi_channel,
... | 11,318 |
def make_demo_measurements(num_measurements, extra_tags=frozenset()):
"""Make a measurement object."""
return [
make_flexural_test_measurement(
my_id=__random_my_id(),
deflection=random.random(),
extra_tags=extra_tags
) for _ in range(num_measurements)
] | 11,319 |
def _nrc_coron_rescale(self, res, coord_vals, coord_frame, siaf_ap=None, sp=None):
"""
Function for better scaling of NIRCam coronagraphic output for sources
that overlap the image masks.
"""
if coord_vals is None:
return res
nfield = np.size(coord_vals[0])
psf_sum = _nrc_coron_ps... | 11,320 |
def main():
"""main function
"""
if " !!!" in sys.argv[1]:
print("Result: p=0.9 --> WUT") | 11,321 |
def re_list(request):
""" Returns the available relation tasks for a specific user
Accessed through a JSON API endpoint
"""
from .serializers import DocumentRelationSerializer
cmd_str = ""
with open('mark2cure/api/commands/get-relations.sql', 'r') as f:
cmd_str = f.read()
# Star... | 11,322 |
def run_tc(discover):
"""
BeautifulReport模块实现测试报告
:param discover: 测试套件
:return:
"""
if not os.path.exists(path_conf.REPORT_PATH):
os.makedirs(path_conf.REPORT_PATH)
fileName = path_conf.PROJECT_NAME + '_' + time.strftime('%Y-%m-%d %H_%M_%S') + '.html'
try:
result = Beau... | 11,323 |
def test_majority_label():
"""Verifies that we correctly select the most common element"""
def checkme(expected_val, values):
"""Utility"""
if not hasattr(expected_val, '__iter__'):
expected_val = {expected_val}
nose.tools.assert_in(majority_label(values), expected_val)
... | 11,324 |
def maps_subcommand(args, api_config):
"""
Maps Subcommand
"""
print("Generating maps")
builder = MapBuilder(args.height, api_config)
builder.run() | 11,325 |
def csv_to_blob_ref(csv_str, # type: str
blob_service, # type: BlockBlobService
blob_container, # type: str
blob_name, # type: str
blob_path_prefix=None, # type: str
charset=None # type: str
):
... | 11,326 |
def set_default_file_handler(logger, log_path, log_level=logging.DEBUG):
"""
:type logger: logging.Logger
:param log_path: str
:param log_level: str
"""
logger.setLevel(log_level)
formatter = logging.Formatter(constants.log.DEFAULT_FORMAT)
fh = logging.FileHandler(filename=log_path, mode="w")
fh.setFo... | 11,327 |
def col_rev_reduce(matrix, col, return_ops=False):
"""
Reduces a column into reduced echelon form by transforming all numbers above the pivot position into 0's
:param matrix: list of lists of equal length containing numbers
:param col: index of column
:param return_ops: performed operations are retu... | 11,328 |
def calculate_correlations(tetra_z: Dict[str, Dict[str, float]]) -> pd.DataFrame:
"""Return dataframe of Pearson correlation coefficients.
:param tetra_z: dict, Z-scores, keyed by sequence ID
Calculates Pearson correlation coefficient from Z scores for each
tetranucleotide. This is done longhand here... | 11,329 |
def rowfuncbynumber(tup,othertable, number):
"""tup is the tuple of row labels for the current row. By default it is passed back unmodified.
You can supply your own rowfunc to transform it when the tables being merged do not have the
same structure or if you want to prevent the merging of certain rows... | 11,330 |
def test_build_url_filter_for_get_list_entries():
"""
Given:
Arguments To filter with.
When:
The function builds a URL filter from these arguments.
Then:
We check that the URL filter matches what the command asks for.
"""
from CiscoEmailSecurity import build_url_filter_f... | 11,331 |
def populate_stations(path='/opt/code/vvs_data/HaltestellenVVS_simplified_utf8_stationID.csv'):
"""
parse simplified csv, add elements to database
"""
with open(path, 'r') as f:
reader = csv.reader(f, delimiter=',')
# skip first row
next(reader, None)
for row in reader:
... | 11,332 |
def test__get_features(first_fileGDB_path: str) -> None:
"""All fields from the 0th row of the 0th layer."""
data_source = Open(first_fileGDB_path)
layer = data_source.GetLayer()
features_generator = _get_features(layer)
*properties, geometry = next(features_generator)
shapely_object = loads(byt... | 11,333 |
def save_book_metadata() -> FlaskResponse:
"""
XHR request. Update the information about a book.
Raises:
404: if the user is not admin or the request is not POST.
"""
if not is_admin():
abort(404) # pragma: no cover
if not (
all(
x in request.form
... | 11,334 |
def query_category_members(category, language='en', limit=100):
"""
action=query,prop=categories
Returns all the members of a category up to the specified limit
"""
url = api_url % (language)
query_args = {
'action': 'query',
'list': 'categorymembers',
'cmtitle': category... | 11,335 |
def _tokenize_text(text: str, language: str) -> List[str]:
"""Splits text into individual words using the correct method for the given language.
Args:
text: Text to be split.
language: The configured language code.
Returns:
The text tokenized into a list of words.
"""
if language == constants.LA... | 11,336 |
def ml64_sort_order(c):
"""
Sort function for measure contents.
Items are sorted by time and then, for equal times, in this order:
* Patch Change
* Tempo
* Notes and rests
"""
if isinstance(c, chirp.Note):
return (c.start_time, 10)
elif isinstance(c, Rest):
re... | 11,337 |
def binary_logistic_loss_grad(linear_o, y):
"""Derivative of the binary_logistic_loss w.r.t. the linear output"""
# Sometimes denom overflows, but it's OK, since if it's very large, it would
# be set to INF and the output correctly takes the value of 0.
# TODO: Fix overflow warnings.
denom = 1 + np.... | 11,338 |
def electron_mass_MeVc2():
"""The rest mass of the electron in MeV/c**2
https://en.wikipedia.org/wiki/Electron
"""
return 0.5109989461 | 11,339 |
def test_workflow_docker_build_error():
"""
This is a test for what happens when the docker build fails.
"""
flexmock(DockerfileParser, content='df_content')
this_file = inspect.getfile(PreRaises)
mock_docker()
fake_builder = MockInsideBuilder(failed=True)
flexmock(InsideBuilder).new_ins... | 11,340 |
def test_pipette_settings_update_none(mutable_config: str):
"""Should accept none values."""
s = settings.PipetteSettingsUpdate(fields={mutable_config: None})
assert s.setting_fields[mutable_config] is None | 11,341 |
def opensearch_plugin(request):
"""Render an OpenSearch Plugin."""
host = "%s://%s" % ("https" if request.is_secure() else "http", request.get_host())
# Use `render_to_response` here instead of `render` because `render`
# includes the request in the context of the response. Requests
# often include... | 11,342 |
def serialize_time(output_value: datetime.time) -> str:
""" Serializes an internal value to include in a response. """
return output_value.isoformat() | 11,343 |
def find_posix_python(version):
"""Find the nearest version of python and return its path."""
from . import persist
if version:
# Try the exact requested version first
path = find_executable('python' + version)
persist.debug('find_posix_python: python{} => {}'.format(version, path)... | 11,344 |
def asg_sync_cmdb():
"""最小和所需都为0的ASG数据同步"""
asg_list = get_asg_list()
with DBContext('w') as session:
session.query(Asg).delete(synchronize_session=False) # 清空数据库的所有记录
for asg in asg_list:
asg_name = asg.get("AutoScalingGroupName", "")
asg_arn = asg.get("AutoScaling... | 11,345 |
def decode_binary(state_int):
"""
Decode binary representation into the list view
:param state_int: integer representing the field
:return: list of GAME_COLS lists
"""
assert isinstance(state_int, int)
bits = int_to_bits(state_int, bits=GAME_COLS*GAME_ROWS + GAME_COLS*BITS_IN_LEN)
res = ... | 11,346 |
def clean_features(vgsales):
"""
This function cleans up some of the dataset's features. The dataset is
quite messy as many values are missing from both categorical and numerical
features. Many of these features are difficult to impute in a reasonable
manner.
<class 'pandas.core.frame.DataFrame... | 11,347 |
def get_object(proposition):
"""[75]
Returns the object of a given proposition
"""
return proposition[2][0] | 11,348 |
def __verify_hmac(data: bytes, ohmac: bytes, key: bytes) -> bool:
"""
This function verifies that a provided HMAC matches a computed HMAC for
the data given a key.
Args:
data: the data to HMAC and verify
ohmac: the original HMAC, normally appended to the data
key: the key to HMA... | 11,349 |
def create_block_option_from_template(text: str, value: str):
"""Helper function which generates the option block for modals / views"""
return {"text": {"type": "plain_text", "text": str(text), "emoji": True}, "value": str(value)} | 11,350 |
def get_token_payload(token: str) -> Any:
"""Extract the payload from the token.
Args:
token (str):
A JWT token containing the session_id and other data.
Returns:
dict
"""
decoded = json.loads(_base64_decode(token.split('.')[0]))
del decoded['session_id']
return... | 11,351 |
def create_mock_target(number_of_nodes, number_of_classes):
"""
Creating a mock target vector.
"""
return torch.LongTensor([np.random.randint(0, number_of_classes-1) for node in range(number_of_nodes)]) | 11,352 |
def _i2045(node: ast.ImportFrom) -> Iterable[Tuple[int, int, str, type]]:
"""
The from syntax should not be used.
"""
yield _error_tuple(2045, node) | 11,353 |
def initFindAndFit(parameters):
"""
Initialize and return a SplinerFISTAFinderFitter object.
"""
# Create spline object.
spline_fn = splineToPSF.loadSpline(parameters.getAttr("spline"))
# Create peak finder.
finder = SplinerFISTAPeakFinder(parameters = parameters,
... | 11,354 |
def UpdateDatabase(asset, images, status):
"""Update the database entries of the given asset with the given data."""
return {'asset': asset} | 11,355 |
def get_max_word_length(days: dict, keys: list) -> int:
"""
Находит длину самого длинного слова.
"""
max_word_len = 0
for key in keys:
if days.get(key):
for _, data in days.get(key).items():
value = data.split(" ")
for word in value:
... | 11,356 |
def rateCBuf(co2: float, par: float, params: dict,
rates: dict, states: dict) -> float:
"""
Rate of increase of carbohydrates in the buffer
During the light period, carbohydrates produced by
photosynthesis are stored in the buffer and, whenever
carbohydrates are available in the buffer... | 11,357 |
def get_config_tag(config):
"""Get configuration tag.
Whenever configuration changes making the intermediate representation
incompatible the tag value will change as well.
"""
# Configuration attributes that affect representation value
config_attributes = dict(frame_sampling=config.proc.frame_... | 11,358 |
def ctf_to_pickle(trace_directory: str, target: Pickler) -> int:
"""
Load CTF trace, convert events, and dump to a pickle file.
:param trace_directory: the trace directory
:param target: the target file to write to
:return: the number of events written
"""
ctf_events = get_trace_ctf_events(... | 11,359 |
def list_lines(lines):
"""Returns the list of trimmed lines.
@param lines Multi-line string
"""
return list(filter(None, (x.strip() for x in lines.splitlines()))) | 11,360 |
def test_can_log_in_returns_200(user, testapp):
"""Login successful (irrespective of casing)."""
# Goes to homepage.
res = testapp.get('/')
# Fills out login form.
username_with_different_casing = user.email.upper() # Default would be userN@example.com.
form = res.forms['loginForm']
form['u... | 11,361 |
def _histogram_2d_vectorized(
*args, bins=None, weights=None, density=False, right=False, block_size=None
):
"""Calculate the histogram independently on each row of a 2D array"""
N_inputs = len(args)
a0 = args[0]
# consistency checks for inputa
for a, b in zip(args, bins):
assert a.ndi... | 11,362 |
def carbon_offset_cost(kWh):
"""
Donation to Cool Earth (in USD) needed to offset carbon emssions.
"""
return KG_CO2_PER_KWH * USD_PER_KG_CO2 * kWh | 11,363 |
def run(
duration: int, runtime_mode: str, connection_mode: str
) -> List[Tuple[str, Union[int, float]]]:
"""Test memory usage."""
# pylint: disable=import-outside-toplevel,unused-import
# import manually due to some lazy imports in decision_maker
import aea.decision_maker.default # noqa: F401
... | 11,364 |
def tf_fermion_massmatrix(t_A3, t_potential, tc_masses_factor):
"""Computes the spin-1/2 mass matrix from the A3-tensor."""
# The extra factor 2.0 relative to https://arxiv.org/abs/1906.00207
# makes the fermion masses align with the way particle states are
# grouped into SUSY multiplets in appendix (B.2) of:
... | 11,365 |
def filter_nsa_catalog_to_approximate_sky_area(nsa, bricks, visualise=False):
"""
DECALS is only in a well-defined portion of sky (which depends on the data release version). Filter the NSA catalog
so that it only includes galaxies in that approximate area. This saves time matching later.
Args:
... | 11,366 |
def apply_variants(variants: Dict[Union[str, List[str]], int], parameters: Optional[Dict[Any, Any]] = None, variant=DEFAULT_VARIANT_VARIANTS) -> Tuple[PetriNet, Marking, Marking]:
"""
Apply the chosen IM algorithm to a dictionary/list/set of variants obtaining a Petri net along with an initial and final marking... | 11,367 |
def test_skip_include_tags(
_create_ecr_repository, _docker_build, _docker_tag, _docker_push, ys3
):
"""Only includes the stage with the corresponding tag."""
with patch("builtins.open", mock_open(read_data=ys3)) as mock_file:
pipeline = process_image(
image_name="image0",
s... | 11,368 |
def test_unionfind_compression():
"""
Test path compression and the union by rank.
"""
# Test the ranking
elements = list(range(100))
u = UnionFind(elements)
for i in range(len(elements) - 1):
u.union(elements[i], elements[i + 1])
assert max(u._rank.values()) =... | 11,369 |
def query_update(request: HttpRequest, **kwargs: str) -> str:
"""Update the query string with new values."""
updated = request.GET.copy()
for key, value in kwargs.items():
updated[key] = value
return updated.urlencode() | 11,370 |
def get_user_info(user_id):
""" Fetches User Info Based On User ID
:param user_id:
:return: user
"""
user = session.query(User).filter_by(id=user_id).one_or_none()
return user | 11,371 |
def test_load_db_data_from_json_content(fxtr_setup_logger_environment):
"""Test Load Database Data - disallowed database table."""
cfg.glob.logger.debug(cfg.glob.LOGGER_START)
# -------------------------------------------------------------------------
initial_database_data_path = pathlib.Path(cfg.glob.... | 11,372 |
def gatk_version(request) -> GATKVersion:
"""Given a version number, return a GATKVersion."""
return GATKVersion(request.param) | 11,373 |
def load_objs(name_obj_dat, sim, obj_ids, auto_sleep=True):
"""
- name_obj_dat: List[(str, List[
transformation as a 4x4 list of lists of floats,
int representing the motion type
])
"""
static_obj_ids = []
for i, (name, obj_dat) in enumerate(name_obj_dat):
if len(obj_id... | 11,374 |
def test_quickSort_with_list():
"""To test quickSort method with a list."""
s = Sort([3, 2, 7, 4, 6, 5])
s.quickSort()
assert s.lst == [2, 3, 4, 5, 6, 7] | 11,375 |
def test_refresh_repositories_error(nexus_mock_client):
"""
Ensure the method does't modify the existing repositories attribute when
the client request fails.
"""
nexus_mock_client._request.return_value.status_code = 400
nexus_mock_client.repositories._repositories_json = None
with pytest.r... | 11,376 |
def get_mod_metadata(module: Module):
"""
Get descriptions for produced dependencies.
"""
meta = {}
has_meta = hasattr(module, 'prod_meta')
for prod in module.produces:
prod = prod.replace('?', '').replace('!', '')
if not has_meta:
meta[prod] = '<no descritption>'
... | 11,377 |
def register_module():
"""Registers this module in the registry."""
dashboard.dashboard.DashboardRegistry.add_analytics_section(
dashboard.analytics.QuestionScoreHandler)
global_handlers = []
for path, handler_class in mapreduce_main.create_handlers_map():
# The mapreduce and pipeline ... | 11,378 |
def theta_b(wlen, d, n=1):
"""return the Bragg angle, $\theta_{B}$, (deg) for a given wavelength
(\AA$^{-1}$) and d-spacing (\AA)"""
if not (d == 0):
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
_thb = np.rad2deg(np.arcsin(((wlen * ... | 11,379 |
def replace_newlines(s, replacement=' / ', newlines=(u"\n", u"\r")):
"""
Used by the status message display on the buddy list to replace newline
characters.
"""
# turn all carraige returns to newlines
for newline in newlines[1:]:
s = s.replace(newline, newlines[0])
# while ... | 11,380 |
def get_user_data(prs, client_id, client_secret):
"""Get user data from PR data."""
users = {}
for owner, repo, number, pr in prs:
username = pr.username
# Initialize the User if needed
if username not in users:
print(pr.user_url, file=sys.stderr)
payload = {... | 11,381 |
def unassign_images(project, image_names):
"""Removes assignment of given images for all assignees.With SDK,
the user can be assigned to a role in the project with the share_project
function.
:param project: project name or folder path (e.g., "project1/folder1")
:type project: str
:param image_... | 11,382 |
def default_bucket_name():
"""Obtain the default Google Storage bucket name for this application.
Returns:
A string that is the name of the default bucket.
"""
return files._default_gs_bucket_name() | 11,383 |
def hold_out_validation(train_data, test_data, ratio):
"""
:param train_data: 所有训练数据
:param test_data: 测试数据集
:param ratio: 验证数据集的比例
"""
num_validation_samples = round(len(train_data) * ratio)
# 打乱训练数据,保证随机性,防止数据的某种特性在某个区域过于集中
np.random.shuffle(train_data)
# 定义训练数据集和验证数据集
traini... | 11,384 |
def LineGaussSeidel_i(Uo, Beta):
"""Return the numerical solution of dependent variable in the model eq.
This routine uses the Line-Gauss Seidel method along constant i
direction (parallel to y-axis)
to obtain the solution of the Poisson's equation.
Call signature:
LineGaussSeide... | 11,385 |
def add_padding_to_grid(
component,
grid_size=127,
x=10,
y=10,
bottom_padding=5,
layers=[pp.LAYER.PADDING],
suffix="p",
):
""" returns component width a padding layer on each side
matches a minimum size
"""
c = pp.Component(name=f"{component.name}_{suffix}")
c << componen... | 11,386 |
def _find_role(oneandone_conn, role):
"""
Given a name, validates that the role exists
whether it is a proper ID or a name.
Returns the role if one was found, else None.
"""
for _role in oneandone_conn.list_roles(per_page=1000):
if role in (_role['id'], _role['name']):
return... | 11,387 |
def load_vgg(sess, vgg_path):
"""
Load Pretrained VGG Model into TensorFlow.
:param sess: TensorFlow Session
:param vgg_path: Path to vgg folder, containing "variables/" and "saved_model.pb"
:return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out)
"""... | 11,388 |
def created_median_mask(disparity_map, valid_depth_mask, rect=None):
"""生成掩模,使得矩形中不想要的区域的掩模值为0,想要的区域的掩模值为1"""
if rect is not None:
x, y, w, h = rect
disparity_map = disparity_map[y:y + h, x:x + w]
valid_depth_mask = valid_depth_mask[y:y + h, x:x + w]
# 获得中位数
median = np.median(di... | 11,389 |
def l2_loss(pred_traj, pred_traj_gt, mode='sum'):
"""
Input:
- pred_traj: Tensor of shape (seq_len, batch, 2). Predicted trajectory.
- pred_traj_gt: Tensor of shape (seq_len, batch, 2). Groud truth
predictions.
- mode: Can be one of sum, average, raw
Output:
- loss: l2 loss depending on ... | 11,390 |
def test_member_access():
"""Check .field functionality of namedtuple."""
t = Task('buy milk', 'brian')
assert t.summary == 'buy milk'
assert t.owner == 'brian'
assert (t.done, t.id) == (False, None) | 11,391 |
def printt(*args):
"""printt(*args)
Same exact functionality as print *args, except output will be written to log
file as well as stdout. Similar to Unix command "tee", hence the extra t.
If the logfile has not been initialized, same as print.
"""
printed = ''
for s in args:
printed += s... | 11,392 |
def findpeer(port = None, os = None):
"""Args: port (defaults to any port)
Finds a socket, which is connected to the specified port.
Leaves socket in ESI."""
if os == 'linux':
code = """
findpeer:
push -1
push SYS_socketcall_getpeername
mov ebp, esp
pop ebx
pop esi
.loop:
... | 11,393 |
def api_wowlight_version_check(version: str) -> bool:
"""
Checks incoming wow-lite wallet version, returns False when the version is too old and needs to be upgraded.
:param version:
:return: bool
"""
url = "https://raw.githubusercontent.com/wownero/wow-lite-wallet/master/src/renderer/components... | 11,394 |
def fruit_growth(jth: int, last_24_canopy_t):
"""
Equations 9.38
fruit_growth_rate_j = POTENTIAL_FRUIT_DRY_WEIGHT*math.exp(-math.exp(-curve_steepness*(days_after_fruit_set - fruit_development_time)))
Returns: fruit growth rate [mg {CH2O} fruit^-1 d^-1]
"""
fruit_development_rate = fruit_developm... | 11,395 |
def _pickled_cache_s(filepath: str) -> Callable[[Callable], Callable]:
"""Store the last result of the function call
in a pickled file (string version)
Args:
filepath (str): The path of the file to read/write
Returns:
Callable[[Callable], Callable]: function decorator.
The decorated function will ... | 11,396 |
def home(request):
"""Index page view
:param request: HTTP request
:return: index page render
"""
today = datetime.date.today()
return render(request, 'taskbuster/index.html',
{'today': today, 'now': now()}) | 11,397 |
def get_trials_for_drug(
drug: Tuple[str, str], *, client: Neo4jClient
) -> Iterable[Node]:
"""Return the trials for the given drug.
Parameters
----------
client :
The Neo4j client.
drug :
The drug to query.
Returns
-------
:
The trials for the given drug.
... | 11,398 |
def convert_features_to_dataset(all_features: List[InputFeaturesTC],
dataset_type: str = 'pytorch'
) -> TensorDataset:
"""Converts a list of features into a dataset.
Args:
all_features (:obj:`list` of :obj:`InputFeatureTC`): the list of
... | 11,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.