content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def serialize_pipeline(preprocessor, clf):
"""Serialize preprocessor and model."""
print("Serializing preprocessor and model.")
with open(DATA_DIR + "/preprocessor.dill", "wb") as prep_f:
dill.dump(preprocessor, prep_f)
with open(DATA_DIR + "/model.dill", "wb") as model_f:
dill.dump(cl... | 44,300 |
def _find_connection_file(connection_file):
"""Return the absolute path for a connection file
- If nothing specified, return current Kernel's connection file
- Otherwise, call jupyter_client.find_connection_file
"""
if connection_file is None:
# get connection file from current kernel
... | 44,301 |
def _symbols_of_input(label: str) -> List[str]:
"""Extracts FST symbols that compose complex input label of the rewrite rule.
FST symbols of a complex input label is;
- Epsilon symbol if the complex input label is an epsilon symbol
(e.g. ['<eps>'] for label '<eps>').
- Digits of the complex input lab... | 44,302 |
def preset_select_func(area, preset):
"""Create preset selection packet."""
return DynetPacket.select_area_preset_packet(area, preset, 0) | 44,303 |
def init_model(model_name,
network_config,
classes,
word_dict,
init_weight=None,
log_path=None,
learning_rate=0.0001,
optimizer='adam',
momentum=0.9,
weight_decay=0,
metr... | 44,304 |
def boxed_img(img_data):
"""return base64 encoded boxed image."""
if isinstance(img_data, str):
img_path = img_data
else:
img_path = img_buffer(img_data)
img, result = obj_detect(img_path)
boxed_np_image = draw_boxes(
img.numpy(),
boxes=result["detection_boxes"],
... | 44,305 |
def extract_moe_descriptors(dataframe, column, url):
"""
Extracting molecular MOE-type descriptors using PyChem package and
SMILES strings of compounds.
:param dataframe: The dataframe containing SMILES info for which MOE
descriptors info must be evaluated
:param column: the column containing SM... | 44,306 |
def select_regularization_parameter(n_samples: int = 50, n_evaluations: int = 500):
"""
Using sklearn's diabetes dataset use cross-validation to select the best fitting regularization parameter
values for Ridge and Lasso regressions
Parameters
----------
n_samples: int, default=50
Number of samples to generate... | 44,307 |
def exec(statement, table_name=None, commit=True):
""" execute a SQL statement in the database and commit the transaction.
If a table_name is passed in, then the query will be checked for proper completion, returning a boolean """
conn = connection()
cursor = conn.cursor(buffered=True)
if table_nam... | 44,308 |
def isvalid(gridstr, x, y, test_value):
""" Check if it would be legal to place a in pos x,y """
sq_indexes = ((0, 1, 2), (3, 4, 5), (6, 7, 8))
group_indexes = [(x_ind, y_ind)
for x_ind in sq_indexes[x // 3]
for y_ind in sq_indexes[y // 3]]
for index in range(9... | 44,309 |
def wrapped_sire(*args):
"""
Make sure that the directory is deleted if there is an error during sire
"""
try:
sire(*args)
except KeyboardInterrupt:
print("Process stopped by user. Aborting and cleaning up ...")
shutil.rmtree(args[0], ignore_errors=True)
except Exception:... | 44,310 |
def _find_manifest_path():
"""
combs through settings.STATICFILES_DIRS to find the path of the manifest
file.
"""
static_dirs = settings.STATICFILES_DIRS
if len(static_dirs) == 1:
return os.path.join(static_dirs[0], APP_SETTINGS['manifest_file'])
for static_dir in static_dirs:
... | 44,311 |
def GilmoreEick(R0_in, v0_in, Requ, \
t_start, t_end, t_step, \
T_l=20.):
"""Run the calculation (Gilmore + Eick)
with the given initial conditions and parameters.
returns: t, R, R_dot, pg, T, i
"""
global T
global T_gas_0, sc_pvapour
T_gas_0 = T0_Ke... | 44,312 |
def gamma(x):
"""
element-wise gamma function
"""
return Gamma().forward(x) | 44,313 |
def build_model_with_precision(pp, mm, ii, tt, *args, **kwargs):
"""Build model with its inputs/params for a specified precision context.
This is highly specific to this codebase, and not intended to be general API.
Advanced users only. DO NOT use it if you don't know what it does.
NOTE: short argument... | 44,314 |
def bisection(a, b, poly, tolerance):
"""
Assume that poly(a) <= 0 and poly(b) >= 0.
Modify a and b so that abs(b-a) < tolerance and poly(b) >= 0 and poly(a) <= 0.
Return (a+b)/2
:param a: poly(a) <= 0
:param b: poly(b) >= 0
:param poly: polynomial coefficients, low order first
:... | 44,315 |
def get_roc_with_band(quotes: Iterable[Quote], lookback_periods: int, ema_periods: int, std_dev_periods: int):
"""Get ROCWB calculated.
Rate of Change with Bands (ROCWB) is the percent change of Close price
over a lookback window with standard deviation bands.
Parameters:
`quotes` : Iterable[Q... | 44,316 |
def summarizeLD(args):
"""
%prog summarizeLD ld1 ld2 ... output_prefix
summarize LD results from plink results
args:
ld1: the output file from Plink, add more if you have many
output_prefix: the output prefix of the summarizing results
"""
p = OptionParser(summarizeLD.__doc__)
... | 44,317 |
def get_poetry_page_links(html):
"""Read in the html from a poetry page and return an array of links"""
clean_links = []
html_soup = BeautifulSoup(html, 'html.parser')
# remove the table of contents
try:
[e.extract() for e in html_soup.find("div", {"id": "toc"})]
except:
pass
# parse out the... | 44,318 |
def setStatusFile(conf:Configuration) -> bool:
"""
Attempts to set the status file according to this server's reported status in Traffic Ops.
.. warning:: This will create the directory '/opt/ORTstatus' if it does not exist, and may
delete files there without warning!
:param conf: An object that contains the co... | 44,319 |
def _exponential_rv(t, tau, T):
"""Generate truncated exponential random variable from uniform [0, 1) random variable.
Parameters
----------
t : array-like
Uniform [0, 1) random variable.
tau : array-like
Lifetime.
T : array-like
Truncation parameter.
"""
return ... | 44,320 |
def apply_noise_filtering(
fully_calibrated_gmr: NDArray[(2, Any), int],
scipy_filter_sos_coefficients: NDArray[(Any, Any), float],
) -> NDArray[(2, Any), int]:
"""Apply the result of an empty plate calibration.
Actual empty plate calibration will be performed once information obtained from Jason.
... | 44,321 |
def read_file(filename: Text, encoding: Text = "utf-8") -> Any:
"""Read text from a file."""
with io.open(filename, encoding=encoding) as f:
return f.read() | 44,322 |
def pattern_note_to_midi_note(pattern_note_byte, octave_offset=0):
"""
Convert pattern note byte value into midi note value
:param pattern_note_byte: GT note value
:type pattern_note_byte: int
:param octave_offset: Should always be zero unless some weird midi offset exists
:type octave_offset:... | 44,323 |
def upload_audio_and_predictions(clip_path, clip_start_time, source_guid, local_confidences, annotation_threshold, round_id, blob_service_client, dataset_folder):
"""
"""
audio_uri = assemble_blob_uri(PODCAST_AZURE_AUDIO_CONTAINER, round_id, os.path.basename(clip_path))
data = {}
data["uri"] ... | 44,324 |
def copyfile(filename, filename2, sedstring=None):
""" copy a file with optional sed. """
if os.path.isdir(filename): return
try: f = open(filename, 'r')
except IOError: return
ddir = ""
for x in filename2.split(os.sep)[:-1]:
ddir += os.sep + x
if not os.path.isdir(ddir):
... | 44,325 |
def FileHole(thisMesh, topologyEdgeIndex, multiple=False):
"""
Given a starting "naked" edge index, this function attempts to determine a "hole"
by chaining additional naked edges together until if returns to the start index.
Then it triangulates the closed polygon and either adds the faces to the mesh.... | 44,326 |
def wide_to_narrow(X, Y, bins):
"""
Convert data from predicting a Y(Zbin,Cbin) as a vector to
individual predictions of Y(Zbin,Cbin) given a Zbin and Cbin label
in the input data.
"""
varname = "variable"
valname = "Y"
x_vars = get_xnames()
dev = pd.concat([X, Y], axis=1)
left ... | 44,327 |
def get_coords(p):
"""Function to get coordinates of N, Ca, C.
It also calculates Cb positions from those.
"""
nres = pyrosetta.rosetta.core.pose.nres_protein(p)
# three anchor atoms to build local reference frame
N = np.stack([np.array(p.residue(i).atom('N').xyz()) for i in range(1,nr... | 44,328 |
def main():
"""
2 steps should be followed:
1. 利用read_dictionary讀取文字檔,並且將所有文字檔按照字數與單次整理起來,方便之後查閱。
(Use read_dictionary to read text files, and all text files according to the number of words
and a single sorting up, convenient after access.)
2. 將輸入的單字透過find_anagrams整理,並且將得到的結果與字典內的單字進行比較... | 44,329 |
def xmkdir(path):
"""Create directory PATH recursively if it does not exist."""
os.makedirs(path, exist_ok=True) | 44,330 |
def test_client_init_no_remindermail(some_client: Dict[str, str]) -> None:
"""It sets `remindermail` to `email`, if no `remindermail` is given.
Args:
some_client (Dict[str, str]): Data for an example client
"""
some_client.pop("remindermail")
client = Client(**some_client)
assert client... | 44,331 |
def expand_dataset(sentences_file, scores_file, category_getter_fn):
""" Expands Stanford Sentiment Treebank dataset file by substituting nouns, verbs and adjectives in each sentence with synonyms
retrieved from WordNet. Processes into a set of of sentence strings and a set of scores.
"""
space_regex = ... | 44,332 |
def load_as_hsv(fname: str) -> np.ndarray:
"""
Load a file into HSV colour space.
Takes a file path and opens the image then converts to HSV colour space.
returns numpy array dtype float 64. Strips the alpha (fourth) channel if it exists.
Input must be colour image. One channel images will be rejec... | 44,333 |
def get_databases ():
"""
Returns a list of all Database objects stored.
"""
return _dbobjects[:] | 44,334 |
def GenomicRegions_FilterToOverlapping(
new_name, gr_a, other_grs, summit_annotator=None, sheet_name="Overlaps"
):
"""Filter to just those that overlap one in *all* other_grs.
Note that filtering does not change the coordinates, it only filters,
non annotator additional rows are kept, annotators are rec... | 44,335 |
def reloadModules():
"""
Reload all light editor modules
"""
pass | 44,336 |
def deep_getsizeof(obj: Any) -> int:
"""
Deeply inspects any Python object for its data usage.
:param o:
:return:
"""
stack: List[Any] = [obj]
seen: Set[int] = set()
total = 0
while stack:
n_obj = stack.pop()
if id(n_obj) in seen:
continue
seen.... | 44,337 |
def findPowerPlant(mirror, name):
"""Return power plant agent, if it exists"""
if name in mirror.ppDict:
return mirror.ppDict[name]
else:
print("*** Power Plant '%s' not found." % name)
return None | 44,338 |
def create_cruise_adjust_msg(spdCtrlLvr_stat, turnIndLvr_Stat, real_steering_wheel_stalk):
"""Creates a CAN message from the cruise control stalk.
Simluates pressing the cruise control stalk (STW_ACTN_RQ.SpdCtrlLvr_Stat)
and turn signal stalk (STW_ACTN_RQ.TurnIndLvr_Stat)
It is probably best not to flood these... | 44,339 |
def get_build_history(build_ids):
"""Returns build object for the last finished build of project."""
build_getter = BuildGetter()
history = []
last_successful_build = None
for build_id in reversed(build_ids):
project_build = build_getter.get_build(build_id)
if project_build['status'] not in ('SUCCE... | 44,340 |
def add_cortes(Base, session):
"""
Guarda el enum de causas de una anomalia
"""
# pdb.set_trace()
TipoCorte = Base.classes.tipo_corte
json_tipos_cortes = os.path.realpath(
"../dashboard-operativo-transito/static/data/tipos_cortes.json")
with open(json_tipos_cortes) as tipos_cortes:
... | 44,341 |
def point_translate(point_in, vector_in):
""" Translates the input points using the input vector.
:param point_in: input point
:type point_in: list, tuple
:param vector_in: input vector
:type vector_in: list, tuple
:return: translated point
:rtype: list
"""
try:
if point_in ... | 44,342 |
def pcmh_1_1b__1_2_3_4():
"""Clinical advice (telephone encounters)"""
telephone_encounter_table_url = URL('init', 'word', 'telephone_log.doc',
vars=dict(type="meeting", **request.get_vars),
hmac_key=MY_KEY, salt=session.MY_SA... | 44,343 |
def distance(x1, y1, x2, y2):
"""
l2 distance
"""
return math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) | 44,344 |
def slice_signal(signal, window_size, stride=0.5):
""" Return windows of the given signal by sweeping in stride fractions
of window
"""
assert signal.ndim == 1, signal.ndim
n_samples = signal.shape[0]
offset = int(window_size * stride)
slices = []
for beg_i, end_i in zip(rang... | 44,345 |
def get_railway() -> User:
"""鉄道用ユーザ情報を取得する
Raises:
DynamoDBError: 鉄道用ユーザ情報が登録されていない
Returns:
User: 鉄道用ユーザ情報
"""
railway_user = get_user("railway")
if railway_user is None:
raise DynamoDBError("鉄道用ユーザ情報が登録されていません。")
return railway_user | 44,346 |
def check_threshold(service, config_high_threshold, config_low_threshold, curr_util):
""" Checks whether Utilization crossed discrete threshold
Args:
service: Name of the micro/macroservice
config_high_threshold: Upper limit threshold to utilization set in config file
config_low_thresho... | 44,347 |
def is_human(captcha_response):
""" Validating recaptcha response from google server.
Returns True captcha test passed for the submitted form
else returns False.
"""
secret = RECAPTCHA_KEYS["secret_key"]
if secret != "":
payload = {'response':captcha_response, 'secret':secret}
... | 44,348 |
def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):
"""Given the anchors and GT boxes, compute overlaps and identify positive
anchors and deltas to refine them to match their corresponding GT boxes.
anchors: [num_anchors, (y1, x1, y2, x2)]
gt_class_ids: [num_gt_boxes] Integer c... | 44,349 |
def ols_data():
"""
draper and smith p.8
"""
xs = [35.3, 29.7, 30.8, 58.8, 61.4, 71.3, 74.4, 76.7, 70.7, 57.5,
46.4, 28.9, 28.1, 39.1, 46.8, 48.5, 59.3, 70, 70, 74.5, 72.1,
58.1, 44.6, 33.4, 28.6]
ys = [10.98, 11.13, 12.51, 8.4, 9.27, 8.73, 6.36, 8.50,
7.82, 9.14, 8.2... | 44,350 |
def check_runfiles_test_suite(name):
"""Entry-point macro called from the BUILD file.
Args:
name: Name of the macro.
"""
_check_runfiles_test()
native.test_suite(
name = name,
tests = [
":check_runfiles_lib_test",
":check_runfiles_bin_test",
... | 44,351 |
def explore_missing_values(dataframes_dict: dict, number_of_features: int):
""" Missing values explorer
This function plots the amount of missing values for given amount of features among all datasets.
:param dict dataframes_dict: A dictionary of pandas dataframes e.g. {"train": train_dataframe,
... | 44,352 |
def print_pdb_path(beads, cell, filedesc = sys.stdout):
"""Prints all the bead configurations, into a pdb formatted file.
Prints the ring polymer springs as well as the bead positions using the
CONECT command. Also prints the cell parameters in standard pdb form. Note
that the angles are in degrees.
Ar... | 44,353 |
def get_as_type(obj):
"""Find the name of ActionScript class mapped to the class of given python object.
If the mapping for the given object class is not found, return the class name of the object."""
type = obj.__module__ + '.' + obj.__class__.__name__
if class_mappings:
for as_class, p... | 44,354 |
def svn_auth_get_ssl_client_cert_pw_file_provider2(*args):
"""
svn_auth_get_ssl_client_cert_pw_file_provider2(svn_auth_plaintext_passphrase_prompt_func_t plaintext_passphrase_prompt_func,
void prompt_baton,
apr_pool_t pool)
"""
return _core.svn_auth_get_ssl_client_cert_pw_file_provid... | 44,355 |
def valid_field(obj, field):
"""Returns ``True`` if given object (BaseDocument subclass or an instance thereof) has given field defined."""
return object.__getattribute__(obj, 'nanomongo').has_field(field) | 44,356 |
def construct_location_name(location: dict) -> str:
"""
Constructs a location name based on the supplied dictionary of elements, ensuring that
they are in the correct format
"""
if location["type"] == "location":
city_name = capwords(location["city"])
if "country" in location:
... | 44,357 |
def test_app_handle_404():
"""Application returns a 404 status code if no resource is found."""
app = wsgiservice.get_app(globals())
req = Request.blank('/foo', {'HTTP_ACCEPT': 'text/xml'})
res = app._handle_request(req)
print res
assert res.status == '404 Not Found'
assert res.body == '<res... | 44,358 |
def anammox(k_anammox, o2s_dn, nh4, no2, o2):
"""Anammox: NO2- + NH4+ -> N2 + 2H2O
k_anammox - velocity of anammox
o2s_dn - half-saturation oxygen inhibitor constant for anammox and denitrification"""
return k_anammox*nh4*no2*hyper_inhibitor(o2s_dn, o2, 1) | 44,359 |
def createXML(corpus, name, typ):
"""
Creates an XML file... Proposed Format:
<document id="quantitative | qualitative">
<sentence id="" text="">
<entity id="" text="" charOffset="" /> <!-- the drug from the drug list and multiple of this-->
<pair id="" e1="" e2="" ddi="" /> <!-- the e1-e2 ddi pair-->
</... | 44,360 |
def argprun(f, sigint_shell=True, **kwargs): # command line overrides kwargs
""" use this to enable command-line access to kwargs of function (useful for main run methods) """
def handler(sig, frame):
# find the frame right under the argprun
print("custom handler called")
original_fram... | 44,361 |
def gripper_follow_ass_dir():
""" Function invoked by user to change grasp face.
This triggers set_grasp_face_following_assembly_direction
"""
process = get_process()
artist = get_process_artist()
beam_id = artist.selected_beam_id
process.set_grasp_face_following_assembly_direction(beam_id)
... | 44,362 |
def courbe_vers_c(l, l2, n0,CP): #c,C
"""
B=Bez()
B.co=[l[0],l[1],l[2],l[3],l[4],l[5]]
B.ha=[0,0]
courbes.ITEM[n0].beziers_knot.append(B)
"""
B=Bez()
B.co=[G_move(l[2],0),
G_move(l[3],1),
G_move(l[4],0),
G_move(l[5],1),
G_move(l[0],0),
G... | 44,363 |
def _synthesize_human_beta_vj_background(ts,fn = None, df = None):
"""
_build_vj_background
Parameters
----------
ts: tcrsampler.TCRsampler()
a TCRsampler instance, with gene usage frequencies (ideally computed get_stratified_gene_usage_frequency()
fn: str
file path to MIRA set... | 44,364 |
def test_translation_statuses_pagination(client):
"""Tests fetching of translation statuses with pagination
"""
statuses = client.translation_statuses(PROJECT_ID, {
"page": 2,
"limit": 1
})
assert statuses.project_id == PROJECT_ID
assert statuses.items[0].title == "waiting for ap... | 44,365 |
def swissPairings():
"""Returns a list of pairs of players for the next round of a match.
Args:
tournament: the id number of the tournament played
Returns:
A list of tuples, each of which contains (id1, name1, id2, name2)
id1: the first player's unique id
name1: the first playe... | 44,366 |
def double_bin_pharmacophore_graph(distance, bins, delta):
""" Assign two bin values to the distance between pharmacophoric points.
Parameters
----------
distance : float
The distance that will be binned.
bins : np.ndarray
Array of bins. It h... | 44,367 |
def get_help(path):
"""
Context Sensitive Help (currently not implemented).
"""
try:
helpitem = HelpItem.objects.get(link=path)
except HelpItem.DoesNotExist:
helpitem = ""
return { 'helpitem': helpitem } | 44,368 |
def remote():
"""
Fixture allowing setup of a mocked remote session & access to sub-mocks.
Yields a `MockRemote` object (which may need to be updated via
`MockRemote.expect`, `MockRemote.expect_sessions`, etc; otherwise a default
session will be used) & calls `MockRemote.stop` on teardown.
"""
... | 44,369 |
def validate_ip_pools(data, valid_values=None):
"""Validate that start and end IP addresses are present.
In addition to this the IP addresses will also be validated
"""
if not isinstance(data, list):
msg = _("Invalid data format for IP pool: '%s'") % data
LOG.debug(msg)
return m... | 44,370 |
def _clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default.
If we spawn a child process that also calls MPI_Init and
has MPI environment variables defined, MPI will think that the child process is
an MPI process just like the parent and do bad things such as hang or crash.
... | 44,371 |
def _GKEConnectNamespace(kube_client, project_id):
"""Returns the namespace into which to install or update the connect agent.
Connect namespaces are identified by the presence of the hub.gke.io/project
label. If there is one existing namespace with this label in the cluster, its
name is returned; otherwise, a... | 44,372 |
def version_cmp(ver1, ver2, ignore_epoch=False):
"""
.. versionadded:: 2015.8.9
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` t... | 44,373 |
def triplet_loss_compute_semihard(feature1, feature2, labels, margin=1.0):
""" triplet loss with semi-hard negative pairs
"""
batch_size = labels.get_shape().as_list()[0]
labels = tf.cast(tf.reshape(labels, [batch_size, 1]), tf.float32)
feature1 = tf.nn.l2_normalize(tf.reshape(feature1, [batch_size... | 44,374 |
def get_all_markups() -> List[Type[AbstractMarkup]]:
"""
:returns: list of all markups (both standard and custom ones)
"""
try: # Python 3.10+
entrypoints = entry_points(group="pymarkups")
except TypeError: # Older versions
entrypoints = entry_points()["pymarkups"]
return [entry_point.load() for entry_point... | 44,375 |
def esg_route_list(client_session, esg_name):
"""
This function return the configured static routes
:param client_session: An instance of an NsxClient Session
:param esg_name: The name of the ESG of which the routes should be listed
:return: returns a tuple, the firt item of the tuple contains a lis... | 44,376 |
def create_instance_profile(profile_name, role_name=None):
""" Creates IAM instance profile
:param profile_name: Name of profile to be created
:param role_name: Name of role to attach to instance profile
:return: API response
"""
try:
creat... | 44,377 |
def is_empty_dir(target_dir):
"""return is empty directory or not
:param str target_dir: target dir
"""
for root, _, files in os.walk(target_dir):
for f in files:
if os.path.isfile(os.path.join(root, f)):
return False
return True | 44,378 |
def is_primary(flag):
"""
:return bool: Returns whether the current record is primary alignment
"""
if flag is None:
raise ValueError("No flag associated with this record")
return not SamFlag.IS_UNMAPPED & flag and not SamFlag.IS_SECONDARY_ALIGNMENT & flag | 44,379 |
def write_to_service_file(file_name,params):
"""Write Avahi service file"""
with open(file_name,'w') as output:
output.write("""<service-group>
<name replace-wildcards="yes">Freebox Server</name>
<service protocol="ipv4">
<type>_fbx-api._tcp</type>
<port>8... | 44,380 |
def run_js_tests():
"""Run Javascript tests."""
has_xvfb = spawn.find_executable('xvfb-run')
return execute_cmd(
'%s python butler.py js_unittest' % ('xvfb-run' if has_xvfb else ''),
os.environ.copy()) | 44,381 |
def extract_years(text: str, default: Optional[str] = None) -> Set[str]:
"""Try to locate year numbers in a string such as 'circa 1990'. This will fail if
any numbers that don't look like years are found in the string, a strong indicator
that a more precise date is encoded (e.g. '1990 Mar 03')."""
years... | 44,382 |
def is_absolute_url(parsed_url):
""" check if it is an absolute url """
return all([parsed_url.scheme, parsed_url.netloc]) | 44,383 |
def so3_exp_map(log_rot: torch.Tensor, eps: float = 0.0001) -> torch.Tensor:
"""
Convert a batch of logarithmic representations of rotation matrices `log_rot`
to a batch of 3x3 rotation matrices using Rodrigues formula [1].
In the logarithmic representation, each rotation matrix is represented as
a... | 44,384 |
def get_example_summary_file():
"""Convenience wrapper to retrieve file path from package data."""
return pkg_resources.resource_filename('tempset', 'data/electric/summary.zip') | 44,385 |
def set_pH(in_smi):
"""Function to set the pH of a molecule
Currently uses OpenBabel to perform protonation (to pH 7.4)
Takes a smiles string
Returns the protonated smiles string"""
# Attempt to use the babel that has been included in the distro
try:
d = sys._MEIPASS
bab... | 44,386 |
def get_hardware_status(ip, port, username, password) -> dict:
"""Gets CPU memory statuses IOS-XE\n
Cisco-IOS-XE-platform-software-oper:cisco-platform-software/control-processes/control-process"""
###### Future Use
data = {}
try:
uri = f"https://{ip}:{port}/restconf/data/Cisco-IOS-XE-... | 44,387 |
def generate_resources():
"""Responsible for generating the resources pages"""
# Create content pages directory if does not already exist
util.buildhelpers.create_content_pages_dir()
# Verify if resources directory exists
if not os.path.isdir(site_config.resources_markdown_path):
os.mkdir(... | 44,388 |
def q2_2(df: pd.DataFrame) -> tuple:
"""
Calculates mean and median for V2 of df, returns tuple of (mean, median)
"""
V2 = df["V2"]
return V2.mean(), V2.median() | 44,389 |
def dup_rr_primitive(f, K):
"""Returns content and a primitive polynomial over a ring. """
cont = dup_content(f, K)
if not f or K.is_one(cont):
return cont, f
else:
return cont, dup_exquo_ground(f, cont, K) | 44,390 |
def iter_slices(X, shape, shift=0):
"""Iter over slice indices of a dataset.
Slicing is done in a way that ensures that only pieces
on boundaries of the sliced dataset can have leftovers
in regard to a specified shape.
Parameters
----------
X : array_like
Daataset represented as a ... | 44,391 |
def develop():
"""
Call "python setup_py develop".
"""
sh("python setup.py develop") | 44,392 |
def mk_png(html: str, folder=None) -> str:
"""Return generated PNG file path"""
folder = (local.path(folder) if folder else local.path('/tmp/ccb_png')) / uuid4()
folder.mkdir()
png = folder / 'code.png'
(
convert['-trim', '-trim', '-', png]
<< HTML(string=html, media_type='screen').w... | 44,393 |
def entry_breadcrumbs(entry):
"""
Breadcrumbs for an Entry.
"""
date = entry.publication_date
if is_aware(date):
date = localtime(date)
return [year_crumb(date), month_crumb(date),
day_crumb(date), Crumb(entry.title)] | 44,394 |
def w_desired_supply_line():
"""
Real Name: b'W Desired Supply Line'
Original Eqn: b'W Delivery Delay*W Expected Customer Orders'
Units: b'SKU'
Limits: (None, None)
Type: component
b''
"""
return w_delivery_delay() * w_expected_customer_orders() | 44,395 |
def _ShardName(name, number):
"""Add a shard number to the end of a target.
Arguments:
name: name of the target (foo#target)
number: shard number
Returns:
Target name with shard added (foo_1#target)
"""
return _SuffixName(name, str(number)) | 44,396 |
def ReadMartiniMolecules(GroFile, First, Last):
""" Generate the normalized coordinates, name, and vector of the Martini molecule
Access the Martini3 small molecules library and reads the parameterized coordinates from it,
with future view of looking at generating automatically generating Martini 3 r... | 44,397 |
def average_gen_fock(filename, fock_type='plus', estimator='back_propagated',
eqlb=1, skip=1, ix=None):
"""Average AFQMC genralised Fock matrix.
Parameters
----------
filename : string
QMCPACK output containing density matrix (*.h5 file).
fock_type : string
Whic... | 44,398 |
def start_ignite(test_context, ignite_version: str, rebalance_params: RebalanceParams) -> IgniteService:
"""
Start IgniteService:
:param test_context: Test context.
:param ignite_version: Ignite version.
:param rebalance_params: Rebalance parameters.
:return: IgniteService.
"""
node_cou... | 44,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.