content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def versionPropertiesDictionary(sql_row_list):
"""
versionPropertiesDictionary(sql_row_list)
transforms a row gotten via SQL request (list), to a dictionary
"""
properties_dictionary = \
{
"id": sql_row_list[0],
"model_id": sql_row_list[1],
"version": sql_row_list[2]... | 5,316,900 |
def remove_unused_compartments(model):
# type: (COPASI.CModel) -> None
"""
Goes through all compartments of the model, and removes all that are not being used by
other parts of the model.
:param model: the model
"""
to_delete = []
for comp in model.getCompartments():
assert (i... | 5,316,901 |
def register():
"""
Register a new user
"""
logger.debug('register()')
return render_template('register.html', user=None) | 5,316,902 |
def verify_received_aes_key(key: dict, rsa_public_key) -> bool:
"""
Verifies the AES key received as a dict and passed here is valid.
:param dict key: An AES key, as a dictionary.
:param rsa_public_key: The RSA public key of the author.
:return bool: True if the information is a valid AES key... | 5,316,903 |
def remove_indices(dist_array, indices):
"""
Remove given indices from dist_array
:param dist_array: a flattened version of the dist_matrix in the format of entries (node0/ window0, node1/ window1, distance),
usually sorted
:param indices: indices which should be removed
:return:
""... | 5,316,904 |
def bow_net(data, dict_dim, emb_dim=128, hid_dim=128, hid_dim2=96, class_dim=2):
"""
Bow net
"""
# embedding layer
emb = fluid.layers.embedding(
input=data,
size=[dict_dim, emb_dim],
param_attr=fluid.ParamAttr(name="@HUB_senta_bow@embedding_0.w_0"))
# bow layer
bow =... | 5,316,905 |
def close_story(request):
"""
Tags: logs+stories
---
Closes an open story.
---
story_id:
in: path
type: string
required: true
"""
auth_context = auth_context_from_request(request)
# Only available to Owners for now.
if not auth_context.is_owner():
raise... | 5,316,906 |
def start_scheduler_service():
"""Starts the Scheduler component"""
sched = Scheduler(maxJobs=MAX_JOBS, unitCPU=CPU_UNIT, unitMem=MEM_UNIT, maxCPU=MAX_CPU, portLower=PORT_RANGE_LOWER,
portUpper=PORT_RANGE_UPPER, strategy=STRATEGY)
sched.start() | 5,316,907 |
def print_otx_mitre_technique(mitre_technique, mitre_techniques):
"""Searches through Mitre ATT&CK for a Technique and pulls the inforation out and prints to the screen.
Requried Parameters:
mitre_techniqe - derived from the is_mitre_tactic_technique_sub_tecnique function
mitre_techn... | 5,316,908 |
def convert_dates_to_ISO(date: str, date_2: str):
"""Assumes both dates are current system year. If the latter one occurs chronologically
before the former (i.e given "december 4 2021" and "january 4 2021", january comes first in the year.
This means that the second date is likely the next year, so we'll assume tha... | 5,316,909 |
def findliteralblocks(blocks):
"""Finds literal blocks and adds a 'type' field to the blocks.
Literal blocks are given the type 'literal', all other blocks are
given type the 'paragraph'.
"""
i = 0
while i < len(blocks):
# Searching for a block that looks like this:
#
# ... | 5,316,910 |
def test_bad_data_type() -> None:
"""
Asserts that the appropriate exception is raised for a bad response data type.
"""
with pytest.raises(SpecificationError, match="The response is <class 'dict'> when it should be <class 'list'>"):
_list(schema=schema, data={'test': data}, case_func=is_camel_c... | 5,316,911 |
def get_parser():
""" Return parser """
parser = argparse.ArgumentParser(description='BioWardrobe Migration', add_help=True)
parser.add_argument("-c", "--config", help="Path to the BioWardrobe config file", default="/etc/wardrobe/wardrobe")
logging_level = parser.add_mutually_exclusive_group()
loggi... | 5,316,912 |
def _relabel_date(excel, wb, cell_range: str ='A1'):
"""
Currently date is coming in with odd name, replace with Date
"""
ws = wb.Sheets('Sheet')
ws.Range(cell_range).Value = 'Date' | 5,316,913 |
def packet_events(packet: dict) -> Generator:
"""Return list of all events in the packet.
>>> x = list(packet_events({
... 'protocol': 'alecto v1',
... 'id': 'ec02',
... 'temperature': 1.0,
... 'temperature_unit': '°C',
... 'humidity': 10,
... 'humidity_unit': '%'... | 5,316,914 |
def urlcheck():
"""takes all devurls and checks their header return"""
urlstatus = []
for elem in get_bundle_dev_url():
appads = "https://" + elem[1] + "/app-ads.txt"
try:
x = requests.head(appads, timeout=3.5, allow_redirects=True)
except requests.exceptions.Timeout:
... | 5,316,915 |
def get_vpc_dhcp_options(dhcp_options_id=None,filters=None,tags=None,opts=None):
"""
Retrieve information about an EC2 DHCP Options configuration.
## Example Usage
### Lookup by DHCP Options ID
```python
import pulumi
import pulumi_aws as aws
example = aws.ec2.get_vpc_dhcp_options(dhc... | 5,316,916 |
def main(string):
"""Application entry point.
:param str string: The character string to be hashed.
:returns: None
:rtype: None
"""
print("The hashes for {0} are:".format(string))
print("- MD5: {0}".format(hashlib.md5(string).hexdigest()))
print("- SHA1: {0}".format(hashlib.sha1(s... | 5,316,917 |
def do_precip12(ts, ds):
"""Compute the 24 Hour precip at 12 UTC, we do some more tricks though"""
offset = iemre.daily_offset(ts)
ets = utc(ts.year, ts.month, ts.day, 12)
sts = ets - datetime.timedelta(hours=24)
offset1 = iemre.hourly_offset(sts)
offset2 = iemre.hourly_offset(ets)
if ts.mon... | 5,316,918 |
def test_remove_key_eauth(salt_key_cli, salt_master, saltdev_account):
"""
test salt-key -d usage
"""
min_name = random_string("minibar-")
pki_dir = salt_master.config["pki_dir"]
key = os.path.join(pki_dir, "minions", min_name)
with salt.utils.files.fopen(key, "w") as fp:
fp.write(P... | 5,316,919 |
def main():
"""Run main part of code."""
# Be a bit smart about which populations need to be loaded
load = True
if not MAKE and not OBSERVE:
load = False
pop = get_cosmic_pop('standard', SIZE, load=load, overwrite=MAKE)
for telescope in TELESCOPES:
pattern = 'airy'
if ... | 5,316,920 |
def moduleName(file):
"""Extract a module name from the python source file name, with appended ':'."""
return os.path.splitext(os.path.split(file)[1])[0] + ":" | 5,316,921 |
def ms2str(v):
"""
Convert a time in milliseconds to a time string.
Arguments:
v: a time in milliseconds.
Returns:
A string in the format HH:MM:SS,mmm.
"""
v, ms = divmod(v, 1000)
v, s = divmod(v, 60)
h, m = divmod(v, 60)
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" | 5,316,922 |
def regroup(X, N):
"""
Regroup the rows and columns in X.
Rows/Columns that are N apart in X are adjacent in Y.
Parameters:
X (np.ndarray): Image to be regrouped
N (list): Size of 1D DCT performed (could give int)
Returns:
Y (np.ndarray): Regoruped image
"""
# if N is a 2-eleme... | 5,316,923 |
def uint_to_two_compl(value: int, length: int) -> int:
"""Convert int to two complement integer with binary operations."""
if value >> (length - 1) & 1 == 0: # check sign bit
return value & (2 ** length - 1)
else:
return value | (~0 << length) | 5,316,924 |
def synthetic_pattern_program():
"""A program that tests pattern matching of `PrimOp` outputs.
Returns:
program: `instructions.Program`.
"""
block = instructions.Block(
[
instructions.prim_op(
[], ("one", ("five", "three")), lambda: (1, (2, 3))),
instructions.prim_op... | 5,316,925 |
def generator(z, out_channel_dim, is_train=True, alpha=0.2):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:param alpha : leaky relu rate
:return: The tens... | 5,316,926 |
def manual_filtration(word, neg_list):
"""作用在 word 上, 若该词为负例则返回 True, 否则返回 False"""
pattern_1 = r',|\.|:|;|"'
pattern_2 = r'行|示|为|较|见|天|音'
pattern_3 = r'切除|标本|摄取|存在|活检|穿刺|开口|引流|胸痛|患者|治疗|不适|受限|疼痛|基本|压缩'
pattern_4 = r'^[A-Za-z0-9_]+$'
remove_word_list = neg_list + ['病理', '癌', '炎', '占位']
... | 5,316,927 |
def two(f):
"""Church numeral 2: same as successor(successor(zero))"""
"*** YOUR CODE HERE ***"
return lambda x: f(f(x)) | 5,316,928 |
def _find_indexes(obj, var_name, min_limit, max_limit, use_dask):
"""
Function to find array indexes where failing limit tests
Parameters
----------
obj : Xarray.Dataset
Dataset containing data to use in test
var_name : str
Variable name to inspect
min_limit : float or numpy... | 5,316,929 |
def test_unit_raises_error(
dev_context: DevAmpelContext, ingest_stock, config, expect_success
):
"""Run is marked failed if units raise an exception"""
dev_context.register_unit(Mutineer)
t3 = T3Processor(context=dev_context, process_name="test", raise_exc=False, **mutineer_process(config))
t3.run(... | 5,316,930 |
def bubble_sort(arr):
"""
冒泡排序 O(n^2)
:param arr:
:return:
"""
for j in range(1, len(arr)):
for i in range(0, len(arr) - j): # 这里不是len(arr) - 1而是len(arr) - j, 因为每一轮遍历都会把每一轮最大元素挪到最后一位
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i] | 5,316,931 |
def asinh_grad(orig, grad):
"""Returns [grad * 1/((1 + (x ^ 2)) ^ (1/2))]"""
x = orig.args[0]
ones = ones_like(x)
return [grad * ones / sqrt(ones + (x * x))] | 5,316,932 |
def runner_discovery():
"""Execute compiler discovery on the builder instance."""
instance = RunnerInstance.instance()
exec_remote_to_stdout(instance, ['bash', '-c', 'cd /infra && sudo /infra/init/do-discovery.sh']) | 5,316,933 |
def find_all(a_str, sub):
"""
Find all occurrences of a substring in a string.
NOTE: I don't understend how it work....
"""
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub) | 5,316,934 |
def inject_test_seed(seed, signature, user_data_dir):
"""Injects the given test seed.
Args:
seed (str): A variations seed.
signature (str): A seed signature.
user_data_dir (str): Path to the user data directory used to launch Chrome.
Returns:
bool: Whether the injection succeeded.
"""
seed_d... | 5,316,935 |
def _scale_stage_depth(stack_args, repeats, depth_multiplier=1.0, depth_trunc='ceil'):
""" Per-stage depth scaling
Scales the block repeats in each stage. This depth scaling impl maintains
compatibility with the EfficientNet scaling method, while allowing sensible
scaling for other models that may have ... | 5,316,936 |
def tokenize(s):
"""
Ковертирует строку в питон список токенов
"""
return s.replace('(',' ( ').replace(')',' ) ').split() | 5,316,937 |
def anonymous_command(update: Update, context: CallbackContext) -> None:
"""Set anonymous status"""
command_words = update.message.text.split()
if len(command_words) == 1:
for user in data['users']:
if user['id'] == update.message.from_user.id:
update.message.reply_text("... | 5,316,938 |
def vote_entropy(votes, classes):
"""Calculates the vote entropy for measuring the level of disagreement in
QBC.
Parameters
----------
votes : array-like, shape (n_samples, n_estimators)
The class predicted by the estimators for each sample.
classes : array-like, shape (n_classes)
... | 5,316,939 |
def drawTravelTimeData(ax, data, t=None):
"""
Draw first arrival traveltime data into mpl ax a.
data of type \ref DataContainer must contain sensorIdx 's' and 'g'
and thus being numbered internally [0..n)
"""
x = pg.x(data.sensorPositions())
# z = pg.z(data.sensorPositions())
... | 5,316,940 |
def create_teacher(teacher_name, teacher_email):
"""
Creates a document in db['teachers']. Happens upon first login.
Parameters:
String teacher_name
String teacher_email
"""
teachers = db['teachers']
if teachers.find_one({'teacher_email': teacher_email}) == None:
new_teac... | 5,316,941 |
def printModelDict(localsDict):
"""Convert serverConfig model configuration to a dictionary. This writes
the dictionary as text. This does not create a usable modelDict, just one to
use to print out the dictionary as python code."""
modelDict={}
parmsDict={}
tcDict={}
dbs=DATABASES
scTe... | 5,316,942 |
def ira_equinox(jd_tdb, equinox, accuracy=0):
"""
To compute the intermediate right ascension of the equinox at
the input Julian date, using an analytical expression for the
accumulated precession in right ascension. For the true equinox,
the result is the equation of the origins.
Parameters
... | 5,316,943 |
def test_updates_url() -> None:
"""Tests if the VSCode updates page works fine"""
links = vscvm.get_vscode_version_links()
assert len(links) != 0 | 5,316,944 |
def load_plugins(plugins_folder, verbose=True):
"""Import all plugins from target folder recursively."""
found_plugins = []
for pack in os.walk(plugins_folder):
for filename in pack[2]:
if "_" == filename[:1] or ".py" != filename[-3:]:
continue
path_to_modu... | 5,316,945 |
def remove_repo_tree(target):
"""Function that removes repository.
Required since removing git repos on windows require a chmod operation.
Parameters
----------
target : str
Dir path to removed repo
"""
if os.path.exists(target) and os.path.isdir(target):
def del_rw(action... | 5,316,946 |
def predict(model_name, models):
"""
Make predictions for a given model.
"""
lib = _configure_from_cli_arguments(models, [model_name], {})
model = lib.get(model_name)
while True:
r = click.prompt(f"[{model_name}]>")
if r:
res = model(json.loads(r))
click.s... | 5,316,947 |
def _generate_steps(
episode: Sequence[Any],
step_fn: Callable[[Dict[str, Any]], Dict[str, Any]]) -> Dict[str, Any]:
"""Constructs a dictionary of steps for the given episode.
Args:
episode: Sequence of steps (envlogger.StepData). Assumes that there is at
least one step.
step_fn: function tha... | 5,316,948 |
def test_event_details_from_json(resource_dir, data, attribute, expected_value):
"""
An EventDetails entity can be created from the JSON data provided by the web api.
"""
json_data = json.loads((resource_dir / "responses" / "event" / data).read_text(encoding="utf-8"))
event_details = EventDetails.fr... | 5,316,949 |
def format_results_data(results_data, compute_rank=True):
"""Formats results_data as sorted list of rows so it can be easily displayed as results_table
Appends user and ranks.
Side effect: This function modifies objects (i.e. individual results)
contained in results_data
"""
Result = namedtuple(... | 5,316,950 |
def encode_triangle(X, centroids):
"""
Perform triangle k-means encoding
"""
X3 = X.reshape(X.shape[0], 1, X.shape[1])
centroids3 = centroids.reshape(1, centroids.shape[0], centroids.shape[1])
z = np.sqrt(((X3 - centroids3) ** 2).sum(2))
means = z.mean(1).reshape(-1, 1)
return np.maximum... | 5,316,951 |
def get_user_and_check_password(username, password):
"""
Called by account controller and/or AuthKit valid_password to return a user from local db
"""
try:
q = Session.query(User).select_from(join(User, UserLogin, User.login_details))
q = q.filter(User.id == make_username(usernam... | 5,316,952 |
def get_db_for_id(id_value):
"""
Work out the database number containing a Review record with pk of
"id_value".
"""
# XXX: If we were interested in being able to add databases and do minimal
# data moving, it would be better to use a consistent hashing algorithm
# here (distribute the result... | 5,316,953 |
def subclass(request):
"""Return a Object subclass"""
try:
params = request.param
except AttributeError:
params = {}
class TestObject(Object):
@property
def fields(self):
return params.get("fields", {})
TestObject.__name__ = params.get("name", "TestObjec... | 5,316,954 |
def test_list_g_month_day_enumeration_2_nistxml_sv_iv_list_g_month_day_enumeration_3_2(mode, save_output, output_format):
"""
Type list/gMonthDay is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/gMonthDay/Schema+Instance/NISTSchema-SV-IV-list-gMonthDay-enumeration-3... | 5,316,955 |
def is_index(file_name: str) -> bool:
"""Determines if a filename is a proper index name."""
return file_name == "index" | 5,316,956 |
def _recv_n_get_rsp(event: "Event") -> List[str]:
"""Logging handler when an N-GET-RSP is received.
Parameters
----------
event : events.Event
The evt.EVT_DIMSE_RECV event that occurred.
"""
msg = event.message
cs = msg.command_set
dataset = "None"
if msg.data_set and msg.d... | 5,316,957 |
def GenerateShardedFilenames(spec): # pylint:disable=invalid-name
"""Generate the list of filenames corresponding to the sharding path.
Args:
spec: Sharding specification.
Returns:
List of filenames.
Raises:
ShardError: If spec is not a valid sharded file specification.
"""
basename, num_sha... | 5,316,958 |
def _tseries_from_nifti_helper(coords, data, TR, filter, normalize, average):
"""
Helper function for the function time_series_from_nifti, which does the
core operations of pulling out data from a data array given coords and then
normalizing and averaging if needed
"""
if coords is not None:
... | 5,316,959 |
def hash_short(message, length=16):
""" Given Hash Function"""
return hashlib.sha1(message).hexdigest()[:length / 4] | 5,316,960 |
def entry_point():
"""Function setup.py links cafe-runner to"""
try:
runner = UnittestRunner()
exit(runner.run())
except KeyboardInterrupt:
print_exception("Runner", "run", "Keyboard Interrupt, exiting...")
os.killpg(0, 9) | 5,316,961 |
def feincms_frontend_editing(cms_obj, request):
"""
{% feincms_frontend_editing feincms_page request %}
"""
if hasattr(request, 'session') and request.session.get('frontend_editing'):
context = template.RequestContext(request, {
"feincms_page": cms_obj,
'FEINCMS_ADMIN_ME... | 5,316,962 |
def run_visualization(url, target_path, skeleton_point=None, skeleton_box=None):
"""Inferences DeepLab model and visualizes result."""
# TODO :: Need to modify url to path
try:
# f = urllib.request.urlopen(url)
# jpeg_str = f.read()
# original_im = Image.open(BytesIO(jpeg_str))
original_im = Ima... | 5,316,963 |
def _add_tensor_cores(tt_a, tt_b):
"""Internal function to be called from add for two TT-tensors.
Does the actual assembling of the TT-cores to add two TT-tensors.
"""
ndims = tt_a.ndims()
dtype = tt_a.dtype
shape = shapes.lazy_raw_shape(tt_a)
a_ranks = shapes.lazy_tt_ranks(tt_a)
b_ranks = shapes.lazy_... | 5,316,964 |
def generictest(e):
"""Documentation"""
if e.skip:
pytest.xfail("%s skipped, known issue" % e.name)
g = rdflib.Graph()
for i in [rdf, rdfs, xsd, owl, test, n3test, rdft, triage, mf, qt]:
g.bind(str(i), i)
g.parse(e.file, format="n3") | 5,316,965 |
def create_mosaic_iterative(dataset_in, clean_mask=None, no_data=-9999, intermediate_product=None):
"""
Description:
Creates a most recent - oldest mosaic of the input dataset. If no clean mask is given,
the 'cf_mask' variable must be included in the input dataset, as it will be used
to create... | 5,316,966 |
def dicom_file_loader(
accept_multiple_files: bool, stop_before_pixels: bool
) -> Sequence["pydicom.Dataset"]:
"""A Streamlit component that provides DICOM upload functionality.
Parameters
----------
accept_multiple_files : ``bool``
Whether or not the wrapped
`st.file_uploader <http... | 5,316,967 |
def get_substrings(source: str):
"""Get all substrings of a given string
Args:
string (str): the string to generate the substring from
Returns:
list: list of substrings
"""
# the number of substrings per length is the same as the length of the substring
# if the characters are... | 5,316,968 |
def _write_output_csv(reader: csv.DictReader, writer: csv.DictWriter,
config: dict) -> list:
"""Reads each row of a CSV and creates statvars for counts of
Incidents, Offenses, Victims and Known Offenders with different bias
motivations.
Args:
reader: CSV dict reader.
... | 5,316,969 |
def set_requires_grad(nets, requires_grad=False):
"""Set requies_grad=Fasle for all the networks to avoid unnecessary computations
Parameters:
nets (network list) -- a list of networks
requires_grad (bool) -- whether the networks require gradients or not
"""
if not isinstance(nets, list):
... | 5,316,970 |
def get_vehicle_lay_off_engine_acceleration(carla_vehicle):
"""
Calculate the acceleration a carla vehicle faces by the engine on lay off
This respects the following forces:
- engine brake force
:param carla_vehicle: the carla vehicle
:type carla_vehicle: carla.Vehicle
:return: acceleratio... | 5,316,971 |
def create_data(name: str) -> Dict[str, Any]:
"""Arbitrary function that returns a dictionary.
This demonstration uses pydantic, but any dictionary can be tested!
"""
return User(id=sys.maxsize, name=name).dict() | 5,316,972 |
def _run_docker_shell_script(script_name, docker_dir, trailing_args=None,
env_variables=dict()):
"""
script_name (String) filename of a script in the nest/docker/ directory
docker_dir (String) directory of docker scripts in the nest repo. expected
to be /code_live/docker, but may be different is... | 5,316,973 |
def _create_functional_connect_edges_dynamic(n_node, is_edge_func):
"""Creates complete edges for a graph with `n_node`.
Args:
n_node: (integer scalar `Tensor`) The number of nodes.
is_edge_func: (bool) callable(sender, receiver) that returns tf.bool if connected. Must broadcast.
Returns:
A di... | 5,316,974 |
def _BreakoutFilesByLinter(files):
"""Maps a linter method to the list of files to lint."""
map_to_return = {}
for f in files:
extension = os.path.splitext(f)[1]
if extension in PYTHON_EXTENSIONS:
pylint_list = map_to_return.setdefault(_PylintFiles, [])
pylint_list.append(f)
elif extension... | 5,316,975 |
def simulateBERParallel(codes, channelfun, params, printValue=True):
"""
Simulates BER values at multiple SNRs, where the massively parallel algorithm is used. This implementation is especially designed for cupy.
Args:
codes (ndarray): an input codebook, which is generated on the CPU memory and is ... | 5,316,976 |
def modify_app_description(s, base_url, app_id, description):
"""
Modifies the description of an app
"""
rjson = app_full(s, base_url, app_id)[1]
rjson["modifiedDate"] = str(
((datetime.today()) + timedelta(days=1)).isoformat() + "Z"
)
rjson["description"] = description
data = ... | 5,316,977 |
def main(arv=None):
"""ebs-snapper command line interface."""
# Check for Python 2.7 (required for Lambda)
if not (sys.version_info[0] == 2 and sys.version_info[1] == 7):
raise RuntimeError('ebs-snapper requires Python 2.7')
# allow 90m for the cli, instead of lambda's 5
CTX.set_remaining_t... | 5,316,978 |
def search_tag(resource_info, tag_key):
"""Search tag in tag list by given tag key."""
return next(
(tag["Value"] for tag in resource_info.get("Tags", []) if tag["Key"] == tag_key),
None,
) | 5,316,979 |
def compute_GARCH_price(theta,
num_periods,
init_price,
init_sigma,
risk_free_rate,
num_simulations=50000):
"""
Compute asset price at period t + s (s periods ahead) given estimated theta... | 5,316,980 |
def create_order_nb(size: float,
price: float,
size_type: int = SizeType.Amount,
direction: int = Direction.All,
fees: float = 0.,
fixed_fees: float = 0.,
slippage: float = 0.,
min... | 5,316,981 |
def from_sample(sample):
"""Upload results of processing from an analysis pipeline sample.
"""
upload_config = sample.get("upload")
if upload_config:
approach = _approaches[upload_config.get("method", "filesystem")]
for finfo in _get_files(sample):
approach.update_file(finfo,... | 5,316,982 |
def topological_sort(graph: DiGraph[K, N, E], sorting_key: t.Optional[t.Callable[[K], Comparable]] = None) -> t.Iterator[K]:
""" Calculate the topological order for elements in the *graph*.
@raises RuntimeError: If there is a cycle in the graph. """
seen: set[K] = set()
roots = graph.roots
while roots:
... | 5,316,983 |
def transform_style_bold_italic(soup, tag):
"""
Replace the input tag name with `b` and a child of `i` and remove style attr
"""
new_b_tag = soup.new_tag("b")
new_i_tag = soup.new_tag("i")
new_i_tag.string = tag.text
new_b_tag.append(new_i_tag)
tag.replace_with(new_b_tag) | 5,316,984 |
def generate_noise_2d_fft_filter(F, randstate=None, seed=None, fft_method=None,
domain="spatial"):
"""Produces a field of correlated noise using global Fourier filtering.
Parameters
----------
F : dict
A filter object returned by
:py:func:`pysteps.noise... | 5,316,985 |
def _get_image_files_and_labels(name, csv_path, image_dir):
"""Process input and get the image file paths, image ids and the labels.
Args:
name: 'train' or 'test'.
csv_path: path to the Google-landmark Dataset csv Data Sources files.
image_dir: directory that stores downloaded images.
Returns:
i... | 5,316,986 |
def test_save(tmpdir):
""" For the save test we are using the tmpdir fixture
as we don't want to save the data permanently
https://docs.pytest.org/en/latest/tmpdir.html
"""
file_path = tmpdir.mkdir("recap").join("statistics.html")
file_path_correct = os.path.join(basepath, "data", "stat... | 5,316,987 |
def get_spending_features(txn, windows_size=[1, 7, 30]):
"""
This function computes:
- the cumulative number of transactions for a customer for 1, 7 and 30 days
- the cumulative average transaction amount for a customer for 1, 7 and 30 days
Args:
txn: grouped transactions of custome... | 5,316,988 |
def break_up(expr):
"""
breaks up an expression with nested parenthesis into sub expressions with
no parenthesis, with the innermost expressions first, that needs to be
calculated before doing the outer expression. also replaces the statement with
a single symbol in the larger expression
"""
p=0
new_ex... | 5,316,989 |
def fft_operation(file_path):
"""
FFT operation
:param file_path: Original wav file path
:return: freqs, 20 * log10(fft/max_fft), name
"""
wave_data, nchannels, sample_width, framerate, numframes = read_file(file_path)
abs_fft = np.abs(np.fft.fft(wave_data))
normalized_abs_fft ... | 5,316,990 |
def _expand_expected_codes(codes):
"""Expand the expected code string in set of codes.
200-204 -> 200, 201, 202, 204
200, 203 -> 200, 203
"""
retval = set()
for code in codes.replace(',', ' ').split(' '):
code = code.strip()
if not code:
continue
elif '-' i... | 5,316,991 |
def predict(
seq: np.ndarray,
aa_cut: Optional[np.ndarray] = None,
percent_peptide: Optional[np.ndarray] = None,
model: Optional[GradientBoostingRegressor] = None,
model_file: Optional[Path] = None,
pam_audit: bool = True,
length_audit: bool = False,
learn_options_override: Optional[dict... | 5,316,992 |
def _is_proper_sequence(seq):
"""Returns is seq is sequence and not string."""
return (isinstance(seq, collections.abc.Sequence) and
not isinstance(seq, str)) | 5,316,993 |
def sigmoid(mat, target = None):
"""
Apply the logistic sigmoid to each element of the matrix mat.
"""
if not target:
target = mat
err_code = _cudamat.apply_sigmoid(mat.p_mat, target.p_mat)
if err_code:
raise generate_exception(err_code)
return target | 5,316,994 |
def mutation_modify_controlaction(controlaction_id: str, actionstatus: ActionStatusType, error: str = None):
"""Returns a mutation for modifying the status and errors of the ControlAction
Arguments:
controlaction_id: The unique identifier of the ControlAction.
actionstatus: the status to update ... | 5,316,995 |
def test_sysargv_set():
"""Test: confirm that sys.argv is mocked appropriately with the test command"""
# set the sys.argv
set_sys_argv()
assert sys.argv == ['executable', 'subcmd', '-s', '--long', '-n', 'shortdef', '--name', 'longdef', '--nameeq=longdefeq', 'lastpos'] | 5,316,996 |
def savefig(Location, bbox_inches='tight', pad_inches=0.1, dpi=300):
"""Saves plots specified by Location and closes all plots to reduce the memory usage"""
plt.savefig(Location, bbox_inches=bbox_inches, pad_inches=pad_inches, dpi=dpi)
plt.close()
plt.clf() | 5,316,997 |
def get_colours(time, flux, data, nuv=[nuvwave, nuvtrans], u=[uwave, utrans], r=[rwave, rtrans], filter_pairs=None):
"""" Calculates the colours of a given sfh fluxes across time given the BC03 models from the magnitudes of the SED.
:time:
Array of times at which the colours should be calcu... | 5,316,998 |
def loginpage():
"""A route to login the user."""
year = date.today().year
return render_template("website/login.html",
base=get_base_data(year),
route=Routes,
year=year,
github_enabled=is_github_supp... | 5,316,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.