content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def state_space_tree(
sequence: List[Union[int, str]],
current_sequence: List[Union[int, str]],
index: int,
index_used: List[int],
) -> None:
"""
Membuat pohon ruang untuk iterasi melalui setiap cabang menggunakan DFS.
Kita tahu bahwa setiap negara memiliki persis len (urutan) - anak-anak i... | 77,900 |
def parse_units(units_str):
"""
Extract and parse the units
Extract the bounds over which the expression is assumed to apply.
Parameters
----------
units_str
Returns
-------
Examples
--------
>>> parse_units('Widgets/Month [-10,10,1]')
('Widgets/Month', (-10,10,1))
... | 77,901 |
def _read_method(schema):
"""Add a write method for named schema to a class.
"""
def func(
self,
filename=None,
data=None,
add_node_labels=True,
combine_on='index',
use_uids=True,
**kwargs):
# Use generic write class to write data.
df0 ... | 77,902 |
def mark_nb_animals_neighbors(neighbors: List[List[int]], w: int, h: int, nb_animals: int, animal_type: str) \
-> ClausesBase:
"""
Permet d'ajouter des contraintes concernant le nombre d'animaux autour d'une cellule
:param neighbors: Liste des cordonnées des cellules voisines
:param w: largeur d... | 77,903 |
def setup_app(command, conf, variables):
"""Place any commands to setup civicboom here"""
if not pylons.test.pylonsapp: # pragma: no cover -- "if not testing" will not be true for testing...
load_environment(conf.global_conf, conf.local_conf)
#######################################################... | 77,904 |
def counter_clear():
"""
计数器清零(每天0点)
:return:
"""
rk_counter_client.clear() | 77,905 |
def predict_next_daterange(dateranges, min_probability=0.8):
""" Takes a list of dateranges (start, end) and tries to predict the next
daterange in the list.
See :func:`predict_next_value` for more information.
"""
return predict_next_value(
values=dateranges,
min_probability=min_... | 77,906 |
def delete_nodenet(nodenet_uid):
"""Unloads the given nodenet from memory and deletes it from the storage.
Simple unloading is maintained automatically when a nodenet is suspended and another one is accessed.
"""
import shutil
if nodenet_uid in nodenets:
unload_nodenet(nodenet_uid)
del ... | 77,907 |
def resize_activations(v, so):
"""
Resize activation tensor 'v' of shape 'si' to match shape 'so'.
:param v:
:param so:
:return:
"""
si = list(v.size())
so = list(so)
assert len(si) == len(so) and si[0] == so[0]
# Decrease feature maps.
if si[1] > so[1]:
v = v[:, :so... | 77,908 |
def write(array, filename, flags=0):
"""Write a (height, width) or (height, width, nchannels) array to
a greyscale, RGB, or RGBA image, with file type deduced from the
filename.
The `flags` parameter should be one or more values from the IoFlags
class defined in this module, or-ed together with | as... | 77,909 |
def show_model(model:nn.Module):
"""
Render graphviz representation of neural network model
"""
hl_graph = hl.build_graph(model, torch.zeros([1, 3, 224, 224]))
hl_graph.theme = hl.graph.THEMES["blue"].copy()
return hl_graph | 77,910 |
def seg_pixel_accuracy_nd(label_imask,
pred_imask,
vague_idx=-1,
use_vague=False,
macro_average=True,
empty_result=0.0):
"""
The segmentation pixel accuracy (for MXNet nd-arrays).
... | 77,911 |
def record_audio(record_len, filename):
"""
records an audio clip from the default input device
@params: length: the length of recorded audio [seconds]
filename: the ouput filename
"""
try:
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
... | 77,912 |
def cylinder(*args, **kwargs):
"""
The cylinder command creates a new cylinder and/or a dependency node that creates one, and returns their names.
Returns: `string[]` Object name and node name
"""
pass | 77,913 |
async def test_call_homegraph_api_retry(hass, aioclient_mock, hass_storage):
"""Test the that the calls get retried with new token on 401."""
config = GoogleConfig(hass, DUMMY_CONFIG)
await config.async_initialize()
with patch(
"homeassistant.components.google_assistant.http._get_homegraph_toke... | 77,914 |
def mesh_planarize_faces_igl(mesh, fixed=None, kmax=100, callback=None, callback_args=None):
"""Planarise a set of connected faces.
Planarisation is implemented as a two-step iterative procedure. At every
iteration, faces are first individually projected to their best-fit plane,
and then the vertices a... | 77,915 |
def getCoursesFromModels():
"""This method imports and inspects Models.py file and adds name of its classes to the list.
User class is skipped so it is not added into list of courses.
Returns:
list: List of string names of classes in Models.py file.
"""
coursesList = []
mod = importlib... | 77,916 |
def logResults(X,A,B,C,N):
"""
Function to log results for debugging purposes.
Parameters
----------
X: np.ndarray, dim=2
Optimized results as yielded by constrainedMinimize(...)
A: 2D numpy.ndarray
B: numpy.array
C: float
describe the cost function used for fitting... | 77,917 |
def render_error_code(response, error_code):
""" Outputs an error code to be read by the client application """
response.headers['Content-Type'] = 'text/plain'
response.out.write(error_code) | 77,918 |
def ds_ctx_common_config_settings(config):
"""
This function describes a base config setup for all models.
"""
assert(isinstance(config, DefaultNetworkConfig))
# Apply classic settings
classic_ctx_common_config_settings(config)
# Increasing memory limit consumption
config.modify_gpu_me... | 77,919 |
def test_config_base_parse_yaml_file01(tmpdir):
"""
API: ConfigBase.parse_yaml_file (#1)
"""
t = tmpdir.mkdir("empty-file").join("apprise.yml")
t.write("")
# Create ourselves a config object
ac = AppriseConfig(paths=str(t))
# The number of configuration files that exist
assert len... | 77,920 |
def format_message(article_dict):
"""
From a dictionary of randomly selected articles, create and
format a message string.
"""
msg = ""
for subject in article_dict:
url = article_dict[subject][1]
abstract, authors = get_abstract(url)
msg = msg + "<h2>" + subject + "</h2>... | 77,921 |
def test_alpha_tiling():
"""Transformation of images with an alpha channel preserve transparency, even when a tiling strategy is used"""
tmpdir = TemporaryDirectory()
# Transform image with alpha
styletransfer([CONTENTS + "dockersmallalpha.png"], [STYLES + "cubism.jpg"], tmpdir.name, alg="chen-schmidt-i... | 77,922 |
def test_get_asset_view_with_vulnerability_summary_async(cbcsdk_mock):
"""Test Get Asset View with Vulnerability Summary"""
cbcsdk_mock.mock_request("POST",
"/vulnerability/assessment/api/v1/orgs/test/devices/vulnerabilities/summary/_search",
GET_ASSET_V... | 77,923 |
def lock_nqueuedjobs(cur, nrows):
"""
Function to lock first N rows for futher processing
:param nrows:
:return: lock_time
"""
lock_time = datetime.now().strftime(defaultDatetimeFormat)
lquery = """UPDATE atlas_pandabigmon.art_results_queue
SET IS_LOCKED = 1,
... | 77,924 |
def extract_seed(path, key):
""" Scrape the 5-character seed from the path and return it as an integer.
:param path: path to the tsv file containing results
:param key: substring preceding the seed, "batch-train" for splits, seed-" for shuffles
"""
try:
i = path.find(key) + len(key)
... | 77,925 |
def UTC2JD1JD2(epoch: datetime.datetime):
"""
:param epoch:
:return:
"""
return astropyTime(epoch, format='datetime', scale='ut1').jd1, astropyTime(epoch, format='datetime', scale='ut1').jd2 | 77,926 |
def test_solver():
"""Check 1st order convergence rate."""
m = 4; b = 0.1
s = lambda u: 2*u
f = lambda v: b*v
import sympy as sym
def ode(u):
"""Return source F(t) in ODE for given manufactured u."""
print 'ode:', m*sym.diff(u, t, 2), f(sym.diff(u,t)), s(u)
return m*sym.... | 77,927 |
def serve():
"""Serve models"""
config = dg.Config()
server_klass = config.get('server.class', None)
if server_klass:
server = get_object(server_klass)()
else:
server = dg.Server()
server.run() | 77,928 |
def spawn(n):
"""
Spawn a list of SeedSequence from the global seed sequence.
Parameters
----------
n : int
Number of seed sequences to spawn
Returns
-------
seed_seq : list
List of spawned seed sequences
"""
return _GLOBAL_SEED_SEQ.spawn(n) | 77,929 |
def compile(code: list, consts: list, names: list, varnames: list,
func_name: str = "<unknown, compiled>",
arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True):
"""
Compiles a set of bytecode instructions into a working function, using Python's bytecode
... | 77,930 |
def get_certificates(country=None):
"""
This function retrieves all the data stored in `certificates.csv` file, which previously was retrieved from
Investing.com. Since the resulting object is a matrix of data, the certificate's data is properly structured
in rows and columns, where columns are the ce... | 77,931 |
def f_t(x_tm1, potential_function, parameters, dt, **kwargs):
"""
NOTE : parameters should reflect potential function at time t (not t-1)
compute f_t(x_tm1) = x_tm1 + 0.5 * dt * forcet(x_tm1) = mu
arguments
x_tm1 : np.array(N)
positions at time t-1
potential_function : funct... | 77,932 |
def read_history_file(filename=None): # real signature unknown; restored from __doc__
"""
read_history_file([filename]) -> None
Load a readline history file.
The default filename is ~/.history.
"""
pass | 77,933 |
def get_neighbor_dict_from_table(db, table_name):
"""
returns a dict with bgp neighbor ip as key and neighbor name as value
:param table_name: config db table name
:param db: config_db
"""
neighbor_dict = {}
neighbor_data = db.get_table(table_name)
try:
for entry in neighbor_data... | 77,934 |
def french_to_english(french_text):
"""This function translates text in french to english"""
if french_text == "":
return ""
english_text = language_translator.translate(text=french_text, model_id='fr-en').get_result()
english_text = english_text.get("translations")[0].get("translation")
re... | 77,935 |
def highlight_cycles(dot_stream, cycle_list):
"""Highlight the include cycles in red."""
for cycle in cycle_list:
cycle_edges = determine_cycle_edges(cycle)
for edge in cycle_edges:
regex = fr'([<"]{edge[0]}[">] -> [<"]{edge[1]}[">])'
match = re.search(regex, dot_stream)... | 77,936 |
def find_role_similarity(roles, i, j, parameters=None):
"""
Calculate a number of similarity between different roles
Parameters
-------------
roles
List of roles
i
Index of the first role
j
Index of the second role
parameters
Parameters of the algorithm
... | 77,937 |
def histogram_matching(mov_scan, ref_scan,
histogram_levels=2048,
match_points=100,
set_th_mean=True):
"""
Histogram matching following the method developed on
Nyul et al 2001 (ITK implementation)
inputs:
- mov_scan: np.array cont... | 77,938 |
def configure_vrrp(module, csv_data):
"""
Method to configure VRRP L3.
:param module: The Ansible module to fetch input parameters.
:param csv_data: String containing vrrp data passed from csv file.
:return: Output string of configuration.
"""
output = ''
vnet_name = get_global_vnet_name... | 77,939 |
def update_priorities(repo, username=None, namespace=None):
"""Update the priorities of a project."""
repo = flask.g.repo
form = pagure.forms.ConfirmationForm()
error = False
if form.validate_on_submit():
weights = [
w.strip()
for w in flask.request.form.getlist("p... | 77,940 |
async def test_total_update_timeout(hass: HomeAssistant, sensor):
"""Test if it raises an error when there is a timeout."""
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
config_entry.add_to_hass(hass)
with patch(
"peco.PecoOutageApi.get_outage_totals",
side_effect=... | 77,941 |
def find_post(url: str) -> Union[Album, None]:
"""Find post with twitter id in the url
Args:
url (str): twitter url
Returns:
Union[Album, None]: Album
"""
return Album.first(F['source.url'].regex(r'https://twitter.com/.*/status/' + url.split('/')[-1])) | 77,942 |
def serialize_categories_ical(category_ids, user, event_filter=True, event_filter_fn=None, update_query=None):
"""Export the events in a category to iCal.
:param category_ids: Category IDs to export
:param user: The user who needs to be able to access the events
:param event_filter: A SQLalchemy criter... | 77,943 |
def process_intf_counters_rest_output(data, single_port=False):
"""
Author: Jagadish Chatrasi (jagadish.chatrasi@broadcom.com)
:param data:
:type dict:
:param single_port:
:type bool:
:return:
:rtype:
"""
ret_val = []
try:
if single_port:
actaul_data = dat... | 77,944 |
def create_attribute(name, snake_case=True):
"""
Gets an attribute name from the enum and convert it to snake_case, by
default, or to CamelCase
"""
# Removes any hyphens or dots from the name, substituting by an underscore
name_normalized = re.sub('[-.]', '_', name)
if snake_case:
na... | 77,945 |
def preprocessing_fn(inputs):
"""Preprocesses Covertype Dataset."""
outputs = {}
# Scale numerical features
for key in features.NUMERIC_FEATURE_KEYS:
outputs[features.transformed_name(key)] = tft.scale_to_z_score(
_fill_in_missing(inputs[key]))
# Generate vocabularies and maps categorical featu... | 77,946 |
def build_model(gridsearch=False):
"""
Create a classification model
:param gridsearch: bool. Activate GridSearch, default = False
:return: pipeline
"""
# Create pipeline with Classifier
moc = MultiOutputClassifier(RandomForestClassifier())
pipeline = Pipeline([
('vect', Coun... | 77,947 |
def main():
""" Starts the sound server, which retains the audio data inside
its process space, and forks out workers when web connections are
made.
"""
t = Thread(target = get_audio_data, args = ())
t.daemon = True
t.setDaemon(True)
t.start()
app.debug = True
app.run() | 77,948 |
def get_cells_to_calculate_variance(file_path, percentage_of_extreme_cells=15):
"""
Get a list of cells to use to calculate the methylation and variance
In this case we have a list of all cells that might be possible and the avg methylation and variance of
them and we want to take the percentage to take... | 77,949 |
def device_smart_capabilities(device):
"""Returns SMART capabilities of the given device.
Args:
device: (Device) Device in question.
Returns:
(tuple): tuple containing:
(bool): True whenever SMART is available, False otherwise.
(bool): True whenever SMART is enable... | 77,950 |
def slice_arrays(arrays, start=None, stop=None):
""" Function extracted from Keras - check keras.utils.generic_utils
for the original version.
Slices an array or list of arrays.
This takes an array-like, or a list of
array-likes, and outputs:
- arrays[start:stop] if `arrays` is an array-lik... | 77,951 |
def test_with_exit(exit_code):
""" We parametrize over the first few exit codes to
ensure they are all handled the same. `utils.with_exit`
should always raise, even in the case where `foo` ran
successfully (`exit_code==0`). """
@utils.with_exit
def foo():
return exit_code
with pytes... | 77,952 |
def load_data_sample(fn):
"""
:param fn:
:return: samples: 1D: n_docs, 2D: n_utterances, 3D: elem=(time, speaker_id, addressee_id, response, ... , label)
"""
samples = []
sample = []
with gzip.open(fn, 'rb') as gf:
for line in gf:
line = line.rstrip().split("\t")
... | 77,953 |
def generate_genpybind_source(self):
"""
Run genpybind on the headers provided in `source` and compile/link the
generated code instead. This works by generating the code on the fly and
swapping the source node before `process_source` is run.
"""
# name of module defaults to name of target
m... | 77,954 |
def calc_buckets(
start: float,
upper_bound: float,
/,
*,
increment_ratio: float = 1.20
) -> tuple[float, ...]:
"""Calculate histogram buckets on a logarithmic scale."""
# See https://amplitude.com/blog/2014/08/06/optimal-streaming-histograms
# for more details.
result: list[float] =... | 77,955 |
def ximp(N, i, real=False, polar=False, show_x=False, v=1, unwrap=False,
get=False):
"""Impulse(s); form e.g. square wave"""
if not isinstance(i, (list, tuple, np.ndarray)):
i = [i]
i = [(idx if idx >= 0 else N + idx) for idx in i]
x = np.array([(v if n in i else 0) for n in range(N)])
... | 77,956 |
def assert_allclose(
actual: float, desired: numpy.float64, err_msg: Literal["(-10, 1.0) ld None"]
):
"""
usage.scipy: 1
"""
... | 77,957 |
def test_slice_begin_size_tensor_grad():
"""
/// Feature: Slice op dynamic shape
/// Description: Slice backward with dynamic shape
/// Expectation: Euqal to expected value
"""
if sys.platform != 'linux':
return
dy = Tensor(np.array([1, 2, 3, 4]), mstype.float32)
x = Tensor(
... | 77,958 |
def submit_add_process_definition(self):
"""Side effect for adding process definition name to global variable."""
process_definition_name.add(self.name) | 77,959 |
def test_deeply_nested_optional_parameter_groups():
"""Same as above test, but deeper hierarchy."""
grandparent: GrandParent = GrandParent.setup()
assert grandparent.niece == None
assert grandparent.nefew == None
grandparent: GrandParent = GrandParent.setup("--niece.child.name Bob")
assert gran... | 77,960 |
def quantizer(forward_number=None, backward_number=None,
forward_rounding="stochastic", backward_rounding="stochastic",
clamping_grad_zero=False, backward_hooks=[]):
"""
Creates a quantization function to support quantizing forward and backward process differently.
Args:
... | 77,961 |
def test_click_in_text_disables_affix_search(client):
"""
The Click-in-Text API should NOT return affix results — too many results!
e.g.,
> search?q=wapamew
should return "wâpamêw" but NOT "asawâpamêw"
"""
click_in_text_response = client.get(
reverse("cree-dictionary-word-click-in-... | 77,962 |
def dumpinfo(id0):
""" print various infos on the idb file """
def ftstring(ft):
if 0 < ft < len(filetypelist):
return "%02x:%s" % (ft, filetypelist[ft])
return "%02x:unknown" % ft
def decodebitmask(fl, bitnames):
l = []
knownbits = 0
for bit, name in enu... | 77,963 |
def is_size_lower_or_equal(size_a: str, size_b: Size):
"""Returns true if size_a is lower or equal than size_b"""
return int(size_a) <= int(size_b.get_value(Unit.MebiByte)) | 77,964 |
def incd_product(*args):
"""
Like `itertools.product` but returns the first modified index (which was
incremented) along with the product tuple itself.
Parameters
----------
*args : iterables
Any number of iterable things that we're taking the product of.
Returns
-------
it... | 77,965 |
def from_hexpoints(s):
"""Parses a string from its codepoints as hex.
Given a string containing one or more code points (as hex values),
parse it to a a string. For example, the input "006E 006F" produces
output "no".
"""
return "".join([chr(int(cp, 16)) for cp in s.split()]) | 77,966 |
def hamming_distance(s1, s2):
""" Defines the minimum number of substitutions required to change one
string into another.
"""
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal lenght.")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) | 77,967 |
def get_pure_function(fcn) -> PureFunction:
"""
Get the pure function form of the function or method ``fcn``.
Arguments
---------
fcn: function or method
Function or method to be converted into a ``PureFunction`` by exposing
the hidden parameters affecting its outputs.
Returns
... | 77,968 |
def img_brighten(img, factor):
"""
Increase the brightness of the input img
:param img: input img
:param factor: the degree of increasing the brightness
:return: output img
"""
img2 = img * factor
img2 = np.clip(img2, 0, 255)
return img2 | 77,969 |
def choose_random_action(all_actions: int) -> int:
"""
Chooses one of the possible actions in the environment randomly
Parameters
----------
all_actions: int
number of all possible actions available
Returns
-------
int
random action number
"""
return np.random.r... | 77,970 |
def _write_package_json(pkg, revision):
""" Write package.json locally.
:param pkg: the package being installed
:type pkg: Package
:param revision: the package revision to install
:type revision: str
:rtype: None
"""
pkg_dir = package_dir(pkg.name())
package_path = os.path.join(pk... | 77,971 |
def display_training_results(results: TrainingResults) -> None:
"""
Display a GUI window showing how the loss and accuracy progressed through the training epochs.
"""
epochs_range = range(results.epochs_count)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, results.ac... | 77,972 |
def generate_equi_width_buckets(quantiles: List[float],
finite_min: float,
finite_max: float,
total_count: float,
num_buckets: int) -> List[Bucket]:
"""Generate buckets for equi-width histog... | 77,973 |
def test_W_out_shape_onlystates():
"""check shape of W_out when trained without input and bias (fit_only_states=True)"""
data = load_mackeyglasst17().reshape(-1, 1)
trainlen = 100
esn = ESNGenerator(
n_reservoir=50,
fit_only_states=True,
random_state=42,
).fit(None, data[:tra... | 77,974 |
def turnover_knee(f, log10_A, gamma, lfb, lfk, kappa, delta):
"""
Generic turnover spectrum with a high-frequency knee.
:param f: sampling frequencies of GWB
:param A: characteristic strain amplitude at f=1/yr
:param gamma: negative slope of PSD around f=1/yr (usually 13/3)
:param lfb: log10 tra... | 77,975 |
def basicFitness(individual, env):
"""
The trivial case, where fitness is just the result of passing through
the environment.
"""
return individual.result | 77,976 |
def map_reward(const=1.0) -> MapReward:
"""
Factory for map_reward argument in GPMultiFidelitySearcher.
"""
def const_minus_x(x):
return const - x
return MapReward(forward=const_minus_x, reverse=const_minus_x) | 77,977 |
def check_for_daemon(limit=10, delay=0.1, timeout=0.1, port=TCP_GIT_PORT):
"""Check for a running TCP daemon.
Defaults to checking 10 times with a delay of 0.1 sec between tries.
Args:
limit: Number of attempts before deciding no daemon is running.
delay: Delay between connection attempts.
... | 77,978 |
def get_acknowledgements():
"""Returns a list of individuals who are acknowledged on the
``about`` page.
The list is generated by reading in the contents of the ``jwql``
``README`` file. In this way, the website will automatically
update with updates to the ``README`` file.
Returns
------... | 77,979 |
def comb_extend(comb, minv, maxv):
"""Extend the comb to minv and maxv"""
# TODO should this truncate if minv>minc or maxc>maxc
# print y_comb
# Find sort order of comb, convert to ascending
reversed = False
if comb[0] > comb[-1]:
comb.reverse()
reversed = True
# Find min and... | 77,980 |
def evaluate_recall(gt_rels, gt_boxes, gt_classes,
pred_rels, pred_boxes, pred_classes, rel_scores=None, cls_scores=None,
iou_thresh=0.5, phrdet=False):
"""
Evaluates the recall
:param gt_rels: [#gt_rel, 3] array of GT relations
:param gt_boxes: [#gt_box, 4] array... | 77,981 |
def test_init(runner, auth_responses, projects_responses):
"""Test project initialization."""
result = runner.invoke(cli.cli, [
'login', 'http://example.com', '--username', 'demo', '--password',
'demo'
])
assert result.exit_code == 0
# 0. must autosync
result = runner.invoke(cli... | 77,982 |
def storage():
"""Manage user storage.""" | 77,983 |
def solution_name() -> str:
"""
Get the Solution Name from environment variable
:return: the solution name
"""
return os.environ["SOLUTION_NAME"] | 77,984 |
def write_feature_on_index(feat, chrom, start, stop, sign, stranded_genome_index):
""" Write one new line in the stranded index file and, if necessary, the unstranded index file. """
grouped_by_biotype_features = []
for biotype, categs in feat.iteritems():
categ_list = []
for cat in set(cate... | 77,985 |
def not_found(arg):
"""Page not found."""
return render_template('404.html', title='404 error.', message='Page Not Found') | 77,986 |
def mte_unobserved(
X, Y, b0, b1_b0, prop_score, bandwidth, gridsize, startgrid, endgrid
):
"""
This function computes the unobserved component of the MTE
in MTE = mte_x + *mte_u*, where *mte_u* depends on the unobserved
esistance to treatment u_D.
Parameters
----------
X: pandas.DataFr... | 77,987 |
def wavepacket(m, x0, p0):
"""Generates normalized Gaussian wavepacket in position and momentum space.
Parameters
----------
m : int
Number of planck cells in one direction.
x0 : float
Initial x-coordinate of localized wavepacket in position space.
p0 : float
... | 77,988 |
def while_Right_faced_equilataral_angle_Triangle():
""" pattern for : Right_faced_equilataral_angle_Triangle"""
i=0
while i<7:
j=0
while j<4:
if j==0 or i==j or i+j==6:
print('*',end=' ')
else:
print(' ',end=' ')
j... | 77,989 |
def make_key_with_salt(seed, salt):
"""generates a key from a given seed, returns the key and a salt
Args:
seed
Returns:
signing key, a salt
Raises:
assertion failure if the signature is not verified
"""
ecdsa_seed = hash_256(seed + salt)
secexp = randrange_from_se... | 77,990 |
def find_missing_integer(arr):
"""
Find the first missing integer in unsorted array of integers
"""
# segregate integers, with negative (including zero) on right and positives
# on left
left = 0
right = len(arr) - 1
while left < right:
if arr[left] > 0:
left += 1
... | 77,991 |
def TypeString(string_to_type,
use_modifiers=False,
keystroke_time=0,
time_between_keystrokes=0):
"""Simulate typing a string on the keyboard.
Args:
string_to_type: the string to print
use_modifiers: specifies whether the following modifier characters
s... | 77,992 |
def PrintFiles(filelist,filename="EnergyDeposition.csv",
tParse=GetThickness,histKey='eDepHist'):
""" PlotFiles
Prints the files files contained in filelist
Keywords:
"""
ws = wb.create_sheet()
ws.title = sheetTitle
row = 0
col = 0
longName = ['Energy','Frequency','Error']
units =['MeV','Particl... | 77,993 |
def insert_as_next_node(current_node,
new_node):
"""
inserts the new node that needs to be inserted after the current node
"""
if current_node.has_next():
temp_holder = current_node.get_next()
current_node.set_next(new_node)
new_node.set_next(temp_holder)... | 77,994 |
def test_payment_statuses_are_restored( # pylint: disable=unused-argument
raiden_network, token_addresses, network_wait
):
""" Test that when the Raiden is restarted, the dictionary of
`targets_to_identifiers_to_statuses` is populated before the transport
is started.
This should happen because if a... | 77,995 |
def break_weights(weights):
"""
Breaks the weights for the different nodes
:param weights:
:return:
"""
bias_node_hidden = weights[4:6]
bias_node_hidden = np.reshape(bias_node_hidden, (2, 1))
bias_node_output = np.reshape(weights[8], (1, 1))
weights_input = weights[0:4]
weights... | 77,996 |
def set_serial_read_buffer(data):
"""Sets the r buffer to data (a bytes object)."""
if data and not isinstance(data, (bytes, bytearray)):
raise TypeError('data must by a bytes or bytearray object.')
with SERIAL_READ_LOCK:
global SERIAL_READ_BUFFER
SERIAL_READ_BUFFER = io.BytesIO(data... | 77,997 |
def get_movies(genre: str):
"""Get first N movies in the specified genre."""
with MongoClient(uri) as client:
movie_collection = client[DB][MSG_COLLECTION]
msg_list = movie_collection.find({"genres": genre}).limit(100)
movie_title_list = []
for msg in msg_list:
movie_... | 77,998 |
def apply_all_transformations(df):
"""Apply all feature transformations."""
df["age_quantile"] = compute_age_quantile(df, 5)
df["competition_open"] = compute_competition_open(df)
df["count"] = df.groupby("store")[["date"]].transform("cumcount")
df["open_lag_1"] = compute_open_lag(df)
df["open_la... | 77,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.