content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_package_path() -> Path:
"""
Get local install path of the package.
"""
return to_path(__file__).parent.absolute() | 48,800 |
def parameterized_class(cls):
"""A class decorator for running parameterized test cases.
Mark your class with @parameterized_class.
Mark your test cases with @parameterized.
"""
test_functions = inspect.getmembers(cls, predicate=inspect.ismethod)
for (name, f) in test_functions:
if name... | 48,801 |
def isStringLike(s):
""" Returns True if s acts "like" a string, i.e. is str or unicode.
Args:
s (string): instance to inspect
Returns:
True if s acts like a string
"""
try:
s + ''
except:
return False
else:
return True | 48,802 |
def velocity_to_wavelength(velocities, input_units, center_wavelength=None,
center_wavelength_units=None, wavelength_units='meters',
convention='optical'):
"""
Conventions defined here:
http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html
* Radio V = c (c/l0 - c/l)/(c/l0) f(V) = (c/l0)... | 48,803 |
def get_social_profile_provider_list(profile):
""" """
sp = None
sp = SocialProfileProvider.objects.filter(user=profile.user).order_by('provider', 'website',)
return sp | 48,804 |
def load_tomogram(path_to_dataset: str, dtype=None) -> np.array:
"""
Verified that they open according to same coordinate system
"""
_, data_file_extension = os.path.splitext(path_to_dataset)
print("file in {} format".format(data_file_extension))
assert data_file_extension in [".em", ".hdf", ".m... | 48,805 |
def ip2long(ip):
""" Convert an IP string to long """
packedIP = socket.inet_aton(ip)
return struct.unpack("!L", packedIP)[0] | 48,806 |
def item_link_copy(request, op):
""" Objekt zum Einblenden markieren """
if request.GET.has_key('id'):
item_container = get_item_container_by_id(request.GET['id'])
else:
item_container = get_my_item_container(request, op)
if item_container.parent_item_id != -1:
#request.session['dms_link_copy_id'] =... | 48,807 |
def get_aggregation_fn_cls(rng):
"""Sample aggregation function for feature"""
return rng.choice(AGGREGATION_OPERATORS) | 48,808 |
def resnet_mvgcnn(depth, pretrained=False, **kwargs):
"""Constructs a MVGCNN based on ResNet-18 model."""
model = ResNetMVGCNN(BasicBlock,
resnet_layers[depth],
**kwargs)
if pretrained:
pretrained_dict = model_zoo.load_url(
model_urls['re... | 48,809 |
def temp_bucket_context(prefix='temp-bucket-'):
"""
Creates a temporary bucket
"""
connection_args = {}
if os.getenv('S3_URL', None):
connection_args['endpoint_url'] = os.environ['S3_URL']
if os.getenv('AWS_DEFAULT_REGION', None):
connection_args['region_name'] = os.environ['AWS_... | 48,810 |
def _smooth_samples_by_weight(values, samples):
"""Add Gaussian noise to each bootstrap replicate.
The result is used to compute a "smoothed bootstrap," where the added noise
ensures that for small samples (e.g. number of bins in the segment) the
bootstrapped CI is close to the standard error of the me... | 48,811 |
def lpc_ref(signal, order):
"""Compute the Linear Prediction Coefficients.
Return the order + 1 LPC coefficients for the signal. c = lpc(x, k) will
find the k+1 coefficients of a k order linear filter:
xp[n] = -c[1] * x[n-2] - ... - c[k-1] * x[n-k-1]
Such as the sum of the squared-error e[i] = ... | 48,812 |
def main():
"""
Generate Guassian-weighted point load distribution
"""
fem_mesh.check_version()
opts = read_cli()
# setup the new output file with a very long, but unique, filename
loadfilename = ("gauss_exc_sigma_%.3f_%.3f_%.3f_center_%.3f_%.3f_%.3f_amp_%.3f_amp_cut_%.3f_%s.dyn" %
... | 48,813 |
def make_mpo_networks(
action_spec,
policy_layer_sizes = (300, 200),
critic_layer_sizes = (400, 300),
):
"""Creates networks used by the agent."""
num_dimensions = np.prod(action_spec.shape, dtype=int)
critic_layer_sizes = list(critic_layer_sizes) + [1]
policy_network = snt.Sequential([
netw... | 48,814 |
def numgrad_x(f: Callable[[Any], Any], x: Tensor, eps: float = 1e-6) -> Tensor:
"""get numgrad with the same shape of x
Args:
f (Callable[[Any], Any]): the original function
x (Tensor): the source x
eps (float, optional): default error. Defaults to 1e-6.
Returns:
Tensor: the numgrad with... | 48,815 |
def throw_darts_serial(n_darts):
"""Throw darts at a square. Execute serially! Count
how many end up in an inscribed circle. Approximate pi.
Parameters
----------
n_darts : int
Number of darts to throw
Returns
-------
pi_approx : float
Approximation of pi
... | 48,816 |
def sample_category(user, name='Movie', slug='film'):
"""Create and return a sample ingredient"""
return Category.objects.create(user=user, name=name, slug=slug) | 48,817 |
def inherit_xdata(source, target):
"""Inherit all fields from source (xdata entry)."""
# Though not stated in the biblatex manual, we do not let xdata inheritance
# overwrite existing fields
for field, value in source:
if field not in target:
setattr(target, field, value) | 48,818 |
def get_all():
"""
gets all genres.
:rtype: list[GenreEntity]
"""
return get_component(GenresPackage.COMPONENT_NAME).get_all() | 48,819 |
def dist(node1, node2):
"""Calculate the distance between two vertices
"""
return np.sqrt(np.sum((node1 - node2)**2)) | 48,820 |
def train(td_steps=0, max_episodes=5000, exp_dir='def_dir', exp_name='No_Name'):
"""
:param td_steps: determines the algorithm used.
if td_steps<0 -> reinforce,
if td_steps=0 -> advantage using replay-buffer and target-network
if td_steps=N>0 -... | 48,821 |
def log_method(log_method, log=None, display_name=''):
"""Decorator to log whenever a method is called including arguments
Main usage is in function log_class
Args:
log_method: Class method that when called emits a log message
log: a file-like object (stream), such as sys.stdout.
... | 48,822 |
def propagate_errors(f, x, dx, jac=None, n_samples=1e4, seed=42):
"""Propagates the errors over all the elements of the array x
To see how the error propagation is performed see the documentation
of dy
Returns:
[array]: Array with the same size of x with the errors
"""
return n... | 48,823 |
def getFibonacciIterative(n: int) -> int:
"""
Calculate the fibonacci number at position n iteratively
"""
a = 0
b = 1
for _ in range(n):
a, b = b, a + b
return a | 48,824 |
def snapshotModifyKeyCtx(q=1,e=1,ex=1,ch=1,i1="string",i2="string",i3="string",n="string"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/snapshotModifyKeyCtx.html
-----------------------------------------
snapshotModifyKeyCtx is undoable, queryable, and editable.
Creates a cont... | 48,825 |
def louvain(graph, min_progress=1000, progress_tries=1):
"""Compute best partition on the `graph` by louvain.
Args:
graph (:class:`Graph`): A projected simple undirected graph.
min_progress: The minimum delta X required to be considered progress, where X is the number of nodes
... | 48,826 |
def compat(data):
"""
Check data type, transform to string if needed.
Args:
data: The data.
Returns:
The data as a string, trimmed.
"""
if not isinstance(data, str):
data = data.decode()
return data.rstrip() | 48,827 |
def cascade(u: np.ndarray, balanced: bool = True, phase_style: str = PhaseStyle.TOP,
error_mean_std: Tuple[float, float] = (0., 0.), loss_mean_std: Tuple[float, float] = (0., 0.)):
"""Generate an architecture based on our recursive definitions programmed to implement unitary :math:`U`,
or a set of :... | 48,828 |
def rsa_decrypt(cipher: int, d: int, n: int) -> int:
"""
decrypt ciphers with the rsa cryptosystem
:param cipher: the ciphertext
:param d: your private key
:param n: your public key (n)
:return: the plaintext
"""
return pow(cipher, d, n) | 48,829 |
def ajax_update_report_findings(request):
"""
Update the ``position`` and ``severity`` fields of all :model:`reporting.ReportFindingLink`
attached to an individual :model:`reporting.Report`.
"""
data = {"result": "error"}
if request.method == "POST" and request.is_ajax():
pos = request.P... | 48,830 |
def cmd_clean(ctx: ProjectContext, args: argparse.Namespace) -> int:
"""Clean up the build directory and build files."""
build_dir: str = ctx.build_dir()
if not os.path.exists(build_dir):
return 0
if not os.path.isdir(build_dir):
print(f'Build directory {build_dir} is not a directory')
... | 48,831 |
def head_pos_to_trans_rot_t(quats):
"""Convert Maxfilter-formatted head position quaternions.
Parameters
----------
quats : ndarray, shape (N, 10)
MaxFilter-formatted position and quaternion parameters.
Returns
-------
translation : ndarray, shape (N, 3)
Translations at eac... | 48,832 |
def geo_to_h3(lats, lngs, res):
"""
Convert arrays describing lat/lng paris to cells.
Parameters
----------
lats, lngs : arrays of floats
res: int
Resolution for output cells.
Returns
-------
array of H3Cells
"""
assert len(lats) == len(lngs)
out = np.zeros(le... | 48,833 |
def create_roads(roads):
""" Create roads information from roads reference data
Args:
roads: dataframe from roads reference data
Returns:
list of road curves for all roads
"""
road_curves = []
for _, row in roads.iterrows():
splitcoords = row["coordinates"].split(",")
... | 48,834 |
def set_extentions(doc):
"""No-param function. Sets 'frequency' and 'instance_list' variable for each token.
The frequency is calculated by lemma_.lower() word of the noun phrase.
And lemma_.lower() is used to add instance to instance list.
Returns: None
"""
freq_count = defaultdict(int)
i... | 48,835 |
def test_basics():
"""
Test mean/standard deviation/mode.
"""
basics = Basics()
mean, sd, mode = basics()
expect_mean = [1.0, 1.0]
expect_sd = np.sqrt(np.array([0.5, 0.5]) / np.square(np.array([0.5, 0.5])))
expect_mode = [0.0, 0.0]
tol = 1e-6
assert (np.abs(mean.asnumpy()- expect... | 48,836 |
def stream_occurrences(read_token, project_slug, last_id=None):
"""
read_token: Rollbar project_access_token with read_scope
project_slug: The name of the project that this token is for
last_id: The lowest occurence_id we are interested in
returns:
Occurrence list
Highest ... | 48,837 |
def custom_print(data):
"""
Print to display in the Blender console.
"""
for window in bpy.context.window_manager.windows:
screen = window.screen
for area in screen.areas:
if area.type == "CONSOLE":
override = {"window": window, "screen": screen, "area": area}... | 48,838 |
def git_describe(repos):
"""Try running git describe on the given repos"""
return run(["git", "-C", str(repos), "describe", "--tags", "--abbrev=8"]) | 48,839 |
def get_parser() -> ArgumentParser:
"""Get the argument parser."""
parser = ArgumentParser(
prog="toml-sort",
formatter_class=argparse.RawDescriptionHelpFormatter,
description="Toml sort: a sorting utility for toml files.",
epilog="""\
Examples:
- **Stdin -> Stdout**: cat inpu... | 48,840 |
def convertToModelZ(z):
""" scale Z-axis coordinate to the model
"""
return z * SCALE_2_MODEL | 48,841 |
def opt_get_model_rest_api(model_id):
"""Retrieve model data
"""
model_id = Markup.escape(model_id)
return retrieve_model_data(model_id) | 48,842 |
def tokenize(texts, context_length=77, truncate=False) -> Tensor:
"""
Returns the tokenized representation of given input string(s)
Parameters
----------
texts : Union[str, List[str]]
An input string or a list of input strings to tokenize
context_length : int
The context length t... | 48,843 |
def patch_keycloak_api(get_realm_role, create_realm_role=None, update_realm_role=None, delete_realm_role=None):
"""Mock context manager for patching the methods in PwPolicyIPAClient that contact the IPA server
Patches the `login` and `_post_json` methods
Keyword arguments are passed to the mock object tha... | 48,844 |
def config_get_timesteps(filepath):
"""Get list of time steps from YAML configuration file.
Parameters
----------
filepath : pathlib.Path or str
Path of the YAML configuration file.
Returns
-------
list
List of time-step indices (as a list of integers).
"""
with op... | 48,845 |
def join_expressions(positions, labels, sep="\t"):
"""Join mean expressions.
Join expressions from different time points and return only those that are
in all samples.
"""
dfs = []
for position, replicates in positions:
dfs.append(
get_mean_expression(
replic... | 48,846 |
def current_snapshot(id_or_symbol):
"""
获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。
市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。
在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。
需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。
如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, hig... | 48,847 |
def infection_rate_symptomatic_50x40():
"""
Real Name: b'infection rate symptomatic 50x40'
Original Eqn: b'Susceptible 40*Infected symptomatic 40x50*contact infectivity symptomatic 40x50*(self quarantine policy SWITCH self 40\\\\ * self quarantine policy 40+(1-self quarantine policy SWITCH self 40))/non con... | 48,848 |
def deepcopy_sqla_object(startobj: object,
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = False,
debug_rewrite_rel: bool = False,
objmap: D... | 48,849 |
def test_nodes_one(test_graph):
"""Test nodes method list."""
assert test_graph[1].nodes() == ['A'] | 48,850 |
def temperature(temp, season, daylight, hours=None):
""" Temperature method for Menu option 1 """
try:
if season == 0:
# Isolate winter to narrow down the target month
df_season = df.loc[df['Season'] == 0]
m_range = (210, 720) # Winter daylight hour range in minutes
... | 48,851 |
def remove_stress_utility(duthost, container_name):
"""Removes the 'stress' utility from container.
Args:
duthost: The AnsibleHost object of DuT.
container_name: Name of container.
Returns:
None.
"""
logger.info("Removing 'stress' utility from '{}' container ...".format(con... | 48,852 |
def cut_limits(x_data: tuple, y_data: tuple, x_lims: tuple):
"""Selecting range of x/y data based on x_lims.
Args:
x_data (tuple): x axis data
y_data (tuple): y axis values
x_lims (tuple): limits to select range from x and y
Raises:
ValueError: If x_lims have wrong shape
... | 48,853 |
def str_to_number_with_uncert(representation):
"""
Given a string that represents a number with uncertainty, returns the
nominal value and the uncertainty.
See the documentation for ufloat_fromstr() for a list of accepted
formats.
When no numerical error is given, an uncertainty of 1 on the la... | 48,854 |
def saveRecipe():
"""
Processing POST method from local for saving the new generated recipe
:return:
"""
method = request.method
if(method == "POST" and checkPassword(request, app.admin_password)):
j = json.loads(request.json)
fields = ['name','url', 'ingredients','picture']
... | 48,855 |
def list_queues_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
List queues in Azure storage account.
Args:
client (Client): Azure Queue Storage API client.
args (dict): Command arguments from XSOAR.
Returns:
CommandResults: outputs, readable outputs and ra... | 48,856 |
def isUnsaturated(mol):
"""
Does the molecule have a bond that's not single?
Eg. a bond that is double or triple or benzene
"""
cython.declare(atom1=Atom,
atom2=Atom,
bonds=dict,
bond=Bond)
for atom1 in mol.atoms:
bonds = mol.getBo... | 48,857 |
def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3):
"""
decorator run test method w/ multiple fixed seeds.
"""
def builder(func):
@wraps(func)
def wrapper(*args, **kwds):
rng = random.Random(master_seed)
for _ in irange(count):
kwd... | 48,858 |
def merge_cv_results(cv_results):
"""
Means across CV
"""
dtypes = ["train", "dev", "test"]
props_l1 = ["mean_loss", "mean_accuracy", "mean_positive_f1", "UL-A", "Joint-A"]
props_l2 = ["accuracy", "positive_f1"]
merged_results = {}
for dtype in dtypes:
merged_results[dt... | 48,859 |
def _broads_cores(sigs_in: List[Tuple[str]],
shapes: Tuple[Tuple[int, ...]],
msg: str
) -> Tuple[List[Tuple[int, ...]], List[Tuple[int, ...]]]:
"""Extract broadcast and core shapes of arrays
Parameters
----------
sigs_in : Tuple[str, ...]
Co... | 48,860 |
def batch_iou(boxes, box):
"""Compute the Intersection-Over-Union of a batch of boxes with another
box.
Args:
box1: 2D array of [cx, cy, width, height].
box2: a single array of [cx, cy, width, height]
Returns:
ious: array of a float number in range [0, 1].
"""
lr = np.maximum(np.min... | 48,861 |
def createRandomIntID(length):
"""
Creates a random number.\n
Useful for identifiers.
"""
global dict_of_ids
final_id = ''
for _ in range(length):
final_id += str(random.randint(0,10))
if int(final_id) in dict_of_ids:
final_id = createRandomIntID(length)
dict_of_ids[i... | 48,862 |
def get_all_colors():
"""
:return: Color Options
"""
return color | 48,863 |
def get_username():
"""Get Windows username
Get current logged in user's username
:return: Username
:Example:
>>> get_username()
'Automagica'
Keywords
windows, login, logged in, lockscreen, user, password, account, lock, locked, freeze, hibernate, sleep
Icon
las la-us... | 48,864 |
def _ParseStepLogIfAppropriate(data, log_name):
"""PConditionally parses the contents of data, based on the log type."""
if not data:
return None
if log_name.lower() == 'json.output[ninja_info]':
# Check if data is malformatted.
try:
json.loads(data)
except ValueError:
logging.error('... | 48,865 |
def perform_fun(username, channel_id):
"""This is the FUNction."""
fun_count = 0
try:
while True:
fun_count += 1
msg = 'Hi %s! This is %ix fun!' % (username, fun_count)
API.chat.post_message(channel_id, msg, as_user=True)
wait = random.randint(1, 10)
... | 48,866 |
def lr_finder_plot(lr_array, batch_loss):
"""Function to plot learning rate vs batch loss
Parameters
----------
lr_array : list
List of learning rates per iteration
batch_loss : list
List of losses per iteration
"""
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
a... | 48,867 |
def _plot_changes_since_last_quarter(report, filename, kind):
"""
Internal function to plot a heatmap of the changes to the
monthly revenue/spending/fund balance totals since last quarter.
"""
kind = kind.lower()
assert kind in ["revenue", "spending", "fund balance"]
this_quarter = f"FY{str... | 48,868 |
def RSIZJ(df, N=3, LL=6, LH=6):
"""
相对强弱专家系统
:param df:
:param N:
:param LL:
:param LH:
:return:
"""
CLOSE = df['close']
LC = REF(CLOSE, 1)
WRSI = SMA(MAX(CLOSE - LC, 0), N, 1) / SMA(ABS(CLOSE - LC), N, 1) * 100
ENTERLONG = CROSS(WRSI, LL)
EXITLONG = CROSS(LH, WRSI)
... | 48,869 |
def autocomplete_service_env(actions, objects):
"""
Returns current service_env for object. Used as a callback for
`default_value`.
Args:
actions: Transition action list
objects: Django models objects
Returns:
service_env id
"""
service_envs = [obj.service_env_id fo... | 48,870 |
def SoftwareProvenanceConst_get_decorator_type_name():
"""SoftwareProvenanceConst_get_decorator_type_name() -> std::string"""
return _RMF.SoftwareProvenanceConst_get_decorator_type_name() | 48,871 |
def collate_fn(batch, train=True):
""" list of tensors to a batch tensors """
premise_batch, _ = pad_batch([row['premise'] for row in batch])
hypothesis_batch, _ = pad_batch([row['hypothesis'] for row in batch])
label_batch = torch.stack([row['label'] for row in batch])
# PyTorch RNN requires batch... | 48,872 |
def test_run_tests_using_unittest_and_display_results(qtbot, tmpdir,
monkeypatch):
"""Basic check."""
os.chdir(tmpdir.strpath)
testfilename = tmpdir.join('test_foo.py').strpath
with open(testfilename, 'w') as f:
f.write("import unittest\n"
... | 48,873 |
def weights_and_neighbours(graph):
"""Compute weight and neighbors matrices from graph
Parameters
----------
graph : scipy.sparse.csr_matrix
sparse distance matrix representing an undirected graph
Returns
-------
weights : array_like (N,M)
corresponding weights for N nodes
... | 48,874 |
async def test_create() -> None:
"""Creating a record using model-based access"""
user = await User.prisma().create({'name': 'Robert'})
assert isinstance(user, User)
assert user.name == 'Robert'
user = await User.prisma().create(
data={
'name': 'Tegan',
'posts': {
... | 48,875 |
def load_archive(args):
"""
Load or create the model, optimizer, and parameters as a `ModelArchive`.
If the command is `start`, this attempts to create a new `ModelArchive`
with name `args.name`, if possible (that is, without overwriting an
existing one).
If the command is `resume`, this attemp... | 48,876 |
def _json_request():
"""
Make an json request
"""
client = HttpClient()
response = client.get('https://api.github.com/')
assert response.status_code == 200
assert response.ok
assert isinstance(response.json, dict) | 48,877 |
def aabb_with_result(a: Rectangle, b: Rectangle, result: Rectangle) -> bool:
"""
Does Axis Aligned Bounding Box collision detection between two rectangles a and b.
Also calculates the intersection rectangle.
:param a:
:param b:
:param result:
:return:
"""
# Horizontal
amin = a.x
... | 48,878 |
def intersperse(iteratorables: List[Iterable]):
""" Given a list of iterables, return a single list with all the individual items interspersed
For example: [[1,2,3], [4,5,6]] should return [1,4,2,5,3,6].
Adapted from: https://www.geeksforgeeks.org/python-merge-two-lists-alternatively/
:param iterator... | 48,879 |
def make_visualizations_from_config(config: Config,
extension: str = 'pdf') -> List[Figure]:
"""
Used to generate the embedding visualizations from a given Config object
:param config: the Config used
:param extension: the extension to be saved the artifacts
:retu... | 48,880 |
def get_intervals(bin_type, thresholds):
""" Returns a list of interval objects. If bin_type is *within*, then
intervals are formed by using each pair of consecutive thresholds. For
bin_type below* the interval [-np.inf, threshold] is used and for bin_type
above* the inveral [threshold, np.inf] is used.
... | 48,881 |
def register_output_contents(coll_scope, coll_name, contents, request_id=None, workload_id=None,
relation_type=CollectionRelationType.Output, session=None):
"""
register contents with collection scope, collection name, request id, workload id and contents.
:param coll_scope: sc... | 48,882 |
def check_bash_path(fname):
"""Check if file is in your bash path and executable (i.e. executable from command line), and prepend path to it if so.
Arguments:
----------
fname : str
Filename to check.
Returns:
--------
fname : str
Potentially updated filename with absolute... | 48,883 |
def plot_eco_rats(bin_centers,y_vals,neigh_val,ax,col_num,plot_idx,only=False):
"""
Returns subplots of ECO density-cut,mass ratios
Parameters
----------
bin_centers: array-like
An array with the medians mass values of the mass bins
y_vals: array-like
An array containing th... | 48,884 |
def shapely_formatter(_, vertices, codes=None):
"""`Shapely`_ style contour formatter.
Contours are returned as a list of :class:`shapely.geometry.LineString`,
:class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
geometry elements.
Filled contours return a list of :class:`shap... | 48,885 |
def _patch_redirect(session):
# type: (requests.Session) -> None
"""Whether redirect policy should be applied based on status code.
HTTP spec says that on 301/302 not HEAD/GET, should NOT redirect.
But requests does, to follow browser more than spec
https://github.com/requests/requests/blob/f6e13cc... | 48,886 |
def cal_rank_from_proc_loc(pnx: int, pi: int, pj: int):
"""Given (pj, pi), calculate the rank.
Arguments
---------
pnx : int
Number of MPI ranks in x directions.
pi, pj : int
The location indices of this rank in x and y direction in the 2D Cartesian topology.
Returns
------... | 48,887 |
def get_kafka_brokers():
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
# NOTE: The Kafka environment variables need to be present. If using
# Apache Kafka on Heroku, they will be available in your app configuration.
if not os.... | 48,888 |
def width_trailing(sdf):
"""Return the FWHM width in arcmin for the trailing tail"""
# Go out to RA=245 deg
trackRADec_trailing=\
bovy_coords.lb_to_radec(sdf._interpolatedObsTrackLB[:,0],
sdf._interpolatedObsTrackLB[:,1],
degree=True)
... | 48,889 |
def load_report_fn(report_path: gpath.GPath) -> Optional[ExperimentReport]:
"""Tries to load report from path, if it exists. Returns None otherwise."""
report = None
if not gfile.Exists(report_path):
print(f'File {report_path} does not exist.')
return report
try:
report = hparams_utils.load_datacla... | 48,890 |
def get_proposal_statistics_report(from_date, to_date, all_fields=False):
"""Gets the proposal statistics report from Cayuse"""
# List of fields we want to retrieve from Cayuse and include in the CSV
REPORT_FIELDS = (
'application_type_code',
'proposal_id',
'employee_id',
'f... | 48,891 |
def emitter_for_format(construct_format):
""" Creates a factory method for the relevant construct format. """
def _factory():
return ConstructEmitter(construct_format)
return _factory | 48,892 |
def get_client(settings):
"""Return a client for the Elasticsearch index."""
host = settings["elasticsearch_url"]
kwargs = {}
# nb. No AWS credentials here because we assume that if using AWS-managed
# ES, the cluster lives inside a VPC.
return Elasticsearch([host], **kwargs) | 48,893 |
def merge_model_predict(
predict: TModelPredict, predict_append: TModelPredict
) -> TModelPredict:
"""Append model predictions to an existing set of model predictions.
TModelPredict is of the form:
{metric_name: [mean1, mean2, ...],
{metric_name: {metric_name: [var1, var2, ...]}})
This... | 48,894 |
def test_static_raw(good_data):
""" Test statically sized raw fields """
packet1 = StaticPacket(raw=good_data)
raw1 = packet1.pack()
packet2 = StaticPacket.from_raw(raw1)
raw2 = struct.pack(u'>256s', good_data)
packet3 = StaticPacket()
packet3.unpack(raw2)
assert packet1['raw'].rs... | 48,895 |
def voucher_objects(states=voucher_states()):
"""
Build ``Voucher`` instances.
"""
return builds(
Voucher,
number=vouchers(),
created=one_of(none(), datetimes()),
expected_tokens=integers(min_value=1),
state=states,
) | 48,896 |
def vpga_u(X,Y,Gamma=1, sigmaX=3, sigmaY=1, polarIn=False, polarOut=False):
"""
Velocity for 2D Gaussian vortex patch asymmetric
"""
print('>>>> TODO vpga is wrong for now')
if polarIn:
r = X
theta = Y
X = r*np*cos(theta)
Y = r*np*sin(theta)
else:
... | 48,897 |
def get_mime(path=None):
"""Returns the MIME type to use for the given path. Defaults to 'text/plain'
if the extension is not recognized, or if no argument is passed."""
if not path:
return MIME_PLAIN
_, ext = os.path.splitext(path)
without_dot = ext[1:]
return MIMES.get(without_dot, MIM... | 48,898 |
def lang_sel(request, langid, idx):
"""
Selects a file to be translated
"""
if langid not in [l[0] for l in settings.LANGUAGES]:
raise Http404
else:
rosetta_i18n_catalog_filter = request.session.get('rosetta_i18n_catalog_filter', 'project')
third_party_apps = rosetta_i18n_c... | 48,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.