content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _find_computecpp_root(repository_ctx):
"""Find ComputeCpp compiler"""
computecpp_path = ""
if _COMPUTECPP_TOOLKIT_PATH in repository_ctx.os.environ:
computecpp_path = repository_ctx.os.environ[_COMPUTECPP_TOOLKIT_PATH].strip()
if computecpp_path.startswith("/"):
_check_computecpp_version(repository_... | 41,800 |
def distance(v):
"""
Estimated distance to the body of the Mandelbuld
"""
z = v
for k in range(MAX_ITERS):
l = (z**2).sum()
if l > BAILOUT:
escape_time = k
break
z = pow3d(z, ORDER) + v
else:
return 0
return np.log(np.log(l)) / MU_NORM ... | 41,801 |
def _depol_error_value_two_qubit(error_param,
gate_time=0,
qubit0_t1=inf,
qubit0_t2=inf,
qubit1_t1=inf,
qubit1_t2=inf):
"""Return 2-qubit depolarizing ... | 41,802 |
def _display_github_milestones(milestones):
"""
Display the specified GitHub milestones
"""
for milestone in milestones:
_display_github_milestone(milestone) | 41,803 |
def time_shift_to_magnetic_poles(inst):
""" OMNI data is time-shifted to bow shock. Time shifted again
to intersections with magnetic pole.
Parameters
----------
inst : Instrument class object
Instrument with OMNI HRO data
Note
----
Time shift calculated using distance to bow s... | 41,804 |
def get_google_order_sheet():
""" Return the google orders spreadsheet """
return get_google_sheet(ANDERSEN_LAB_ORDER_SHEET, 'orders') | 41,805 |
def collision_check(direction):
"""
:param direction: Str : example up
:return:
"""
# really scuffed needs hard rework worked on this in night and its bad
# but it dose its job so i guess its ok for now
if mapGen.map[p.position][direction] is not None:
if mapGen.map[mapGen.... | 41,806 |
def get_freq(freq):
"""
Return frequency code of given frequency str.
If input is not string, return input as it is.
Example
-------
>>> get_freq('A')
1000
>>> get_freq('3A')
1000
"""
if isinstance(freq, compat.string_types):
base, mult = get_freq_code(freq)
... | 41,807 |
def OMRSE(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-08-30", **kwargs
) -> Graph:
"""R... | 41,808 |
def produce_new_shapedir(verts, n_betas=20):
"""Given a matrix of batch of vertices, run PCA through SVD in order to identify
a certain number of shape parameters to best describe the vert shape.
:param verts: (N x V x 3) array
:param n_betas: Number of betas to be fitted to, B
:return vtempl... | 41,809 |
def get_calibration(
df: pd.DataFrame,
features:pd.DataFrame,
outlier_std: float = 3,
calib_n_neighbors: int = 100,
calib_mz_range: int = 20,
calib_rt_range: float = 0.5,
calib_mob_range: float = 0.3,
**kwargs) -> (np.ndarray, float):
"""Wrapper function to get calibrated values for ... | 41,810 |
def argunparse(options: dict, parser: argparse.ArgumentParser) -> List[str]:
"""
Convert a dict of flags back into a list of args.
"""
args = []
for argument in parser.arguments:
single_dash_name = next((arg for arg in argument["args"] if arg.startswith("-")), None)
double_dash_name ... | 41,811 |
def _decode_bytestrings(o):
"""Decode all base64-encoded values (not keys) to bytestrings"""
if isinstance(o, Mapping):
return {key: _decode_bytestrings(value) for key, value in o.items()}
elif isinstance(o, Iterable) and not isinstance(o, (str, bytes)):
return list([_decode_bytestrings(valu... | 41,812 |
def extinction(lambda1in,R,unit = 'microns'):
"""
Calculates A(lambda)/A_V. So, if we know E(B - V), we do
A(lambda) = A(lambda)/A_V * E(B - V) * R.
R is alternatively R_V, usually 3.1---this parameterizes the extinction law, which you should know if you are using this function.
This is the CCM... | 41,813 |
def to_rtp(F0, phi, h):
""" Converts from spherical to Cartesian coordinates (up-south-east)
"""
# spherical coordinates in "physics convention"
r = F0
phi = np.radians(phi)
theta = np.arccos(h)
x = F0*np.sin(theta)*np.cos(phi)
y = F0*np.sin(theta)*np.sin(phi)
z = F0*np.cos(theta)
... | 41,814 |
def _check_format(instruction, arg, argname):
"""Helper to repeat argument validation for an instruction format."""
msg = ''
if not isinstance(arg, (list, tuple)):
msg = '%s %s requires list or tuple of strings, not %s' % (
instruction,
argname,
type(arg)
... | 41,815 |
def to_base(num, base, numerals=NUMERALS):
"""Convert <num> to <base> using the symbols in <numerals>"""
int(num)
int(base)
if not (0 < base < len(numerals)):
raise ValueError("<base> must be in the range [1, %i>" % len(numerals))
if num == 0:
return '0'
if num < 0:
si... | 41,816 |
def save_yaml_file(yamlfile, data):
""" save data{dict} into yamlfile
Filename is mandatory. Data must be a dict{}.
Throw errors using execo logger, and quit
"""
try:
with open(yamlfile, 'w') as fichier:
fichier.write('%YAML 1.1\n---\n')
yaml.safe_dump(data, stream=f... | 41,817 |
def identify_algorithm_hyperparameters(model_initializer): # FLAG: Play nice with Keras
"""Determine keyword-arguments accepted by `model_initializer`, along with their default values
Parameters
----------
model_initializer: functools.partial, or class, or class instance
The algorithm class be... | 41,818 |
async def test_low_battery(hass):
"""Test processing with low battery data and limit set."""
sensor = plant.Plant("other plant", GOOD_CONFIG)
sensor.entity_id = "sensor.mqtt_plant_battery"
sensor.hass = hass
assert sensor.state_attributes["problem"] == "none"
sensor.state_changed(
"senso... | 41,819 |
def cnf_rep_to_text(cnf_rep: List[List[Tuple[str, bool]]]) -> str:
"""
Converts a CNF representation to a text.
:param cnf_rep: The CNF representation to convert.
:return: The text representation of the CNF.
"""
lines = []
for sentence in cnf_rep:
sentence_str = ''
first_in... | 41,820 |
def reshape_for_linear(images):
"""Reshape the images for the linear model
Our linear model requires that the images be reshaped as a 1D tensor
"""
n_images, n_rgb, img_height, img_width = images.shape
return images.reshape(n_images, n_rgb * img_height * img_width) | 41,821 |
def generate_models():
"""Generate all models including 3rd party."""
logger.info('generating models')
out_dir = Path('trestle/oscal')
out_dir.mkdir(exist_ok=True, parents=True)
tmp_dir = out_dir / 'tmp'
tmp_dir.mkdir(exist_ok=True, parents=True)
out_init = out_dir / '__init__.py'
out_in... | 41,822 |
def otp(data, password, encodeFlag=True):
""" do one time pad encoding on a sequence of chars """
pwLen = len(password)
if pwLen < 1:
return data
out = []
for index, char in enumerate(data):
pwPart = ord(password[index % pwLen])
newChar = char + pwPart if encodeFlag else char - pwPart
newChar = newChar + 2... | 41,823 |
def export_actions(path='/tmp', http_response=False):
"""
A script for exporting Enforcement Actions content
to a CSV that can be opened easily in Excel.
Run from within consumerfinance.gov with:
`python cfgov/manage.py runscript export_enforcement_actions`
By default, the script will dump the... | 41,824 |
def reduce_load_R():
"""
Used for reconstructing a copy of the R interpreter from a pickle.
EXAMPLES::
sage: from sage.interfaces.r import reduce_load_R
sage: reduce_load_R()
R Interpreter
"""
return r | 41,825 |
def path_to_playlist_uri(relpath):
"""Convert path relative to playlists_dir to M3U URI."""
if isinstance(relpath, compat.text_type):
relpath = relpath.encode('utf-8')
return b'm3u:%s' % urllib.quote(relpath) | 41,826 |
def read_drive_properties(path_name):
"""
Reads drive properties from json formatted file.
Takes (str) path_name as argument.
Returns (dict) with (bool) status, (str) msg, (dict) conf
"""
from json import load
try:
with open(path_name) as json_file:
conf = load(json_file)... | 41,827 |
def proj(
point: np.ndarray, tol: float = 1e-9, bounds: tuple[float, float] = (0, 1)
) -> tuple[np.ndarray, float]:
"""Find projection on true ROC.
Args:
point: A point in [0, 1]^2.
tol: Tolerance.
bounds: Bounds of projection to help with the calculation.
Returns:
Proj... | 41,828 |
def _split_on_wildcard(string):
"""Split the string into two such that first part does not have any wildcard.
Args:
string (str): The string to be split.
Returns:
A 2-tuple where first part doesn't have any wildcard, and second part does
have a wildcard. If wildcard is not found, the second part is ... | 41,829 |
def esgUSPTOPatentGrantsDF(symbol="", **kwargs):
"""Patent grants are indications that a company has successfully signaled that it values its IP, that its IP is unique in the eyes of the USPTO, and that its initial patent application was a reasonable one.
Patent grants data is issued weekly on Tuesdays.
Cur... | 41,830 |
def pytest_runtest_makereport(item, call):
"""
py.test hook (actually a Python coroutine) that is called when the setup,
call and teardown phase has its result.
We use this hook in the call phase to ignore garbage tracking for skipped
and failed test case outcomes, because pytest creates many colle... | 41,831 |
def get_nln_metrics(model,
train_images,
test_images,
test_labels,
model_type,
args):
"""
Calculates the NLN metrics for either frNN or KNN
Parameters
----------
model (tuple): the mo... | 41,832 |
def load_ms_file(msfile, fieldid=None, datacolumn='RESIDUAL', method='physical', ddid=0, chunksize:int=10**7, bin_count_factor=1):
"""
Load selected data from the measurement set (MS) file and convert to xarray
DataArrays. Transform data for analysis.
Parameters
----------
msfile : string
... | 41,833 |
def get_web_optimized_params(
src_dst,
zoom_level_strategy: str = "auto",
aligned_levels: Optional[int] = None,
tms: morecantile.TileMatrixSet = morecantile.tms.get("WebMercatorQuad"),
) -> Dict:
"""Return VRT parameters for a WebOptimized COG."""
if src_dst.crs != tms.rasterio_crs:
with... | 41,834 |
def AlternatingSignMatrices_n(n):
"""
For old pickles of ``AlternatingSignMatrices_n``.
EXAMPLES::
sage: sage.combinat.alternating_sign_matrix.AlternatingSignMatrices_n(3)
doctest:...: DeprecationWarning: this class is deprecated. Use sage.combinat.alternating_sign_matrix.AlternatingSignMa... | 41,835 |
def _get_band(feature, name, size):
"""
Gets a band normalized and correctly scaled from the raw data.
Args:
feature (obj): the feature as it was read from the files.
name (str): the name of the band.
size (int): the size of the band.
Returns:
tf.Tensor: the b... | 41,836 |
def show_region_depths(depths, centre, half_width=5):
"""Print the depths for a region extending half_width grid points
from centre.
:arg depths: netcdf variable object containing the depths
:type depths: :py:class:`netCDF4.Variable`
:arg centre: Grid point to centre the plot at
:type centre: ... | 41,837 |
def rgetattr(obj, attr, default=sentinel):
"""
from https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects
"""
if default is sentinel:
_getattr = getattr
else:
def _getattr(obj, name):
return getattr(obj, name, default)
return functools.red... | 41,838 |
def unpack_dims(data, vlabels):
"""
Unpacks an interleaved 4th dimension in an imaging data array
Parameters
----------
data : np array
a numpy array of data. Should have 3 spatial dimensions followed by
one nonspatial dimension of interleaved data
vlabels : pandas DataFrame
... | 41,839 |
def env_view_setup_parser(subparser):
"""manage a view associated with the environment"""
subparser.add_argument(
'action', choices=ViewAction.actions(),
help="action to take for the environment's view")
subparser.add_argument(
'view_path', nargs='?',
help="when enabling a vi... | 41,840 |
def start_slaves(server, port, authorization_key, nodes, jobs_per_node, work_dir, remote_shell, global_paths):
""" Start slave prcesses on remote computers.
Arguments:
server -- the master server that the slaves connect to
port -- the port used for communation
authorization_key -- p... | 41,841 |
def bash_this(s):
"""produce a shell fragment that runs the string str inside a fresh bash.
This works around potential strange options that are set in the topmost
bash like POSIX-compatibility mode, -e or similar."""
return 'bash -c %s' % shell_quote(s) | 41,842 |
def assert_action_group_calls(mock_coordinator, push, pop, cancel):
"""
A convenience methods that checks the actionGroup related methods
of the supplied mock TransactionCoordinator object have been called
with the specified arguments. If any of the supplied arguments are None,
then it will be asser... | 41,843 |
async def test_invalid_request(hass):
"""Test handling of an invalid request."""
with patch(
"aiohere.AioHere.weather_for_coordinates",
side_effect=aiohere.HereInvalidRequestError("Invalid"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source"... | 41,844 |
def filter_markdown(md, **kwargs):
"""Python markdown requires markdown="1" on HTML block elements
that contain markdown. AND there's a bug where if you use
markdown.extensions.extra, it replaces code fences in HTML
block elements with garbled text."""
def add_markdown_class(m):
if ... | 41,845 |
def multiply_tensors(tensor1, tensor2):
"""Multiplies two tensors in a matrix-like multiplication based on the
last dimension of the first tensor and first dimension of the second
tensor.
Inputs:
tensor1: A tensor of shape [a, b, c, .., x]
tensor2: A tensor of shape [x,... | 41,846 |
def get_cumulative_collection():
"""获取设备累积数据表
"""
client = MongoClient(connection_string)
db = client.get_database(database)
collection = db.get_collection('equipment_cumulative')
return collection | 41,847 |
def build_up(pq, N):
"""Populate pq with slate of integers."""
delta = 993557 # large prime
k = 0
for _ in range(N):
pq.enqueue(k, k) # use key as the value (doesn't really matter)
k = (k + delta) % N | 41,848 |
def self_closing(xml_str, isSelfClosing):
"""
是否自闭合空标签,
:param isSelfClosing:
:param xml_str:
:return:
"""
if(isSelfClosing=="true"):
xml_str = re.sub(r"<(.*)>(</.*>)", r"<\1/>" , xml_str)
return xml_str
else:
return xml_str | 41,849 |
def split_dataset_folder(root_folder, dest_folder, sets_names=['train','val'], sets_sizes=[0.8,0.2], shuffle=False, verbose=False):
"""Split the folders in a dataset to pytorch format. If the intial format is:
--class1
----img1.jpg
----img2.jpg
--class2
----img1.jpg
----img2.jpg
It trans... | 41,850 |
def setup_dense_net(
num_predictors, neuron_counts=DEFAULT_NEURON_COUNTS,
dropout_rates=DEFAULT_DROPOUT_RATES,
inner_activ_function_name=DEFAULT_INNER_ACTIV_FUNCTION_NAME,
inner_activ_function_alpha=DEFAULT_INNER_ACTIV_FUNCTION_ALPHA,
output_activ_function_name=DEFAULT_OUTPUT_ACT... | 41,851 |
def test_generate_from_schema_using_path(tmp_path: Path) -> None:
"""Test providing a schema path as a str with the file not opened"""
rendered = generate_from_schema(get_test_case_path("basic"))
soup = BeautifulSoup(rendered, "html.parser")
assert_basic_case(soup)
assert_css_and_js_not_copied(tm... | 41,852 |
def init_weights_he(nin, nout, nd, ny):
""" Sample the weights using variance Var(W) = 2/nin according to He initilization
for ReLU nonlinearities from a normal distribution with zero mean.
"""
sigma = np.sqrt(2/(nin))
weights = np.random.normal(0, sigma,((nd, ny))) # Weight vector (nd x ny)
return weights | 41,853 |
def main(args):
"""Entry point for clean command.
:param args: unparsed arguments from the command line.
"""
parser = argparse.ArgumentParser(prog='mupub build')
parser.add_argument(
'--header-file',
help='lilypond file that contains the header'
)
parser.add_argument(
... | 41,854 |
def mkneg_train2(fname,window,size = 8):
# For one class SVM
"""
>>> import feature
>>> [i for i in mkneg_train('.test.pssm',10)]
None
"""
# To Dataset randomly choiced positions
for negid,pssm in parse_pssm(fname):
_indx = [i for i in range(1,len(pssm))]
random.shuffle(_indx)
yield negid,[mkvec(pssm,wind... | 41,855 |
def get_all_message_template():
"""returns all drivers or none"""
try:
return MessageTemplates.objects.all(), "success"
except Exception as e:
return None, str(e) | 41,856 |
def request_pet_name():
"""Requests users pet name as input.
Args:
NONE
Returns:
User's name.
Raises:
ValueError: If input is not a character.
"""
while True:
try:
if (pet_name := input("Enter your pet's name: \n")).isalpha():
break
... | 41,857 |
def butter_bandpass_filter(voltage, lowcut, highcut, fs, order=5):
"""Filter data with a bandpass, butterworth filter
Args:
voltage: array of voltage data from an ECG signal
lowcut: low frequency cutoff
highcut: high frequency cutoff
fs: sampling frequency
... | 41,858 |
def _get_variable_names(expression):
"""Return the list of variable names in the Numexpr `expression`."""
names = []
stack = [expression]
while stack:
node = stack.pop()
if node.astType == 'variable':
names.append(node.value)
elif hasattr(node, 'children'):
... | 41,859 |
def is_readable(path: Path,
access_by: typing.Union[ReadBy, str, None] = None) -> bool:
"""
:return: True if the object at the path `path` is readable
"""
path = pathlib.Path(path).resolve()
if access_by is None or (isinstance(access_by, str) and
access_... | 41,860 |
def add(data_path, _):
"""add templates based on arguments and configurations."""
ask_option = AskOption(data_path)
library_chosen = LibraryChosen()
confirmation = Confirmation()
add_library = AddLibrary()
type_library_name = TypeLibraryName()
possible_states = [
ask_option, librar... | 41,861 |
def GGD(x,d=2,p=1):
"""Two parameter generalized gamma distribution (GGD)
Parameters
----------
x : array_like (positive)
d : float (positive)
p : float (positive)
Returns
-------
pdf : array_like
Notes
-----
.. math::
G(x;d,p) = \frac{p}{\Gamma(d/p)}x^{d-1}\e... | 41,862 |
def update_imported_docs(version_pk):
"""
Check out or update the given project's repository.
"""
version_data = api.version(version_pk).get()
version = make_api_version(version_data)
project = version.project
# Make Dirs
if not os.path.exists(project.doc_path):
os.makedirs(proj... | 41,863 |
def t(string):
"""
add \t
"""
return (string.count(".")) * "\t" + string | 41,864 |
def get_boundary_levels(eris):
"""Get boundary levels for eris."""
return [func(eris.keys()) for func in (min, max)] | 41,865 |
def summary_to_json(d):
""" convert to one json
path: dataset1195/attic/json
dataset1195/json
*map.json
*fastqc.json
*dhs.json,
*frip.json
*pbc.json
*meta.json
*macs2*.json
"""
f = open(os.path.basename(d) + "_compiled_database.xls", 'w')
print >>f, "DatsetId\t... | 41,866 |
def team_changepass():
"""The ``/team/changepass`` endpoint requires authentication and expects
the ``team_id`` and ``password`` as arguments. The team's password
will be set to ``password``
Note that this endpoint requires a POST request.
It can be reached at ``/team/changepass?secret=<API_SECRET... | 41,867 |
def load_options(parser=None, argv=[], positional_args=True):
""" parses sys.argv, possibly exiting if there are mistakes
If you set parser to a ConfigParser object, then you have control
over the usage string and you can prepopulate it with options you
intend to use. But don't set a ``--config`` / ``... | 41,868 |
def read_spans(fname, separator = ';'):
"""
Read in a span file, of the form
Polynomial;NumberOfComplexPlaces;Root;SpanDimension;VolumeSpan;ManifoldSpan;FitRatio
Returns a dictionary object (certainly NOT a Dataset) such that they
keys are polynomials, and the values are dictionaries. These
dic... | 41,869 |
def compress_image(args: argparse.Namespace) -> None:
""" Compresses an image by applying SVD decomposition """
def rescale(x: Matrix) -> Matrix:
return (x - x.min()) / (x.max() - x.min())
img = np.array(Image.open(args.file)) / 255.
n_components = args.k if args.k is not None else img.shape[1... | 41,870 |
def merge_hooks(hooks1: Dict[str, list], hooks2: Dict[str, list]) -> Dict[str, list]:
"""
Overview:
merge two hooks, which has the same keys, each value is sorted by hook priority with stable method
Arguments:
- hooks1 (:obj:`dict`): hooks1 to be merged
- hooks2 (:obj:`dict`): hooks2... | 41,871 |
def version(ctx, kube_context, submodules, repopath):
"""Check versions of services in git submodules
You can provide a comma separated list of submodules
or you can use 'all' for all submodules"""
# Get the repo from arguments defaults to cwd
repo = get_repo(repopath)
submodules = get_submodul... | 41,872 |
def frame_extraction(src , annotationPath, short_side):
"""Extract frames given video_path.
Args:
video_path (str): The video_path.
"""
videoPaths = open(annotationPath, 'r')
video_paths = []
videoLabels = []
frameHW = None
for line in videoPaths.readlines():
# Load the ... | 41,873 |
def fix_protobuf_package():
"""Modifies 'google' package to include path to 'google.protobuf' package.
Prefer our own proto package on the server. Note that this functions is not
used on the Swarming bot nor any other client.
"""
# google.__path__[0] will be google_appengine/google.
import google
if len(... | 41,874 |
def test_get_aws_credentials_file_from_env(env_vars, values):
"""Test that reading credential files names from environment variables works."""
with patch.dict('os.environ', env_vars, clear=True):
assert get_aws_credential_files_from_env() == values | 41,875 |
def get_max_assocs_in_sample_csr(assoc_mat):
"""
Returns the maximum number of co-associations a sample has and the index of
that sample.
"""
first_col = assoc_mat.indptr
n_cols = first_col[1:] - first_col[:-1]
max_row_size = n_cols.max()
max_row_idx = n_cols.argmax()
return max_ro... | 41,876 |
def command_mood(self, args):
"""
/mood [<mood> [text]]
"""
if not args:
return self.xmpp.plugin['xep_0107'].stop()
mood = args[0]
if mood not in pep.MOODS:
return self.information('%s is not a correct value for a mood.'
% mood,
... | 41,877 |
def plot_err_components(stats):
"""
Plot components of the error.
Note: it was chosen to plot(ii, mean_in_time(abs(err_i))),
and thus the corresponding spread measure is MAD.
If one chose instead: plot(ii, std_in_time(err_i)),
then the corresponding measure of spread would have been std.
... | 41,878 |
def putativePrimer(seq,lastShared):
"""
Generate a mock primer based on desired TM or length
and end position. This is used to estimate whether an
exact match restriction site found in the shared region
of two sequences is likely to be captured by a primer
(rendering it necessary to modify the site or throw o... | 41,879 |
def config_flow_monitor_on_interface(device, interface, exporter_name):
""" Config Flow Monitor on Interface
Args:
device (`obj`): Device object
interface (`str`): Interface to be configured
exporter_name (`str`): Flow exporter name
Return:
None
... | 41,880 |
def jsonfile(traptor_type, filename, conn):
""" Reads JSON rules from file, send to Redis """
with open(filename) as f:
rules = [json.loads(line) for line in f]
# Send to Redis
if not conn:
conn = redis.StrictRedis(host=redis_settings['HOST'],
port=redis... | 41,881 |
def default_arg_parser(formatter_class=None):
"""
This function creates an ArgParser to parse command line arguments.
:param formatter_class: Formatting the arg_parser output into a specific
form. For example: In the manpage format.
"""
formatter_class = (CustomFormatter... | 41,882 |
def cleanup_app(app=None):
"""Clean up and delete the QApplication singleton."""
if app is None:
app = QtWidgets.QApplication.instance()
# Reset the global reference to the updater
set_updater(None)
if app:
app.closeAllWindows()
for widg in app.allWindows():
wid... | 41,883 |
def get_config(runner,
raw_uri: str,
root_uri: str,
target: str = BUILDINGS,
nochip: bool = True,
test: bool = False) -> SemanticSegmentationConfig:
"""Generate the pipeline config for this task. This function will be called
by RV, with ... | 41,884 |
def readfmt(s, fmt=DEFAULT_INPUTFMT):
"""Reads a given string into an array of floats using the given format"""
ret = map(float, s.strip().split())
return ret | 41,885 |
def is_image_sharable(context, image, **kwargs):
"""Return True if the image can be shared to others in this context."""
# Is admin == image sharable
if context.is_admin:
return True
# Only allow sharing if we have an owner
if context.owner is None:
return False
# If we own the... | 41,886 |
def run_fct_get_stdout(fct: callable, *args) -> str:
"""Runs a function and collects stdout
:param fct: function to be run
:param args: arguments for the function
:return: collected stdout
"""
# redirect stdout
stdout_old = sys.stdout
stdout_read = StringIO()
sys.stdout = stdout_rea... | 41,887 |
def ksz_radial_function(z,ombh2, Yp, gasfrac = 0.9,xe=1, tau=0, params=None):
"""
K(z) = - T_CMB sigma_T n_e0 x_e(z) exp(-tau(z)) (1+z)^2
Eq 4 of 1810.13423
"""
if params is None: params = default_params
T_CMB_muk = params['T_CMB'] # muK
thompson_SI = constants['thompson_SI']
meterToMega... | 41,888 |
def find_commits(repo, ref='HEAD', grep=None):
"""
Find git commits.
:returns: List of matching commits' SHA1.
:param ref: Git reference passed to ``git log``
:type ref: str
:param grep: Passed to ``git log --grep``
:type grep: str or None
"""
opts = []
if grep:
opts +... | 41,889 |
def stft(y, n_fft=2048, hop_length=None, win_length=None, window='hann',
center=True, dtype=np.complex64, pad_mode='reflect'):
"""Short-time Fourier transform (STFT)
Returns a complex-valued matrix D such that
`np.abs(D[f, t])` is the magnitude of frequency bin `f`
at frame `t`
... | 41,890 |
def user(cmd, directory=None, auto_assert=True, return_io=False,
bash_only=False, silent=True):
"""Used in system tests to emulate a user action"""
if type(cmd) in [list, tuple]:
cmd = ' '.join(cmd)
if not bash_only:
# Handle special cases
for case in _special_user_commands:... | 41,891 |
def findMatches(arg_by_ref, checkForName=False):
"""Finds POIs with the same geometry in 2 datasets.
For each POI in the first dataset, check whether there is a corresponding POI in the 2nd one.
If it exists, move the POI from the second dataset to a resulting dataset B. In any case, the
POIs from the first dataset... | 41,892 |
def _decicelsius_to_kelvins(temperatures_decicelsius):
"""Converts from temperatures from decidegrees Celsius to Kelvins.
:param temperatures_decicelsius: numpy array of temperatures in decidegrees
Celsius.
:return: temperatures_kelvins: numpy array of temperatures in Kelvins, with
same sha... | 41,893 |
def emails_to_warn():
""" who should get warning about errors messages in the chestfreezer? """
emails_for_escalation = _get_array_option_with_default('emails_to_warn', DEFAULT_EMAILS_TO_WARN)
return emails_for_escalation | 41,894 |
def plot_bondcurrents(f, idx_elec, only='+', E=0.0, k='avg', zaxis=2, avg=True, scale='raw', xyz_origin=None,
vmin=None, vmax=None, lw=5, log=False, adosmap=False, ADOSmin=None, ADOSmax=None, arrows=False,
lattice=False, ps=20, ados=False, atoms=None, out=None, ymin=None, ymax=None, xmin=None, xmax=None,
... | 41,895 |
def generate_random_graph (settings, sample):
"""
generate a connected graph, which follows these constraints -
1. does not contain self loop or parallel edges
2. two degree 2 nodes are not connected to each other
3. the graph is connected
""" | 41,896 |
def _rename_bv(vhdr_fname):
"""Rename a BrainVision file, including updating internal links."""
pass | 41,897 |
def get_public_symbols(
root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]:
"""Returns `(symbol_name, symbol)` for all symbols of `root_module`."""
fns = []
for name in getattr(root_module, '__all__'):
o = getattr(root_module, name)
fns.append((name, o))
return fns | 41,898 |
def NewStandardEnv(packager, provider):
"""NewStandardEnv(object packager, object provider) object
NewStandardEnv returns a new *Env with the given params plus standard declarations.
"""
return Env(handle=_checker.checker_NewStandardEnv(packager.handle, provider.handle)) | 41,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.