content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def representative_dataset_gen(export_config):
"""Gets a python generator of numpy arrays for the given dataset."""
quantization_config = export_config.quantization_config
dataset = tfds.builder(
quantization_config.dataset_name,
data_dir=quantization_config.dataset_dir)
dataset.download_and_prepare... | 5,344,100 |
def DesignCustomSineWave(family_list, how_many_gen, amp, per, shift_h, shift_v,
show=False, print_phase_mse=False, return_phases=False):
""" "Grid Search" Approach:
Create sine waves with unknown amp, per, shift_h and shift_v in combinatorial manner
and align famili... | 5,344,101 |
def train_deepfm():
""" train_deepfm """
if config.rank_size > 1:
if config.device_target == "Ascend":
device_id = int(os.getenv('DEVICE_ID'))
context.set_context(mode=context.GRAPH_MODE, device_target=config.device_target, device_id=device_id)
context.reset_auto_para... | 5,344,102 |
def test_two_days():
"""
Test if the code works as intended when we have only two open days
"""
test_data, test_data_results = load_data_results(base_filename="two_days")
for data, result in zip(test_data, test_data_results):
response = client.post('/prettify', data=data)
assert resp... | 5,344,103 |
def RadarRngEq(G, beam_el, filename):
"""Prints SNR, will be modified for other uses later
SNR = (pt*g^2*lambda_^2*sigma)/((4*pi)^3*k*temp_s*nf*l*r^4)
pt = power transmitted - Watts
freq = radar freq - Hz
gain = antenna gain - db (default = 45)
sigma = RCS - m^2
BW = bandwidth - Hz
NF =... | 5,344,104 |
def get_environment_names():
"""Return a list of defined environment names, with user preference first."""
envlist = [r[0] for r in _session.query(models.Environment.name).order_by(models.Environment.name).all()]
# move user preference to top of list
userenvname = _config.userconfig.get("environmentnam... | 5,344,105 |
def plot(direction, speed, **kwargs):
"""Create a WindrosePlot, add bars and other standard things.
Args:
direction (pint.Quantity): wind direction from North.
speed (pint.Quantity): wind speeds with units attached.
**bins (pint.Quantity): wind speed bins to produce the histogram for.
... | 5,344,106 |
def convert_floor(node, **kwargs):
"""Map MXNet's floor operator attributes to onnx's Floor operator
and return the created node.
"""
return create_basic_op_node('Floor', node, kwargs) | 5,344,107 |
def journal_zk_cleanup():
"""
Zk history sqlite node cleanup
"""
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--cfg',
help='Journal config file')
parser.add_argument('-p', '--primary',
help='Zookeeper journal')
parser.add_argum... | 5,344,108 |
def test_no_attribute_name_following_value_and_no_close():
"""
Make sure to test an attribute name without a following attribute value and no close bracket.
"""
# Arrange
input_tag_name = "<meta http:equiv"
start_index = 16
expected_resultant_index = len(input_tag_name)
# Act
actua... | 5,344,109 |
async def get_qrcode_login_info():
"""获取二维码登录信息"""
url = f"{BASE_URL}qrcode/auth_code"
return await post(url, reqtype="app") | 5,344,110 |
def get_global_free_state(self):
"""
Recurse get_global_free_state on all child parameters, and hstack them.
Return: Stacked np-array for all Param except for LocalParam
"""
# check if the child has 'get_local_free_state' method
for p in self.sorted_params:
if isinstance(p, (param.Param,... | 5,344,111 |
def case_activity_update_type():
""" Case Activity Update Types: RESTful CRUD Controller """
return crud_controller() | 5,344,112 |
def dftregistration(buf1ft,buf2ft,usfac=100):
"""
# function [output Greg] = dftregistration(buf1ft,buf2ft,usfac);
# Efficient subpixel image registration by crosscorrelation. This code
# gives the same precision as the FFT upsampled cross correlation in a
# small fraction of the computat... | 5,344,113 |
def parametrize_simulations(args):
"""Parametrize simulations"""
if args.type == INSTANCE_COUNTS:
return instance_count_sims(args)
if args.type == FEATURE_COUNTS:
return feature_count_sims(args)
if args.type == NOISE_LEVELS:
return noise_level_sims(args)
if args.type == SHUFF... | 5,344,114 |
def connect(base_url: Union[str, URL], database_id: int = DJ_DATABASE_ID) -> Connection:
"""
Create a connection to the database.
"""
if not isinstance(base_url, URL):
base_url = URL(base_url)
return Connection(base_url, database_id) | 5,344,115 |
def micore_tf_deps():
"""Dependencies for Tensorflow builds.
Returns:
list of dependencies which must be used by each cc_library
which refers to Tensorflow. Enables the library to compile both for
Android and for Linux. Use this macro instead of directly
declaring dependencies on Tensor... | 5,344,116 |
def de_bruijn(k, n):
"""
de Bruijn sequence for alphabet k
and subsequences of length n.
"""
try:
# let's see if k can be cast to an integer;
# if so, make our alphabet a list
_ = int(k)
alphabet = list(map(str, range(k)))
except (ValueError, TypeError):
... | 5,344,117 |
def audit_(
config: Configuration,
report_only: bool,
report_format: str,
file_format: str,
sources: List[str],
file: TextIO,
) -> None:
"""
Checks a given dependency file against advisory databases.
\b
FILE is the path to the dependency file to audit.
"""
config.report_... | 5,344,118 |
def append_artist(songs, artist):
"""
When the songs gathered from the description just contains the
titles of the songs usually means it's an artist's album.
If an artist was provided appends the song title to the artist
using a hyphen (artist - song)
:param list songs: List of song titles (onl... | 5,344,119 |
def pose2pandas(pose: pyrosetta.Pose, scorefxn: pyrosetta.ScoreFunction) -> pd.DataFrame:
"""
Return a pandas dataframe from the scores of the pose
:param pose:
:return:
"""
pose.energies().clear_energies()
scorefxn.weights() # neccessary?
emopts = pyrosetta.rosetta.core.scoring.methods... | 5,344,120 |
def rantest(seed,N=100):
"""get some random numbers"""
buff = np.zeros(N,dtype=np.double)
ct_buff = buff.ctypes.data_as(ct.POINTER(ct.c_double))
sim.rantest(seed,N,ct_buff)
return buff | 5,344,121 |
def resolve_nomination_action_items():
"""Resolve action items.
Resolve all the action items relevant to nomination reminders after the
10th day of each month.
"""
today = now().date()
if today.day == NOMINATION_END_DAY:
mentors = UserProfile.objects.filter(user__groups__name='Mentor')... | 5,344,122 |
def tf_efficientnet_b0_ap(pretrained=False, **kwargs):
""" EfficientNet-B0 AdvProp. Tensorflow compatible variant """
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet(
'tf_efficientnet_b0_ap', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pre... | 5,344,123 |
def pi_del(
shape,
y_tgt_star,
pad_symbol=0,
plh_symbol=0,
bos_symbol=0,
eos_symbol=0,
Kmax=100,
device="cpu",
):
"""Operations and states to edit a partially deleted version of y_star back to y_star."""
# shape = B x N x M
# y_tgt_star : B x M
shape = list(shape)
sha... | 5,344,124 |
def create_service_account(project_id: str, service_account_name: str,
role_name: str, file_name: str) -> Dict[str, Any]:
"""Create a new service account.
Args:
project_id: GCP project id.
service_account_name: The service account name.
role_name: The role to be assigned to t... | 5,344,125 |
def test_ode_FE():
"""Test that a linear u(t)=a*t+b is exactly reproduced."""
def exact_solution(t):
return a*t + b
def f(u, t): # ODE
return a + (u - exact_solution(t))**m
a = 4
b = -1
m = 6
dt = 0.5
T = 20.0
u, t = ode_FE(f, exact_solution(0), dt, T)
diff ... | 5,344,126 |
def file_finder():
"""
This function allows to the user
to select a file using the dialog with tkinter.
:return path_name
:rtype str
the string of the path_name file.
"""
root = Tk()
root.title("File Finder")
root.geometry("500x400")
root.attributes("-topmost", ... | 5,344,127 |
def htm_search_cone(IndexFile_data,Long,Lat,Radius,Ind=None,Son_index=np.arange(2,6),PolesLong_index=np.arange(6,11,2),PolesLat_index=np.arange(7,12,2)):
#print('I am running htm_search_cone')
"""Description: Search for all HTM leafs intersecting a small circles
Input :-Either a table of HTM data or an... | 5,344,128 |
def getHostOsVersion():
"""
Returns the host OS version. This is platform.release with additional
distro indicator on linux.
"""
sVersion = platform.release();
sOs = getHostOs();
if sOs == 'linux':
sDist = '';
try:
# try /etc/lsb-release first to distinguish betw... | 5,344,129 |
def archived_changes(archivedir='./edi_requests/', scope='knb-lter-jrn',
dedup=True, parsedt=False):
"""
Load archived PASTA change records from xml files and parse into dataframe.
Options
archivedir path to archive directory string ('./edi_requests')
scope EDI scop... | 5,344,130 |
def test_ubuntu_too_old():
"""
Error with a useful message when running in older Ubuntu
"""
output = run_bootstrap('old-distro-test', 'ubuntu:16.04')
assert output.stdout == 'The Littlest JupyterHub requires Ubuntu 18.04 or higher\n'
assert output.returncode == 1 | 5,344,131 |
def get_missing_columns(missing_data):
"""
Returns columns names as list that containes missing data
:param
missing_data : return of missing_data(df)
:return
list: list containing columns with missing data
"""
missing_data = missing_data[missing_data['percent'] > 0]
... | 5,344,132 |
def read(request):
"""Render the page for a group."""
pubid = request.matchdict["pubid"]
slug = request.matchdict.get("slug")
group = models.Group.get_by_pubid(pubid)
if group is None:
raise exc.HTTPNotFound()
if slug is None or slug != group.slug:
url = request.route_url('grou... | 5,344,133 |
def train_model(
model,
device,
train_data_loader,
valid_data_loader,
criterion, optimizer, scheduler, num_epochs=5):
"""
training
Parameters
--------------
model : DogClassificationModel
Network model to be trained.
device : device
cuda or cpu
train_d... | 5,344,134 |
def run(parameter):
"""
The entry function of this code.
Args:
parameter: the super-parameter
"""
print(json.dumps(parameter, indent=2))
time.sleep(2)
slot_set = pickle.load(file=open(parameter["slot_set"], "rb"))
action_set = pickle.load(file=open(parameter["action_set"], "rb"... | 5,344,135 |
def convert(
value: str,
conversion_recipes: Iterable[ConversionRecipe[ConvertResultType]]) -> ConvertResultType:
"""
Given a string value and a series of conversion recipes, attempt to convert the value using the
recipes.
If none of the recipes declare themselves as applicable, then ra... | 5,344,136 |
def test_get_cell_type_error_not_found(graph_cases, selenium_extras):
"""
:type graph_cases: qmxgraph.tests.conftest.GraphCaseFactory
:type selenium_extras: qmxgraph.tests.conftest.SeleniumExtras
"""
graph = graph_cases('empty')
cell_id = "999"
with pytest.raises(WebDriverException) as e:
... | 5,344,137 |
def create_window(seq, n=2):
"""Returns a sliding window (of width n) over data from the iterable,
code taken from https://docs.python.org/release/2.3.5/lib/itertools-example.html"""
it = iter(seq)
result = tuple(itertools.islice(it, n))
if len(result) == n:
yield result
for elem in it:
... | 5,344,138 |
async def test_get_item_from_missing_item_collection(app_client):
"""Test reading an item from a collection which does not exist"""
resp = await app_client.get("/collections/invalid-collection/items/some-item")
assert resp.status_code == 404 | 5,344,139 |
def start(log_file: str) -> None:
"""Create the application log."""
global _LOG_FILENAME
# Disable UDS/ISO-TP library logging
logging.getLogger().addHandler(logging.NullHandler())
# Create the directory if needed
filename = os.path.expanduser(log_file)
filename_parts = os.path.split(filena... | 5,344,140 |
def get_function_name(fcn):
"""Returns the fully-qualified function name for the given function.
Args:
fcn: a function
Returns:
the fully-qualified function name string, such as
"eta.core.utils.function_name"
"""
return fcn.__module__ + "." + fcn.__name__ | 5,344,141 |
def add_to_braindb(run, missing_keys, brain_alternate=None):
"""
This function adds to the braindump database the missing
keys from missing_keys.
"""
my_config = {}
if brain_alternate is None:
my_braindb = os.path.join(run, brainbase)
else:
my_braindb = os.path.join(run, bra... | 5,344,142 |
def log_time(action: str, until: datetime.datetime = None) -> None:
"""Log the start time in the shelve, or remove the start time on stopping.
action: start/stop, as a string."""
if action == "start":
now = datetime.datetime.now()
with shelve.open(get_block_path() + "/data") as data:
... | 5,344,143 |
def clean_cases(text):
"""
Makes text all lowercase.
:param text: the text to be converted to all lowercase.
:type: str
:return: lowercase text
:type: str
"""
return text.lower() | 5,344,144 |
def process(sourceDir, endDir, projectDir, op, software, version, opDescr, inputMaskPath, arguments,
props):
"""
Perform the bulk journaling. If no endDir is specified, it is assumed that the user wishes
to add on to existing projects in projectDir.
:param sourceDir: Directory of source imag... | 5,344,145 |
def root():
"""Refreshes data in database"""
db.drop_all()
db.create_all()
# Get data from api, make objects with it, and add to db
for row in df.index:
db_comment = Comment(user=df.User[row],text=df.Text[row]) # rating = df.Rating[row]
db.session.add(db_comment)
db.sessi... | 5,344,146 |
def run(bind_address='0.0.0.0', port=8008):
"""Run the webapp in a simple server process."""
from werkzeug import run_simple
print "* Starting on %s:%s" % (bind_address, port)
run_simple(bind_address, port, webapp(),
use_reloader=False, threaded=True) | 5,344,147 |
def beast_production_wrapper():
"""
This does all of the steps for a full production run, and can be used as
a wrapper to automatically do most steps for multiple fields.
* make datamodel.py file
* make source density map
* split catalog by source density
* make physics model (SED grid)
... | 5,344,148 |
def test_eap_fast_tlv_nak_oom(dev, apdev):
"""EAP-FAST Phase 2 TLV NAK OOM"""
if not openssl_imported:
raise HwsimSkip("OpenSSL python method not available")
check_eap_capa(dev[0], "FAST")
hapd = start_ap(apdev[0])
with alloc_fail(dev[0], 1, "eap_fast_tlv_nak"):
run_eap_fast_phase2(... | 5,344,149 |
def construct_grammar(grammar_string, allow_sub_grammar_definitions=False, default_flags=flags.DEFAULTS):
"""
Function which accepts a user-defined grammar string and returns an instance of Grammar representing it.
Inputs: grammar_string - The user-defined grammar string representing the grammar we should ... | 5,344,150 |
def print_last(limit=None, file=None):
"""This is a shorthand for 'print_exception(sys.last_type,
sys.last_value, sys.last_traceback, limit, file)'."""
if not hasattr(sys, "last_type"):
raise ValueError("no last exception")
if file is None:
file = sys.stderr
print_exception(sys.last_... | 5,344,151 |
def bond_value_to_description(value):
"""bond_value_to_description(value) -> string
Convert from a bond type string into its text description,
separated by "|"s. The result are compatible with
OEGetFPBontType and are in canonical order.
"""
return _get_type_description("bond", _btype_flags, val... | 5,344,152 |
def check_cfg(cfg):
"""Check options of configuration and catch errors."""
for operation in ('sum', 'mean'):
if operation in cfg:
cfg[operation] = list(set(cfg[operation]))
for coord in cfg.get('sum', []):
if coord in cfg.get('mean', []):
raise ValueError(f"Coordinate... | 5,344,153 |
def read_set_from_file(filename):
"""
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
"""
collection = set()
with open(filename, 'r', encoding='utf-8') as file_:
for line in file_:
collection.add(line.rstrip())
return c... | 5,344,154 |
def filter_0_alleles(allele_df, allele_num=2):
"""Drop alleles that do not appear in any of the strains.
"""
drop_cols = []
for col in allele_df.columns:
if allele_df[col].sum()<allele_num:
drop_cols.append(col)
allele_df.drop(drop_cols, inplace=True, axis=1)
return allele_df | 5,344,155 |
async def test_available_after_update(
hass, pywemo_registry, pywemo_device, wemo_entity
):
"""Test the avaliability when an On call fails and after an update."""
pywemo_device.on.side_effect = ActionException
pywemo_device.get_state.return_value = 1
await entity_test_helpers.test_avaliable_after_up... | 5,344,156 |
def gradient_of_rmse(y_hat, y, Xn):
"""
Returns the gradient of the Root Mean Square error with respect to the
parameters of the linear model that generated the prediction `y_hat'.
Hence, y_hat should have been generated by a linear process of the form
Xn.T.dot(theta)
Args:
y... | 5,344,157 |
def is_commit_in_public_upstream(revision: str, public_upstream_branch: str, source_dir: str):
"""
Determine if the public upstream branch includes the specified commit.
:param revision: Git commit hash or reference
:param public_upstream_branch: Git branch of the public upstream source
:param sour... | 5,344,158 |
def cli(config, **options):
"""Build versioned Sphinx docs for every branch and tag pushed to origin.
Supports only building locally with the "build" sub command
For more information, run with its own --help.
The options below are global and must be specified before the sub command name (e.g. -N build... | 5,344,159 |
def align_down(x: int, align: int) -> int:
"""
Align integer down.
:return:
``y`` such that ``y % align == 0`` and ``y <= x`` and ``(x - y) < align``
"""
return x - (x % align) | 5,344,160 |
def read_config_file(config_id: str = "sample_config") -> ConfigType:
"""Read a config file
Args:
config_id (str, optional): Id of the config file to read.
Defaults to "sample_config".
Returns:
ConfigType: Config object
"""
project_root = str(Path(__file__).resolve()).... | 5,344,161 |
def null():
"""return an empty bit buffer"""
return bits() | 5,344,162 |
def find_coherent_patch(correlations, window=11):
"""Looks through 3d stack of correlation layers and finds strongest correlation patch
Also accepts a 2D array of the pre-compute means of the 3D stack.
Uses a window of size (window x window), finds the largest average patch
Args:
correlations ... | 5,344,163 |
def test():
"""HI :)"""
return 'Hi!' | 5,344,164 |
def soft_sign(x: ArrayLike, *, constant: Optional[bool] = None) -> Tensor:
"""Returns the soft sign function x / (1 + |x|).
Parameters
----------
x : ArrayLike
Input data.
constant : boolean, optional (default=False)
If ``True``, the returned tensor is a constant (it
does n... | 5,344,165 |
def get_vdfdx(stuff_for_time_loop, vdfdx_implementation="exponential"):
"""
This function enables VlaPy to choose the implementation of the vdfdx stepper
to use in the lower level sections of the simulation
:param stuff_for_time_loop: (dictionary) contains the derived parameters for the simulation
... | 5,344,166 |
def worker(args):
"""
1. Create the envelope request object
2. Send the envelope
"""
envelope_args = args["envelope_args"]
# 1. Create the envelope request object
envelope_definition = make_envelope(envelope_args)
# 2. call Envelopes::create API method
# Exceptions will be caught by... | 5,344,167 |
def write_colocated_data_time_avg(coloc_data, fname):
"""
Writes the time averaged data of gates colocated with two radars
Parameters
----------
coloc_data : dict
dictionary containing the colocated data parameters
fname : str
file name where to store the data
Returns
-... | 5,344,168 |
def get_method(client, request, xslt_code, operation,
current_date=datetime.datetime.now(pytz.timezone('US/Pacific')).strftime("%Y-%m-%dT%H:%M:%S"),
print_to_console=False, count=100, add_response_filter=True):
"""
:param client: Zeep client
:param request: request object
:... | 5,344,169 |
def _min(group_idx, a, size, fill_value, dtype=None):
"""Same as aggregate_numpy.py"""
dtype = minimum_dtype(fill_value, dtype or a.dtype)
dmax = np.iinfo(a.dtype).max if issubclass(a.dtype.type, np.integer)\
else np.finfo(a.dtype).max
ret = np.full(size, fill_value, dtype=dtype)
if fill_val... | 5,344,170 |
def autoflake(command):
"""Runs autoflake to remove unused imports on all .py files recursively
Arguments:
command {[type]} -- [description]
"""
print(
"""
Running autoflake to remove unused imports on all .py files recursively
===========================================================... | 5,344,171 |
def find_word(ch, row, boggle_lst, used_positions_lst, current, ans):
"""
:param ch: int, index for each character in a row
:param row: int, index for each row in the boggle list
:param boggle_lst: list, list for all rows
:param used_positions_lst: tuple, index of ch and row that indicates the position of an used ... | 5,344,172 |
def lazy_tt_ranks(tt):
"""Returns static TT-ranks of a TensorTrain if defined, and dynamic otherwise.
This operation returns a 1-D integer numpy array of TT-ranks if they are
available on the graph compilation stage and 1-D integer tensor of dynamic
TT-ranks otherwise.
Args:
tt: `TensorTrain` object.
... | 5,344,173 |
def word_errors(reference, hypothesis, ignore_case=False, delimiter=' '):
"""Compute the levenshtein distance between reference sequence and
hypothesis sequence in word-level.
:param reference: The reference sentence.
:type reference: str
:param hypothesis: The hypothesis sentence.
:type hypoth... | 5,344,174 |
def backup_fs_format(repos_path):
"""Rename the filesystem format file for repository REPOS_PATH.
Do not raise an error if the file is already renamed."""
format_path = os.path.join(repos_path, 'db', 'format')
try:
statinfo = os.stat(format_path)
except OSError:
# The file probably doesn't exist.
... | 5,344,175 |
def augment_note_matrix(nmat, length, shift):
"""Pitch shift a note matrix in R_base format."""
aug_nmat = nmat.copy()
aug_nmat[0: length, 1] += shift
return aug_nmat | 5,344,176 |
def breed_list(request):
""" Фикстура возвращает список всех пород собак """
return request.param | 5,344,177 |
def test_tablemodel(mock_program_dao):
"""Get a data model instance for each test function."""
# Create the device under test (dut) and connect to the database.
dut = RAMSTKDesignElectricTable()
dut.do_connect(mock_program_dao)
yield dut
# Unsubscribe from pypubsub topics.
pub.unsubscribe(... | 5,344,178 |
def norm_layer(norm_type, nc):
"""tbd"""
# normalization layer 1d
norm = norm_type.lower()
if norm == 'batch':
layer = batch_norm_1d(nc)
elif norm == 'layer':
layer = nn.LayerNorm(nc)
else:
raise NotImplementedError('normalization layer [%s] is not found' % norm)
retu... | 5,344,179 |
def does_equipment_channel_exist(code, channel_id, debug):
"""Check if equipment channel exist."""
if debug:
print '\n** does_equipment_channel_exist'
code_exists = False
channel_id_exists = False
query_string = ("SELECT count(*) FROM cable_plugs_view "
"WHERE code='%s' AND channel_id... | 5,344,180 |
def tail(file, n=1, bs=1024):
""" Read Last n Lines of file
credit:
https://www.roytuts.com/read-last-n-lines-from-file-using-python/
https://github.com/roytuts/python/blob/master/read-lines-from-last/last_lines_file.py
"""
f = open(file)
f.seek(0, 2)
l = 1-f.read(1).count('\n')
B ... | 5,344,181 |
def create_hparams(state, FLAGS): # pylint: disable=invalid-name
"""Creates hyperparameters to pass into Ray config.
Different options depending on search or eval mode.
Args:
state: a string, 'train' or 'search'.
FLAGS: parsed command line flags.
Returns:
tf.hparams object.
"""
epochs = ... | 5,344,182 |
def resources_match(resource_one, resource_two):
"""
Checks if resource_one and resource_two match. If two folders, recursively compares contents.
If two files, compares versions.
"""
if resource_one['type'] == FOLDER:
match = recursively_compare_folders(resource_one, resource_two)
else... | 5,344,183 |
def plotfootprints(simplefootprintlist, borderpixels, dimshape, chips, groupid, firstid, nextid, grouplen, heirarchy,
centroid, colorlist, verbose):
# ------------------------------------------------------------------------------------------------------------------------
"""
This function... | 5,344,184 |
def read():
"""Read content of predefined numpy archive file."""
return _read(tml.value('numpy', section='data', subkey='fname')) | 5,344,185 |
def test_run_method_should_raise_command_error_when_command_does_not_exist():
"""
Test HelpCommand.run for non-existing command
"""
options_mock = Mock()
args = ('mycommand',)
help_cmd = HelpCommand()
with pytest.raises(CommandError):
help_cmd.run(options_mock, args) | 5,344,186 |
def elexon_b1630(args):
""" Actual or forecast Wind & Solar Generation """
if not check_api_key(args):
return None
api = B1630(args.apikey)
if args.settlement_period is None:
print("A settlement period should be supplied using the --settlement-period flag (range 1 to 50)."
... | 5,344,187 |
def null_count(df):
"""
df is a dataframe
Check a dataframe for nulls and return the number of missing values.
"""
return df.isnull().sum().sum() | 5,344,188 |
def rpy2r(roll, pitch=None, yaw=None, *, unit="rad", order="zyx"):
"""
Create an SO(3) rotation matrix from roll-pitch-yaw angles
:param roll: roll angle
:type roll: float
:param pitch: pitch angle
:type pitch: float
:param yaw: yaw angle
:type yaw: float
:param unit: angular units:... | 5,344,189 |
def plot3d_embeddings(dataset, embeddings, figure=None):
"""Plot sensor embedding in 3D space using mayavi.
Given the dataset and a sensor embedding matrix, each sensor is shown as
a sphere in the 3D space. Note that the shape of embedding matrix is
(num_sensors, 3) where num_sensors corresponds to the... | 5,344,190 |
def geometry(cnf_save_fs, mod_thy_info, conf='sphere', hbond_cutoffs=None):
""" get the geometry
"""
assert conf in ('minimum', 'sphere')
# Read the file system
if conf == 'minimum':
geom = _min_energy_conformer(
cnf_save_fs, mod_thy_info, hbond_cutoffs=hbond_cutoffs)
elif ... | 5,344,191 |
def exportToVtk(gridFunction, dataType, dataLabel, fileNamesBase, filesPath=None, type='ascii'):
"""
Export a grid function to a VTK file.
*Parameters:*
- gridFunction (GridFunction)
The grid function to be exported.
- dataType ('cell_data' or 'vertex_data')
Determines w... | 5,344,192 |
def plotSources(coords, observations, diameter=12,
include=None, exclude=None,
mosaic=False, width=60, length=60, pa=0.,
mframe='icrs', freq=345., mosonly=False,
plotroot='source', plotsizeo=120., plottype='pdf'):
"""
Plot observations that are ... | 5,344,193 |
def save_img(img, path):
"""
Writes the image to disk
:param img: the rgb image to save
:param path: the target path
"""
img = to_rgb(img)
smisc.imsave(path, img.round().astype(np.uint8)) | 5,344,194 |
def get_fullname(user):
""" Get from database fullname for user
"""
data = frappe.db.sql("""
SELECT full_name FROM `tabUser` WHERE name=%s and docstatus<2""", user, True)
return data | 5,344,195 |
def process_song_data(spark, input_data, output_data):
"""
Gets the data from the s3 bucket and creates the
artists and songs tables
:param spark: the spark session
:param input_data: the basic path for the input data
:param output_data: the basic path where the dat... | 5,344,196 |
def greedy_inference(original, protein_column = 'Protein Accession', peptide_column = 'Base Sequence'):
"""
Greedy protein inference algorithm for matching peptids to corresponding proteins
Notaion:
G : original graph
Gi : inferred graph
Gr : remaining graph
Gd: dropped graph
p : greedi... | 5,344,197 |
def cmd_display(current_board : board.Board, flags : dict):
"""cmd: display [-a]. Display the board state. -a for more information"""
graphics.display_board(current_board)
if 'a' in flags:
current_board.print_data()
if 'p' in flags:
current_board.print_active_pieces() | 5,344,198 |
def statistics_command(message):
"""Statistics command handler"""
sqlighter = db_worker.SQLighter(os.getenv('DB_PATH'))
chat_id = message.chat.id
notes = sqlighter.get('chat_id', chat_id)
ready_num = unready_num = 0
for note in notes:
if note[3]:
ready_num += 1
else:
... | 5,344,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.