content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate_ec2_public_key(
credential_public_key: EC2CredentialPublicKey) -> None:
"""Validate the format of an `EC2CredentialPublicKey`.
Args:
credential_public_key (EC2CredentialPublicKey): The credential public key to
validate.
Raises:
ValidationError: If the given credent... | 42,200 |
def make_variables_snapshots(*, variables: List[Any]) -> str:
"""
Make snapshots of specified variables.
Parameters
----------
variables : list
Variables to make snapshots.
Returns
-------
snapshot_name : str
Snapshot name to be used.
"""
ended: Di... | 42,201 |
def sext_to(value, n):
"""Extend `value` to length `n` by replicating the msb (`value[-1]`)"""
return sext(value, n - len(value)) | 42,202 |
def hyper_perf_plots(collection='pilot_fixed', pred_type='regression', top_n=1, subset='test'):
"""
Get results for models in the given collection. For each training dataset, separate the
results by model type and featurizer, and make a scatter plot of <subset> set r2_score vs
model type/featurizer comb... | 42,203 |
def parse_matching_pairs(pair_txt):
"""Get list of image pairs for matching
Arg:
pair_txt: file contains image pairs and essential
matrix with line format
image1 image2 sim w p q r x y z ess_vec
Return:
list of 3d-tuple contains (q=[wpqr], t=[xyz], essential matrix)
... | 42,204 |
def compile_repo_info(repos, all=False, fetch=False):
"""Compiles all the information about found repos."""
# global to allow for threading work
global git_info
git_info = {}
max_ = len(repos)
threads = []
for i, repo in enumerate(repos):
t = threading.Thread(target=process_repo, ... | 42,205 |
def histogram2d(x, y, bins=10, range=None, weights=None, density=False): # pylint: disable=redefined-builtin
"""
Computes the multidimensional histogram of some data.
Note:
Deprecated numpy argument `normed` is not supported.
Args:
x (Union[list, tuple, Tensor]): An array with shape `(... | 42,206 |
def get_project_arg_details():
"""
**get_project_arg_details**
obtains project details from arguments and then returns them
:return:
"""
project_id = request.args.get('project_id')
names = request.args.get('names')
cell = request.args.get('cell')
email = request.args.get(... | 42,207 |
def vibronic_ls(x, s, sigma, gamma, e_vib, kt=0, n_max=None, m_max=None):
"""
Produce a vibronic (Frank-Condom) lineshape.
The vibronic transition amplitude computed relative to 0 (ie: relative to
the electronic transition energy). Lines are broadened using a voigt
profile.
Parameter... | 42,208 |
def handleFunction(command,func):
"""
Function to calculate, Translate
"""
try:
# re.search(r"(?i)"+func,' '.join(SET_OF_FUNCTIONS))
if("calculate" == func.lower()):
func,command = command.split()
try:
return eval(command)
except:
return "Sorry! We are unable to calculate this expression."
... | 42,209 |
def auth():
"""returns worker_id !!!currently!!! does not have auth logic"""
response_body = {}
status_code = 200
try:
auth_token = request.args.get("auth_token", None)
resp = fl_events_auth({"auth_token": auth_token}, None)
resp = json.loads(resp)["data"]
except Exception as... | 42,210 |
def redo_a_task():
"""Allows the user to unfinish a task
so they can complete it again"""
user = get_user_info()
if user['id'] != g.user['id']:
abort(403)
if request.method == 'POST':
redo = request.form['redoTask']
# get the database connection
with db.get_db() as ... | 42,211 |
def get_templates_environment(templates_dir):
"""Create and return a Jinja environment to deal with the templates."""
env = Environment(
loader=PackageLoader('charmcraft', 'templates/{}'.format(templates_dir)),
autoescape=False, # no need to escape things here :-)
keep_trailin... | 42,212 |
def return_U_given_sinusoidal_u1(i,t,X,u1,**kwargs):
"""
Takes in current step (i), numpy.ndarray of time (t) of shape (N,), state numpy.ndarray (X) of shape (8,), and previous input scalar u1 and returns the input U (shape (2,)) for this time step.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**kwargs
~~~~~~~~... | 42,213 |
def verify(s):
"""
Check if the cube definition string s represents a solvable cube.
@param s is the cube definition string , see {@link Facelet}
@return 0: Cube is solvable<br>
-1: There is not exactly one facelet of each colour<br>
-2: Not all 12 edges exist exactly once<br>
... | 42,214 |
def copy_jsons(o: JSONs) -> MutableJSONs:
"""
Make a new, mutable copy of a JSON array.
>>> a = [{'a': [1, 2]}, {'b': 3}]
>>> b = copy_jsons(a)
>>> b[0]['a'].append(3)
>>> b
[{'a': [1, 2, 3]}, {'b': 3}]
>>> a
[{'a': [1, 2]}, {'b': 3}]
"""
return cast(MutableJSONs, copy.deepc... | 42,215 |
def string_to_dot(typed_value):
# type: (TypedValue) -> Tuple[List[str], List[str]]
"""Serialize a String object to Graphviz format."""
string = f'{typed_value.value}'.replace('"', r'\"')
dot = f'_{typed_value.name} [shape="record", color="#A0A0A0", label="{{{{String | {string}}}}}"]'
return [dot], ... | 42,216 |
def resolve_country_subdivisions(_, info, alpha_2):
"""
Country resolver
:param info: QraphQL request context
:param alpha_2: ISO 3166 alpha2 code
:param code: ISO 3166-2 code
"""
return CountrySubdivision.list_for_country(country_code=alpha_2) | 42,217 |
def getFramesFromVideo(name, nFrames = -1):
"""
This function obtain the frames from a specified video and stores them in the
frames folder.
"""
vidcap = cv2.VideoCapture(name)
success, image = vidcap.read()
count = 0
success = True
while success:
cv2.imwrite("./frames/f... | 42,218 |
def bool2bson(val: bool) -> Tuple[bytes, bytes]:
"""Encode bool as BSON Boolean."""
assert isinstance(val, bool)
return BSON_BOOLEAN, ONE if val else ZERO | 42,219 |
def isbn13_to_isbn10 (isbn_str, cleanse=True):
"""
Convert an ISBN-13 to an ISBN-10.
:Parameters:
isbn_str : string
The ISBN as a string, e.g. " 0-940016-73-6 ". It should be 13
digits after normalisation.
cleanse : boolean
If true, formatting will be stripped from the ISBN before
conversion.
:Re... | 42,220 |
def import_data():
"""Import datasets to internal memory"""
with open('data/names.json') as f:
data_names = json.load(f)
with open('data/issues.json') as f:
data_issues = json.load(f)
with open('data/disasters.json') as f:
data_disasters = json.load(f)
with open('data/options... | 42,221 |
def append_credentials(new_dict):
"""Uses the path to the credentials to add or update dictionary keys"""
with open(credentials_path, "r") as file:
old_dict = json.load(file)
old_dict.update(new_dict)
with open(credentials_path, "w") as file:
json.dump(old_dict, file, indent=4) | 42,222 |
def synthesize_ntf_dunn(order=3, osr=64, H_inf=1.5):
"""
Alias of :func:`ntf_dunn`
.. deprecated:: 0.11.0
Function has been moved to the :mod:`NTFdesign` module with
name :func:`ntf_dunn`.
"""
warn("Function superseded by ntf_dunn in "
"NTFdesign module", PyDsmDeprecationWarn... | 42,223 |
def schedule_notification() -> str:
"""Randomly select either news or covid stats to add to the notifcation column,
if there is already a 'news' item in the notificaitons column then it will
update the item with a newer piece of news"""
#NEWS
news_title, news_content = get_news()
notif_e... | 42,224 |
def _parse_hexblob(blob: str) -> bytes:
"""
Binary conversions from hexstring are handled by bytes(hstr2bin()).
:param blob:
:return:
"""
return bytes(hstr2bin(blob)) | 42,225 |
def _row_to_col_index_dict(headers: List[Cell]) -> Dict[str, int]:
"""Calculate a mapping of cell contents to column index.
Returns:
dict[str, int]: {MFP nutrient name: worksheet column index} mapping.
int: N
"""
return {h.value: h.col - 1 for h in headers} | 42,226 |
def main():
"""Python main function, intended for usage via command line.
"""
# parse command-line args
try:
args = parse_args()
except RuntimeError:
sys.exit(1)
if getattr(args, 'help'):
sys.exit(0)
igpack_filename = getattr(args, 'igpack')
target_url = getattr... | 42,227 |
def preprocess_cat_cols(X_train, y_train, cat_cols=[], X_test=None,
one_hot_max_size=1, learning_task=LearningTask.CLASSIFICATION):
"""Preprocess categorial columns(cat_cols) in X_train
and X_test(if specified) with cat-counting(the same as in catboost)
or with one-hot-encoding,
depends ... | 42,228 |
def assert_and_fix_args_for_init(args):
"""
Asserts, fixes and sets parameters from init parser.
"""
if args.config is None:
args.config = get_airflow_config(args.home) | 42,229 |
def get_start_time(period, time_zone=None):
"""Doc."""
today = pd.Timestamp.today(tz=time_zone or 'Europe/Stockholm')
if period == 'thisyear':
return pd.Timestamp(f'{today.year}0101').strftime('%Y-%m-%d %H:%M:%S')
elif period in DAYS_MAPPER:
return (today - pd.Timedelta(days=DAYS_MAPPER.... | 42,230 |
def setup_textbox(parent,
font="monospace",
width=70, height=12):
"""Setup for the textboxes, including scrollbars and Text widget."""
hsrl = ttk.Scrollbar(parent, orient="horizontal")
hsrl.pack(side=tk.BOTTOM, fill=tk.X)
vsrl = ttk.Scrollbar(parent)
vsrl.pack(sid... | 42,231 |
def generate_mock_statuses(naive_dt=True, datetime_fixtures=None):
"""
A dict of statuses keyed to their id. Useful for mocking an API response.
These are useful in``Timeline`` class testing.
May be set to have a utc timezone with a ``False`` value for the ``naive_dt`` argument.
"""
mock_status... | 42,232 |
def test_set_param_landscape(lscape, params):
"""Parameters can be set on landscape classes"""
BioSim(island_map="W", ini_pop=[], seed=1).set_landscape_parameters(lscape, params) | 42,233 |
def get_current_ingest_id():
"""Get the uuid of the active ingest
:return: the id of the active ingest
:rtype: uuid
"""
return os.getenv('JETA_CURRENT_INGEST_ID') | 42,234 |
def hashlib_mapper(algo):
"""
:param algo: string
:return: hashlib library for specified algorithm
algorithms available in python3 but not in python2:
sha3_224 sha3_256, sha3_384, blake2b, blake2s, sha3_512, shake_256, shake_128
"""
algo = algo.lower()
if algo == "md5":
ret... | 42,235 |
def post_mapping_cluster(infiles, outfile):
"""post mapping against the cluster tRNAs """
fastqfile, database, bowtie_index_cluster = infiles
genome_name = bowtie_index_cluster.replace(".1.ebwt","")
temp_file = P.get_temp_filename(".")
statement = """bowtie -n 3 -k 1 --best -e 800 --sam %(genom... | 42,236 |
def partition_cells(config, cells, edges):
""" Partition a set of cells
- cells -- A DataFrame of cells
- edges -- a list of edge times delimiting boundaries between cells
Returns a DataFrame of combined cells, with times and widths adjusted to account for missing cells
"""
# get indices of... | 42,237 |
def timing_stats(results: List[Result]) -> List[str]:
"""Calculate and format lines with timings across completed results."""
def percentile(data: List[float], percent: int) -> Union[float, str]:
if not data:
return '-'
data_sorted = sorted(data)
pos = max(int(round(percent /... | 42,238 |
def analyse_gamma(
snps_object,
output_summary_filename,
output_logger,
SWEEPS,
TUNE,
CHAINS,
CORES,
N_1kG,
fix_intercept=False,
):
"""
Bayesian hierarchical regression on the dataset with the gamma model.
:param snps_object: snps instance
:param output_summary_file... | 42,239 |
def dpc_variant_to_string(variant: _DV) -> str:
"""Convert a Basix DPCVariant enum to a string.
Args:
variant: The DPC variant
Returns:
The DPC variant as a string.
"""
return variant.name | 42,240 |
async def refresh_token(request: web.Request) -> web.Response:
""" Refresh Token endpoints """
try:
content = await request.json()
if "token" not in content:
return web.json_response({"error": "Wrong data. Provide token."}, status=400)
except Exception:
return web.json_r... | 42,241 |
def get_my_choices_projects():
""" Retrieves all projects in the system
for the project management page
"""
proj_list = Project.objects.all()
proj_tuple = []
counter = 1
for proj in proj_list:
proj_tuple.append((counter, proj))
counter = counter + 1
return proj_tuple | 42,242 |
def delete_locked(locked):
"""
function to delete locked objects
"""
locked.delete_locked() | 42,243 |
def _get_sys_info() -> dict[str, JSONSerializable]:
"""
Returns system information as a JSON serializable dictionary.
"""
uname_result = platform.uname()
language_code, encoding = locale.getlocale()
return {
"commit": _get_commit_hash(),
"python": ".".join([str(i) for i in sys.ve... | 42,244 |
def normalDistributionBand(collection, band, mean=None, std=None,
name='normal_distribution'):
""" Compute a normal distribution using a specified band, over an
ImageCollection. For more see:
https://en.wikipedia.org/wiki/Normal_distribution
:param band: the name of the prope... | 42,245 |
def add_success(self, test):
"""
This function add the passed test cases in list i.e. TextTestResult.passed
:param self:TextTestResult class
:type self: TextTestResult object
:param test: test case
:type test: test case object
:return: None
"""
if self.showAll:
self.passed.ap... | 42,246 |
def compute_ctrness_targets(reg_targets):
"""
:param reg_targets:
:return:
"""
if len(reg_targets) == 0:
return reg_targets.new_zeros(len(reg_targets))
left_right = reg_targets[:, [0, 2]]
top_bottom = reg_targets[:, [1, 3]]
ctrness = (left_right.min(dim=-1)[0] / left_right.max(d... | 42,247 |
def new_group(gid: str, description: str) -> None:
"""
Creates new group
:param gid: Group's symbolic code
:type gid: str
:param description: Short description (optional)
:type description: str
:raise click.BadParameter: if wrong `id` has been passed
"""
try:
Group.objects.... | 42,248 |
def test_console_disambiguation(ipyconsole, qtbot):
"""Test the disambiguation of dedicated consoles."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None, timeout=SHELL_TIMEOUT)
# Create directories and file for TEMP_DIRECTORY/a/b/c.py
# and TEMP_D... | 42,249 |
def create_hmac_signature(key:bytes, data_to_sign:str, hashmech:hashlib=hashlib.sha256) -> str:
"""
Creates an HMAC signature for the provided data string
@param key: HMAC key as bytes
@param data_to_sign: The data that needs to be signed
@param hashmech: The hashing mechanism to use, defaults to s... | 42,250 |
def paste_and_search(input_text: str = "") -> None:
"""Enters data and makes a search query on Google Scholar"""
move_mouse_to(*TEXT_INPUT_POSITION, duration=0.5)
pyautogui.click(button="left")
pyautogui.hotkey("ctrl", "a") # Select anything inside the input
pyautogui.typewrite(["backspace"]) # Re... | 42,251 |
def calculate_cruise():
"""Solves a basic sum of forces equation to determine direction and magnitude of force required to align
horizontal components (in landing frame) of velocity and position vectors"""
# Define all vectors in the vessel surface reference frame
pos0 = (-position()[0], -posi... | 42,252 |
def CV_range(
bit_depth: Integer = 10, is_legal: Boolean = False, is_int: Boolean = False
) -> NDArray:
"""
Returns the code value :math:`CV` range for given bit depth, range legality
and representation.
Parameters
----------
bit_depth
Bit depth of the code value :math:`CV` range.
... | 42,253 |
def bw_transform(x):
"""Transform rgb separated balls to a single color_channel."""
x = x.sum(2)
x = torch.clamp(x, 0, 1)
x = torch.unsqueeze(x, 2)
return x | 42,254 |
def do_test():
"""Perform functional test for plastid.bin.counts_in_region"""
for x in execute_helper(test_info, counts_in_region_tests):
yield x | 42,255 |
def fom(A, b, x0=None, maxiter=None, residuals=None, errs=None):
"""Full orthogonalization method
Parameters
----------
A : {array, matrix, sparse matrix, LinearOperator}
n x n, linear system to solve
b : {array, matrix}
right hand side, shape is (n,) or (n,1)
x0 : {array, matri... | 42,256 |
def get_gprMax_materials(fname):
"""
Returns the soil permittivities. Fname is an .in file.
"""
materials = {'pec': 1.0, # Not defined, usually taken as 1.
'free_space': 1.000536}
for mat in get_lines(fname, 'material'):
props = mat.split()
materials[props[-1]] = f... | 42,257 |
def main(client, destination, b, l, directory, image, bar):
"""Classify images stored locally or on Impresso S3 server, using AWS or GoogleCloud Vision"""
classifier = classifiers[client]
destination = os.path.abspath(destination)
if b: # Batch mode
if l:
batch_label_local(clas... | 42,258 |
def generate_utt_pairs(librispeech_md_file, utt_pairs, n_src):
"""Generate pairs of utterances for the mixtures."""
# Create a dict of speakers
utt_dict = {}
# Maps from speaker ID to list of all utterance indices in the metadata file
speakers = list(librispeech_md_file["speaker_ID"].unique())
f... | 42,259 |
def simpson(so, spl: str, attr: str, *, local=True, key_added=None, graph_key='knn', inplace=True) -> None:
"""Computes the Simpson Index on the observation or the sample level
Args:
so: SpatialOmics instance
spl: Spl for which to compute the metric
attr: Categorical feature in SpatialO... | 42,260 |
def test_list_string_enumeration_1_nistxml_sv_iv_list_string_enumeration_2_4(mode, save_output, output_format):
"""
Type list/string is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/string/Schema+Instance/NISTSchema-SV-IV-list-string-enumeration-2.xsd",
inst... | 42,261 |
def _rk4(dparam=None, k0=None, y=None, kwdargs=None):
"""
a traditional RK4 scheme, with:
- y = array of all variables
- p = parameter dictionnary
dt is contained within p
"""
if 'itself' in dparam[k0]['kargs']:
dy1 = dparam[k0]['func'](itself=y, **kwdargs)
dy2 = dpar... | 42,262 |
def generate_discord_markdown_string(lines):
"""
Wraps a list of message into a discord markdown block
:param [str] lines:
:return: The wrapped string
:rtype: str
"""
output = ["```markdown"] + lines + ["```"]
return "\n".join(output) | 42,263 |
def _sanitize_ndim(
result: ArrayLike, data, dtype: Optional[DtypeObj], index: Optional[Index]
) -> ArrayLike:
"""
Ensure we have a 1-dimensional result array.
"""
if getattr(result, "ndim", 0) == 0:
raise ValueError("result should be arraylike with ndim > 0")
elif result.ndim == 1:
... | 42,264 |
def from_list_dict(f: Callable[[Any], T], x: Any) -> List[Dict[str, T]]:
"""Parses list of dictionaries, applying `f` to the dictionary values.
All items must be dictionaries.
"""
assert isinstance(x, list)
assert all(isinstance(d, dict) for d in x)
return [ { k: f(v) for (k, v) in d.items() } f... | 42,265 |
def TSTR_eICU(identifier, epoch):
"""
"""
# get "train" data
exp_data = np.load('./experiments/tstr/' + identifier + '_' + str(epoch) + '.data.npy').item()
X_synth = exp_data['synth_data']
Y_synth = exp_data['synth_labels']
n_synth = X_synth.shape[0]
X_synth = X_synth.reshape(n_synth, -1... | 42,266 |
def test_predicted_type(
data: pd.DataFrame,
model_params: Dict[str, Any],
active_run_id: str,
) -> None:
"""Test predictions data type
"""
passed = 0
# Select single not null value
random_idx = random_not_null_idx( data, model_params )
prediction = data.loc[[random_idx], 'predicted_... | 42,267 |
def wizard_active(step, current):
"""
Return the proper classname for the step div in the badge wizard.
The current step needs a 'selected' class while the following step needs a
'next-selected' class to color the tip of the arrow properly.
"""
if current == step:
return 'selected'
... | 42,268 |
def set_token(token: OAuth2Token):
"""Set dynamics client token in a thread, so it can be done in an async context."""
def task():
name = "dynamics-client-token"
expires = int(token["expires_in"]) - 60
cache.set(name, token, expires)
with ThreadPoolExecutor() as executor:
... | 42,269 |
def pFind_clumps(f_list, n_smooth=32, param=None, arg_string=None, verbose=True):
"""
A parallel implementation of find_clumps. Since SKID is not parallelized
this can be used to run find_clumps on a set of snapshots from one
simulation.
**ARGUMENTS**
f_list : list
A list cont... | 42,270 |
def gamma_dis(x):
"""fix gamma = 2
https://www.itl.nist.gov/div898/handbook/eda/section3/eda366b.htm
"""
x = round(x, 14)
res = round(x*math.exp(-x) / TAU_2, 14)
return res | 42,271 |
def init(config: "Config") -> None:
"""
Initialize logger
"""
# make sure logs directory exists
logs_dir = config.get_dir()
logs_dir.mkdir(parents=True, exist_ok=True)
os.chmod(logs_dir, stat.S_IRWXU)
# configure logging
name = config.get_name()
file_name = logs_dir / f"{name}.... | 42,272 |
def generate_schema_dictionary(source_type, csdl_schema_dirs, json_schema_dirs,
entity, schema_file_name, oem_entities=None,
oem_schema_file_names=None, profile=None, schema_url=None,
copyright=None):
""" Generate the schem... | 42,273 |
def get_month_number(year):
""" Function to get month from the user input. The month should be number from 1-12.
:returns: the number of month enterd by user
:rtype: int
"""
year = int(year)
while True:
val = input("Please, enter the number of month? (1-12)\n")
closed = Fal... | 42,274 |
def reconstruct_with_whole_molecules(struct):
""" Build smallest molecule representation of struct.
"""
rstruct = Structure()
rstruct.set_lattice_vectors(struct.get_lattice_vectors())
molecule_struct_list = get_molecules(struct)
for molecule_struct in molecule_struct_list:
geo_arra... | 42,275 |
def _json_serialize_no_param(cls):
""" class decorator to support json serialization
Register class as a known type so it can be serialized and deserialzied
properly
"""
return _patch(cls, _get_type_key(cls), 0) | 42,276 |
def aireTriangle(a,b,c):
"""
Aire du triangle abc dans l'espace.
C'est la moitié de la norme du produit vectoriel ab vect ac
"""
u,v=b-a,c-a
r=u[2]*v[0]-u[0]*v[2]
s=u[0]*v[1]-u[1]*v[0]
t=u[1]*v[2]-u[2]*v[1]
return 0.5*sqrt(r*r+s*s+t*t) | 42,277 |
def ez_admin(admin_client, admin_admin, skip_auth):
"""A Django test client that has been logged in as admin. When EZID endpoints are
called via the client, a cookie for an active authenticated session is included
automatically. This also sets the admin password to "admin".
Note: Because EZID does not ... | 42,278 |
def _template_message(desc, descriptor_registry):
# type: (Descriptor, DescriptorRegistry) -> str
"""
Returns cls_def string, list of fields, list of repeated fields
"""
desc = SimpleDescriptor(desc)
descriptor_registry[desc.identifier] = desc
slots = desc.field_names
# NOTE: the "pass... | 42,279 |
def get_ec2_dns_names(cluster):
"""
Generates the public DNS names of instances in the cluster.
"""
ecs = boto3.client("ecs")
resp = ecs.list_container_instances(cluster="api_cluster")
arns = resp["containerInstanceArns"]
resp = ecs.describe_container_instances(
cluster="api_cluste... | 42,280 |
def parse_archive(path, objdump):
"""Parses a list of ObjectFiles from an objdump archive output.
Args:
path: String path to the archive.
objdump: List of strings of lines of objdump output to parse.
Returns:
List of ObjectFile objects representing the objects contained wi... | 42,281 |
def plot_overlapping_distributions_2d(clusters,
out_path: str,
colors: Optional[List]=['khaki', 'lightcyan'],
img_fmt: Optional[str]='png',
export: Optional[bool]=F... | 42,282 |
async def async_validate_trigger_config(
hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
config = TRIGGER_SCHEMA(config)
device_registry = await hass.helpers.device_registry.async_get_registry()
device = device_registry.async_get(config[CONF_DEVICE_ID])
trigger ... | 42,283 |
def decode(size, num_agents, id_agent, sa, debug=False):
"""
Transform from array to list
"""
list_indices = torch.tensor([idx for idx in range(id_agent * size, id_agent * size + size)]).to(device)
out = sa.index_select(1,list_indices)
if (debug):
print("\nDebug decode:\n size=", size,... | 42,284 |
def p_multikv(p):
"""multikvcmd : MULTIKV"""
p[0] = ParseTreeNode('COMMAND', raw='multikv') | 42,285 |
def process_files(filelist, filemgmt, task_id, archive_name, do_commit):
"""Ingests file metadata for all files in filelist.
"""
# filelist[fullname] = {'path': path, 'filetype': filetype, 'fullname':fullname,
# 'filename', 'compression'}
totfilecnt = sum([len(x) for x in list... | 42,286 |
def get_vgg_dilate_conv(data):
"""
vgg-16
shared convolutional layers,use dilated convolution in group 5
:param data: Symbol
:return: Symbol
"""
# ====group 1
conv1_1 = mx.symbol.Convolution(data=data, kernel=(3,3), pad=(1,1), \
num_filter=64, name='... | 42,287 |
def _get_func_aliases(tree) -> Dict:
"""
Get __func_alias__ dict for mapping function names
"""
fun_aliases = {}
assignments = [node for node in tree.body if isinstance(node, ast.Assign)]
for assign in assignments:
try:
if assign.targets[0].id == "__func_alias__":
... | 42,288 |
def admin_only(view_func):
"""Restrict page access to only admins"""
@wraps(view_func)
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'profile':
return redirec... | 42,289 |
def _im_distance(adj1, adj2, hwhm):
"""Computes the Ipsen-Mikhailov distance for two symmetric adjacency
matrices
Note : Requires networks with the same number of nodes. The networks
can be directed and weighted (with weights in the range [0,1]).
Params
------
adj1, adj2 (array): adjacenc... | 42,290 |
def verify_challenge_transaction(
challenge_transaction: str,
server_account_id: str,
home_domains: Union[str, Iterable[str]],
web_auth_domain: str,
network_passphrase: str,
) -> None:
"""Verifies if a transaction is a valid
`SEP0010 v1.2 <https://github.com/stellar/stellar-protocol/blob/mas... | 42,291 |
def pob(genomes_dir, readsf, output_dir, maxdist, logger):
"""use plentyofbugs to identify best reference
Uses plentyofbugs, a package that useqs mash to
find the best reference genome for draft genome
"""
pobcmd = str("plentyofbugs -g {genomes_dir} -f {readsf} -o {output_dir} " +
... | 42,292 |
def add_segmentation_ssdf(basedir, ptcode, ctcode, cropname, seeds, model,
graphname, s2=None, modelname='modelavgreg',
stentType=None, params=None):
""" Add a model to an existing ssdf but separate from the existing graph
s2 = ssdf of existing model to add... | 42,293 |
def get_movement_endtime(dT, T):
"""
Returns the end time of the movement assuming that the start time is zero.
"""
_t = 0.
for i, _dT in enumerate(T):
_t = np.max([_t, np.sum(dT[:i]) + T[i]])
return _t | 42,294 |
def getGroupUpcomingEvents(request, group):
"""
Return all the upcoming events that are assigned to the specified group.
:param request: Django request object
:param group: for this group page
:rtype: list of the namedtuple ThisEvent (title, page, url)
"""
# Get events that are a child of a... | 42,295 |
def ModifyInstanceMetadata(metadata):
"""Sends instance data to the metadata daemon.
Uses the Luxi transport layer to communicate with the metadata
daemon configuration server. It starts the metadata daemon if it is
not running.
The daemon must be enabled during at configuration time.
@type metadata: dic... | 42,296 |
def get_marginal_probabilities(probs_table):
"""
Get the marginal probability of each event given a
contingency table.
"""
ind = []
for transp in get_transpositions(probs_table):
marginal_probs = [probs_table.transpose(transp)[1, ...].sum(),
probs_table.transpo... | 42,297 |
def get_graph_map():
"""Get the graph rail network mapbox map.
Returns:
go.Figure: Scattermapbox of rail network graph
"""
# Get the nodes and edges and pandas dataframes from the database
nodes, edges = get_berths()
if nodes is None or edges is None:
return None
# Plot the... | 42,298 |
def upload(key, secret, host, bucket, filename):
"""
call this function when using this file as a library
date header must be relatively in sync with server or you
get forbidden error
returns True on success
raises on error
"""
base_name = os.path.basename(filename)
try:
h... | 42,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.