content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def e() -> ProcessBuilder:
"""
Euler's number (e)
:return: The numerical value of Euler's number.
"""
return process('e', ) | 5,354,800 |
def get_or_create_anonymous_cart_from_token(token,
cart_queryset=Cart.objects.all()):
"""Returns open anonymous cart with given token or creates new.
:type cart_queryset: saleor.cart.models.CartQueryset
:type token: string
:rtype: Cart
"""
return cart... | 5,354,801 |
def outcar_parser(request):
"""A fixture that loads OUTCAR."""
try:
name = request.param
except AttributeError:
# Test not parametrized
name = 'OUTCAR'
testdir = os.path.dirname(__file__)
outcarfile = testdir + '/' + name
outcar = Outcar(file_path=outcarfile)
return... | 5,354,802 |
def accept_data(x: Any) -> Any:
"""Accept any types of data and return it as convenient type.
Args:
x: Any type of data.
Returns:
Any: Accepted data.
"""
if isinstance(x, str):
return x
elif isinstance(x, list):
return x
elif isinstance(x, dict):
... | 5,354,803 |
def custom_model_template(model_type: str, target: str, result0: str, result1: str) -> str:
"""Template for feature behaviour reason generated from DICE
Returns:
str: behaviour
"""
if model_type == 'classifier':
tipo = 'category'
elif model_type == 'regressor':
tipo = 'con... | 5,354,804 |
def merge_dict_list(merged, x):
""" merge x into merged recursively.
x is either a dict or a list
"""
if type(x) is list:
return merged + x
for key in x.keys():
if key not in merged.keys():
merged[key] = x[key]
elif x[key] is not None:
merged[key... | 5,354,805 |
def test_certificate_index_page(rf):
"""
test for certificate index page
"""
home_page = HomePageFactory()
assert models.CertificateIndexPage.can_create_at(home_page)
certifcate_index_page = CertificateIndexPageFactory.create(parent=home_page)
request = rf.get(certifcate_index_page.get_url(... | 5,354,806 |
def test__heavy_atom_indices():
""" test graph.heavy_atom_indices
"""
mgrph = (('H', 'H', 'C', 'H', 'C', 'C', 'H', 'H', 'H'),
frozenset([(frozenset([5, 6]), 1), (frozenset([4, 7]), 1),
(frozenset([8, 4]), 1), (frozenset([0, 5]), 1),
(frozenset([1,... | 5,354,807 |
def is_ref(variant, exclude_alleles=None):
"""Returns true if variant is a reference record.
Variant protos can encode sites that aren't actually mutations in the
sample. For example, the record ref='A', alt='.' indicates that there is
no mutation present (i.e., alt is the missing value).
Args:
variant:... | 5,354,808 |
def gomc_sim_completed_properly(job, control_filename_str):
"""General check to see if the gomc simulation was completed properly."""
job_run_properly_bool = False
output_log_file = "out_{}.dat".format(control_filename_str)
if job.isfile(output_log_file):
# with open(f"workspace/{job.id}/{output... | 5,354,809 |
def reset_tasks(name=None):
"""
Resets tasks for constellation name. If name is None,
tasks are reset for all running constellations.
After reset, the current task is empty and any task that was
- starting
- running
- stopping
set to stopped, and it can't be run again.
Stopped ta... | 5,354,810 |
def rv_precision(
wavelength: Union[Quantity, ndarray],
flux: Union[Quantity, ndarray],
mask: Optional[ndarray] = None,
**kwargs,
) -> Quantity:
"""Calculate the theoretical RV precision achievable on a spectrum.
Parameters
----------
wavelength: array-like or Quantity
Wavelengt... | 5,354,811 |
def changenonetoNone(s):
"""Convert str 'None' to Nonetype
"""
if s=='None':
return None
else:
return s | 5,354,812 |
def quaternion_2_rotation_matrix(q):
"""
四元数转化为旋转矩阵
:param q:
:return: 旋转矩阵
"""
rotation_matrix = np.array([[np.square(q[0]) + np.square(q[1]) - np.square(q[2]) - np.square(q[3]),
2 * (q[1] * q[2] - q[0] * q[3]), 2 * (q[1] * q[3] + q[0] * q[2])],
... | 5,354,813 |
def sum(mat, axis, target=None):
"""
Sum the matrix along the given dimension, where 0 represents the leading
dimension and 1 represents the non-leading dimension. If a target is
not prvided, a new vector is created for storing the result.
"""
m = _eigenmat.get_leading_dimension(mat.p_mat)
n = _eigenmat.... | 5,354,814 |
def extract_wikidata_prop():
"""
Obtain all the relevant triples of the movies from the wikidata and output the percentage of coverage from all the
movies on the dataset
:return: a csv file with all properties related to the movies form the latest small movielens dataset
"""
# read movies link ... | 5,354,815 |
def convert_created_time_to_datetime(datestring):
"""
Args:
datestring (str): a string object either as a date or
a unix timestamp
Returns:
a pandas datetime object
"""
if len(datestring) == 30:
return pd.to_datetime(datestring)
else:
return pd.to_datetim... | 5,354,816 |
def clear_fixture_quickcache(domain, data_types):
"""
Clears quickcache for fixtures.dbaccessors
Args:
:domain: The domain that has been updated
:data_types: List of FixtureDataType objects with stale cache
"""
if not data_types:
return
type_ids = set()
for data_typ... | 5,354,817 |
def identify_word_classes(tokens, word_classes):
"""
Match word classes to the token list
:param list tokens: List of tokens
:param dict word_classes: Dictionary of word lists to find and tag with the
respective dictionary key
:return: Matched word classes
:rtype: list
"""
if w... | 5,354,818 |
def find_connecting_stops(routes) -> List[Tuple[Stop, List[Route]]]:
"""
Find all stops that connect more than one route.
Return [Stop, [Route]]
"""
stops = {}
for route in sorted(routes, key=Route.name):
for stop in route.stops():
id_ = stop.id()
if id_ not in st... | 5,354,819 |
def freeze_loop(src, start, end, loopStart, loopEnd=None):
""" Freezes a range of frames form start to end using the frames
comprended between loopStart and loopEnd.
If no end frames are provided for the range or the loop,
start frames will be used instead.
"""
core = vs.get_core()
if loopE... | 5,354,820 |
def timevalue(cflo, prate, base_date=0, utility=None):
"""
Computes the equivalent net value of a generic cashflow at time `base_date`
using the periodic interest rate `prate`. If `base_date` is 0, `timevalue`
computes the net present value of the
cashflow. If `base_date` is the index of the last e... | 5,354,821 |
def munge(examples, multiplier, prob, loc_var, data_t, seed=0):
""" Generates a dataset from the original one
:param examples: Training examples
:type examples: 2d numpy array
:param multiplier: size multiplier
:type multiplier: int k
:param prob: probability of swapping values
:type prob: ... | 5,354,822 |
def is_interested_source_code_file(afile):
"""
If a file is the source code file that we are interested.
"""
tokens = afile.split(".")
if len(tokens) > 1 and tokens[-1] in ("c", "cpp", "pl", "tmpl", "py", "s", "S"):
# we care about C/C++/perl/template/python/assembly source code files
... | 5,354,823 |
def write_mirror_mesh_dict(case, normalLine):
"""defines the axes for mirroring the quarter cylinder"""
mirror_mesh_dict = {
'planeType' : 'pointAndNormal',
'pointAndNormalDict' : {'basePoint':[0,0,0], 'normalVector':normalLine},
'planeTolerance' : 1e-06
}
with case.mutable_... | 5,354,824 |
def handle_survey_answers():
"""
Receives form data adds submission to database.
Args:
data (str): From the POST request arguments. Should in JSON form and
have all the quiz response information.
Raises:
AssertionError: When the quiz type is not valid.
Returns:
... | 5,354,825 |
def recursively_extract(node, exfun, maxdepth=2):
"""
Transform a html ul/ol tree into a python list tree.
Converts a html node containing ordered and unordered lists and list items
into an object of lists with tree-like structure. Leaves are retrieved by
applying `exfun` function to the html nodes... | 5,354,826 |
def run_cmd(command):
"""
command execution
Run taken command as a process and raise error if any
"""
proc = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc.wait()
if proc.returncode != 0:
out,... | 5,354,827 |
def group_v2_deconv_decoder(latent_tensor,
output_shape,
hy_ncut=1,
group_feats_size=gin.REQUIRED,
lie_alg_init_scale=gin.REQUIRED,
lie_alg_init_type=gin.REQUIRED,
... | 5,354,828 |
def cptfile2dict(filepath):
"""
Extracts a color dictionary and list for a colormap object from a .cpt file
Parameters
----------
filepath: str
filepath of a .cpt file including file extension
Returns
-------
colormap name, list containing all colors, dictionary containing all ... | 5,354,829 |
def test_tensor_array_of_numpy_arrays_four():
"""Performing tensor product on four numpy array of numpy arrays."""
input_arr = np.array([np.identity(2), np.identity(2), np.identity(2), np.identity(2)])
res = tensor(input_arr)
expected_res = np.identity(16)
bool_mat = np.isclose(res, expected_res)
... | 5,354,830 |
def UncertaintyLossNet():
"""Creates Uncertainty weighted loss model https://arxiv.org/abs/1705.07115
"""
l1 = layers.Input(shape=())
l2 = layers.Input(shape=())
loss = UncertaintyWeightedLoss()([l1, l2])
model = Model(inputs=[l1, l2], outputs=loss)
return model | 5,354,831 |
def inject_signals(
frame_files: Iterable[str],
channels: [str],
ifos: [str],
prior_file: str,
n_samples: int,
outdir: str,
fmin: float = 20,
waveform_duration: float = 8,
snr_range: Iterable[float] = [25, 50],
):
"""Injects simulated BBH signals into a frame, or set of correspo... | 5,354,832 |
async def lyric(id: int, endpoint: NeteaseEndpoint = Depends(requestClient)):
"""
## Name: `lyric`
> 歌词
---
### Required:
- ***int*** **`id`**
- Description: 单曲ID
"""
return await endpoint.lyric(id=id) | 5,354,833 |
def test_ae_jaguar():
"""
Test autoencoder forecasting with the Jaguar dataset
"""
# Sample data
df = jaguar()
# Hyperparameters
batch_size = 10
num_past = 10
num_future = 5
# Prepare the dataloader
data_loaders = dataset.MultiModalDataLoader(
df,
batch_size... | 5,354,834 |
def get_body(m):
"""extract the plain text body. return the body"""
if m.is_multipart():
body = m.get_body(preferencelist=('plain',)).get_payload(decode=True)
else:
body = m.get_payload(decode=True)
if isinstance(body, bytes):
return body.decode()
else:
return body | 5,354,835 |
def get_image(img_path, ch=3, scale=None, tile_size=None, interpolate=cv2.INTER_AREA):
"""
Loads image data into standard Numpy array
Reads image and reverses channel order.
Loads image as 8 bit (regardless of original depth)
Parameters
------
img_path: str
Image file path.... | 5,354,836 |
def density(mass, volume):
"""
Calculate density.
"""
return mass / volume * 1 | 5,354,837 |
def is_pascal_case(key: str) -> None:
"""
Asserts that a value is PascalCased.
:param key: str
:return: None
:raises: django_swagger_tester.exceptions.CaseError
"""
logger.debug('Verifying that `%s` is properly pascal cased', key)
if len(key) == 0:
return
if len(key) == 1 an... | 5,354,838 |
def test__anharmonic_zpve():
""" test the anharmonic ZPVE read/write functions
"""
ref_anh_zpve = -25.123455
anh_zpve_file_name = autofile.data_types.name.anharmonic_zpve('test')
anh_zpve_file_path = os.path.join(TMP_DIR, anh_zpve_file_name)
anh_zpve_str = autofile.data_types.swrite.anharmonic_... | 5,354,839 |
def _is_global(obj, name=None):
"""Determine if obj can be pickled as attribute of a file-backed module"""
if name is None:
name = getattr(obj, '__qualname__', None)
if name is None:
name = getattr(obj, '__name__', None)
module_name = _whichmodule(obj, name)
if module_name is None:... | 5,354,840 |
def download(args):
"""
Download artefacts matching the regular expressions.
"""
storage = s3.S3Storage(args.storage_endpoint)
matching_objects = storage.search(args.expression)
if not matching_objects:
LOGGER.warning("Did not found any matching folders/artefacts")
return
L... | 5,354,841 |
def get_augmenter(augmenter_type: str,
image_size: ImageSizeType,
dataset_mean: DatasetStatType,
dataset_std: DatasetStatType,
padding: PaddingInputType = 1. / 8.,
pad_if_needed: bool = False,
subset_size: int = ... | 5,354,842 |
def query(limit=None, username=None, ids=None, user=None):
"""# Retrieve Workspaces
Receive a generator of Workspace objects previously created in the Stark Bank API.
If no filters are passed and the user is an Organization, all of the Organization Workspaces
will be retrieved.
## Parameters (option... | 5,354,843 |
def _add_output_tensor_nodes(net, preprocess_tensors, output_collection_name='inferece_op'):
"""
Adds output nodes for all preprocess_tensors.
:param preprocess_tensors: a dictionary containing the all predictions;
:param output_collection_name: Name of collection to add output tensors to.
:return: ... | 5,354,844 |
def bf_print_answer(answer_json):
# type: (Dict) -> None
"""Print the given answer JSON to console."""
print(bf_str_answer(answer_json)) | 5,354,845 |
def _configure_logger(
fmt, quiet, level, fpath, processors, metric_grouping_interval, minimal
):
"""
configures a logger when required write to stderr or a file
"""
# NOTE not thread safe. Multiple BaseScripts cannot be instantiated concurrently.
global _GLOBAL_LOG_CONFIGURED
if _GLOBAL_L... | 5,354,846 |
def start_pane(pane, callback, program_info=''):
"""Open the user interface with the given initial pane."""
frame = Window(footer=program_info + ' | q: quit, ?: help')
frame.open(pane, callback)
palette = _add_calendar_colors(getattr(colors, pane.conf['view']['theme']),
... | 5,354,847 |
def gen_add_requests(trace_folder, number_names=10000, first_name=0, append_to_file=False, lns_ids=None,
name_prefix=None):
"""Generates 'add' requests for 'number_names' from a set of local name servers
# Workload generation parameters
number_names = 10000 # number of names in worklo... | 5,354,848 |
def list_file_details(dxm_state, rulesetname, envname, metaname):
"""
Display file details.
Output list will be limited by value of --rulesetname, --envname
or --metaname options if set
and return non-zero return code if metaname is not found.
"""
exit(tab_listfile_details(
dxm_state... | 5,354,849 |
def _set_constance_value(key, value):
"""
Parses and sets a Constance value from a string
:param key:
:param value:
:return:
"""
form = ConstanceForm(initial=get_values())
field = form.fields[key]
clean_value = field.clean(field.to_python(value))
setattr(config, key, clean_val... | 5,354,850 |
def f_prob(times, lats, lons, members):
"""Probabilistic forecast containing also a member dimension."""
data = np.random.rand(len(members), len(times), len(lats), len(lons))
return xr.DataArray(
data,
coords=[members, times, lats, lons],
dims=["member", "time", "lat", "lon"],
... | 5,354,851 |
def dunning_total_by_corpus(m_corpus, f_corpus):
"""
Goes through two corpora, e.g. corpus of male authors and corpus of female authors
runs dunning_individual on all words that are in BOTH corpora
returns sorted dictionary of words and their dunning scores
shows top 10 and lowest 10 words
:par... | 5,354,852 |
def generate_normals_dataset(in_zarr, out_directory, variables=None, overwrite=False):
"""
Compute the normal (day-of-year (DOY) mean) for given variables in the provided Zarr dataset. Creates one
xarray Dataset for each DOY, with dimensions "time", "latitude", and "longitude" and coordinates "time",
... | 5,354,853 |
def send_mail(content,uid,image,subject=None):
#主题
"""**主题如果是纯中文或纯英文则字符数必须大于等于5个,
不然会报错554 SPM被认为是垃圾邮件或者病毒** """
if not subject:
subject = f"fc2热度更新{uid}{content.split(',')[0]}"
#内容
#contents=f'{content}\n{image}'
contents = f"<html><body><h1>{content}</h1><p><img src='cid:0'></p></b... | 5,354,854 |
def get_apikey() -> str:
"""
Read and return the value of the environment variable ``LS_API_KEY``.
:return: The string value of the environment variable or an empty string
if no such variable could be found.
"""
api_key = os.environ.get("LS_API_KEY")
if api_key is None:
warnings... | 5,354,855 |
def test_pdf():
"""
测试pdf报表输出
:return:
"""
res = ResMsg()
report_path = current_app.config.get("REPORT_PATH", "./report")
file_name = "{}.pdf".format(uuid.uuid4().hex)
path = os.path.join(report_path, file_name)
path = pdf_write(path)
path = path.lstrip(".")
res.update(data=p... | 5,354,856 |
def vprint(*args, apply=print, **kwargs):
"""
Prints the variable name, its type and value.
::
vprint(5 + 5, sum([1,2]))
> 5 + 5 (<class 'int'>):
10
sum([1,2]) (<class 'int'>):
3
"""
def printarg(_name, _val) -> str:
_string = f'{_name}: {... | 5,354,857 |
def get_int(prompt: Optional[str] = None,
min_value: Optional[int] = None,
max_value: Optional[int] = None,
condition: Optional[Callable[[int], bool]] = None,
default: Optional[int] = None) -> int:
"""Gets an int from the command line.
:param prompt: Input prompt... | 5,354,858 |
def make_stream_callback(observer, raw, frame_size, start, stop):
"""
Builds a callback function for stream plying. The observer is an object
which implements methods 'observer.set_playing_region(b,e)' and
'observer.set_playing_end(e)'. raw is the wave data in a str object.
frame_size is the number of by... | 5,354,859 |
def predictCNN(segments, artifacts, device:torch.device = torch.device("cpu")):
"""
Perform model predictions on unseen data
:param segments: list of segments (paragraphs)
:param artifacts: run artifacts to evaluate
:param device: torch device
:return category predictions
"""
# Retrieve ... | 5,354,860 |
def load(dataset_directory: List, corpus_path: str, validate: bool = False):
"""
Given the path to a directory containing one or more h5ad files and a group name, call the h5ad loading function
on all files, loading/concatenating the datasets together under the group name
"""
with tiledb.scope_ctx(c... | 5,354,861 |
def transform_url(url):
"""Normalizes url to 'git@github.com:{username}/{repo}' and also
returns username and repository's name."""
username, repo = re.search(r'[/:](?P<username>[A-Za-z0-9-]+)/(?P<repo>[^/]*)', url).groups()
if url.startswith('git@'):
return url, username, repo
return 'git@g... | 5,354,862 |
def prettyprint(data: dict, command: str, modifier: Optional[str] = '') -> str:
"""
Prettyprint the JSON data we get back from the API
"""
output = ''
# A few commands need a little special treatment
if command == 'job':
command = 'jobs'
if 'data' in data and 'jobs' in data['data'... | 5,354,863 |
def decompress(src, dest, verbose, verify=False):
""" Deompresses a file from src to dest
@param src Path to the compressed file
@param dest Path to the decompressed file
@param verbose Path to the compressed file
@param verify Bool value indicating if the decompressed file should be
ch... | 5,354,864 |
def get_address(get_address: GetAddressData, include_elster_responses: bool = False):
"""
The address data of the given idnr is requested at Elster and returned. Be aware, that you need a permission
(aka an activated unlock_code) to query a person's data.
:param get_address: the JSON input data for the... | 5,354,865 |
def kmor(X: np.array, k: int, y: float = 3, nc0: float = 0.1, max_iteration: int = 100, gamma: float = 10 ** -6):
"""K-means clustering with outlier removal
Parameters
----------
X
Your data.
k
Number of clusters.
y
Parameter for outlier detection. Increase this to make ... | 5,354,866 |
def compile_pipeline(pipeline_source: str, pipeline_name: str) -> str:
"""Read in the generated python script and compile it to a KFP package."""
# create a tmp folder
tmp_dir = tempfile.mkdtemp()
# copy generated script to temp dir
copyfile(pipeline_source, tmp_dir + '/' + "pipeline_code.py")
... | 5,354,867 |
def turnout_div(turnout_main, servo, gpo_provider):
"""Create a turnout set to the diverging route"""
turnout_main.set_route(True)
# Check that the route was set to the diverging route
assert(servo.get_angle() == ANGLE_DIV)
assert(gpo_provider.is_enabled())
return turnout_main | 5,354,868 |
def num_jewels(J: str, S: str) -> int:
"""
Time complexity: O(n + m)
Space complexity: O(n)
"""
jewels = set(J)
return sum(stone in jewels for stone in S) | 5,354,869 |
def internet(host="8.8.8.8", port=53, timeout=3):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
logger.info('Internet is the... | 5,354,870 |
def run():
"""
convert infer json to bin, each sentence is one file bin
"""
args = parse_args()
_params = sstcfg
import_modules()
dataset_reader_params_dict = _params.get("dataset_reader")
dataset_reader = dataset_reader_from_params(dataset_reader_params_dict)
train_wrapper = dataset... | 5,354,871 |
def map_family_situation(code):
"""Maps French family situation"""
status = FamilySituation
mapping = {
"M": status.MARRIED.value,
"C": status.SINGLE.value,
"V": status.WIDOWED.value,
"D": status.DIVORCED.value,
"O": status.PACSED.value,
}
if code in mapping.k... | 5,354,872 |
def transform(x, channels, img_shape, kernel_size=7, threshold=1e-4):
"""
----------
X : WRITEME
data with axis [b, 0, 1, c]
"""
for i in channels:
assert isinstance(i, int)
assert i >= 0 and i <= x.shape[3]
x[:, :, :, i] = lecun_lcn(x[:, :, :, i],
... | 5,354,873 |
def test_error():
"""Expect raising SystemExit"""
with pytest.raises(SystemExit):
error('Error') | 5,354,874 |
def delete_files(files=[]):
"""This decorator deletes files before and after a function.
This is very useful for installation procedures.
"""
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(self, *args, **kwargs):
# Inside the decorator
... | 5,354,875 |
async def update_role(guild_id: int, role: RoleModel, db: AsyncSession = Depends(get_db_session)):
"""Update a role by id"""
await crud.roles.update_role(db=db, role=role) | 5,354,876 |
def get_town_table(screenshot_dir):
"""Generate python code for town table
Its format is
table[town_name] = (nearby town1, nearby town2...nearby town5)
The length of tuple may be different depends on town.
Arguments:
screenshot_dir (str): Directory which have town_name directory
... | 5,354,877 |
def pip_install(pkg, upgrade=True):
"""
Call ``pip install`` for a given package.
If ``upgrade==True``, call with ``--upgrade`` key (upgrade current version if it is already installed).
"""
if upgrade:
subprocess.call([sys.executable, "-m", "pip", "install", "--upgrade", pkg])
else:... | 5,354,878 |
def add_note(front, back, tag, model, deck, note_id=None):
"""
Add note with `front` and `back` to `deck` using `model`.
If `deck` doesn't exist, it is created.
If `model` doesn't exist, nothing is done.
If `note_id` is passed, it is used as the note_id
"""
model = mw.col.models.byName(model... | 5,354,879 |
def main():
"""
Main method for the test run simulation app
:return: None
"""
# init steps timing
event_period_s = 3
total = [20, 15, 30, 10]
# create status object table
status = []
# fill up test run start info
for i in range(4):
status.append(RunStatus(BLYNK_A... | 5,354,880 |
def indices_to_one_hot(data, nb_classes): #separate: embedding
"""Convert an iterable of indices to one-hot encoded labels."""
targets = np.array(data).reshape(-1)
return np.eye(nb_classes)[targets] | 5,354,881 |
def translateToceroZcoord(moleculeRDkit):
"""
Translate the molecule to put the first atom in the origin of the coordinates
Parameters
----------
moleculeRDkit : RDkit molecule
An RDkit molecule
Returns
-------
List
List with the shift value applied to X, Y, Z
"""
... | 5,354,882 |
def disable_directory(DirectoryArn=None):
"""
Disables the specified directory. Disabled directories cannot be read or written to. Only enabled directories can be disabled. Disabled directories may be reenabled.
See also: AWS API Documentation
Exceptions
:example: response = client.disable... | 5,354,883 |
def standardize(mri):
"""
Standardize mean and standard deviation of each channel and z_dimension slice to mean 0 and standard
deviation 1.
Note: setting the type of the input mri to np.float16 beforehand causes issues, set it afterwards.
Args:
mri (np.array): input mri, shape (dim_x, dim... | 5,354,884 |
def current_floquet_kets(eigensystem, time):
"""
Get the Floquet basis kets at a given time. These are the
|psi_j(t)> = exp(-i energy[j] t) |phi_j(t)>,
using the notation in Marcel's thesis, equation (1.13).
"""
weights = np.exp(time * eigensystem.abstract_ket_coefficients)
weights = we... | 5,354,885 |
def summary():
""" DB summary stats """
cur = get_cur()
res = []
try:
cur.execute('select count(study_id) as num_studies from study')
res = cur.fetchone()
except:
dbh.rollback()
finally:
cur.close()
if res:
return Summary(num_studies=res['num_studies... | 5,354,886 |
def get_clockwork_conformations(molobj, torsions, resolution,
atoms=None,
debug=False,
timings=False):
"""
Get all conformation for specific cost
cost defined from torsions and resolution
"""
n_torsions = len(torsions)
if atoms is None:
atoms, xyz = cheminfo.molobj_to_xyz... | 5,354,887 |
def rotate_affine(img, rot=None):
"""Rewrite the affine of a spatial image."""
if rot is None:
return img
img = nb.as_closest_canonical(img)
affine = np.eye(4)
affine[:3] = rot @ img.affine[:3]
return img.__class__(img.dataobj, affine, img.header) | 5,354,888 |
async def announce(ctx, destination, counter: Counter, /, **kwargs):
"""Announce the current count of a `Counter` somewhere."""
announcement = counter.get_announcement(**kwargs)
await ctx.module_message(destination, announcement)
if (msg := SPECIAL_NUMBERS.get(counter.count)) is not None:
await ... | 5,354,889 |
def load_default(name):
"""Load the default session.
Args:
name: The name of the session to load, or None to read state file.
"""
if name is None and session_manager.exists('_autosave'):
name = '_autosave'
elif name is None:
try:
name = configfiles.state['general... | 5,354,890 |
def test_grad_hermite_multidimensional_numba_vs_finite_differences(tol):
"""Tests the gradients of hermite_numba. The gradients of parameters are tested by finite differences"""
cutoff = 4
R = np.random.rand(cutoff, cutoff) + 1j * np.random.rand(cutoff, cutoff)
R += R.T
y = np.random.rand(cutoff) + ... | 5,354,891 |
def decode_file_example():
"""
Example for decoding a file
:return:
"""
with open("ais.exploratorium.edu", "r") as file:
for aline in file:
try:
msg = aline.rstrip("\n")
ais_data = pyAISm.decod_ais(msg) # Return a dictionnary
ais_... | 5,354,892 |
def validate_ttl(options):
"""
Check with Vault if the ttl is valid.
:param options: Lemur option dictionary
:return: 1. Boolean if the ttl is valid or not.
2. the ttl in hours.
"""
if 'validity_end' in options and 'validity_start' in options:
ttl = math.floor(abs(options['v... | 5,354,893 |
def vgg16(pretrained:bool=False,progress:bool=True,**kwargs:Any) ->VGG:
"""
Args:
pretrained(bool):是否加载预训练参数
progress(bool):是否显示下载数据的进度条
Return:
返回VGG模型
"""
return _vgg("vgg16","D",False,pretrained,progress,**kwargs) | 5,354,894 |
def cy_gate(N=None, control=0, target=1):
"""Controlled Y gate.
Returns
-------
result : :class:`qutip.Qobj`
Quantum object for operator describing the rotation.
"""
if (control == 1 and target == 0) and N is None:
N = 2
if N is not None:
return gate_expand_2toN(cy... | 5,354,895 |
def sqf(f, *gens, **args):
"""
Compute square-free factorization of ``f``.
**Examples**
>>> from sympy import sqf
>>> from sympy.abc import x
>>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
2*(1 + x)**2*(2 + x)**3
"""
return _generic_factor(f, gens, args, method='sqf') | 5,354,896 |
def update_options_dpd2(dpd1_val):
"""
Updates the contents of the second dropdown menu based of the value of the first dropdown.
:param dpd1_val: str, first dropdown value
:return: list of dictionaries, labels and values
"""
all_options = [
strings.CITY_GDANSK,
strings.CITY_GDY... | 5,354,897 |
def compute_min_paths_from_monitors(csv_file_path, delimiter='\t', origin_as=PEERING_ORIGIN):
"""
Inputs: csv_file_path, delimiter : csv file containing entries with the following format:
|collector|monitor|as_path, and the delimiter used
origin_as: the ASN you want to use as the ter... | 5,354,898 |
def _blanking_rule_ftld_or3a(rule):
""" See _blanking_rule_ftld_or2a for rules """
if rule == 'Blank if Question 1 FTDIDIAG = 0 (No)':
return lambda packet: packet['FTDIDIAG'] == 0
elif rule == 'Blank if Question 3 FTDFDGPE = 0 (No)':
return lambda packet: packet['FTDFDGPE'] == 0
elif ru... | 5,354,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.