content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def phi(input):
"""Phi function.
:param input:
Float (scalar or array) value.
:returns:
phi(input).
"""
return 0.5 * erfc(-input/np.sqrt(2)) | 34,800 |
def _is_correct_task(task: str, db: dict) -> bool:
"""
Check if the current data set is compatible with the specified task.
Parameters
----------
task
Regression or classification
db
OpenML data set dictionary
Returns
-------
bool
True if the task and the da... | 34,801 |
def is_valid_semver(version: str) -> bool:
"""return True if a value is a valid semantic version
"""
match = re.match(r'^[0-9]+\.[0-9]+\.[0-9]+(-([0-9a-z]+(\.[0-9a-z]+)*))?$', version)
return match is not None | 34,802 |
def test_OutOfStock():
"""
Tests if the stock status value is received correctly
for two stock status conditions (Out of Stock, Error Occurred)
on www.walmart.com.
"""
walmartScraper = WalmartScraper(OutStockUrl)
stock_info, cost = walmartScraper.job()
assert stock_info == "Out of Stock"... | 34,803 |
def main():
"""
This is a test.
"""
options = get_options()
layout = generate_matrix(options.board_grid, options.unit_grid,
options.unit_n, options.positions)
make_dir(options.outdir)
save_matrix(layout, options.outdir + '/' + options.file_name)
save_fig(layo... | 34,804 |
async def role_assignments_for_team(
name: str, project_name: Optional[str] = None
) -> List[RoleAssignment]:
"""Gets all role assignments for a team."""
try:
return zen_store.get_role_assignments_for_team(
team_name=name, project_name=project_name
)
except KeyError as error:... | 34,805 |
def set_nested_dict_value(input_dict, key, val):
"""Uses '.' or '->'-splittable string as key and returns modified dict."""
if not isinstance(input_dict, dict):
# dangerous, just replace with dict
input_dict = {}
key = key.replace("->", ".") # make sure no -> left
split_key = key.split... | 34,806 |
def cube_1(cube_mesh):
""" Viewable cube object shifted to 3 on x """
obj = Mock()
obj.name = 'cube_1'
obj.mode = 'OBJECT'
obj.mesh_mock = cube_mesh
obj.to_mesh.return_value = cube_mesh
obj.matrix_world = Matrix.Identity(4)
obj.mesh_mock.vertices = cube_vertices(3)
obj.update_from_ed... | 34,807 |
def deserialize_model_fixture():
"""
Returns a deserialized version of an instance of
the Model class. This simulates the idea that a
model instance would be serialized and loaded
from disk.
"""
class Model:
def predict(self, values):
return [1]
return Model() | 34,808 |
def _get_bfp_op(op, name, bfp_args):
"""
Create the bfp version of the operation op
This function is called when a bfp layer is defined. See BFPConv2d and BFPLinear below
"""
op_name = _get_op_name(name, **bfp_args)
if op_name not in _bfp_ops:
_bfp_ops[name] = _gen_bfp_op(op, name, bfp_a... | 34,809 |
def compute_dmdt(jd: Sequence, mag: Sequence, dmdt_ints_v: str = "v20200318"):
"""Compute dmdt matrix for time series (jd, mag)
See arXiv:1709.06257
:param jd:
:param mag:
:param dmdt_ints_v:
:return:
"""
jd_diff = pwd_for(jd)
mag_diff = pwd_for(mag)
dmdt, ex, ey = np.histogram... | 34,810 |
def all_bin_vecs(arr, v):
"""
create an array which holds all 2^V binary vectors
INPUT
arr positive integers from 1 to 2^V, (2^V, ) numpy array
v number of variables V
OUTPUT
edgeconfs all possible binary vectors, (2^V, V) numpy array
"""
to_str_func = np.vectorize(lambda x: np.binary_repr... | 34,811 |
def unpack_domains(df):
"""Unpack domain codes to values.
Parameters
----------
df : DataFrame
"""
df = df.copy()
for field, domain in DOMAINS.items():
if field in df.columns:
df[field] = df[field].map(domain)
return df | 34,812 |
def validate_saml_response(html):
"""Parse html to validate that saml a saml response was returned."""
soup = BeautifulSoup(html, "html.parser")
xml = None
for elem in soup.find_all("input", attrs={"name": "SAMLResponse"}):
saml_base64 = elem.get("value")
xml = codecs.decode(saml_base64... | 34,813 |
def generate_region_info(region_params):
"""Generate the `region_params` list in the tiling parameter dict
Args:
region_params (dict):
A `dict` mapping each region-specific parameter to a list of values per FOV
Returns:
list:
The complete set of `region_params` sort... | 34,814 |
def is_decorator(tree, fname):
"""Test tree whether it is the decorator ``fname``.
``fname`` may be ``str`` or a predicate, see ``isx``.
References of the forms ``f``, ``foo.f`` and ``hq[f]`` are supported.
We detect:
- ``Name``, ``Attribute`` or ``Captured`` matching the given ``fname``
... | 34,815 |
def without_oaiset_signals(app):
"""Temporary disable oaiset signals."""
from invenio_oaiserver import current_oaiserver
current_oaiserver.unregister_signals_oaiset()
yield
current_oaiserver.register_signals_oaiset() | 34,816 |
def history(mac, hostname):
"""Read the history from the sensor."""
global json_body
global clear_hosts
temp = []
poller = MiFloraPoller(mac, backend)
history_list = poller.fetch_history()
for entry in history_list:
measurement = {
"measurement": "monitor_reading",
... | 34,817 |
def _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers,
steps_per_epoch, validation_data, validation_steps,
mode, kwargs):
"""Raises errors if arguments are invalid.
Arguments:
is_sequence: Boolean, whether data is a `keras.utils.data_utils... | 34,818 |
def Nbspld1(t, x, k=3):
"""Same as :func:`Nbspl`, but returns the first derivative too."""
kmax = k
if kmax > len(t)-2:
raise Exception("Input error in Nbspl: require that k < len(t)-2")
t = np.array(t)
x = np.array(x)[:, np.newaxis]
N = 1.0*((x > t[:-1]) & (x <= t[1:]))
dN = np.zero... | 34,819 |
def getStyleSheet():
"""Returns a stylesheet object"""
stylesheet = StyleSheet1()
stylesheet.add(ParagraphStyle(name='Normal',
fontName="Helvetica",
fontSize=10,
leading=12))
stylesheet.add(ParagraphS... | 34,820 |
async def test_create_event_format_missing_mandatory_property(
client: _TestClient,
mocker: MockFixture,
token: MockFixture,
event: dict,
) -> None:
"""Should return 422 HTTPUnprocessableEntity."""
EVENT_ID = "event_id_1"
RACECLASS_ID = "290e70d5-0933-4af0-bb53-1d705ba7eb95"
mocker.patch... | 34,821 |
def parse_faq_entries(entries):
"""
Iterate through the condensed FAQ entries to expand all of the keywords and answers
"""
parsed_entries = {}
for entry in entries:
for keyword in entry["keywords"]:
if keyword not in parsed_entries:
parsed_entries[keyword] = ... | 34,822 |
def make_dqn(statesize, actionsize):
"""
Create a nn.Module instance for the q leanring model.
@param statesize: dimension of the input continuous state space.
@param actionsize: dimension of the descrete action space.
@return model: nn.Module instance
"""
pass | 34,823 |
def dh_to_dt(day_str, dh):
"""decimal hour to unix timestamp"""
# return dt.replace(tzinfo=datetime.timezone.utc).timestamp()
t0 = datetime.datetime.strptime(day_str, '%Y%m%d') - datetime.datetime(1970, 1, 1)
return datetime.datetime.strptime(day_str, '%Y%m%d') + datetime.timedelta(seconds=float(dh*3600... | 34,824 |
def get_statistic(key, key_type, fromtime, endtime, var_names):
"""
根据key和时间戳 来获取对应小时统计的报表数据
Paramters:
key:
key_type: ip, ipc, page, user, did
timestamp:
t: 生成统计key 对应的type段, 现在默认为None是因为暂时查询key只有ip,ipc 类型的, @todo 视图函数里面扔进来
Return:
if key is None:
{ key(统计leveldb的索引中除了开头... | 34,825 |
def run(cmd: Sequence[Union[str, Path]], check=True) -> int:
"""Run arbitrary command as subprocess"""
returncode = run_subprocess(
cmd, capture_stdout=False, capture_stderr=False
).returncode
if check and returncode:
cmd_str = " ".join(str(c) for c in cmd)
raise PipxError(f"{c... | 34,826 |
def write_docker_compose_file(compose_configuration, path):
"""
Writes the new docker-compose file
"""
# Check if docker-compose file already exists
if os.path.exists(path):
rename_existing_file(path)
# Write new docker-compose file
yaml_for_compose = ruamel.yaml.round_trip_dump(comp... | 34,827 |
def dump_bases(glyphs, records, printable_function):
"""Prints bases with their classes."""
index = 0
for glyph in glyphs:
record = records[index]
print_indented("%s: %s" % (glyph, printable_function(record)), indents=2)
index += 1 | 34,828 |
def _createTopics(topicMap: Mapping[str, str], topicMgr: TopicManager):
"""
Create notification topics. These are used when some of the notification flags have been set to True (see
pub.setNotificationFlags(). The topicMap is a dict where key is the notification type, and value is the topic
name to crea... | 34,829 |
def getDict(fname):
"""Returns the dict of values of the UserComment"""
s = getEXIF(fname, COMMENT_TAG)
try:
s = s.value
except Exception: pass
return getDictFromString(s) | 34,830 |
def path_count_cache(metric):
"""
Decorator to apply caching to the DWWC and DWPC functions from
hetmatpy.degree_weight.
"""
def decorator(user_function):
signature = inspect.signature(user_function)
@functools.wraps(user_function)
def wrapper(*args, **kwargs):
... | 34,831 |
def test_optim_params1(test_output_dirs: OutputFolderForTests) -> None:
"""
Test if the optimizer parameters are read correctly for InnerEye configs.
"""
model = DummyModel()
model.set_output_to(test_output_dirs.root_dir)
runner = MLRunner(model_config=model)
runner.setup()
lightning_mod... | 34,832 |
def get_metabolite_mapping() -> Mapping[str, Set[Reference]]:
"""Make the metabolite mapping."""
metabolites_df = get_metabolite_df()
smpdb_id_to_metabolites = defaultdict(set)
for pathway_id, metabolite_id, metabolite_name in tqdm(metabolites_df.values, desc='mapping metabolites'):
smpdb_id_to_... | 34,833 |
def has_merge_conflict(commit: str, target_branch: str, remote: str = 'origin') -> bool:
""" Returns true if the given commit hash has a merge conflict with the given target branch.
"""
try:
# Always remove the temporary worktree. It's possible that we got
# interrupted and left it around. T... | 34,834 |
def create_folder():
"""Creates a temp_folder on the users desktop"""
new_folder_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop\\temp_folder')
try:
if not os.path.exists(new_folder_path):
os.makedirs(new_folder_path)
except OSError:
print("Error:... | 34,835 |
def load_csr(data):
"""
Loads a PEM X.509 CSR.
"""
return x509.load_pem_x509_csr(data, default_backend()) | 34,836 |
def parseIMACS(hdul):
"""
Parses information from a given HDU, for data produced at IMACS
"""
start = hdul[0].header['CRVAL1']
step = hdul[0].header['CDELT1']
total = hdul[0].header['NAXIS1']
corr = (hdul[0].header['CRPIX1'] - 1) * step
wave = np.arange(start - corr, start + total*st... | 34,837 |
def boll_cross_func_jit(data:np.ndarray,) -> np.ndarray:
"""
布林线和K线金叉死叉 状态分析 Numba JIT优化
idx: 0 == open
1 == high
2 == low
3 == close
"""
BBANDS = TA_BBANDS(data[:,3], timeperiod=20, nbdevup=2)
return ret_boll_cross | 34,838 |
def rank_genes_groups(
X,
labels, # louvain results
var_names,
groups=None,
reference='rest',
n_genes=100,
**kwds,
):
"""
Rank genes for characterizing groups.
Parameters
----------
X : cupy.ndarray of shape (n_cells, n_genes)
The cellxgene matrix to rank gene... | 34,839 |
def init_graph_handler():
"""Init GraphHandler."""
graph = get_graph_proto()
graph_handler = GraphHandler()
graph_handler.put({graph.name: graph})
return graph_handler | 34,840 |
def visualize_2d_activation_map(activation_map: np.ndarray, args: ModelConfigBase, slice_index: int = 0) -> None:
"""
Saves all feature channels of a 2D activation map as png files
:param activation_map:
:param args:
:param slice_index:
:return:
"""
destination_directory = str(args.outpu... | 34,841 |
def add_average_column(df, *, copy: bool = False):
"""Add a column averaging the power on all channels.
Parameters
----------
%(df_psd)s
An 'avg' column is added averaging the power on all channels.
%(copy)s
Returns
-------
%(df_psd)s
The average power across channels h... | 34,842 |
def _is_globbed(name, glob):
"""
Return true if given name matches the glob list.
"""
if not glob:
return True
return any((fnmatch.fnmatchcase(name, i) for i in glob)) | 34,843 |
def test_notebookclient_get_kernel_id_with_error_status(plugin, mocker):
"""Test NotebookClient.get_kernel_id() when response has error status."""
response = mocker.Mock()
content = b'{"message": "error"}'
response.content = content
response.status_code = requests.codes.forbidden
mocker.patch('r... | 34,844 |
def read_vec_flt(file_or_fd):
"""[flt-vec] = read_vec_flt(file_or_fd)
Read kaldi float vector, ascii or binary input,
Parameters
----------
file_or_fd : obj
An ark, gzipped ark, pipe or opened file descriptor.
Raises
------
ValueError
Unsupported data-type of the input ... | 34,845 |
def arg_export(name):
"""Export an argument set."""
def _wrapper(func):
_ARG_EXPORTS[name] = func
if 'arg_defs' not in dir(func):
func.arg_defs = []
return func
return _wrapper | 34,846 |
def get_od_base( mode = "H+S & B3LYP+TPSS0"): # od is OrderedDict()
"""
initial parameters are prepared.
mode = "H+S & B3LYP+TPSS0" --> ["B3LYP", "TPSS0"] with speration of H and S
"H+S & B3LYP" --> ["B3LYP"] with speration of H and S
"H+S & TPSSO" --> ["TPSS0"] with speration of H and S
"""
if mode == ... | 34,847 |
def generate_all_specs(
population_specs, treatment_specs, outcome_specs, model_specs, estimator_specs
):
"""
Generate all combinations of population, treatment,
outcome, causal model and estimator
"""
causal_graph = CausalGraph(treatment_specs, outcome_specs, model_specs)
model_specs = caus... | 34,848 |
def wsFoc(r,psi,L1,z0,alpha):
"""Return optimum focal surface height at radius r
as given by Chase & Van Speybroeck
"""
return .0625*(psi+1)*(r**2*L1/z0**2)/tan(alpha)**2 | 34,849 |
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, draw_function=draw_lines, **kwargs):
"""
`img` should be the output of a Canny transform.
draw_function: Which which accepts image & line to render lanes. Default: draw_lines()
Returns an image with hough lines drawn.
"""
... | 34,850 |
def check(data, shape, splits=100):
"""Check dataset properties."""
assert data.data.shape == shape
assert data.target.shape[0] == shape[0]
assert len(list(data.outer_cv)) == splits
check_estimator(data) | 34,851 |
def test_get_py_loglevel():
"""
Ensure function _get_py_loglevel is exposed
"""
assert getattr(log, "_get_py_loglevel", None) is not None | 34,852 |
def compare_FISM_diff_spect_by_dn(dns, _f107):
"""
Compare FISM spectrum for several dates
paraeters:
----------
dns <List[datetime]>: List of datetime of the events
"""
fig = plt.figure(figsize=(6,4), dpi=120)
ax = fig.add_subplot(111)
ax.set_xlabel(r"Waveband ($\lambda$), nm")
... | 34,853 |
def config_macsec_keychain_on_device(device, keychain_name, key,
crypt_algorithm, key_string, lifetime=None):
""" Configures macsec key chain on device
Args:
device ('obj'): device to use
keychain_name ('str'): keychain name to configure
key_string ('str'): key ... | 34,854 |
def instances_to_topographies(topographies, surfaces, tags):
"""Returns a queryset of topographies, based on given instances
Given topographies, surfaces and tags are resolved and
all topographies are returned which are either
- explicitly given
- given indirectly by a surface
- given indirectl... | 34,855 |
def plot_histogram(
s: pd.Series,
*,
number_bins: Optional[int] = None,
bin_range: Union[Tuple[int, int], Tuple[int, int]] = None,
figsize: Optional[Tuple[int, int]] = (8, 6),
bin_width: Optional[int] = None,
edgecolor: Optional[str] = '#ffffff',
linewidth: Optional[int] = 1,
bin_lab... | 34,856 |
def get_tracks():
"""
Returns all tracks on the minerva DB
"""
# connect to the database
db = connect_minerva_db()
# return all the tracks as a list
tracks = list(db.tracks.find())
return tracks | 34,857 |
def test_alphabet_as_fstring_violation(
assert_errors,
parse_ast_tree,
default_options,
):
"""Testing that the fstrings violate the rules."""
tree = parse_ast_tree('f"{0}"'.format(string.ascii_letters))
visitor = WrongStringVisitor(default_options, tree=tree)
visitor.run()
assert_error... | 34,858 |
def mult_pair(pair):
"""Return the product of two, potentially large, numbers."""
return pair[0]*pair[1] | 34,859 |
def _raise(exception):
"""To raise an exception in a lambda function or expression"""
raise exception | 34,860 |
def getproblem(URLs):
"""
getproblem() : It takes input from the user of codeforces problemID and difficulty
level and then by using selenium and chrome webdriver, capturing screenshot of the
Codeforces problem using ttypography tag because all the problems of codeforces are
stored inside this ... | 34,861 |
def get_only_filename(file_list):
"""
Get filename from file's path and return list that has only filename.
Input:
file_list: List. file's paths list.
Attribute:
file_name: String. "01.jpg"
file_name_without_ext: String. "01"
Return:
filename_list: Only fil... | 34,862 |
def simple_calculate_hmac(sym_key, message,
digest_algo=DIGEST_ALGORITHM.SHA256):
"""Calculates a HMAC of given message using symmetric key."""
message_param = _get_char_param_nullify_if_zero(message)
mac = _ctypes.POINTER(_ctypes.c_char)()
mac_length = _ctypes.c_size_t()
_... | 34,863 |
def convert_from_sliced_object(data):
"""Fix the memory of multi-dimensional sliced object."""
if isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):
if not data.flags.c_contiguous:
_log_warning("Usage of np.ndarray subset (sliced data) is not recommended "
... | 34,864 |
def write_file(conf, data):
"""Write the data to the file specified in the conf.
If there is an existing file in the destination, compare the new
contents with the existing contents. Return True if there is a difference.
"""
owner = conf.get('owner')
# Check for user and group id in the environ... | 34,865 |
def merge_to_media(apps, schema_editor):
"""
Migration step that will merge the CarbonSource table and the
"Carbon Source (workaround)" metadata, into the "Media" metadata.
The values merge with newlines between any existing values, and
renders the CarbonSource table as a line each for name, descrip... | 34,866 |
def stat_helper(path):
"""os.path.exists will return None for PermissionError (or any other
exception) , leading us to believe a file is not present when it, in fact,
is. This is behavior is awful, so stat_helper preserves any exception
other than FileNotFoundError.
"""
try:
return path... | 34,867 |
def create_beacon_and_now_datetime(
game_name: str = "st",
waiting_time: float = 12.0,
platform_name: str = "pc"
) -> Tuple[beacons.BeaconBase, datetime.datetime]:
"""Return a BeaconBase instance with start time to current time."""
now = datetime.datetime.now(datetime.timezone.utc) \
... | 34,868 |
def validate(number, check_country=True):
"""Checks to see if the number provided is a valid IBAN. The country-
specific check can be disabled with the check_country argument."""
number = compact(number)
# ensure that checksum is valid
mod_97_10.validate(number[4:] + number[:4])
# look up the nu... | 34,869 |
def read_group(fname):
"""Reads the symmetry group in from the 'rot_perms' styled group
output by enum.x.
:arg fname: path to the file to read the group from.
"""
i=0
groupi = []
with open(fname) as f:
for line in f:
if i > 5:
if ('Perm #:') in line:
... | 34,870 |
def inject_path(path):
"""
Imports :func: from a python file at :path: and executes it with *args, **kwargs arguments. Everytime this function
is called the module is reloaded so that you can alter your debug code while the application is running.
The result of the function is returned, otherwise the e... | 34,871 |
def install_and_import_module(module_name, package_name=None, global_name=None):
"""
Installs the package through pip and attempts to import the installed module.
:param module_name: Module to import.
:param package_name: (Optional) Name of the package that needs to be installed. If None it is assumed t... | 34,872 |
def find_last_layer(model):
"""
Find last layer.
Args:
model (_type_): Model.
Returns:
_type_: Last layer.
"""
for layer in reversed(model.layers):
return layer | 34,873 |
def _update_color_state(widget, state):
"""Update the colors on `widget`, depending on a given state.
Args:
widget (:class:`PySide.QtGui.QWidget`): The widget to change.
state (:class:`PySide.QtGui.QValidator.State`): A state to display as a new color.
Raises:
ValueError: If `state... | 34,874 |
def seconds_to_time(sec):
"""
Convert seconds into time H:M:S
"""
return "%02d:%02d" % divmod(sec, 60) | 34,875 |
def check_dmd_computation_simple_timeseries(exact, total):
""" Check DMD computations on a problem where the
true solution is known. All variants of DMD
should give identical outputs.
"""
num_snapshots = 10
A = np.array([[0.9, 0.1], [0.0, 0.8]])
# Create a time series of data
... | 34,876 |
def _compute_nfp_real(l, u, counts, sizes):
"""Computes the expected number of false positives caused by using
u to approximate set sizes in the interval [l, u], using the real
set size distribution.
Args:
l: the lower bound on set sizes.
u: the upper bound on set sizes.
counts:... | 34,877 |
def tail_log():
"""
Watch the tilestache logs
"""
run("sudo tail -f /var/log/uwsgi/app/tilestache.log") | 34,878 |
def is_equal_subset(
subset: Union[Dict, List, Set], superset: Union[Dict, List, Set]
) -> bool:
"""determine if all shared keys have equal value"""
if isinstance(subset, dict):
return all(
key in superset and is_equal_subset(val, superset[key])
for key, val in subset.items(... | 34,879 |
def test_main_help(monkeypatch, usage, capsys):
"""Test the help command without argument."""
monkeypatch.setattr(sys, "argv", ["foo", "help"])
main.main()
result_lines = capsys.readouterr().out.splitlines()
assert len(result_lines) == len(usage) | 34,880 |
def concatenate_over(argname):
"""Decorator to "vectorize" functions and concatenate outputs
"""
def _prepare_args(arg_map, value):
params = copy(arg_map)
params[argname] = value
return params
@decorator
def _concatenate_over(func, *args, **kwargs):
"""Validate that ... | 34,881 |
def checkFile(path: str):
"""
Checks if a file exists, exists program if not readable
Only used if a file needs to exist
"""
if not os.path.exists(path):
print('File: "' + path + '", is not readable.')
exit(0)
return path | 34,882 |
def logicalToPhysicalPoint(window, x, y):
"""Converts the logical coordinates of a point in a window to physical coordinates.
This should be used when points are received directly from a window that is not DPI aware.
@param window: The window handle.
@param x: The logical x coordinate.
@type x: int
@param y... | 34,883 |
def _node2vec_walks(Tdata, Tindptr, Tindices,
sampling_nodes,
walklen,
return_weight,
neighbor_weight):
"""
Create biased random walks from the transition matrix of a graph
in CSR sparse format. Bias method comes from Node2... | 34,884 |
def send_top(update: Update, context: CallbackContext) -> None:
"""Process incoming message, send top tracks by the given artist or send an error message."""
logger.info(
f'(send_top) Incoming message: args={context.args}, text="{update.message.text}"'
)
keyphrase = update.message.text
conte... | 34,885 |
def update(params):
"""Handles the 'change' operation for modifying a file.
Expected flags in 'params' are translated to Json Field names to identify modifications to be made"""
dsid = params.get("--dsid", "missing_id")
fileid = params.get("--fileid", "missing_id")
expectedArgs = {'--catid': 'tar... | 34,886 |
def turn(direction):
"""Send the string provided to this function the the fifo
to steer the robot in the correct direction
"""
fifo = open(FIFO, "w", 0) #open the file without buffering; hence the 0
fifo.write(direction)
fifo.close()
time.sleep(wait) #ensure the reader process can read it be... | 34,887 |
def schedule_prettify(schedule):
"""
Принимает на вход расписание в формате:
[День недели, Время, Тип занятия, Наименование занятия, Имя преподавателя, Место проведения]
Например: ['Чт', '13:00 – 14:30', 'ПЗ', 'Физическая культура', '', 'Кафедра']
"""
if not schedule:
return 'Сегодня зан... | 34,888 |
def autodelegate(prefix=''):
"""
Returns a method that takes one argument and calls the method named prefix+arg,
calling `notfound()` if there isn't one. Example:
urls = ('/prefs/(.*)', 'prefs')
class prefs:
GET = autodelegate('GET_')
def GET_password(self): pass
... | 34,889 |
def _compute_new_static_size(image, min_dimension, max_dimension):
"""Compute new static shape for resize_to_range method."""
image_shape = image.get_shape().as_list()
orig_height = image_shape[0]
orig_width = image_shape[1]
num_channels = image_shape[2]
# Scale factor such that maximal dimensi... | 34,890 |
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
... | 34,891 |
def set_gae_attributes(span):
"""Set the GAE environment common attributes."""
for env_var, attribute_key in GAE_ATTRIBUTES.items():
attribute_value = os.environ.get(env_var)
if attribute_value is not None:
pair = {attribute_key: attribute_value}
pair_attrs = Attributes(... | 34,892 |
def _omega_spectrum_odd_c(n, field):
"""Spectra of groups \Omega_{2n+1}(q) for odd q.
[1, Corollary 6]
"""
n = (n - 1) // 2
q = field.order
p = field.char
# (1)
t = (q ** n - 1) // 2
a1 = [t, t + 1]
# (2)
a2 = SemisimpleElements(q, n, min_length=2)
# (3)
k = 1
... | 34,893 |
def cli() -> None:
"""File Sort a tool to organize images on a path.
To get started, run collect:
$ files_sort_out collect
To show collected image folders:
$ files_sort_out show
To remove(exclude) directories from list run:
$ files_sort_out exclude <path>
Then copy files to ... | 34,894 |
def get_service(hass, config, discovery_info=None):
"""Get the ClickSend notification service."""
if not _authenticate(config):
_LOGGER.error("You are not authorized to access ClickSend")
return None
return ClicksendNotificationService(config) | 34,895 |
def mock_features_dtypes(num_rows=100):
"""Internal function that returns the default full dataset.
:param num_rows: The number of observations in the final dataset. Defaults to 100.
:type num_rows: int, optional
:return: The dataset with all columns included.
:rtype tuple: (str, str)
"""
f... | 34,896 |
def random_bitstring(n, p, failcount=0):
"""
Constructs a random bitstring of length n with parity p
Parameters
----------
n : int
Number of bits.
p : int
Parity.
failcount : int, optional
Internal use only.
Returns
-------
numpy.ndarray
"""
bi... | 34,897 |
def serializer(message):
"""serializes the message as JSON"""
return json.dumps(message).encode('utf-8') | 34,898 |
def send_mail(request, format=None):
"""
Send mail to admin
"""
# serialize request data
serializer = MailSerializer(data=request.data)
if serializer.is_valid():
try:
# create data for mail
subject = settings.EMAIL_SUBJECT.format(
first_name=reque... | 34,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.