content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _fix_nested_array(func_ir):
"""Look for assignment like: a[..] = b, where both a and b are numpy arrays, and
try to eliminate array b by expanding a with an extra dimension.
"""
"""
cfg = compute_cfg_from_blocks(func_ir.blocks)
all_loops = list(cfg.loops().values())
def find_nest_level(l... | 5,354,900 |
def compute_angular_differences(matrix, orientation1, orientation2, cutoff):
""" Compute angular difference between two orientation ndarrays
:param matrix: domain matrix
:type matrix: np.ndarray
:param orientation1: orientation as (x, y, z, 3)
:type orientation1: np.ndarray
... | 5,354,901 |
def await(*args):
"""Runs all the tasks specified in args,
and finally returns args unwrapped.
"""
return _await(args) | 5,354,902 |
def convert_action_move_exists(action, board, player_turn):
"""
Converts action index to chess.Move object.
Assume the action key exists in map_action_uci
:param action:
:param board:
:param player_turn:
:return:
"""
move = chess.Move.from_uci(map_action_uci[action])
... | 5,354,903 |
def find_phase_files(input_filePath, run_number=1):
"""
Returns a list of the phase space files, sorted by z position
(filemname , z_approx)
"""
path, infile = os.path.split(input_filePath)
prefix = infile.split('.')[0] # Astra uses inputfile to name output
phase_import_file = ''
... | 5,354,904 |
def test_password_and_confirmed_password_must_be_the_same():
"""Password and confirmed password must be the same.""" | 5,354,905 |
def _get_system_username():
"""Return the current system user."""
if not win32:
import pwd
return pwd.getpwuid(getuid())[0]
else:
import win32api
import win32security
import win32profile
return win32api.GetUserName() | 5,354,906 |
def _get_vmedia_device():
"""Finds the device filename of the virtual media device using sysfs.
:returns: a string containing the filename of the virtual media device
"""
sysfs_device_models = glob.glob("/sys/class/block/*/device/model")
vmedia_device_model = "virtual media"
for model_file in s... | 5,354,907 |
def create_new_transaction_type(txn_type_model: transaction_type_model.TransactionTypeModel) -> None:
"""Save a new transaction type model"""
txn_type_dto = txn_type_model.export_as_at_rest()
_log.info(f"Adding transaction index for {txn_type_model.txn_type}")
redisearch.create_transaction_index(txn_typ... | 5,354,908 |
def convert_to_posixpath(file_path):
"""Converts a Windows style filepath to posixpath format. If the operating
system is not Windows, this function does nothing.
Args:
file_path: str. The path to be converted.
Returns:
str. Returns a posixpath version of the file path.
"""
if ... | 5,354,909 |
def generateCards(numberOfSymb):
"""
Generates a list of cards which are themselves a list of symbols needed on each card to respect the rules of Dobble.
This algorithm was taken from the french Wikipedia page of "Dobble".
https://fr.wikipedia.org/wiki/Dobble
:param numberOfSymb: Number of symbols needed on each c... | 5,354,910 |
def map_period_average(
inputfile,
var,
periods=[("2020", "2040"), ("2040", "2060"), ("2060", "2080"), ("2080", "2100")],
):
"""
Produces a dataset containing period averages of 'var' from an input dataset path.
Parameters
---------
inputfile : str
path to data file.
var : ... | 5,354,911 |
def get_metadata(tmpdirname):
"""
Get metadata from kmp.json if it exists.
If it does not exist then will return get_and_convert_infdata
Args:
inputfile (str): path to kmp file
tmpdirname(str): temp directory to extract kmp
Returns:
list[5]: info, system, options, keyboards... | 5,354,912 |
def assert_single_entry_approx_value(
numbers: List[Any],
index: int,
value: float = 1.0,
value_abs_eps: float = 1e-14,
zero_abs_eps: float = 0.0,
) -> None:
"""The input numbers should all be zero except for a single entry,
which should equal the expected value approximately at the given in... | 5,354,913 |
def match_facilities(facility_datasets,
authoritative_dataset,
manual_matches_df=None,
max_distance=150,
nearest_n=10,
meters_crs='epsg:5070',
reducer_fn=None):
"""Matches facilities. The da... | 5,354,914 |
def has_field_warning(meta, field_id):
"""Warn if dataset has existing field with same id."""
if meta.has_field(field_id):
print(
"WARN: Field '%s' is already present in dataset, not overwriting."
% field_id
)
print("WARN: Use '--replace' flag to overwrite existin... | 5,354,915 |
def volume(surface):
"""Compute volume of a closed triangulated surface mesh."""
properties = vtk.vtkMassProperties()
properties.SetInput(surface)
properties.Update()
return properties.GetVolume() | 5,354,916 |
def parse_json_to_csv(json_file_in, csv_file_out):
"""
This method will take in a JSON file parse it and will generate a CSV file with the
same content.
Parameters:
json_file_in -- Input file containing list of JSON objects
csv_file_out -- Output file for CSV content
"""
with open(json_... | 5,354,917 |
def simulate():
"""
Simulate one thing
"""
doors = getRandomDoorArray()
pickedDoor = chooseDoor()
goatDoor, switchDoor = openGoatDoor(pickedDoor, doors)
return doors[pickedDoor], doors[switchDoor] | 5,354,918 |
def depart(visitor: DocxTranslator, node: Node):
"""Finish processing image node"""
assert isinstance(visitor, DocxTranslator)
assert isinstance(node, Node) | 5,354,919 |
def fc_layer(x):
"""Basic Fully Connected (FC) layer with an activation function."""
return x | 5,354,920 |
def get_slot_counts(cls: type) -> Dict[str, int]:
"""
Collects all of the given class's ``__slots__``, returning a
dict of the form ``{slot_name: count}``.
:param cls: The class whose slots to collect
:return: A :class:`collections.Counter` counting the number of occurrences of each slot
"""
... | 5,354,921 |
def sequence_pipeline(message):
"""Sequence pipeline.
Send to test backend twice.
"""
yield send(NullOutput(test_arg=2))
yield send(NullOutput(test_arg=1)) | 5,354,922 |
def rot6d_to_axisAngle(x):
""""Convert 6d rotation representation to axis angle
Input:
(B,6) Batch of 6-D rotation representations
Output:
(B,3) Batch of corresponding axis angle
"""
rotMat = rot6d_to_rotmat(x)
return rotationMatrix_to_axisAngle(rotMat) | 5,354,923 |
def mark_boundaries(simulation):
"""
Mark the boundaries of the mesh with different numbers to be able to
apply different boundary conditions to different regions
"""
simulation.log.info('Creating boundary regions')
# Create a function to mark the external facets
mesh = simulation.data['mes... | 5,354,924 |
def within_tolerance(x, y, tolerance):
"""
Check that |x-y| <= tolerance with appropriate norm.
Args:
x: number or array (np array_like)
y: number or array (np array_like)
tolerance: Number or PercentageString
NOTE: Calculates x - y; may raise an error for incompatible shapes.
... | 5,354,925 |
def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a Hermite_e series.
Returns the Hermite_e series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The sca... | 5,354,926 |
def test_log() -> None:
"""Test log and log filtering."""
logs = simplejson.loads(execute_cli_command(["--json", "log"]))
assert len(logs) == 0
execute_cli_command(["branch", "dev_test_log"])
table = _new_table("test_log_dev")
make_commit("log.foo.dev", table, "dev_test_log", author="nessie_user... | 5,354,927 |
def model_netradiation(minTair = 0.7,
maxTair = 7.2,
albedoCoefficient = 0.23,
stefanBoltzman = 4.903e-09,
elevation = 0.0,
solarRadiation = 3.0,
vaporPressure = 6.1,
extraSolarRadiation = 11.7):
"""
- Description:
* Title: NetRadi... | 5,354,928 |
def main():
"""
Testing function for DFA brzozowski algebraic method Operation
"""
argv = sys.argv
if len(argv) < 2:
targetfile = 'target.y'
else:
targetfile = argv[1]
print 'Parsing ruleset: ' + targetfile,
flex_a = Flexparser()
mma = flex_a.yyparse(targetfile)
p... | 5,354,929 |
def get_tagset(sentences, with_prefix):
""" Returns the set of entity types appearing in the list of sentences.
If with_prefix is True, it returns both the B- and I- versions for each
entity found. If False, it merges them (i.e., removes the prefix and only
returns the entity type).
"""
iobs =... | 5,354,930 |
def pdb_to_psi4(starting_geom, mol_name, method, basis_set, charge=0, multiplicity=1, symmetry='C1', geom_opt=True,
sp_energy=False, fixed_dih=None, mem=None, constrain='dihedral', dynamic_level=3,
consecutive_backsteps=None, geom_maxiter=250, xyz_traj=True):
"""
:param pdb: str... | 5,354,931 |
def normpath(s: str) -> str:
"""Normalize path. Just for compatibility with normal python3."""
return s | 5,354,932 |
def threshold_num_spikes(
sorting,
threshold,
threshold_sign,
sampling_frequency=None,
**kwargs
):
"""
Computes and thresholds the num spikes in the sorted dataset with the given sign and value.
Parameters
----------
sorting: SortingExtractor
The sort... | 5,354,933 |
def mad(stack, axis=0, scale=1.4826):
"""Median absolute deviation,
default is scaled such that +/-MAD covers 50% (between 1/4 and 3/4)
of the standard normal cumulative distribution
"""
stack_abs = np.abs(stack)
med = np.nanmedian(stack_abs, axis=axis)
return scale * np.nanmedian(np.abs(st... | 5,354,934 |
def set_up_logging(
*,
log_filename: str = "log",
verbosity: int = 0,
use_date_logging: bool = False,
) ->logging.Logger:
"""Set up proper logging."""
# log everything verbosely
LOG.setLevel(logging.DEBUG)
logging.Formatter.converter = time.gmtime
handler: Any
... | 5,354,935 |
def dir_tree(root, dir_exclude=None, ext_exclude=None):
""" Return all files at or under root directory """
ext_exclude = [] if ext_exclude is None else ext_exclude
ext_exclude = ['.'+item for item in ext_exclude]
dir_exclude = [] if dir_exclude is None else dir_exclude
dir_exclude = [os.path.join(r... | 5,354,936 |
def _get_window(append, size=(1000, 600)):
"""
Return a handle to a plot window to use for this plot.
If append is False, create a new plot window, otherwise return
a handle to the given window, or the last created window.
Args:
append (Union[bool, PlotWindow]): If true, return the last
... | 5,354,937 |
def cufftExecC2C(plan, idata, odata, direction=CUFFT_FORWARD):
""" Execute the planned complex->complex FFT.
Parameters
----------
`plan` : cufftHandle
The plan handle.
`idata` : pointer to cufftComplex array
`odata` : pointer to cufftComplex array
The input and output arrays. T... | 5,354,938 |
def _proxies_dict(proxy):
"""Makes a proxy dict appropriate to pass to requests."""
if not proxy:
return None
return {'http': proxy, 'https': proxy} | 5,354,939 |
def distribute(data_schema, columns, entity_ids=None, codes=None, histnorm="percent", nbinsx=20, filters=None):
"""
distribute indicators(columns) of entities
:param data_schema:
:param columns:
:param entity_ids:
:param codes:
:param histnorm: "percent", "probability", default "percent"
... | 5,354,940 |
def _get_schedule_times(name, date):
"""
Fetch all `from_time` from [Healthcare Schedule Time Slot]
:param name: [Practitioner Schedule]
:param date: [datetime.date]
:return:
"""
mapped_day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
time_slots = frap... | 5,354,941 |
def setConsoleName(name):
"""
This sets the name of the python logger that represents the console.
"""
_console_name = name | 5,354,942 |
def delete(client, data, force=False):
"""
"""
param = {'logical-router-port-id': get_id(client, data)}
if force:
param['force'] = True
request = client.__getattr__(MODULE).DeleteLogicalRouterPort(**param)
response, _ = request.result()
return response | 5,354,943 |
def doc():
"""
Static methods are methods that are related to a class in some way,
but don’t need to access any class-specific data. You don’t have to use self,
and you don’t even need to instantiate an instance, you can simply call your method.
The @staticmethod decorator is used to tell Python that this method... | 5,354,944 |
def z_standardization(
spark,
idf,
list_of_cols="all",
drop_cols=[],
pre_existing_model=False,
model_path="NA",
output_mode="replace",
print_impact=False,
):
"""
Standardization is commonly used in data pre-processing process. z_standardization standardizes the selected
attri... | 5,354,945 |
def event_stats(wit_df, wit_im, wit_area, pkey='SYSID'):
"""
Compute inundation event stats with given wit wetness, events defined by (start_time, end_time)
and polygon areas
input:
wit_df: wetness computed from wit data
wit_im: inundation event
wit_area:... | 5,354,946 |
def upvote_book(book_id):
"""
Allows a user to upvote a book.
The upvotes field on the book document is updated,
as well as the booksUpvoted array on the user document
and the upvotedBy array on the book document.
"""
user_to_update = mongo.db.users.find_one({"username": session["user"]})
... | 5,354,947 |
def bottlegrowth_split_mig(params, ns):
"""
params = (nuB, nuF, m, T, Ts)
ns = [n1, n2]
Instantanous size change followed by exponential growth then split with
migration.
nuB: Ratio of population size after instantanous change to ancient
population size
nuF: Ratio of contempoary t... | 5,354,948 |
def arch_to_macho(arch):
"""Converts an arch string into a macho arch tuple."""
try:
arch = rustcall(lib.symbolic_arch_to_macho, encode_str(arch))
return (arch.cputype, arch.cpusubtype)
except ignore_arch_exc:
pass | 5,354,949 |
def visualize_3d(img, proc_param, joints, verts, cam, joints3d):
"""
Renders the result in original image coordinate frame.
"""
import matplotlib.pyplot as plt
cam_for_render, vert_shifted, joints_orig = vis_util.get_original(
proc_param, verts, cam, joints, img_size=img.shape[:2])
# R... | 5,354,950 |
def limit_ops_skeleton(**kwargs):
"""This function provides a skeleton for limit ops calculations"""
group_phase = kwargs['group_phase']
tail = kwargs['tail']
loading_phase = kwargs['loading_phase']
final_phase = kwargs['final_phase']
grouped_df = limit_ops_general_groups(
**group_phase... | 5,354,951 |
def xy2traceset(xpos, ypos, **kwargs):
"""Convert from x,y positions to a trace set.
Parameters
----------
xpos, ypos : array-like
X,Y positions corresponding as [nx,Ntrace] arrays.
invvar : array-like, optional
Inverse variances for fitting.
func : :class:`str`, optional
... | 5,354,952 |
def Fn(name, f, n_out=1): # pylint: disable=invalid-name
"""Returns a layer with no weights that applies the function `f`.
`f` can take and return any number of arguments, and takes only positional
arguments -- no default or keyword arguments. It often uses JAX-numpy (`jnp`).
The following, for example, would... | 5,354,953 |
def leer_pdf_slate(ubicacion_archivo, password=None):
"""
Utiliza la librería slate3k para cargar un archivo PDF y extraer el texto de sus páginas.
:param ubicacion_archivo: (str). Ubicación del archivo PDF que se desea leer.
:param password: (str). Valor por defecto: None. Parámetro opcional para lee... | 5,354,954 |
def gen_run_entry_str(query_id, doc_id, rank, score, run_id):
"""A simple function to generate one run entry.
:param query_id: query id
:param doc_id: document id
:param rank: entry rank
:param score: entry score
:param run_id: run id
"""
return f'{query_id} Q0 {doc_id} {rank}... | 5,354,955 |
async def mesh_auto_send(args):
"""Asynchronously sends messages from the queue via mesh link
"""
send_method, mesh_queue, gid = args
while True:
async for data in mesh_queue:
send_method(gid=gid, message=data, binary=True) | 5,354,956 |
def remove_template(args, output_file_name):
"""
remove the arg to use template; called when you make the template
:param args:
:param output_file_name:
:return:
"""
template_name = ''
dir_name = ''
template_found = False
for i in args:
if i.startswith('--template'):
... | 5,354,957 |
def replaceext(filepath, new_ext, *considered_exts):
"""replace extension of filepath with new_ext
filepath: a file path
new_ext: extension the returned filepath should have (e.g ".ext")
considered_exts: Each is a case insensitive extension that should be considered a
single extension and replace... | 5,354,958 |
def do_rename(cs, args):
"""Rename a vsm."""
kwargs = {}
if args.display_name is not None:
kwargs['display_name'] = args.display_name
if args.display_description is not None:
kwargs['display_description'] = args.display_description
_find_vsm(cs, args.vsm).update(**kwargs) | 5,354,959 |
def textarea(name, content="", id=NotGiven, **attrs):
"""Create a text input area.
"""
attrs["name"] = name
_set_id_attr(attrs, id, name)
return HTML.tag("textarea", content, **attrs) | 5,354,960 |
def graphics_renderer(player, walls):
"""
"""
# Background
screen.fill(PURE_LIME_GREEN)
# Build maze
build_maze(screen, walls)
# Build player
game.draw.rect(screen, player.get_color(), player.get_body())
# Flip display
game.display.flip() | 5,354,961 |
def get_score_checkpoint(loss_score):
"""Retrieves the path to a checkpoint file."""
name = "{}{:4f}.pyth".format(_SCORE_NAME_PREFIX, loss_score)
return os.path.join(get_checkpoint_dir(), name) | 5,354,962 |
def start_automated_run(path, automated_run_id):
"""Starts automated run. This will automatically create
base learners until the run finishes or errors out.
Args:
path (str): Path to Xcessiv notebook
automated_run_id (str): Automated Run ID
"""
with functions.DBContextManager(path)... | 5,354,963 |
def StretchContrast(pixlist, minmin=0, maxmax=0xff):
""" Stretch the current image row to the maximum dynamic range with
minmin mapped to black(0x00) and maxmax mapped to white(0xff) and
all other pixel values stretched accordingly."""
if minmin < 0: minmin = 0 # pixel minimum is 0
if maxm... | 5,354,964 |
def detection(array, psf, bkg_sigma=1, mode='lpeaks', matched_filter=False,
mask=True, snr_thresh=5, plot=True, debug=False,
full_output=False, verbose=True, save_plot=None, plot_title=None,
angscale=False, pxscale=0.01):
""" Finds blobs in a 2d array. The algorithm is desi... | 5,354,965 |
def get_database_uri(application):
""" Returns database URI. Prefer SQLALCHEMY_DATABASE_URI over components."""
if application.config.get('SQLALCHEMY_DATABASE_URI'):
return application.config['SQLALCHEMY_DATABASE_URI']
return '{driver}://{username}:{password}@{host}:{port}/{name}'\
.form... | 5,354,966 |
def get_s_vol_single_sma(c: CZSC, di: int = 1, t_seq=(5, 10, 20, 60)) -> OrderedDict:
"""获取倒数第i根K线的成交量单均线信号"""
freq: Freq = c.freq
s = OrderedDict()
k1 = str(freq.value)
k2 = f"倒{di}K成交量"
for t in t_seq:
x1 = Signal(k1=k1, k2=k2, k3=f"SMA{t}多空", v1="其他", v2='其他', v3='其他')
x2 = S... | 5,354,967 |
def sampler(value, percentile):
"""Score based on sampling task model output distribution
Args:
value: The output of the task model
percentile: the (sorted) index of the sample we use
Returns:
The percentile largest distance from the mean of the samples.
"""
softmaxed = nn.f... | 5,354,968 |
def pretty_print(node, indent=' '*2, show_offsets=False):
"""
Pretty print node
:param node: Instance of `ast.Node`
:param indent: Number of spaces to indent
:param show_offsets: Show offsets. Boolean
:return:
"""
astpretty.pprint(node, indent=indent, show_offsets=show_offsets) | 5,354,969 |
def gists_by(username, number=-1, etag=None):
"""Iterate over gists created by the provided username.
.. deprecated:: 1.2.0
Use :meth:`github3.github.GitHub.gists_by` instead.
:param str username: (required), if provided, get the gists for this user
instead of the authenticated user.
... | 5,354,970 |
def needs_spark(test_item):
"""
Use as a decorator before test classes or methods to only run them if Spark is usable.
"""
test_item = _mark_test('spark', test_item)
try:
# noinspection PyUnresolvedReferences
import pyspark
except ImportError:
return unittest.skip("Skipp... | 5,354,971 |
def get_school_years_from_db() -> Generator:
"""Get all school years from the database.
:return: iterable with all availabe school years
"""
session: db.orm.session.Session = Session()
return (e[0] for e in set(session.query(Holiday.school_year).all())) | 5,354,972 |
def user_delete(handle, name):
"""
deletes user
Args:
handle (UcscHandle)
name (string): name
Returns:
None
Raises:
UcscOperationError: If AaaUser is not present
Example:
user_delete(handle, name="test")
"""
mo = user_get(handle, name)
if... | 5,354,973 |
def get_api(context=None):
"""
This function tries to detect if the app is running on a K8S cluster or locally
and returns the corresponding API object to be used to query the API server.
"""
if app.config.get("MODE") == "KUBECONFIG":
return client.CustomObjectsApi(config.new_client_from_con... | 5,354,974 |
def is_variant(title) -> bool:
"""
Check if an issue is variant cover.
"""
return "variant" in title.lower() | 5,354,975 |
def _decode_common(hparams):
"""Common graph for decoding."""
features = get_input(hparams, FLAGS.data_files)
decode_features = {}
for key in features:
if key.endswith("_refs"):
continue
decode_features[key] = features[key]
_, _, _, references = seq2act_model.compute_logits(
features, hpar... | 5,354,976 |
def _lex_single_line_comment(header: str) -> Tuple[str, str]:
"""
>>> _lex_single_line_comment("a=10")
('', 'a=10')
>>> _lex_single_line_comment("//comment\\nb=20")
('', 'b=20')
"""
if header[:2] != "//":
return "", header
line_end_pos = header.find("\n")
return "", header[li... | 5,354,977 |
def create_loaders(config, save_dir=None):
"""Prepares the task and data loaders for a model trainer based on a provided data configuration.
This function will parse a configuration dictionary and extract all the information required to
instantiate the requested dataset parsers. Then, combining the task me... | 5,354,978 |
def in_box(X, box):
"""Get a boolean array indicating whether points X are within a given box
:param X: n_pts x n_dims array of points
:param box: 2 x n_dims box specs (box[0, :] is the min point and box[1, :] is the max point)
:return: n_pts boolean array r where r[idx] is True iff X[idx, :] is within... | 5,354,979 |
def test_partial_field_square():
"""Fields that do not extend over the whole wall"""
field = np.zeros((40, 40))
field[:10, 0] = 1
fields = {kw_field_map: field}
walls = "L"
assert func(fields, "s", walls=walls) == 0.25
field[:20, 0] = 1
assert func(fields, "s", walls=walls) == 0.5
fi... | 5,354,980 |
def get_countries():
"""
The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Returns:
Dictionary: A dictionary with the country codes as the keys and the
country names as the values.
"""
#Initialize the countries dictionary.
countries = {... | 5,354,981 |
def get_empty_faceid(current_groupid, uuid, embedding,
img_style, number_people, img_objid, forecast_result):
"""
当softmax无结果时(无模型/预测置信度低)调用遍历数据库识别
:param current_groupid:
:param uuid:
:param embedding:
:param img_style:
:param number_people:
:param img_objid:
:retu... | 5,354,982 |
def dz_and_top_to_phis(
top_height: xr.DataArray, dz: xr.DataArray, dim: str = COORD_Z_CENTER
) -> xr.DataArray:
""" Compute surface geopotential from model top height and layer thicknesses"""
return _GRAVITY * (top_height + dz.sum(dim=dim)) | 5,354,983 |
def altPDF(peaks,mu,sigma=None,exc=None,method="RFT"):
"""
altPDF: Returns probability density using a truncated normal
distribution that we define as the distribution of local maxima in a
GRF under the alternative hypothesis of activation
parameters
----------
peaks: float or list of floats
list of peak heigt... | 5,354,984 |
def implicit_quantile_network(num_actions, quantile_embedding_dim,
network_type, state, num_quantiles):
"""The Implicit Quantile ConvNet.
Args:
num_actions: int, number of actions.
quantile_embedding_dim: int, embedding dimension for the quantile input.
network_type: named... | 5,354,985 |
def execute_command_line(cmd_list):
"""Executes the given command list on the command line
:param cmd_list: The list of commands
:type cmd_list: []
"""
logger.debug('Executing: %s', ' '.join(cmd_list))
try:
subprocess.check_output(cmd_list, stderr=subprocess.STDOUT)
except subproce... | 5,354,986 |
def destroy_droplets(ctx):
"""Destroy the droplets - node-1, node-2, node-3"""
manager = Manager(token=DIGITAL_OCEAN_ACCESS_TOKEN)
for num in range(3):
node = f"node-{num + 1}"
droplets = manager.get_all_droplets(tag_name=node)
for droplet in droplets:
droplet.destroy()
... | 5,354,987 |
def test_series_index_name_change(spark_context) -> None:
"""
Test pontem_series attributes against pandas series attributes of same data
"""
import pontem as pt
sc = spark_context
pontem_series = pt.Series(sc=sc, data=DATA)
pontem_series.index.name = 'new_name'
# Ensure the name stay... | 5,354,988 |
def get_waitlist(usercode):
"""
Запрос /api/waitlists/{usercode} - возвращает waitlist контент по usercode
"""
user_by_usercode = (
AppUsers.query.filter(AppUsers.usercode == usercode).one_or_none()
)
if user_by_usercode is None:
abort(
409,
"Usercode {us... | 5,354,989 |
def not_empty(message=None) -> Filter_T:
"""
Validate any object to ensure it's not empty (is None or has no elements).
"""
def validate(value):
if value is None:
_raise_failure(message)
if hasattr(value, '__len__') and value.__len__() == 0:
_raise_failure(messag... | 5,354,990 |
def process_mark_time():
""" Determine if DOT or DASH timing has elapsed """
global mark_has_begun, mark_start_time
if not mark_has_begun: return
clear_extra_space()
mark_interval = running_time() - mark_start_time
if mark_interval > DOT_TIME_MIN and mark_interval < DOT_TIME_MAX:
mess... | 5,354,991 |
def temporal_affine_forward(x, W, b):
"""
Run a forward pass for temporal affine layer. The dimensions are consistent with RNN/LSTM forward passes.
Arguments:
x: input data with shape (N, T, D)
W: weight matrix for input data with shape (D, M)
b: bias with shape (M,)
Outputs:
... | 5,354,992 |
def uniform_regular_knot_vector(n, p, t0=0.0, t1=1.0):
"""
Create a p+1-regular uniform knot vector for
a given number of control points
Throws if n is too small
"""
# The minimum length of a p+1-regular knot vector
# is 2*(p+1)
if n < p+1:
raise RuntimeError("Too small n for a u... | 5,354,993 |
def include_file(filename, global_vars=None, local_vars=None):
"""
.. deprecated 2.1::
Don't use this any more.
It's not pythonic.
include file like php include.
include is very useful when we need to split large config file
"""
if global_vars is None:
global_vars = s... | 5,354,994 |
def rm(path: PathType,
*, is_dir: bool = True, globs: Optional[str] = None,
quiet: bool = True, verbose: bool = True):
# pylint: disable=invalid-name,too-many-arguments
"""Remove a directory, a file, or glob-pattern-matched items from S3."""
s3_command: str = (f'aws s3 rm {path}' +
... | 5,354,995 |
def generateCM(labelValue, predictValue):
"""Generates the confusion matrix and rteturn it.
Args:
labelValue (np.ndarray): true values.
predictValue (np.ndarray): predicted values.
"""
FPMtx = np.logical_and((labelValue <= 0), (predictValue > 0))
FPIndices = np.argwhere(FPMtx)
FPNum = np.sum(FP... | 5,354,996 |
def get_cosine_similarity(word2vec: Word2Vec) -> np.ndarray:
"""Get the cosine similarity matrix from the embedding.
Warning; might be very big!
"""
return cosine_similarity(word2vec.wv.vectors) | 5,354,997 |
def get_bot_id() -> str:
"""
Gets the app bot ID
Returns:
The app bot ID
"""
response = CLIENT.auth_test()
return response.get('user_id') | 5,354,998 |
def plot_dr_viability(data, y_label, path):
"""Plots response vs viability. The DataFrame should contain columns ['Compound', 'Dose','logDose', 'Viability', 'Response'] (at least)."""
import pandas as pd
import matplotlib as mpl
import matplotlib.colors as colors
import matplotlib.pyplot as plt
... | 5,354,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.