content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_dims(a):
""" update dimensions
"""
assert a.dims == ('d0','d1')
a.dims = ('newa','newb')
assert a.dims == ('newa','newb')
assert a.axes[0].name == 'newa'
assert a.axes[1].name == 'newb' | 5,358,500 |
async def statuslist(ctx, *, statuses: str):
"""Manually make a changing status with each entry being in the list."""
bot.x = 0
statuses = statuses.replace("\n", bot.split)
status_list = statuses.split(bot.split)
if len(status_list) <= 1:
return await bot.send_embed(ctx, f"You cannot have ... | 5,358,501 |
def edgeplot(LA, Kbar=Kbar, Lbar=Lbar, alpha=alpha, beta=beta):
"""Draw an edgeworth box
arguments:
LA -- labor allocated to ag, from which calculate QA(Ka(La),La)
"""
KA = edgeworth(LA, Kbar, Lbar, alpha, beta)
RTS = (alpha/(1-alpha))*(KA/LA)
QA = F(KA, LA, alpha)
QM = G(Kbar-KA, ... | 5,358,502 |
def kebab(string):
"""kebab-case"""
return "-".join(string.split()) | 5,358,503 |
def getUserID(person):
"""
Gets Humhub User ID using name information
:param person: Name of the person to get the Humhub User ID for
:type person: str.
"""
# search for person string in humhub db
# switch case for only one name (propably lastname) or
# two separate strings (firstname +... | 5,358,504 |
def analyze_dir(data_dir,px_size,category,ch_actin,sigma_actin,version):
""" Analyzes all linescan pairs in a directory full of linescans
Args:
data_dir (str): the directory containing the linescans
px_size (float): the pixel size for the linescans (for the whole directory)
category (st... | 5,358,505 |
def test_frequency_encoder_strings():
"""Test the FrequencyEncoder on string data.
Ensure that the FrequencyEncoder can fit, transform, and reverse
transform on string data. Expect that the reverse transformed data
is the same as the input.
Input:
- 4 rows of string data
Output:
... | 5,358,506 |
def assert_equal(actual: Literal["lstsq"], desired: Literal["lstsq"]):
"""
usage.statsmodels: 1
"""
... | 5,358,507 |
def parse_atom(s, atom_index=-1, debug=False):
""" Parses an atom in a string s
:param s: The string to parse
:type s: str
:param atom_index: the atom_index counter for continous parsing. Default is -1.
:type atom_index: int
:return: a list of atoms, a list of bonds and an ... | 5,358,508 |
def b58decode(v, length):
""" decode v into a string of len bytes
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base**i)
result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + resu... | 5,358,509 |
def get_submission_by_id(request, submission_id):
"""
Returns a list of test results assigned to the submission with the given id
"""
submission = get_object_or_404(Submission, pk=submission_id)
data = submission.tests.all()
serializer = TestResultSerializer(data, many=True)
return Response(... | 5,358,510 |
def get_resource_path(resource_name):
"""Get the resource path.
Args:
resource_name (str): The resource name relative to the project root
directory.
Returns:
str: The true resource path on the system.
"""
package = pkg_resources.Requirement.parse(PACKAGE_NAME)
retur... | 5,358,511 |
def die_info_rec(die, indent_level=' '):
""" A recursive function for showing information about a DIE and its
children.
"""
print(indent_level + 'DIE tag=%s, attrs=' % die.tag)
for name, val in die.attributes.items():
print(indent_level + ' %s = %s' % (name, val))
child_indent = ... | 5,358,512 |
def do_cluster(items, mergefun, distfun, distlim):
"""Pairwise nearest merging clusterer.
items -- list of dicts
mergefun -- merge two items
distfun -- distance function
distlim -- stop merging when distance above this limit
"""
def heapitem(d0, dests):
"""Find nearest neighbor for ... | 5,358,513 |
def write_features(features, path):
"""
Write a list of features to a file at `path`. The repr of each
feature is written on a new line.
@param features list of features to write
@param path path to write to
"""
with open(path,'w') as f:
for feat in features:
print >>f, repr(feat) | 5,358,514 |
def read_csv(input_file, quotechar='"'):
"""Reads a tab separated value file."""
with open(input_file, "r") as f:
reader = csv.reader(f,quotechar=quotechar)
lines = []
for line in reader:
lines.append(line)
return lines | 5,358,515 |
def test_get_mode(ecomax: EcoMAX) -> None:
"""Test getting mode."""
data = _test_data
ecomax.set_data(data)
assert ecomax.mode == MODES[MODE_HEATING]
# Test with unknown mode.
data[DATA_MODE] = 69
ecomax.set_data(data)
assert ecomax.mode == DATA_UNKNOWN | 5,358,516 |
def rotate_coordinates(local3d, angles):
"""
Rotate xyz coordinates from given view_angles.
local3d: numpy array. Unit LOCAL xyz vectors
angles: tuple of length 3. Rotation angles around each GLOBAL axis.
"""
cx, cy, cz = np.cos(angles)
sx, sy, sz = np.sin(angles)
mat33_x = np.array([
... | 5,358,517 |
def verify_selected_option_by_text(element, text):
"""Verify an element has a selected option by the option text
Parameters:
element : element
text : value
"""
element = get_browser().find(element)
with _verify_step('Verify selected option text of element {} is {}'
... | 5,358,518 |
def quantize_enumerate(x_real, min, max):
"""
Randomly quantize in a way that preserves probability mass.
We use a piecewise polynomial spline of order 3.
"""
assert min < max
lb = x_real.detach().floor()
# This cubic spline interpolates over the nearest four integers, ensuring
# piecew... | 5,358,519 |
def plot_speed(dataframe1, colour, legend_label):
"""Plot the speed of the vessel throughout the cruise to identify outlying speeds."""
# Plot speed data
plt.scatter(dataframe1.iloc[::60].longitude, dataframe1.iloc[::60].speed, c=colour, label=legend_label)
plt.title("Speed of vessel along track")
... | 5,358,520 |
def counter_format(counter):
"""Pretty print a counter so that it appears as: "2:200,3:100,4:20" """
if not counter:
return "na"
return ",".join("{}:{}".format(*z) for z in sorted(counter.items())) | 5,358,521 |
def drot(x, y, c, s):
"""
Apply the Givens rotation {(c,s)} to {x} and {y}
"""
# compute
gsl.blas_drot(x.data, y.data, c, s)
# and return
return x, y | 5,358,522 |
def _update_dict_within_dict(items, config):
""" recursively update dict within dict, if any """
for key, value in items:
if isinstance(value, dict):
config[key] = _update_dict_within_dict(
value.items(), config.get(key, {})
)
else:
config[key]... | 5,358,523 |
def masterProductFieldUpdate(objectId: str):
"""
Submit handler for updating & removing field overrides.
:param objectId: The mongodb master product id.
"""
key = request.form.get("field-key")
value = request.form.get("field-value")
# Clean up and trim tags if being set.
if key == MAST... | 5,358,524 |
def recalc_Th(Pb, age):
"""Calculates the equivalent amount of ThO_2 that would be required to produce the
measured amount of PbO if there was no UO_2 in the monazite.
INPUTS:
Pb: the concentration of Pb in parts per million
age: the age in million years
"""
return (232. / 208.) * Pb / (np... | 5,358,525 |
def relative_periodic_trajectory_wrap(
reference_point: ParameterVector,
trajectory: ArrayOfParameterVectors,
period: float = 2 * np.pi,
) -> ArrayOfParameterVectors:
"""Function that returns a wrapped 'copy' of a parameter trajectory such that
the distance between the final point of the traject... | 5,358,526 |
def planToSet(world,robot,target,
edgeCheckResolution=1e-2,
extraConstraints=[],
equalityConstraints=[],
equalityTolerance=1e-3,
ignoreCollisions=[],
movingSubset=None,
**planOptions):
"""
Creates a MotionPlan obje... | 5,358,527 |
def itkimage_to_json(itkimage, manager=None):
"""Serialize a Python itk.Image object.
Attributes of this dictionary are to be passed to the JavaScript itkimage
constructor.
"""
if itkimage is None:
return None
else:
direction = itkimage.GetDirection()
directionMatrix = d... | 5,358,528 |
def test_two_agents(tmp_path, empty_ensemble):
"""
:tmp_path: https://docs.pytest.org/en/stable/tmpdir.html
"""
@fdb.transactional
def get_started(tr):
return joshua_model._get_snap_counter(tr, ensemble_id, "started")
assert len(joshua_model.list_active_ensembles()) == 0
ensemble_i... | 5,358,529 |
def project(pnt, norm):
"""Projects a point following a norm."""
t = -np.sum(pnt*norm)/np.sum(norm*norm)
ret = pnt+norm*t
return ret/np.linalg.norm(ret) | 5,358,530 |
def RunExtraTreesClassifier(trainDf, testDf):
"""RunExtraTreesClassifier
Runs a Extra Trees Classifier on training and testing dataframes.
Input:
trainDf -- the training DataFrame (pandas)
testDf -- the testing DataFrame (pandas)
"""
train_X, train_y, test_X = createArrays(trainDf, testDf)
# Split... | 5,358,531 |
def fix_trajectory(traj):
"""Remove duplicate waypoints that are introduced during smoothing.
"""
cspec = openravepy.ConfigurationSpecification()
cspec.AddDeltaTimeGroup()
iwaypoint = 1
num_removed = 0
while iwaypoint < traj.GetNumWaypoints():
waypoint = traj.GetWaypoint(iwaypoint, ... | 5,358,532 |
def calculate_edt(im, outpath=''):
"""Calculate distance from mask."""
mask = im.ds[:].astype('bool')
abs_es = np.absolute(im.elsize)
dt = distance_transform_edt(~mask, sampling=abs_es)
# mask = im.ds[:].astype('uint32')
# dt = edt.edt(mask, anisotropy=im.elsize, black_border=True, order='F', ... | 5,358,533 |
def select_report_data(conn):
""" select report data to DB """
cur = conn.cursor()
cur.execute("SELECT * FROM report_analyze")
report = cur.fetchall()
cur.close()
return report | 5,358,534 |
def test__get_obj__nonentity(obj, get_func):
"""Test getting of entities"""
with patch.object(SYN, get_func, return_value=obj) as patch_get:
return_obj = GET_CLS._get_obj(obj)
if isinstance(obj, (synapseclient.Team, synapseclient.Evaluation)):
patch_get.assert_called_once_with(obj.na... | 5,358,535 |
def func_lorentz_by_h_pv(z, h_pv, flag_z: bool = False, flag_h_pv: bool = False):
"""Gauss function as function of h_pv
"""
inv_h_pv = 1./h_pv
inv_h_pv_sq = numpy.square(inv_h_pv)
z_deg = z * 180./numpy.pi
c_a = 2./numpy.pi
a_l = c_a * inv_h_pv
b_l = 4.*inv_h_pv_sq
z_deg_sq = numpy.s... | 5,358,536 |
def test_train_rl_main(tmpdir):
"""Smoke test for imitation.scripts.train_rl.rollouts_and_policy."""
run = train_rl.train_rl_ex.run(
named_configs=["cartpole"] + ALGO_FAST_CONFIGS["rl"],
config_updates=dict(
common=dict(log_root=tmpdir),
),
)
assert run.status == "COM... | 5,358,537 |
async def test_update_not_playing(hass, lastfm_network):
"""Test update when no playing song."""
lastfm_network.return_value.get_user.return_value = MockUser(None)
assert await async_setup_component(
hass,
sensor.DOMAIN,
{"sensor": {"platform": "lastfm", "api_key": "secret-key", "u... | 5,358,538 |
def backup_postgres_db() -> Tuple[Optional[str], bytes]:
"""Backup postgres db to a file."""
try:
time_str = datetime.now().strftime("%d-%m-%YT%H:%M:%S")
filename = f"backup_restore/backups/{time_str}-{settings.POSTGRES_CUSTOM_DB}.dump"
backup_name = f"{time_str}-{settings.POSTGRES_CUSTO... | 5,358,539 |
def get_profile(aid):
"""
get profile image of author with the aid
"""
if 'logged_in' in session and aid ==session['logged_id']:
try:
re_aid = request.args.get("aid")
re = aController.getAuthorByAid(re_aid)
if re != None:
return re
... | 5,358,540 |
def SystemSettings_GetMetric(*args, **kwargs):
"""SystemSettings_GetMetric(int index, Window win=None) -> int"""
return _misc_.SystemSettings_GetMetric(*args, **kwargs) | 5,358,541 |
def all_files(dir, pattern):
"""Recursively finds every file in 'dir' whose name matches 'pattern'."""
return [f.as_posix() for f in [x for x in Path(dir).rglob(pattern)]] | 5,358,542 |
def get_identity_groups(ctx):
"""Load identity groups definitions."""
return render_template('identity-groups', ctx) | 5,358,543 |
def main():
"""
Entry point
"""
# Prepare factorials for O(1) lookup
factorials = [1]
for i in range(1, 101):
factorials.append(factorials[-1] * i)
# Now start counting
ncr_count = 0
for n in range(1, 101):
for r in range(1, n+1):
ncr = factorials[n] / (f... | 5,358,544 |
def get_video_stream(consumer):
"""
Here is where we recieve streamed images from the Kafka Server and convert
them to a Flask-readable format.
"""
meta = False
while True:
if not meta:
yield(b'<meta http-equiv="refresh" content="300">\n')
meta = True
els... | 5,358,545 |
def test_api_challenges_get_ctftime_public():
"""Can a public user get /api/v1/challenges if ctftime is over"""
app = create_ctfd()
with app.app_context(), freeze_time("2017-10-7"):
set_config("challenge_visibility", "public")
with app.test_client() as client:
r = client.get("/ap... | 5,358,546 |
def write_buffer_values(output_dir, buffer_filename, buffer_quant, i_bits=12, q_bits=None):
"""
:param output_dir:
:param buffer_filename:
:param buffer_quant:
:param i_bits:
:param q_bits:
:return:
"""
q_bits = i_bits if not q_bits else q_bits
with open(os.path.join(output_dir,... | 5,358,547 |
def fix_behaviour_contrib_auth_user_is_anonymous_is_authenticated_callability(utils):
"""
Make user.is_anonymous and user.is_authenticated behave both as properties and methods,
by preserving their callability like in earlier Django version.
"""
utils.skip_if_app_not_installed("django.contrib.c... | 5,358,548 |
def BZPoly(pnts, poly, mag, openPoly=False):
"""TODO WRITEME.
Parameters
----------
pnts : list
Measurement points [[p1x, p1z], [p2x, p2z],...]
poly : list
Polygon [[p1x, p1z], [p2x, p2z],...]
mag : [M_x, M_y, M_z]
Magnetization = [M_x, M_y, M_z]
"""
dgz = calcP... | 5,358,549 |
def conv(structure_file, file_format):
"""
Convert a structure into the conventional unit cell.
"""
from pybat.cli.commands.util import conventional_structure
conventional_structure(structure_file=structure_file,
fmt=file_format) | 5,358,550 |
def verify_rotation_speeds_have_units(step, human_readable):
"""Verify all rotation speeds have units."""
for prop, val in step.properties.items():
if step.PROP_LIMITS.get(prop, None) is ROTATION_SPEED_PROP_LIMIT:
if step.properties.get('stir', None):
assert f'{format_number(... | 5,358,551 |
def matches(spc, shape_):
"""
Return True if the shape adheres to the spc (spc has optional color/shape
restrictions)
"""
(c, s) = spc
matches_color = c is None or (shape_.color == c)
matches_shape = s is None or (shape_.name == s)
return matches_color and matches_shape | 5,358,552 |
def jsonsafe(obj: Any) -> ResponseVal:
"""
Catch the TypeError which results from encoding non-encodable types
This uses the serialize function from my.core.serialize, which handles
serializing most types in HPI
"""
try:
return Response(dumps(obj), status=200, headers={"Content-Type": "a... | 5,358,553 |
def get_appliances(self) -> list:
"""Get all appliances from Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliance
- GET
- /appliance
:return: Returns list of dictionaries of each appliance
:r... | 5,358,554 |
def delete_result_files(path, name):
""" Deletes opensees result files.
Parameters:
path (str): Path to the opensees input file.
name (str): Name of the structure.
Returns:
None
"""
out_path = os.path.join(path, name + '_output')
shutil.rmtree(out_path) | 5,358,555 |
def save_from_form(event, POST):
"""Save an event from form data."""
# save items
names = POST.getlist('item_name')
quantities = POST.getlist('item_quantity')
prices_per_unit = POST.getlist('item_price_per_unit')
funding_already_received =\
POST.getlist('item_funding_already_received')
... | 5,358,556 |
def is_str(element):
"""True if string else False"""
check = isinstance(element, str)
return check | 5,358,557 |
def worker(repo_url: str, project_path: str, docker_port: int, host_port: int):
"""Main worker that will:
- create required directories
- clone repository
- build Dockerfile
- start container
- remove container and temporary directory
"""
if not project_path:
project_path = mkdte... | 5,358,558 |
def anonymize_and_streamline(old_file, target_folder):
"""
This function loads the edfs of a folder and
1. removes their birthdate and patient name
2. renames the channels to standardized channel names
3. saves the files in another folder with a non-identifyable
4. verifies that the new files h... | 5,358,559 |
def test_normal():
"""Test multi_map with no default_dict."""
# first char is key
data = iter(SEQ)
res = multi_map(lambda x: x[0], data)
assert res == {'A': ['APPLE', 'AARDVARK'],
'B': ['BANANA']}
assert list(data) == []
with pytest.raises(KeyError):
tmp = res['C']... | 5,358,560 |
def test_registry_delete_key_async(cbcsdk_mock):
"""Test the response to the 'reg delete key' command."""
cbcsdk_mock.mock_request('POST', '/appservices/v6/orgs/test/liveresponse/sessions', SESSION_INIT_RESP)
cbcsdk_mock.mock_request('GET', '/appservices/v6/orgs/test/liveresponse/sessions/1:2468', SESSION_P... | 5,358,561 |
def main():
"""
This program will ask user to enter a number to check the movement of alphabet's order, then user can enter a
ciphered word or sentence base on their alphabet movement.
Then function 'deciphered(x,y)' will transform those ciphered characters into right word or sentence.
"""
secre... | 5,358,562 |
def readiter(inputFile, *args):
"""Returns an iterator that calls read(*args) on the inputFile."""
while True:
ch = inputFile.read(*args)
if ch:
yield ch
else:
raise StopIteration | 5,358,563 |
def main() -> None:
"""main function"""
# Look for default ini file in "/etc/actworkers.ini" and ~/config/actworkers/actworkers.ini
# (or replace .config with $XDG_CONFIG_DIR if set)
args = worker.handle_args(parseargs())
actapi = worker.init_act(args)
if not args.apikey:
worker.fatal... | 5,358,564 |
def deal_text(text: str) -> str:
"""deal the text
Args:
text (str): text need to be deal
Returns:
str: dealed text
"""
text = " "+text
text = text.replace("。","。\n ")
text = text.replace("?","?\n ")
text = text.replace("!","!\n ")
text = text.replace(";"... | 5,358,565 |
def extract_zip(src, dest):
"""extract a zip file"""
bundle = zipfile.ZipFile(src)
namelist = bundle.namelist()
for name in namelist:
filename = os.path.realpath(os.path.join(dest, name))
if name.endswith('/'):
os.makedirs(filename)
else:
path = os.path.... | 5,358,566 |
def refresh_cuda_memory():
"""
Re-allocate all cuda memory to help alleviate fragmentation
"""
# Run a full garbage collect first so any dangling tensors are released
gc.collect()
# Then move all tensors to the CPU
locations = {}
for obj in gc.get_objects():
if not isinstance(ob... | 5,358,567 |
def _find_timepoints_1D(single_stimulus_code):
"""
Find the indexes where the value of single_stimulus_code turn from zero to non_zero
single_stimulus_code : 1-D array
>>> _find_timepoints_1D([5,5,0,0,4,4,4,0,0,1,0,2,0])
array([ 0, 4, 9, 11])
>>> _find_timepoints_1D([0,0,1,2,3,0,1,0,0])
a... | 5,358,568 |
def stiffness_tric(
components: np.ndarray = None,
components_d: dict = None
) -> np.ndarray:
"""Generate triclinic fourth-order stiffness tensor.
Parameters
----------
components : np.ndarray
21 components of triclinic tensor, see
stiffness_component_dict
components_d : dic... | 5,358,569 |
def get_dataset(
dataset_name: str,
path: Optional[Path] = None,
regenerate: bool = False,
) -> TrainDatasets:
"""
Get the repository dataset.
Currently only [Retail Dataset](https://archive.ics.uci.edu/ml/datasets/online+retail) is available
Parameters:
dataset_name:
nam... | 5,358,570 |
def get_info_safe(obj, attr, default=None):
"""safely retrieve @attr from @obj"""
try:
oval = obj.__getattribute__(attr)
except:
logthis("Attribute does not exist, using default", prefix=attr, suffix=default, loglevel=LL.WARNING)
oval = default
return oval | 5,358,571 |
def mkviewcolbg(view=None, header=u'', colno=None, cb=None,
width=None, halign=None, calign=None,
expand=False, editcb=None, maxwidth=None):
"""Return a text view column."""
i = gtk.CellRendererText()
if cb is not None:
i.set_property(u'editable', True)
i.... | 5,358,572 |
def list2str(lst, indent=0, brackets=True, quotes=True):
"""
Generate a Python syntax list string with an indention
:param lst: list
:param indent: indention as integer
:param brackets: surround the list expression by brackets as boolean
:param quotes: surround each item with quotes
:return... | 5,358,573 |
def full_path(path):
"""
Get an absolute path.
"""
if path[0] == "/":
return path
return os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", path)
) | 5,358,574 |
def _roi_pool_shape(op):
"""Shape function for the RoiPool op.
"""
dims_data = op.inputs[0].get_shape().as_list()
channels = dims_data[3]
dims_rois = op.inputs[1].get_shape().as_list()
num_rois = dims_rois[0]
pooled_height = op.get_attr('pooled_height')
pooled_width = op.get_attr('pooled_width')
ou... | 5,358,575 |
def get_users(*, limit: int, order_by: str = "id", offset: Optional[str] = None) -> APIResponse:
"""Get users"""
appbuilder = current_app.appbuilder
session = appbuilder.get_session
total_entries = session.query(func.count(User.id)).scalar()
to_replace = {"user_id": "id"}
allowed_filter_attrs = ... | 5,358,576 |
def extract_sicd(
img_header: Union[ImageSegmentHeader, ImageSegmentHeader0],
transpose: True,
nitf_header: Optional[Union[NITFHeader, NITFHeader0]] = None) -> SICDType:
"""
Extract the best available SICD structure from relevant nitf header structures.
Parameters
----------
... | 5,358,577 |
def ppo_clip_policy_loss(
logps: torch.Tensor,
logps_old: torch.Tensor,
advs: torch.Tensor,
clipratio: Optional[float] = 0.2
) -> torch.Tensor:
"""
Loss function for a PPO-clip policy.
See paper for full loss function math: https://arxiv.org/abs/1707.06347
Args:
- logps (torch.T... | 5,358,578 |
def reconstruct_modelseed_model(genome_id, model_id, template_reference=None):
""" Reconstruct a draft ModelSEED model for an organism.
Parameters
----------
genome_id : str
Genome ID or workspace reference to genome
model_id : str
ID of output model
template_reference : str, op... | 5,358,579 |
def tide_pred_correc(modfile,lon,lat,time,dbfile,ID,z=None,conlist=None):
"""
Performs a tidal prediction at all points in [lon,lat] at times in vector [time]
Applies an amplitude and phase correction based on a time series
"""
from timeseries import timeseries, loadDBstation
p... | 5,358,580 |
def generate_new_filename(this_key):
"""Generates filename for processed data from information in this_key."""
[_, _, source_id, experiment_id, _, _] = this_key.split('.')
this_fname = THIS_VARIABLE_ID+'_'+experiment_id+'_'+source_id
return this_fname | 5,358,581 |
def cls(cpu):
"""Clears the display"""
cpu.display.clear() | 5,358,582 |
def get_connection(user, pwd):
""" Obtiene la conexion a Oracle """
try:
connection = cx_Oracle.connect(user + '/' + pwd + '@' +
config.FISCO_CONNECTION_STRING)
connection.autocommit = False
print('Connection Opened')
return connection
... | 5,358,583 |
def process_dataset(file_name):
""" Evaluate the tivita index values for each record.
The evaluation is defined in task(args) where args are the entries of the
attached tables.
"""
start = timer()
file_path = os.path.join(data_path, file_name)
with tables.open_file(file_path, "r+") as file:... | 5,358,584 |
def _generate_select_expression_for_extended_string_unix_timestamp_ms_to_timestamp(source_column, name):
"""
More robust conversion from StringType to TimestampType. It is assumed that the
timezone is already set to UTC in spark / java to avoid implicit timezone conversions.
Is able to additionally hand... | 5,358,585 |
def get_webf_session():
"""
Return an instance of a Webfaction server and a session for authentication
to make further API calls.
"""
import xmlrpclib
server = xmlrpclib.ServerProxy("https://api.webfaction.com/")
print("Logging in to Webfaction as %s." % env.user)
if env.password is None... | 5,358,586 |
def _unpack_school_column_aliases() -> Dict[str, List[str]]:
"""
Unpack the known aliases for lookup table of alias_column_name -> schema_column_name.
:return: lookup table.
:raises: ValueError if an alias has more than one mapping to a schema column
"""
result = dict()
# add to the lookup t... | 5,358,587 |
def suntimecorr(ra, dec, obst, coordtable, verbose=False):
"""
This function calculates the light-travel time correction from
observer to a standard location. It uses the 2D coordinates (RA
and DEC) of the object being observed and the 3D position of the
observer relative to the standard location. ... | 5,358,588 |
def validate_numeric(array, name="array", caller=None):
""" Ensure that the array has some numeric dtype
If the shapes are not equal, then raise a ValueError.
Parameters
----------
array : np.array
A numpy array
name : string
A name for the variable in the error message
... | 5,358,589 |
def normalize_address(address: str, asHex: bool=False) -> Union[Tuple[str, str], Tuple[str, bytes]]:
"""Takes an address as raw byte or id__ and provides both formats back"""
try:
# convert recipient to raw if provided as id__
if address.startswith("id__"):
address_raw = NyzoStringEn... | 5,358,590 |
async def test_update_missing_mac_unique_id_added_from_dhcp(hass, remotews: Mock):
"""Test missing mac and unique id added."""
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_OLD_ENTRY, unique_id=None)
entry.add_to_hass(hass)
with patch(
"homeassistant.components.samsungtv.async_setup",
... | 5,358,591 |
def do_gen_binaryimage(inName, outName):
"""Generate binary image for testing"""
f_in = open(inName, "r")
contour = pickle.load(f_in)
f_in.close()
imageBinary, width, height = gen_binaryimage_from_contour( contour )
f_out = open( outName, "w" )
f_out.write( str(width) + " " + str(heigh... | 5,358,592 |
def get_welcome_response():
""" Prompt the user for the prayer
"""
session_attributes = {}
card_title = "Welcome"
speech_output = "What would you like me to pray with you? I can pray the Rosary and the Divine Mercy Chaplet."
reprompt_text = "What would you like me to pray with you?"
sho... | 5,358,593 |
async def test_bad_trigger_platform(hass):
"""Test bad trigger platform."""
with pytest.raises(vol.Invalid) as ex:
await async_validate_trigger_config(hass, [{"platform": "not_a_platform"}])
assert "Invalid platform 'not_a_platform' specified" in str(ex) | 5,358,594 |
def get_news(
limit: int = 60,
post_kind: str = "news",
filter_: Optional[str] = None,
region: str = "en",
) -> pd.DataFrame:
"""Get recent posts from CryptoPanic news aggregator platform. [Source: https://cryptopanic.com/]
Parameters
----------
limit: int
number of news to fetc... | 5,358,595 |
def login():
""" Display log in form and handle user login."""
email = request.args.get('emailLogin')
password = request.args.get('passwordLogin')
user = User.query.filter(User.email == email).first()
if user is None or not check_password_hash(user.password, password):
flash('Invalid ... | 5,358,596 |
def build():
"""Build benchmark."""
# Backup the environment.
new_env = os.environ.copy()
# Build afl with qemu (shared build code afl/afl++)
afl_fuzzer_qemu.build()
# Next, build a binary for Eclipser.
src = os.getenv('SRC')
work = os.getenv('WORK')
eclipser_outdir = get_eclipser_... | 5,358,597 |
def create_heart_rate(df):
"""Create heart rate based on provided."""
min = 50
max = 110
increments = 1
amount = 1000
integer_list = randomize_int(min, max, increments, amount)
heart_rate_array = np.array(integer_list)
df["HR"] = heart_rate_array | 5,358,598 |
def model_from_queue(model):
""" Returns the model dict if model is enqueued, else None."""
return _queue.get(model, None) | 5,358,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.