content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_metadata(metadata_filepath: Union[str, Path]) -> Dict:
"""Parse the metadata file retreived from the BEACO2N site
Args:
metadata_filepath: Path of raw CSV metadata file
pipeline: Are we running as part of the pipeline? If True
return the parsed site information dictionary.
... | 100 |
def unit_norm(model,axis=0):
"""
Constrains the weights incident to each hidden unit to have unit norm.
Args:
axis (int):axis along which to calculate weight norms.
model : the model contains weights need to setting the constraints.
"""
def apply_constraint(t: Tensor):
w_d... | 101 |
def responsive_units(spike_times, spike_clusters, event_times,
pre_time=[0.5, 0], post_time=[0, 0.5], alpha=0.05):
"""
Determine responsive neurons by doing a Wilcoxon Signed-Rank test between a baseline period
before a certain task event (e.g. stimulus onset) and a period after the tas... | 102 |
def create_link(seconds, image_name, size):
"""
Function returns temporary link to the image
"""
token = signing.dumps([str(timezone.now() + timedelta(seconds=int(seconds))), image_name, size])
return settings.SERVER_PATH + reverse("image:dynamic-image", kwargs={"token": token}) | 103 |
def test_paragraph_series_m_tb_ul_t_nl_ul_t_nl_ulb_nl_tb():
"""
Test case: Unordered list text newline unordered list (b) new line thematic break
"""
# Arrange
source_markdown = """- abc
- def
*
---
"""
expected_tokens = [
"[ulist(1,1):-::2:: ]",
"[para(1,3):]",
"[te... | 104 |
def read_one_hot_labels(filename):
"""Read topic labels from file in one-hot form
:param filename: name of input file
:return: topic labels (one-hot DataFrame, M x N)
"""
return pd.read_csv(filename, dtype=np.bool) | 105 |
def make_randint_list(start, stop, length=10):
""" Makes a list of randomly generated integers
Args:
start: lowest integer to be generated randomly.
stop: highest integer to be generated randomly.
length: length of generated list.
Returns:
list of random numbers between sta... | 106 |
def merge(intervals: list[list[int]]) -> list[list[int]]:
"""Generate a new schedule with non-overlapping intervals by merging intervals which overlap
Complexity:
n = len(intervals)
Time: O(nlogn) for the initial sort
Space: O(n) for the worst case of no overlapping intervals
... | 107 |
def df_drop_duplicates(df, ignore_key_pattern="time"):
"""
Drop duplicates from dataframe ignore columns with keys containing defined pattern.
:param df:
:param noinfo_key_pattern:
:return:
"""
ks = df_drop_keys_contains(df, ignore_key_pattern)
df = df.drop_duplicates(ks)
return d... | 108 |
def get_mediawiki_flow_graph(limit, period):
"""
:type limit int
:type period int
:rtype: list[dict]
"""
# https://kibana5.wikia-inc.com/goto/e6ab16f694b625d5b87833ae794f5989
# goreplay is running in RES (check SJC logs only)
rows = ElasticsearchQuery(
es_host=ELASTICSEARCH_HOST,... | 109 |
def showsounding(ab2, rhoa, resp=None, mn2=None, islog=True, xlab=None):
"""
Display a sounding curve (rhoa over ab/2) and an additional response.
"""
if xlab is None:
xlab = r'$\rho_a$ in $\Omega$m'
ab2a = N.asarray(ab2)
rhoa = N.asarray(rhoa)
if mn2 is None:
if islog:
... | 110 |
def cfg_from_list(cfg_list):
"""Set config keys via list (e.g., from command line)."""
from ast import literal_eval
assert len(cfg_list) % 2 == 0
for k, v in zip(cfg_list[0::2], cfg_list[1::2]):
key_list = k.split('.')
d = __C
for subkey in key_list[:-1]:
assert d.has... | 111 |
def bsplslib_Unperiodize(*args):
"""
:param UDirection:
:type UDirection: bool
:param Degree:
:type Degree: int
:param Mults:
:type Mults: TColStd_Array1OfInteger &
:param Knots:
:type Knots: TColStd_Array1OfReal &
:param Poles:
:type Poles: TColgp_Array2OfPnt
:param Weight... | 112 |
def genomic_del3_abs_37(genomic_del3_37_loc):
"""Create test fixture absolute copy number variation"""
return {
"type": "AbsoluteCopyNumber",
"_id": "ga4gh:VAC.Pv9I4Dqk69w-tX0axaikVqid-pozxU74",
"subject": genomic_del3_37_loc,
"copies": {"type": "Number", "value": 2}
} | 113 |
def set_atommap(mol, num=0):
"""Set the atom map number for all atoms in the molecule.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
A molecule.
num : int
The atom map number to set for all atoms. If 0, it will clear the atom map.
"""
for atom in mol.GetAtoms():
... | 114 |
def write_data_to_file(training_data_files, out_file, image_shape, truth_dtype=np.uint8, subject_ids=None,
normalize=True, crop=True):
"""
Takes in a set of training images and writes those images to an hdf5 file.
:param training_data_files: List of tuples containing the training data... | 115 |
def get_configinfo(env):
"""Returns a list of dictionaries containing the `name` and `options`
of each configuration section. The value of `options` is a list of
dictionaries containing the `name`, `value` and `modified` state of
each configuration option. The `modified` value is True if the value
d... | 116 |
def fabric_wired(ctx, obj):
"""DNA Center Fabric Wired API (version: 1.3.1).
Wraps the DNA Center Fabric Wired API and exposes the API as native Python commands.
"""
ctx.obj = obj.fabric_wired | 117 |
def main():
"""
Run all the tests
"""
files = utils.get_files(PATH)
with open('results.txt', 'w') as f:
f.write(f'{sys.version}\n')
f.write(LINE)
for exe in ['./sort1', './sort2', './sort3']:
for file in files:
cmd = subprocess.run(['t... | 118 |
def given_energy(n, ef_energy):
"""
Calculate and return the value of given energy using given values of the params
How to Use:
Give arguments for ef_energy and n parameters
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERS... | 119 |
def departures(stop: location.Stop, day: date, fname: str, days: int = 1) -> None:
"""Departures from a given stop for a given date (range)"""
servinglines = set((c.line, c.id) for c in stop.courses)
deps: List[Tuple[datetime, schedule.TripStop]] = []
for currdate in (day + timedelta(days=n) for n in ra... | 120 |
def dt_getreferences_rmap_na():
"""
>>> old_state = test_config.setup(cache=None, url="https://jwst-crds-dev.stsci.edu")
>>> os.environ["CRDS_MAPPATH_SINGLE"] = test_config.TEST_DATA
>>> heavy_client.getreferences({"META.INSTRUMENT.NAME":"NIRISS", "META.INSTRUMENT.DETECTOR":"NIS", "META.INSTRUMENT.FILT... | 121 |
def sequence_sigmoid_cross_entropy(labels,
logits,
sequence_length,
average_across_batch=True,
average_across_timesteps=False,
average_across_cla... | 122 |
def stats(func):
"""Stats printing and exception handling decorator"""
def inner(*args):
try:
code, decoded, res = func(*args)
except ValueError as err:
print(err)
else:
if FORMATTING:
code_length = 0
for el in code:
... | 123 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in PLATFORMS
]
... | 124 |
def get_ucp_worker_info():
"""Gets information on the current UCX worker, obtained from
`ucp_worker_print_info`.
"""
return _get_ctx().ucp_worker_info() | 125 |
def check_can_collect_payment(id):
"""
Check if participant can collect payment this is true if :
- They have been signed up for a year
- They have never collected payment before or their last collection was more than 5 months ago
"""
select = "SELECT time_sign_up FROM SESSION_INFO WHERE u... | 126 |
def plus_tensor(wx, wy, wz=np.array([0, 0, 1])):
"""Calculate the plus polarization tensor for some basis.c.f., eq. 2 of https://arxiv.org/pdf/1710.03794.pdf"""
e_plus = np.outer(wx, wx) - np.outer(wy, wy)
return e_plus | 127 |
def duplicate_objects(dup_infos):
"""Duplicate an object with optional transformations.
Args:
dup_infos (list[dict]): A list of duplication infos.
Each info is a dictionary, containing the following data:
original (str): Name of the object to duplicate.
name (str): D... | 128 |
def determineOptimalStartingPoint(options,logger_proxy,logging_mutex):
"""
If options.checkpoint is set to -1 then operations will start from the beginning but will skip steps to regenerate files
For all other values of options.checkpoint, pre-generated data will be overwritten
"""
flag = checkForNe... | 129 |
def _list_data_objects(request, model, serializer):
"""a factory method for querying and receiving database objects"""
obj = model.objects.all()
ser = serializer(obj, many=True)
return Response(ser.data, status=status.HTTP_200_OK) | 130 |
def load_conf(file='./config', section='SYNTH_DATA'):
"""load configuration
Args:
file (str, optional): path to conf file. Defaults to './config'.
section (str, optional): name of section. Defaults to 'SYNTH_DATA'.
Returns:
[str]: params of configuration
"""
log_me... | 131 |
def plot_proper_motion(df):
"""Plot proper motion.
df: DataFrame with `pm_phi1` and `pm_phi2`
"""
x = df['pm_phi1']
y = df['pm_phi2']
plt.plot(x, y, 'ko', markersize=0.3, alpha=0.3)
plt.xlabel('Proper motion phi1 (mas/yr)')
plt.ylabel('Proper motion phi2 (mas/yr)')
plt.xlim(-1... | 132 |
def consume(context, state):
"""
*musicpd.org, playback section:*
``consume {STATE}``
Sets consume state to ``STATE``, ``STATE`` should be 0 or
1. When consume is activated, each song played is removed from
playlist.
"""
if int(state):
context.core.tracklist.con... | 133 |
def distance(a, b):
"""
Computes a
:param a:
:param b:
:return:
"""
x = a[0] - b[0]
y = a[1] - b[1]
return math.sqrt(x ** 2 + y ** 2) | 134 |
def test_immunization_3(base_settings):
"""No. 3 tests collection for Immunization.
Test File: immunization-example-refused.json
"""
filename = base_settings["unittest_data_dir"] / "immunization-example-refused.json"
inst = immunization.Immunization.parse_file(
filename, content_type="applic... | 135 |
def approve_pipelines_for_publishing(pipeline_ids): # noqa: E501
"""approve_pipelines_for_publishing
:param pipeline_ids: Array of pipeline IDs to be approved for publishing.
:type pipeline_ids: List[str]
:rtype: None
"""
pipe_exts: [ApiPipelineExtension] = load_data(ApiPipelineExtension)
... | 136 |
def test_k8s_plugin_gets_raw_metrics_empty(postfix, mocked_http):
"""
K8sCollector returns a empty dict in case of problems.
GIVEN: K8s stats server won't return a JSON response for some reason
(Unauthorized, exceptions, internal errors, etc).
WHEN: K8sCollector method `_get_raw_metrics` is ... | 137 |
def make_tokenizer_module(tokenizer):
"""tokenizer module"""
tokenizers = {}
cursors = {}
@ffi.callback("int(int, const char *const*, sqlite3_tokenizer **)")
def xcreate(argc, argv, ppTokenizer):
if hasattr(tokenizer, "__call__"):
args = [ffi.string(x).decode("utf-8") for x in a... | 138 |
def looping_call(interval, callable):
"""
Returns a greenlet running your callable in a loop and an Event you can set
to terminate the loop cleanly.
"""
ev = Event()
def loop(interval, callable):
while not ev.wait(timeout=interval):
callable()
return gevent.spawn(loop, in... | 139 |
def obj2sta(obj, sta_filename, workshop=None):
"""
Convert an object(json format) to sta file
:param obj: ready to convert
:param sta_filename: output sta filename
:param workshop: means path to read binary file
:return:
"""
if workshop is None:
workshop = ''
with open(sta_... | 140 |
def print_twin_results_vec(vec_dat, labels):
"""Print out comparison results, stored in 1d vector.
Parameters
----------
vec_dat : 1d array
Vector of data to print out.
labels : list of str
Labels for what data each row corresponds to.
"""
for ind, label in enumerate(labels... | 141 |
def rsquared_adj(r, nobs, df_res, has_constant=True):
"""
Compute the adjusted R^2, coefficient of determination.
Args:
r (float): rsquared value
nobs (int): number of observations the model was fit on
df_res (int): degrees of freedom of the residuals (nobs - number of model params... | 142 |
def run_tests(test_folder: str, build_folder: str) -> None:
""" Discover and run tests. """
sys.path.insert(0, '.')
# Make sure log messages are not shown on stdout/stderr. We can't simply
# increase the log level since some unit tests expect logging to happen.
logging.getLogger().addHandler(logging... | 143 |
def metadata_factory(repo, json=False, **kwargs):
"""
This generates a layout you would expect for metadata storage with files.
:type json: bool
:param json: if True, will return string instead.
"""
output = {
"baseline_filename": None,
"crontab": "0 0 * * *",
"exclude_r... | 144 |
def saveTextData(file_name, data, fmt):
"""Save data array in text format
Args:
file_name (str): output file name
data (ndarray): numpy ndarray data
fmt (str): format string, e.g. "%.2e"
"""
numpy.savetxt(file_name, data, fmt=fmt) | 145 |
def inpand(clip: vs.VideoNode, sw: int, sh: Optional[int] = None, mode: XxpandMode = XxpandMode.RECTANGLE,
thr: Optional[int] = None, planes: int | Sequence[int] | None = None) -> vs.VideoNode:
"""
Calls std.Minimum in order to shrink each pixel with the smallest value in its 3x3 neighbourhood
fr... | 146 |
def pre_update(ctx, ref=settings.UPDATE_REF):
"""Update code to pick up changes to this file."""
update_code(ref)
update_info() | 147 |
def test_instantiation(adb_executable):
"""
Just make sure that we can instantiate the ADB object
:return: None
"""
try:
adb = ADB(adb_executable) # noqa: W0612
except: # noqa
pytest.fail("No failure should be raised") | 148 |
def _extract_aggregate_functions(before_aggregate):
"""Converts `before_aggregate` to aggregation functions.
Args:
before_aggregate: The first result of splitting `after_broadcast` on
`intrinsic_defs.FEDERATED_AGGREGATE`.
Returns:
`zero`, `accumulate`, `merge` and `report` as specified by
`can... | 149 |
def process_site_eb(err, product_id, sid, data):
"""Errorback from process_site transaction."""
msg = f"process_site({product_id}, {sid}, {data}) got {err}"
common.email_error(err, msg) | 150 |
def _make_system(A, M, x0, b):
"""Make a linear system Ax = b
Args:
A (cupy.ndarray or cupyx.scipy.sparse.spmatrix or
cupyx.scipy.sparse.LinearOperator): sparse or dense matrix.
M (cupy.ndarray or cupyx.scipy.sparse.spmatrix or
cupyx.scipy.sparse.LinearOperator): precond... | 151 |
def merge_intersecting_segments(segments: List[Segment]) -> List[Segment]:
"""
Merges intersecting segments from the list.
"""
sorted_by_start = sorted(segments, key=lambda segment: segment.start)
merged = []
for segment in sorted_by_start:
if not merged:
merged.append(Segmen... | 152 |
def test_set_dids_metadata_bulk_multi(did_factory):
""" DID (CORE) : Test setting metadata in bulk with multiple key-values on multiple dids"""
skip_without_json()
nb_dids = 5
dids = [did_factory.make_dataset() for _ in range(nb_dids)]
for did in dids:
testkeys = list(map(lambda i: 'testkey... | 153 |
def change_log_root_key():
"""Root key of an entity group with change log."""
# Bump ID to rebuild the change log from *History entities.
return ndb.Key('AuthDBLog', 'v1') | 154 |
def load_file(filename):
"""Loads a TESS *spoc* FITS file and returns TIME, PDCSAP_FLUX"""
hdu = fits.open(filename)
time = hdu[1].data['TIME']
flux = hdu[1].data['PDCSAP_FLUX']
flux[flux == 0] = numpy.nan
return time, flux | 155 |
def AcProgRanlib(context, selection=None):
"""Corresponds to AC_PROG_RANLIB_ autoconf macro
:Parameters:
context
SCons configuration context.
selection
If ``None`` (default), the program will be found automatically,
otherwise the method will return the value ... | 156 |
def blit_anchors(dest, dest_anchor, src, src_anchor):
""" Blits the source onto the destination such that their anchors align.
src_anchor and dest_anchor can be strings of one of the point attributes (topleft, center,
midbottom, etc.) or a position on their respective surfaces (e.g [100, 200]).
"""
... | 157 |
def updateGraph( Graph, GraphNumber ):
"""
The function calls an appropriate plot-function based on the mode (value) of
the radio-button
:param Graph: an instance of VibroP_GraphObject class
:param GraphNumber: int
:return:
"""
# Update the graph ID ( GraphNumber - it's a built-in bohek... | 158 |
def create_insight_id_extension(
insight_id_value: str, insight_system: str
) -> Extension:
"""Creates an extension for an insight-id with a valueIdentifier
The insight id extension is defined in the IG at:
https://alvearie.io/alvearie-fhir-ig/StructureDefinition-insight-id.html
Args:
... | 159 |
def ReadNotifyResponseHeader(payload_size, data_type, data_count, sid, ioid):
"""
Construct a ``MessageHeader`` for a ReadNotifyResponse command.
Read value of a channel. Sent over TCP.
Parameters
----------
payload_size : integer
Size of DBR formatted data in payload.
data_type ... | 160 |
def substitute_T5_cols(c, cols, nlu_identifier=True):
"""
rename cols with base name either <t5> or if not unique <t5_<task>>
"""
new_cols = {}
new_base_name = 't5' if nlu_identifier=='UNIQUE' else f't5_{nlu_identifier}'
for col in cols :
if '_results' in col : new_cols[col] = n... | 161 |
def _get_trigger_func(name, trigger_name):
"""
Given a valid vulnerability name, get the trigger function corresponding
to the vulnerability name and trigger name.
If the trigger function isn't found, raise NotFound.
"""
try:
return get_trigger(name, trigger_name)
except AttributeEr... | 162 |
def _get_rotated_bounding_box(size, quaternion):
"""Calculates the bounding box of a rotated 3D box.
Args:
size: An array of length 3 specifying the half-lengths of a box.
quaternion: A unit quaternion specifying the box's orientation.
Returns:
An array of length 3 specifying the half-lengths of the... | 163 |
def Cos(
a: float = 1.,
b: float = 1.,
c: float = 0.) -> InternalLayer:
"""Affine transform of `Cos` nonlinearity, i.e. `a cos(b*x + c)`.
Args:
a: output scale.
b: input scale.
c: input phase shift.
Returns:
`(init_fn, apply_fn, kernel_fn)`.
"""
return Sin(a=a, b=b, c=c + np.pi / ... | 164 |
def key_make_model(chip):
""" Given a chip, return make and model string.
Make and model are extracted from chip.misc using the keys "make" and
"model". If they are missing it returns None for that value. If misc
missing or not a dictionary, (None, None) is returned.
Args:
chip: A chip nam... | 165 |
def check_concentration(R,D):
"""
check the concentration of a halo
by finding where the power law is most similar to alpha^-2
return 1./radius, which is the concentration.
(so find the scale radius by taking 1./concentration)
"""
func = np.log10(R**-2.)-np.log10(D)
print('Concentrati... | 166 |
def _mergesort_space_optimized(nums: list, start: int, end: int) -> None:
"""Performing merge operation in-place by overwriting associated indexes of input array
Complexity:
n = len(nums)
Space: n = O(n)
for (2 * n/2) copies of sorted left/right subarrays
Examples:
... | 167 |
def test_has_object_destroy_permission_owner(api_rf, km_user_accessor_factory):
"""
The Know Me user the accessor grants access on should be able to
destroy the accessor.
"""
accessor = km_user_accessor_factory()
api_rf.user = accessor.km_user.user
request = api_rf.get("/")
assert acces... | 168 |
def alternating_epsilons_actor_core(
policy_network: EpsilonPolicy, epsilons: Sequence[float],
) -> actor_core_lib.ActorCore[EpsilonActorState, None]:
"""Returns actor components for alternating epsilon exploration.
Args:
policy_network: A feedforward action selecting function.
epsilons: epsilons to al... | 169 |
def get_keywords(
current_user: models.User = Depends(deps.get_current_active_user),
controller_client: ControllerClient = Depends(deps.get_controller_client),
labels: List = Depends(deps.get_personal_labels),
q: Optional[str] = Query(None, description="query keywords"),
offset: int = Query(0),
... | 170 |
def _compile_unit(i):
"""Append gas to unit and update CO2e for pint/iam-unit compatibility"""
if " equivalent" in i["unit"]:
return i["unit"].replace("CO2 equivalent", "CO2e")
if i["unit"] in ["kt", "t"]:
return " ".join([i["unit"], i["gas"]])
else:
return i["unit"] | 171 |
def get_fdfs_url(file):
"""
上传文件或图片到FastDFS
:param file: 文件或图片对象,二进制数据或本地文件
:return: 文件或图片在FastDFS中的url
"""
# 创建FastDFS连接对象
fdfs_client = Fdfs_client(settings.FASTDFS_CONF_PATH)
"""
client.upload_by_filename(文件名),
client.upload_by_buffer(文件bytes数据)
"""
# 上传文件或图片到fastDFS... | 172 |
def test_download(mocker: MockFixture):
"""Test happy Path"""
# Mocking cmd line arguments
testArgs = Namespace(output="file.out", slot="Test")
mocker.patch("argparse.ArgumentParser.parse_args", return_value=testArgs)
mocker.patch("requests.request", side_effect=fakeQnAMakerAPI)
fileOut = mock... | 173 |
def updateDb(dbObj, resultTupleList):
"""
Write the results to the dbOj.
"""
for (benchmarkInfo, benchmarkResults) in resultTupleList:
dbObj.addResults(benchmarkInfo, benchmarkResults) | 174 |
def get_all_edge_detects(clip: vs.VideoNode, **kwargs: Any) -> List[vs.VideoNode]:
"""Allows you to get all masks inheriting from EdgeDetect.
Args:
clip (vs.VideoNode):
Source clip.
kwargs:
Arguments passed to EdgeDetect().get_mask
Returns:
List[vs.VideoNod... | 175 |
def add_overwrite_arg(parser):
"""
Add overwrite option to the parser.
Parameters
----------
parser: argparse.ArgumentParser object
"""
parser.add_argument(
'-f', dest='overwrite', action='store_true',
help='Force overwriting of the output files.') | 176 |
def get_ustz(localdt, timezone):
"""
Returns the timezone associated to a local datetime and an IANA timezone.
There are two common timezone conventions. One is the Olson/IANA and
the other is the Microsoft convention. For example, the closest IANA
timezone for Boston, MA is America/New_York. More ... | 177 |
def plot_rolling_sharpe(returns, rolling_window=APPROX_BDAYS_PER_MONTH * 6,
**kwargs):
"""
Plots the rolling Sharpe ratio versus date.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.cre... | 178 |
def test_data_format_avro(sdc_builder, sdc_executor, gcp):
"""
Write data to Google cloud storage using Avro format.
The pipeline looks like:
google_cloud_storage_origin >> wiretap
"""
DATA = {'name': 'boss', 'age': 60, 'emails': ['boss@company.com', 'boss2@company.com'], 'boss': None}
... | 179 |
def saveSolution(name, C):
"""save set C to file name as a VertexCover solution"""
f = open(name, "w")
s = ",".join([str(c) for c in C])
f.write(s)
f.close() | 180 |
def ResolveNamespace(namespace):
"""Validate app namespace, providing a default.
If the argument is None, namespace_manager.get_namespace() is substituted.
Args:
namespace: The namespace argument value to be validated.
Returns:
The value of namespace, or the substituted default.
Always a non-empt... | 181 |
def Calculo_por_etapas(Diccionario):
"""Calculo de la hornilla por etapas"""
Lista_Contenido=[]
Lista_columnas=[]
#Normalización de la capacidad de la hornilla
#Mem_dias=float(Diccionario['¿Cada cuantos días quiere moler? (días)'])
#Mem_Temp=Normalizar_Capacidad(float(Diccionario['Capacidad ... | 182 |
def venus_equ_proportional_minute(x, y, e, R):
"""
Venus equation proportional minute
:param x: true argument (av) in degree
:param y: mean center (cm) in degree
:param e: eccentricity
:param R: radius of the epicycle
:return: minutes proportional in degree
"""
return utils.minuta_p... | 183 |
def e2_cond(p, m, sigma, alpha, mu):
"""
This function is dependent from the gamma function.
Conditional mean of the square of the normal distribution.
See the article for more informations.
Parameters
----------
p : float
Proportion of persistent species.
m : float
Me... | 184 |
def concline_generator(matches, idxs, df, metadata,
add_meta, category, fname, preserve_case=False):
"""
Get all conclines
:param matches: a list of formatted matches
:param idxs: their (sent, word) idx
"""
conc_res = []
# potential speedup: turn idxs into dict
fr... | 185 |
def main():
"""Create a flow that uses the 'say_hello' task and run it.
This creates a Prefect flow and runs it a couple times with
different inputs.
"""
with Flow("My First Flow") as flow:
name = Parameter('name')
say_hello(name)
flow.run(name='World')
flow.run(name='NH Pyt... | 186 |
def match_detections(predicted_data, gt_data, min_iou):
"""Carry out matching between detected and ground truth bboxes.
:param predicted_data: List of predicted bboxes
:param gt_data: List of ground truth bboxes
:param min_iou: Min IoU value to match bboxes
:return: List of matches
"""
all... | 187 |
def map_string(affix_string: str, punctuation: str, whitespace_only: bool = False) -> str:
"""Turn affix string into type char representation. Types are 'w' for non-whitespace char,
and 's' for whitespace char.
:param affix_string: a string
:type: str
:param punctuation: the set of characters to tr... | 188 |
def info(input, verbose, pyformat, **kwargs):
"""
Provides info about the input. Requires valid input.
"""
if not input:
input = '-'
with click.open_file(input, mode='rb') as f:
data = json_utils.load_ordered(f)
d = {
'length': len(data),
'keys': sorte... | 189 |
def config_loads(cfg_text, from_cfg=None, whitelist_keys=None):
"""Same as config_load but load from a string
"""
try:
cfg = AttrDict(yaml.load(cfg_text))
except TypeError:
# empty string
cfg = AttrDict()
if from_cfg:
if not whitelist_keys:
whitelist_keys ... | 190 |
def align_column ( table , index , align = 'left') :
"""Aling the certain column of the table
>>> aligned = align_column ( table , 1 , 'left' )
"""
nrows = [ list ( row ) for row in table ]
lmax = 0
for row in nrows :
if index <= len ( row ) :
item = decolorize ( row [ i... | 191 |
def calculate_shared_private_key(partner):
"""
Calculate a shared private key
:param partner: Name of partner
"""
print('generating {}'.format(get_private_filename(partner)))
private_key = get_key(private_filename)
public_key = get_key(public_filename)
shared_modified_key = get_key(get_... | 192 |
def make_form(domain, parent, data, existing=None):
"""simulate a POST payload from the location create/edit page"""
location = existing or Location(domain=domain, parent=parent)
def make_payload(k, v):
if hasattr(k, '__iter__'):
prefix, propname = k
prefix = 'props_%s' % pr... | 193 |
def score_auroc(y_true: Iterable[int], y_prob: Iterable[Iterable[float]]) -> float:
"""
Computes the Area Under ROC curve (AUROC).
Parameters
----------
y_true : List
TODO
y_prob : List
TODO
References
----------
.. [1] `Wikipedia entry for the Receiver operating ch... | 194 |
def set_group(pathname,group_name):
"""Change the group for the given file or directory"""
#group=grp.getgrnam(group_name)
#gid = group.gr_gid
#os.lchown(pathname, -1, gid)#To leave one of the ids unchanged, set it to -1. This function will not follow symbolic links.
shutil.chown(path, group=group_name) | 195 |
def test_add_item_db(session):
"""Test if through session we can add an item
Args:
session (SQLAlchemy Object Session): It's the session object from SQLALchemy Instance
"""
add_item = Items("Conjured Mana Cake", 5, 8)
session.add(add_item)
session.commit()
assert add_item.name ==... | 196 |
def abs_densitye_seed(model, inputs, args, tokenizer, **kwargs):
"""Maximum density sampling by calculating information density for
example when passed through [model]"""
# print('getting embedding_a')
X_a = load_and_embed_examples(args, model, tokenizer, evaluate=True, text = 'text_a')
# print('get... | 197 |
def get_marketplace_image_output(instance_type: Optional[pulumi.Input[Optional[str]]] = None,
label: Optional[pulumi.Input[str]] = None,
zone: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOpti... | 198 |
def read_capacity_from_file(experiment_name):
""" Read and return the min capacity, max capacity, interpolation, gamma as a tuple if the capacity
is variable. Otherwise return the constant capacity as is.
TODO: This is a bit brittle at the moment - We should take a look at fixing this for static bet... | 199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.