content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def helicsPublicationPublishBytes(pub: HelicsPublication, data: bytes):
"""
Publish raw data from a char * and length.
**Parameters**
- **`pub`** - The publication to publish for.
- **`data`** - A pointer to the raw data.
"""
if HELICS_VERSION == 2:
f = loadSym("helicsPublicationPu... | 77,100 |
def _step(context, element, coordinate, thing, ruler, rulerWidth):
"""
:type context: HackedContext
"""
scaleFactor = scaling_factor(context, ruler, rulerWidth)
measuredItem = context.driver.simple_find(thing)
actualCoord = int(measuredItem.location[coordinate] / scaleFactor)
item = conte... | 77,101 |
def weighted_correlation_rank(x, y, wt):
"""Calculatees the weighted spearman rank correlation"""
from scipy.stats import rankdata
x = rankdata(x)
y = rankdata(y)
return weighted_correlation(x, y, wt) | 77,102 |
def main():
"""Numpy array is accessed as (r, c) while a point is (x, y). The code
follows (r, c) convention everywhere. Hence, be careful whenever using a
point with opencv.
Takes one command line argument: Folder that has the environment and
config.
"""
folder = sys.argv[1]
image = f... | 77,103 |
def get_auth(api_key_id=None, api_key_path=None, region=None, api_url=None, seer_auth=None,
use_email=None, email=None, password=None, timeout=None):
"""
Get the correct Auth implementation based on passed parameters and the existence of config
files.
If seer_auth is passed, it will be use... | 77,104 |
def test_tapped_rock():
"""
Test tapped_rock static method
"""
for cost,mana in zip(range(4), range(4)):
spell = Card.tapped_rock(cost, mana)
assert spell.land is False
assert spell.cost == cost
assert spell.mana_sequence == Sequence.repeat(mana).prefixed_by([0])
... | 77,105 |
def riFromCSI(csi: str) -> str:
""" Get the ri from an CSEBase resource by its csi. """
if (res := resourceFromCSI(csi)) is None:
return None
return cast(str, res.ri) | 77,106 |
async def test_uses_loop_provided_by_custom_policy():
"""Asserts that test cases use the event loop
provided by the custom event loop policy"""
assert type(asyncio.get_event_loop()).__name__ == "TestEventLoop" | 77,107 |
def run_parser() -> None:
"""
Function to collect command line arguments.
Construct main object with correct set of parameters.
"""
parser = ArgumentParser(description='Emerge in temporary RAM disk')
parser.add_argument('-s', '--size', action='store', dest='size', default='4G', help='Size or RA... | 77,108 |
def plot_uvj_cluster(groupID, axis_obj='False'):
"""given a groupID, plot the UVJ diagram of the composite and all galaxies within cluster
Parameters:
groupID (int): ID of the cluster to plot
axis_obj (matplotlib axis): If given an axis, don't make a new figure - just plot on the given axis
Return... | 77,109 |
def func_ord():
"""
ord(c) takes string of length one and return integer representing
the Unicode code point or value of byte when c is an 8-bit string.
Examples: ord('Z'), ord(u'\u2020')
"""
print 'A and z = {} and {}'.format(ord('A'), ord('z'))
print "u'\u3030' = {}".format(ord(u'\u3030')) | 77,110 |
def solr(request):
"""
Displays ils view for the MARC Batch App
"""
APP['view'] = 'solr'
return direct_to_template(request,
'marc_batch/solr.html',
{'app':APP,
'institution':INSTITUTION}) | 77,111 |
def process_failed(returncode, stdout):
"""Return True if the process failed."""
if returncode != 0:
return True
if 'badly_formatted' in stdout:
return True
return False | 77,112 |
def init():
"""
Set world coordinates and call drawRecTree,
prints the total length of tree branches
-
:pre: (relative)pos (0,0), heading(east), pen down
:post: (relative)pos (0,0), heading(east), pen up
:return: None
"""
turtle.setworldcoordinates(-WINDOW_LENGTH / 2, -WINDOW_LENGTH / 2,... | 77,113 |
def main(vtktype='vts'):
""" メイン
Args:
vtktype : vtk ファイルの種類を指定する.(vts | vtr)
"""
calc_range = 1.0 # 計算範囲 -calc_range から calc_range
nsamples = 200 # 分割数
k = 1/(4 * const.pi * const.epsilon_0)
charge = [
{'q': -1.0, 'px': -0.2, 'py': 0.0, 'pz': 0.0},
{... | 77,114 |
def find_co_double_bonds(atoms, mol):
""" looking for
R
|
C=O
|
R
"""
CO_list = []
for _ in range(len(atoms)):
name = atoms[_].get_atom_name()
if name != 'C':
continue
nghs_c = atoms[_].get_ngh()
nums_c, nghs_list_c = pa... | 77,115 |
def p2b_list_point2D(pylist, dtype):
"""
Converts a python list of feature descriptors stored in 64bit floats into a BoofCV compatible format
:param pylist: Python list of 2d points
:type pylist: list[(float,float)]
:return: List of 2d points in BoofCV format
"""
java_list = gateway.jvm.java... | 77,116 |
def plot_example_for_colormap(name, colorpath, outdir='./'):
"""Create plots of given color map using python."""
logger.info("Plotting example for '%s'", name)
fig = plt.figure(1)
axis = fig.add_axes([0.1, 0.3, 0.5, 0.5])
np.random.seed(12345678)
data = np.random.randn(30, 30)
psm = axis.pco... | 77,117 |
def transform_coords(c1, c2, out=None):
"""Return Coordinates by applying c1 to c2 from the left
Parameters
----------
c1 : skrobot.coordinates.Coordinates
c2 : skrobot.coordinates.Coordinates
Coordinates
c3 : skrobot.coordinates.Coordinates or None
Output argument. If this valu... | 77,118 |
def compare_fiff(fname_1, fname_2, fname_out=None, show=True, indent=' ',
read_limit=np.inf, max_str=30, verbose=None):
"""Compare the contents of two fiff files using diff and show_fiff.
Parameters
----------
fname_1 : str
First file to compare.
fname_2 : str
Se... | 77,119 |
def interp1(x, xdata, ydata, silent=0): # --DC
"""DETERMINES y AS LINEAR INTERPOLATION OF 2 NEAREST ydata"""
SI = argsort(xdata)
# NEW numpy's take IS ACTING FUNNY
# NO DEFAULT AXIS, MUST BE SET EXPLICITLY TO 0
xdata = xdata.take(SI, 0).astype(float).tolist()
ydata = ydata.take(SI, 0).astype(fl... | 77,120 |
def wrap_in_list(maybe_sequence:Any) -> Sequence:
""" If `maybe_sequence` is not a sequence, then wrap it in a list
See :func:`pyllars.validation_utils.is_sequence` for more details about
what counts as a sequence.
Parameters
----------
maybe_sequence : typing.Any
An object which m... | 77,121 |
def evaluate_quadratic(J, g, s, diag=None):
"""Compute values of a quadratic function arising in least squares.
The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s.
"""
if s.dim() == 1:
Js = J.mv(s)
q = Js.dot(Js)
if diag is not None:
q += s.dot(s * diag)
e... | 77,122 |
def all_in_any(a, b):
"""return true if every item of 'a' is found
inside 'b'
else return false
"""
if len([x for x in a if x in b]) == len(a):
return True
else:
return False | 77,123 |
def _get_upgrader_impl(service):
"""
Instantiate the MagmaUpgrader implementation to be used for magmad, as
specified in the service YML config.
Args:
service (MagmaService): magmad service
Returns:
magma.magmad.upgrade.upgrader.Upgrader: specified upgrader instance
"""
# G... | 77,124 |
def apply_stack(initial_msg):
"""
Execute the effect stack at a single site according to the following scheme:
1. For each ``Messenger`` in the stack from bottom to top,
execute ``Messenger._process_message`` with the message;
if the message field "stop" is True, stop;
... | 77,125 |
async def check_name_and_abbreviation(
db, ref_id: str, name: Optional[str] = None, abbreviation: Optional[str] = None
) -> Union[bool, str]:
"""
Check is a otu name and abbreviation are already in use in the reference identified by `ref_id`. Returns a message
if the ``name`` or ``abbreviation`` are alr... | 77,126 |
def get_test_data(suite):
###############################################################################
"""
For a given suite, returns (inherit, time, share, tests)
"""
raw_dict = _ALL_TESTS[suite]
for key in raw_dict.keys():
expect(key in ["inherit", "time", "share", "tests"], "Unexpected... | 77,127 |
def slafbfiles(date):
"""Observation file locator stub
.. note:: User-specified stub
:param date: The verification date in string format ``'%Y%m%d'``
:returns: List of files
"""
files = ['slafb.nc']
return files | 77,128 |
def test_add_same_input():
"""
Check that adding two inputs with the same key raises and error
"""
base_filter = BaseFilterTester()
base_filter.add_input("key", 1)
with pytest.raises(FilterInputKeyError):
base_filter.add_input("key", 2) | 77,129 |
def eager_setup():
"""
it eables an eager execution in tensorflow with config that allows us to flexibly access to a GPU
from multiple python scripts
:return:
"""
config = tf.compat.v1.ConfigProto(allow_soft_placement=True,
intra_op_parallelism_threads=1,
... | 77,130 |
def quick_sort(the_list, start=0, end=None):
"""
Sort a segment defined by the `start` and `end` indices of `the_list`
by the Quick Sort algorithm.
"""
if end is None:
end = len(the_list) - 1
# Base case: do nothing if the list has just one element / is empty
if end <= start:
... | 77,131 |
def plot_roc_curve(y_true, y_score, size=None):
"""plot_roc_curve."""
false_positive_rate, true_positive_rate, thresholds = roc_curve(
y_true, y_score)
if size is not None:
plt.figure(figsize=(size, size))
plt.axis('equal')
plt.plot(false_positive_rate, true_positive_rate, lw=2, ... | 77,132 |
def main():
"""
Actual program execution starts from this function
"""
try:
# Starting point of script
dir_path = os.path.abspath(os.path.dirname(__name__))
# enable compute.googleapis.com
print("Enabling compute.googleapis.com service...")
subprocess.run(COMPUTE_... | 77,133 |
def expansionhunter_unclear_expected():
""":return: Returns dictionary with expected results for ExpansionHunter - UNCLEAR."""
return {
"AR": (
"Unclear - repeat AR observed outside defined ranges (34/37). "
"Normal range: 9 - 35. Expansion range: 38 - 62."
),
"FM... | 77,134 |
def create_temporay_element_type(name, attrs=()):
"""
"""
if not attrs:
bases = (TemporarySingleValueInternalElement,)
else:
if 'codeinfo' not in attrs:
attrs = tuple((*attrs, 'codeinfo'))
bases = (namedtuple(f'_{name}Base', attrs), TemporaryInternalElement)
retur... | 77,135 |
def enrich_url(base_url, client_doc) -> str:
"""
Add payment form API parameters for this client.
"""
url = base_url
params = ''
cl_name = make_client_name(client_doc, include_title=False)
cl_street = client_doc.get('address', {}).get('street', ' ')
cl_city = client_doc.get('address', {}... | 77,136 |
def under_pebble(_function):
"""
decorator to spin up an external pebble server
"""
@wraps(_function)
def _wrapper(*args, **kwargs):
log.info("`pebble`: spinning up")
log.info("`pebble`: PEBBLE_CONFIG : %s", PEBBLE_CONFIG)
res = None # scoping
with psutil.Popen(
... | 77,137 |
def test_goannot_for_all_species_exists():
"""
Test GO Annotation for Expected Species Exists
Not used for SARS-CoV-2.
"""
query = """MATCH (s:Species)--(g:Gene)-[hp:ANNOTATED_TO]-(got:GOTerm)
RETURN count(distinct s) AS counter"""
result = execute_transaction(query)
for reco... | 77,138 |
def test_single_ssh_command_with_missing_ssh_binary(
_mock_which: Mock, c8yserver: FixtureCumulocityAPI, env: Environment
):
"""Execute command via ssh then exit"""
@responses.activate
def run():
serial = "ext-device-01"
c8yserver.simulate_pre_authenticated(serial)
runner = Cli... | 77,139 |
def destroy_stack(stack_id):
"""
"""
try:
stack = Stack.objects.get(id=stack_id)
stack.set_status(destroy_stack.name, Stack.DESTROYING,
'Performing final cleanup of stack.')
hosts = stack.get_hosts()
if hosts.count() > 0:
stack.set_status... | 77,140 |
def bind_raw(func: Callable[[bytes], HTTPHandler]) -> HTTPHandler:
"""Executes passed `func` on request body.
Args:
func (Callable[[bytes], HTTPHandler]): to run on request body.
"""
@handler
def _handler(nxt: HTTPFunc, ctx: HTTPContext) -> Future[HTTPContext | None]:
handle = (Pip... | 77,141 |
def GetTask(task_guid, service_guid):
"""
Retrieve the detail of a task
It is handler for GET /services/<service_guid>/task_list/<task_guid>
"""
return handlers.GetTaskHandler(task_guid, service_guid) | 77,142 |
def partially_decrypt(
guardian_keys: ElectionKeyPair,
elgamal: ElGamalCiphertext,
extended_base_hash: ElementModQ,
nonce_seed: ElementModQ = None,
) -> Tuple[ElementModP, ChaumPedersenProof]:
"""
Compute a partial decryption of an elgamal encryption
:param elgamal: the `ElGamalCiphertext` ... | 77,143 |
def del_item(config_data, config_data_map, key):
"""
"""
for i, x in enumerate(config_data):
if x[0] == ITEM and x[1] == key:
config_data[i] = (COMM, "#%s = %s" % (x[1], x[2]))
if key in config_data_map:
del config_data_map[key] | 77,144 |
def check_lowercase_prefix(node: ir.Node, module_prefixes: ModulePrefixLookup) -> bool:
"""check that node starts with the lower-case module prefixed followed by
an underscore."""
if node.Name:
for file in containing_modules(node):
if file in module_prefixes:
if not node.... | 77,145 |
def count_params(text):
"""Return number of parameters."""
return len(parse.parse_qs(text)) | 77,146 |
def broadcast(msg, prefix=""): # prefix is for name identification.
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send(bytes(prefix, "utf8") + msg) | 77,147 |
def test_predict_only_one_or_minus_one(estimator, build_dataset,
with_preprocessor):
"""Test that all predicted values are either +1 or -1"""
input_data, _, preprocessor, _ = build_dataset(with_preprocessor)
estimator = clone(estimator)
estimator.set_params(preprocessor=pr... | 77,148 |
def GetJobDirFlag(upload_help=True, allow_local=False):
"""Get base.Argument() for `--job-dir`.
If allow_local is provided, this Argument gives a str when parsed; otherwise,
it gives a (possibly empty) ObjectReference.
Args:
upload_help: bool, whether to include help text related to object upload.
O... | 77,149 |
async def test_get_auth_qrcode(api: TalkApi):
"""`getAuthQrcode`のテストコード
この関数で実際にAPIとの疎通が出来るか確認する
"""
res = await api.getAuthQrcode(FContext(), False, "pyne", False)
assert bool(res) | 77,150 |
def get_cl_source(name):
"""Get the source code for a openCL source file located in the chroma cuda
directory at src/[name]."""
with open('%s/%s' % (srcdir, name)) as f:
source = f.read()
return source | 77,151 |
def verify_layout_signatures(layout_metablock, keys_dict):
"""
<Purpose>
Iteratively verifies the signatures of a Metablock object containing
a Layout object for every verification key in the passed keys dictionary.
Requires at least one key to be passed and requires every passed key to
find a vali... | 77,152 |
def beam2pix(header):
"""
Calculate the beam to pixel conversion ratio, which is used to convert
between Jy/beam and Jy.
Parameters
----------
header : fits header
The header of the data.
Returns
-------
b2p : float
The ratio of the beam size to the pixel size.
... | 77,153 |
async def del_sudo_cmd(message: Message):
""" delete sudo cmd """
if '-all' in message.flags:
sudo.COMMANDS.clear()
await asyncio.gather(
SUDO_CMDS_COLLECTION.drop(),
message.edit("**SUDO** cmds cleared!", del_in=5))
return
cmd = message.filtered_input_str
... | 77,154 |
def prepare_bxsf_for_skeaf(
in_fhandle,
out_fhandle,
band_to_keep,
shift_fermi=0.0,
verbose=False,
print_minmax=False,
):
"""
SKEAF wants:
- a single band - we're going to filter it
- expected units are different!!!
- It expects Ry instead of eV. This does not matter for th... | 77,155 |
def main(argv, stdout, environ):
"""Program main entry point."""
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding("utf8")
parser, args = parse_args(argv)
logging.basicConfig(
format="[%(asctime)s] %(levelname)-8s %(message)s",
datefmt="%m/%d %H:%M:%S",
... | 77,156 |
def add_user_favorites(itemid):
"""
Add item to user's favorite list.
Args:
itemid (int) – item id
Status Codes:
201 Created – when favorite successfully created
"""
path = '/users/{}/favorites'.format(userid())
data = {'itemid': itemid}
return post(path, data, auth=Tr... | 77,157 |
def test_search_based_stream_should_not_attempt_to_get_more_than_10k_records(requests_mock, common_params, fake_properties_list):
"""
If there are more than 10,000 records that would be returned by the Hubspot search endpoint,
the CRMSearchStream instance should stop at the 10Kth record
"""
respons... | 77,158 |
def have_a_chat():
"""
Main function used to run our chatbot.
Partially used code and comments from A3.
"""
greeting_msg = '''Welcome to the Steam charts bot!
I love to track the data on all of the
top 500 games people are playing right now on Steam!!!
Input a video game that is avaliable on Steam.... | 77,159 |
def decode_varint(stream: BytesIO) -> int:
"""
Decode bytes into int
"""
shift = 0
result = 0
while True:
i = _read_one(stream)
result |= (i & 0x7F) << shift
shift += 7
if not (i & 0x80):
break
return result | 77,160 |
def get_linguist_projects(args, default_all=False):
""" Get Linguist Projects """
worktree = get_linguist_worktree(args)
project_args = args.projects
pml_paths = list()
project_names = list()
for arg in project_args:
if arg.endswith(".pml"):
pml_paths.append(qisys.sh.to_nativ... | 77,161 |
def parse_opts_args(argv):
""" parse options and arguments """
usage = "USAGE: find_class.py [options] class_name [[class_name] ...]"
p = OptionParser(usage=usage)
p.add_option('-v', '--verbose', dest='verbose', action='count', default=0,
help='verbose output. specify twice for debug-l... | 77,162 |
def bucketcall(queryfield="", name="", title="", sortby="", lastnamefirst=False,
infotext="", description="", query="", alphabetical=False,
insert_entries=None, page_url=""):
"""Bucket call helper."""
q_data = {"buckets": "%s.bucket" % queryfield}
if query:
q_data["q"] ... | 77,163 |
def brute_force_mscs(seq: list) -> tuple:
"""Brute-force approach to compute the sum of all subsequences of seq.
There are n + (n - 1) + (n - 2) + ... + 1 different subsequences.
Time complexity: O(n³)."""
_sum = _max = seq[0]
start = end = 0
for i in range(0, len(seq)):
for j in ran... | 77,164 |
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass. Because of internal type checks
# we also need to make sure that ... | 77,165 |
def cli(ctx, todoist_api_key, tw_config_file, debug):
"""Manage the migration of data from Todoist into Taskwarrior. """
ctx.ensure_object(Ctx)
# Configure Todoist with API key and cache
ctx.obj.todoist = TodoistAPI(todoist_api_key, cache=gateways.TODOIST_CACHE)
ctx.obj.td = gateways.Todoist(todois... | 77,166 |
def expand_files(
files: List[Path],
extension: Union[str, List[str]] = ".sql",
base_path: Path = Path("."),
) -> List[Path]:
"""
Expands the list of files or folders,
with all SQL files in a folder as seperate files.
"""
if isinstance(extension, str):
extensions = [extension]
... | 77,167 |
def generate_launch_description():
"""Launch file for gritsbot in Gazebo."""
# Get input arguments
input_args = get_args()
pos_y = '1.45'
neg_y = '-1.45'
def_z = '0.91'
x_val = [
0.3 * -1, 0.3 * -2, 0.3 * -3, 0.3 * -4, 0.3 * -5,
0.3 * 0.0,
0.3 * 1, 0.3 * 2, 0.3 * 3, ... | 77,168 |
def mywalk(top, noparallel=False, skipdirs=['.snapshot',]):
""" returns subset of os.walk """
if noparallel:
for root, dirs, files in os.walk(top,topdown=True,onerror=walkerr):
for skipdir in skipdirs:
if skipdir in dirs:
dirs.remove(skipdir) # don'... | 77,169 |
def f1_score_missing(y_true, y_pred, individual=False, micro=False):
"""
Compute the f1 score, accounting for missing labels in `y_true`.
"""
assert not (individual and micro)
assert y_true.shape == y_pred.shape
assert len(y_true.shape) == 2
if micro:
# average over attributes usi... | 77,170 |
def sim1(x_0, v_0, N):
"""
Driver routine for RK4 integration and file output
for SHM
"""
E0 = 0.5*x_0**2+0.5*v_0**2
te = 4*math.pi
ts = 0.0
h = (te-ts)/float(N)
t = ts;
x = x_0
v = v_0
while (t < te):
#Write the old values to file
de = 0.5*x**2+0.5*v**2 ... | 77,171 |
def load_ply(ply_fpath: _PathLike) -> np.ndarray:
"""Load a point cloud file from a filepath.
Args:
ply_fpath: Path to a PLY file
Returns:
arr: Array of shape (N, 3)
"""
data = pyntcloud.PyntCloud.from_file(os.fspath(ply_fpath))
x = np.array(data.points.x)[:, np.newaxis]
y = ... | 77,172 |
def setup():
"""Not yet implemented"""
#TODO split it in 3 different methods
pass | 77,173 |
def run(connection, reporter, object_list):
"""Run the reporter :class Reporter: for the give object list :class CheckObjectList:"""
xml = Marshal().serialize(object_list)
resp = connection.execute('POST', object_list.objtype.basepath,
accept=CheckReportList.objtype.mimetype,... | 77,174 |
def horizontal_flip(image_data, output_encoding=PNG):
"""Flip the image horizontally.
Args:
image_data: str, source image data.
output_encoding: a value from OUTPUT_ENCODING_TYPES.
Raises:
Error when something went wrong with the call. See Image.ExecuteTransforms
for more details.
"""
ima... | 77,175 |
def test_swath_bathymetry_summary_count(file_info):
"""Test the header record count."""
assert file_info[8].record_count == 1 | 77,176 |
def split_page(encoded_inputs, max_seq_len=512):
"""
truncate is often used in training process
"""
for key in encoded_inputs:
encoded_inputs[key] = paddle.to_tensor(encoded_inputs[key])
if encoded_inputs[key].ndim <= 1: # for input_ids, att_mask and so on
encoded_inputs[key... | 77,177 |
def _intToColor(color_number):
""" legacy color support for converting integers to color objects based on the
cadnano 2 file format
Args:
color_number (int): integer value of a RGB color
Returns:
Color: the :class:`Color` object
"""
return Color('#%0.6x' % (color_number)) | 77,178 |
def test_points():
"""Test points of different styles with/without label and different label positions"""
coordinate_system = cartesius.CoordinateSystem(bounds=(-.5, 5, -.5, 5))
# Without labels:
coordinate_system.add(elements.Point((1, 4), style='.'))
coordinate_system.add(elements.Point((2, 4), s... | 77,179 |
def obter_todas(possui_oferta: bool = None) -> dict:
"""Consulta a lista de todas as categorias que possuem ofertas dos lojistas parceiros da Lomadee.
Parameters
----------
possui_oferta: bool, optional
Quando "true" retorna apenas categorias que possuem ofertas.
Returns
-------
di... | 77,180 |
def construct_M_h(tsp,H,dt,Stim):
"""
Performs preliminary processing of the spike trains,
and returns the matrix corresponding to the post-spike filter.
Parameters
----------
Stim : array_like
Stimulus.
tsp : array_like
Spike ti... | 77,181 |
def post_save_category(sender, instance, **kwargs):
"""Remove associated data imports when the category gets deleted."""
if instance.status == 'deleted':
DataImport.objects.filter(category=instance).delete() | 77,182 |
def vdowham(eta, vel_entrain, e_eff, r_eff):
"""
Calculate the velocity parameter of the contact problem according to
Dowson-Hamrock.
Parameters
----------
eta: ndarray, scalar
The dynamic viscosity of the lubricant.
vel_entrain: ndarray, scalar
The entrainment velocity of ... | 77,183 |
def rotate(set_of_points, pivot, rotation_matrix):
"""
set_of_points: numpy.matrix
pivot: tuple(x, y, z)
rotation_matrix: numpy.matrix
"""
return kb.translate(kb.translate(set_of_points, [-i for i in pivot])*rotation_matrix, pivot) | 77,184 |
def get_index_from_tags(session, tags):
"""
Construct a ModuleIndex object from the contents of the provided tags.
:param session: A Koji session
:param tags: A set of Koji tags from which module metadata should be pulled
:return: A ModuleIndex object. Raises an exception if any of the
retrieved... | 77,185 |
def model_fn_builder(config):
"""Build the model for training."""
def model_fn(features, labels, mode, params):
"""Build the model for training."""
model = PretrainingModel(config, features,
mode == tf.estimator.ModeKeys.TRAIN)
print("Model is built!")
tvars = tf.traina... | 77,186 |
def set_content_type(headers, name):
"""根据文件名在headers里设置Content-Type。如果headers中已经存在Content-Type,则直接返回。"""
headers = headers or {}
if 'Content-Type' in headers:
return headers
content_type = content_type_by_name(name)
if content_type:
headers['Content-Type'] = content_type
retu... | 77,187 |
def split_folds(X_train, y_train, num_folds):
"""Split up the training data into `num_folds` folds.
The goal of the functions is to return training sets (features and labels) along with
corresponding validation sets. In each fold, the validation set will represent (1/num_folds)
of the data while the tr... | 77,188 |
def compute_convergence(output, output_prev):
"""
Compute the convergence by comparing with the output from the previous
iteration.
The convergence is measured as the mean of a XOR operation on two vectors.
Parameters
----------
output, output_prev : np.ndarray
Current and previous... | 77,189 |
def folder_creator(path):
"""Create a folder with given path if it doesn't exists."""
if not os.path.exists(path):
os.makedirs(path) | 77,190 |
def disconnect_rest_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account."""
_disconnect(remote, *args, **kwargs)
redirect_url = current_app.config['OAUTHCLIENT_REST_REMOTE_APPS'][
remote.name]['disconnect_redirect_url']
return response_handler(remote, redirect_url) | 77,191 |
def cmake_main():
"""
cmake构建工具入口函数
:return: None
"""
# 构建类型
build_type = "Unknown"
# 打包类型
pack_bin_type = False
pack_src_type = False
# 测试类型
test_type = False
# cmake检查
cmake_check = False
# 生成命令行
generate_arguments = ['cmake', '-S', '.', '-B', 'build']
... | 77,192 |
def viewData():
"""
displays data from the database
"""
con = sqlite3.connect("library.db")
cur = con.cursor()
cur.execute("SELECT * FROM book")
row = cur.fetchall()
con.close()
return row | 77,193 |
def get_sites(vs30_values: List, rrup_values: Dict):
"""Creates a dictionary
pair of a different Vs30 and Sites
Parameters
----------
vs30_values: List
list of Vs30s
rrup_values: Dict
dictionary of Rrups np.ndarray
"""
# sites = {vs30: [] for vs30 in vs30_values}
sit... | 77,194 |
def test_algorithm(func, size=20, max=0):
"""
RUNS GIVEN FUNCTIONS AND OUTPUTS ANALYSIS
ARG func = NAME OF ALGORITHM FUNCTION
ARG size = SIZE OF INPUT
ARG max = MAX INPUT VALUE
"""
import sorting
import timeit
## ARRAY CREATION
a = random_array(size, max)
print("INPUT ARRAY:"... | 77,195 |
def get_reconstruction_models_and_pred_dir(prefix, should_create=True, start_dir=None, previous_purchases=None) -> str:
""" Create the output directory containing reconstruction output
:param prefix: prefix
:param should_create: should we create the directory or not
:param start_dir: the starting direc... | 77,196 |
def part_2():
"""
Returns either a bool or an int. The bool is returned if no end is found in the instructions.
The int is the value in the accumulator before termination.
"""
found_end = False
for i, instruction in enumerate(INSTRUCTIONS):
if instruction[0] == "nop":
INSTRUC... | 77,197 |
def categorical(molecules, threshold, output_dir, plot_suffix):
"""
Categorical scatter plot of all molecules in dictionary.
"""
dx = 0.15
fig, ax = plt.subplots(figsize=(5, 5))
for name in molecules:
out_file = (
f"{output_dir}/"
f"{name.replace(' ', '_').replac... | 77,198 |
def _get_school_options_for_a_b_for_most():
"""Get the educ_options starting March 15th until April 5th.
Situation:
- BY:
- source: https://bit.ly/3lOZowy
- <50 incidence: normal schooling
- 50-100 incidence: A/B schooling
- >100 incidence: distance for all except graduatio... | 77,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.