content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _method_from_mod(block_dets, modname, methodname):
"""
E.g.
from os import getcwd
from os.path import join
from os.path import join as joinpath
<ImportFrom lineno="4" col_offset="0" type="int" module="os" level="0">
<names>
<alias type="str" name="getcwd"/>
"""
imp... | 64,000 |
def label(text='Origin', pos=(0, 0, 0), scale=(0.2, 0.2, 0.2),
color=(1, 1, 1)):
"""Create a label actor.
This actor will always face the camera
Parameters
----------
text : str
Text for the label.
pos : (3,) array_like, optional
Left down position of the label.
s... | 64,001 |
def validate_schema(schema_key: str, value: Any, draft_checker=jsonschema.draft7_format_checker) -> Any:
"""Validate a JSONSchema according a json model.
.. versionadded:: 0.6.0
Raises:
jsonschema.ValidationError: When the current value does not match with expected schema.
Note:
This ... | 64,002 |
def complete_ports(_: Any, __: Any, incomplete: str) -> Sequence[str]:
"""Returns common ports for completion."""
return [k for k in ('80', '443', '8080') if k.startswith(incomplete)] | 64,003 |
def import_modules(modules_path, skip_list=None):
"""
Dynamically imports python modules found in the provided directory and
returns a list of the module objects found.
Args:
modules_path (str): filesystem path containing modules to import
skip_list (list): module names to skip, usually... | 64,004 |
def compute_local_coordinates(cx, cy, x, y, newton_tol=1e-12,
interpolation_scheme='nufft', guess_ind=None, verbose=False, max_iterations=30):
"""
Find (s, r) given (x, y) using the coordinates:
x = X(s) + r n_x(s)
y = Y(s) + r n_y(s)
Where X, Y is given by cx, cy
Uses a NUFFT based... | 64,005 |
def search_linkedin_user(search_string):
"""
Search for an user in LinkedIn.
Results are similar to search in the website.
Shows the information represented as JSON.
Paramters
---------
search_string: str
Search string used for the search.
Could be a name, name and surname or whatever.
Returns
-------
J... | 64,006 |
def parse_search(interms):
"""We go to the trouble of parsing searches ourselves because ADS's syntax
is quite verbose. Terms we support:
(integer) -> year specification
if this year is 2014, 16--99 are treated as 19NN,
and 00--15 is treated as 20NN (for "2015 in prep" papers)
Otherwis... | 64,007 |
def gunicorn_sync_wrapper(wrapped, _instance, args, kwargs):
"""
Wraps the gunicorn sync worker handle request.
Catches request handling errors and finally sending the trace.
:param wrapped: wrapt's wrapped
:param _instance: wrapt's instance
:param args: wrapt's args
:param kwargs: wrapt's k... | 64,008 |
def plot_ratios(dfmed, dfmin, dfmax, subtitle, ideal_dist='numpy'):
"""Plot the timing results.
Plot each line divided by ideal.
"""
ideal = 'ideal ' + ideal_dist
ratios = []
for df in (dfmed, dfmin, dfmax):
if df is None:
ratios.append(None)
continue
ra... | 64,009 |
def make_table(
rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False
) -> str:
"""
:param rows: 2D list containing objects that have a single-line representation (via `str`).
All rows must be of the same length.
:param labels: List containing the column labels. If presen... | 64,010 |
def retrieve_list():
"""Method used to get the list of prime parts or sets of wfm."""
string_set = set()
result = utils.get_request("items")
if result:
item_list = [item["url_name"] for item in result["items"]]
result_file = open("item_list.csv", "w", encoding="utf-8")
f... | 64,011 |
def _get_max_mem():
"""Return the current cgroup's memory high water mark."""
try:
with open("/sys/fs/cgroup/memory/memory.max_usage_in_bytes") as f:
return float(f.read().strip())
except Exception:
return 0 | 64,012 |
def add_image(qc_html, image, title=None):
"""
Adds an image to the report.
"""
if title:
qc_html.write('<center> {} </center>'.format(title))
relpath = os.path.relpath(image, os.path.dirname(qc_html.name))
qc_html.write('<a href="' + relpath + '" >')
qc_html.write('<img src="' + re... | 64,013 |
def gaussian_lowpass(sigma: tf.Tensor, filter_size: int):
"""Generates gaussian windows centered in zero, of std sigma.
Args:
sigma: tf.Tensor<float>[1, 1, C, 1] for C filters.
filter_size: length of the filter.
Returns:
A tf.Tensor<float>[1, filter_size, C, 1].
"""
sigma = tf.clip_by_value(
... | 64,014 |
def predict_on_structure_par_en(structure: Structure, gp: GaussianProcess,
n_cpus: int = None,
write_to_structure: bool = True,
selective_atoms: List[int] = None,
skipped_atom_value = 0) -> (
... | 64,015 |
def suite():
"""Gather all the tests from this package in a test suite."""
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(TestRevokeReport, "test"))
return test_suite | 64,016 |
def get_sender(msg):
"""
Returns the best-guess sender of an email.
Arguments:
email -- the email whose sender is desired
Returns:
Sender of the email.
"""
sender = msg['From']
m = re.match(r'(.*)\s<.*>', sender)
if m:
return m.group(1)
return se... | 64,017 |
def test_variables_dont_raise_warning(model, caplog):
"""
Test if initialization of ``DecayLROnPlateau`` does not raise warnings for variables that are specific for
parent hooks only (not shared among both). See emloop issue #14 for more details.
"""
caplog.set_level(logging.WARNING)
DecayLROnPl... | 64,018 |
def coord_arg_to_coord(carg):
"""
Parameters
----------
carg : str
Argument from parser for coordinates
Eligible formats are like:
J081240.7+320809
122.223,-23.2322
07:45:00.47,34:17:31.1
Returns
-------
icoord : str or tuple
Allowed format for c... | 64,019 |
def clear_geolocation_override() -> dict:
"""Clears the overriden Geolocation Position and Error."""
return {"method": "Emulation.clearGeolocationOverride", "params": {}} | 64,020 |
def amount_in_location(obj, user):
"""
Returns how many instances of this product
are at the current user's location
"""
return obj.get_amount_stocked(user) | 64,021 |
def test_add_get_external_service(rotkehlchen_api_server):
"""Tests that adding and retrieving external service credentials works"""
# With no data an empty response should be returned
response = requests.get(
api_url_for(rotkehlchen_api_server, "externalservicesresource"),
)
assert_proper_r... | 64,022 |
def all_comments():
"""
All comments for each Influencer
:return: wordcloud with all comments
"""
comments_list = []
comments = db.get_post_comments()
for index, row in comments.iterrows():
comments_list = []
for influencer in row['comments']:
for post in influenc... | 64,023 |
def getRayCircleIntersections(startPoint, direction, center, radius):
"""
Calculate distances, from start, where a ray intersects a circle.
Returns a list of distances of length 0, 1 or 2.
The smallest distance always appears 1st and can be negative to represent the case of the intersection being "b... | 64,024 |
def ip_attributes(system, request, row, row_counter, model):
""" IP addresses are set depending on config """
# remove existing IP addresses for this system (not relevant for newly created systems)
if model.csv_remove_ip:
# remove many to many relation between system and ip without deleting existin... | 64,025 |
def delete(**_):
"""Deletes a Credential"""
utils.task_resource_delete(Credential()) | 64,026 |
def is_tree_super_balanced(root):
"""Check if the tree is super balanced or not."""
d_max = depth_of_tree(root)
d_min = depth_of_tree(root, False)
if d_max - d_min > 1:
return False
else:
return True | 64,027 |
def _copy2_ignoring_special_files(src, dest):
# type: (str, str) -> None
"""Copying special files is not supported, but as a convenience to users
we skip errors copying them. This supports tools that may create e.g.
socket files in the project source directory.
"""
try:
copy2_fixed(src, ... | 64,028 |
def load_user(user_id):
"""This function loads the user."""
user = session.query(User).filter_by(id=user_id).first()
if not user:
flash('invalid username or password')
abort(400)
return user | 64,029 |
def CombinatorialAuction(
df,
id_label="id",
price_label="price",
element_label="element",
buyer_label="buyer",
limit=-1,
**kwargs,
):
"""
組合せオークション問題
要素を重複売却せず、購入者ごとの候補数上限を超えないように売却金額を最大化
入力
df: 候補のDataFrameもしくはCSVファイル名
id_label: 候補番号の属性文字
... | 64,030 |
def format_string():
"""Returns the format string of the binary file"""
return "IIccccI?cccc" | 64,031 |
def test_direction():
"""Test definition of the Direction enum."""
assert Direction.X.value == 0
assert Direction.Y.value == 1
assert Direction.Z.value == 2 | 64,032 |
def main():
"""Main."""
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
with TempRepo(bare=True) as bare_repo:
log.info('Bare repo = %s', bare_repo.path)
clone = bare_repo.clone
log.info('Clone = %s', clone.working_dir)
bare_repo.update_script... | 64,033 |
def test_convert__convert_storage__3(zodb_storage, zodb_root):
"""It decodes binary string using encoding given by section name."""
zodb_root['obj'] = Example(
title=u'bïnäry'.encode('utf-8'), text=u'bïnäry'.encode('latin-1'))
transaction.commit()
mapping = {
'zodb.py3migrate.testing.Exa... | 64,034 |
def crear_actualizar_ciudadano_reniec(numero_documento, uuid=None):
"""
Obtiene datos de ciudadano desde RENIEC
:param numero_documento: Número de documento a consultar en RENIEC
:param uuid: UUID de ciudadano a actualizar
:return: ciudadano
"""
verificar_conexion_internet()
ciudadano ... | 64,035 |
def write_dbtables(database, validation):
"""write the splitted data
Parameters
----------
dbfile: result from `generate_input_db(args, logger, run_id)`
alldatatable: `string`
ntables: `int`, (2, by default)
"""
import sqlite3
conn = sqlite3.connect(database)
table = "data... | 64,036 |
def obj_box_zoom(
im, classes=None, coords=None, zoom_range=(0.9,
1.1), row_index=0, col_index=1, channel_index=2, fill_mode='nearest',
cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12.
):
"""Zoom i... | 64,037 |
def view_points_in_water(reconstructor, cam_id, pts3d, water, distorted=True):
"""
pts3d : (N,3) array of 3D points
returns:
(2,N) projection of 3D points
"""
assert isinstance(water, WaterInterface)
pts3d = np.array(pts3d)
assert pts3d.ndim == 2
assert pts3d.shape[1] == 3 # pt... | 64,038 |
def test_transition_eval():
"""
The transition can be fired when its guard is true, which i checked with the eval function
"""
t1 = Transition("T1", guards.from_str("a && b"), actions.from_str("!a, c"))
print(t1)
s1 = State(a = False, b = True, c = False)
s2 = State(a = True, b = True, c = F... | 64,039 |
def isel_variable_and_index(
name: Hashable,
variable: "Variable",
index: Index,
indexers: Mapping[Hashable, Union[int, slice, np.ndarray, "Variable"]],
) -> Tuple["Variable", Optional[Index]]:
"""Index a Variable and pandas.Index together."""
from .variable import Variable
if not indexers:... | 64,040 |
def respostas_iguais(r1,r2):
"""
respostas_iguais: resposta x resposta --> logico
respostas_iguais(r1,r2) devolve o valor verdadeiro se as respostas r1 e r2
contiverem os mesmos tuplos, e falso caso contrario.
"""
return resposta_string(r1) == resposta_string(r2) | 64,041 |
def pytest_addoption(parser):
"""
Add command-line options to the pytest application.
Although these "options" are prefixed by '--', they
are all required for the test suite to run.
"""
parser.addoption(
'--user_address',
dest='user_address',
help="DNS name or IP address... | 64,042 |
def test_file_listing_and_url_retrieval():
"""
Tests that files can be uploaded and then retrieved
with presigned urls
"""
src_path = test_file_data_root + "keys_and_values.json"
dest_path = "test_file_list.json"
assert client.upload(dataset_id, src_path, dest_path).successful()
listed_f... | 64,043 |
def getCountryData(df):
"""
Implement a function to get counts of data based on show type
"""
country_df = df[["country","type","index"]]
country_df = country_df.groupby(['country','type']).count().unstack()
country_df.columns = ['Movie','TV Show']
country_df = country_df.reset_index(... | 64,044 |
def GetBptEA(n):
"""
Get breakpoint address
@param n: number of breakpoint, is in range 0..GetBptQty()-1
@return: addresss of the breakpoint or BADADDR
"""
bpt = idaapi.bpt_t()
if idaapi.getn_bpt(n, bpt):
return bpt.ea
else:
return BADADDR | 64,045 |
def flexible_pileup(features, data_select, data_snip, mapper=map):
"""
TAKEN from cooltool.snipping.pileup -> patched in a fashion that allows differently sized
windows.
Handles on-diagonal and off-diagonal cases.
Parameters
----------
features : DataFrame
Table of features. Requires... | 64,046 |
def test_compose():
"""
Test compose instance method
"""
func = lambda x: memory.append(x) or 0
memory = []
assert Sequence([], [1]).compose(func, Sequence([], [2])) == Sequence.zero
assert memory == [(1,2)]
memory = []
assert Sequence([1], [2]).compose(func, Sequence([], [2])) == ... | 64,047 |
def delete_customer(request, customer_id):
"""deleting customer"""
# verify that the calling user has a valid token
token = request.headers.get('Token')
if token is None:
return request_response(badRequestResponse, ErrorCodes.INVALID_CREDENTIALS, "Token is missing in the request headers")
#... | 64,048 |
def list_conferences_groups(request_ctx, group_id, per_page=None, **request_kwargs):
"""
Retrieve the list of conferences for this context
This API returns a JSON object containing the list of conferences,
the key for the list of conferences is "conferences"
Examples:
curl 'https:... | 64,049 |
def all_success(mgmt_commands):
"""Determines if all child processes were successful.
Args:
mgmt_commands : A list of all Command objects
Returns:
True if all child processes succeeded
"""
for mgmt_command in mgmt_commands:
if mgmt_command.retcode != 0:
return False
return True | 64,050 |
def get_nameservice(hdfs_site):
"""
Multiple nameservices can be configured for example to support seamless distcp
between two HA clusters. The nameservices are defined as a comma separated
list in hdfs_site['dfs.nameservices']. The parameter
hdfs['dfs.internal.nameservices'] was introduced in Hadoop 2.6 to d... | 64,051 |
def checkChanList(chanprof, profile, chanList):
""" Return non-zero value if any element of chanlist is not in the channel list of profile
"""
for c in chanList:
if c not in chanprof[profile-1]:
return 1
return 0 | 64,052 |
def train(
lexicon: LEXICON_TYPE,
model_path: typing.Union[str, Path],
corpus_path: typing.Optional[typing.Union[str, Path]] = None,
env: typing.Optional[typing.Dict[str, str]] = None,
):
"""Create a new grapheme to phoneme model based on a lexion"""
if env is None:
env = guess_environme... | 64,053 |
def someweta_de(data: List[List[str]], model=None) -> (
List[List[str]], List[str]):
"""
model (Default: None)
Preloaded instance of the NLP model. See nlptasks.pos.get_model
"""
# (1) load model
if not model:
model = someweta.ASPTagger()
model.load(f"{str(Path.home()... | 64,054 |
def contest_login(request, contest_id):
"""Generates a contest-local SID for a contest."""
sid = srvctl_sid(request)
hdrs, resp = _runcgi(request, "new-master", SID=sid, action=3, contest_id=contest_id)
if "Location" not in hdrs:
if _xpath(resp, "//title").text.endswith("Permission denied"):
... | 64,055 |
def is_pyflakes_available():
"""
Checks if pyflakes is availalbe.
:returns: **True** if we can use pyflakes and **False** otherwise
"""
return _module_exists('pyflakes.api') and _module_exists('pyflakes.reporter') | 64,056 |
def recursively_iterdir(path):
"""Iterate over files, exclusively, in path and its sub directories."""
for item in Path(path).iterdir():
if item.is_dir():
yield from recursively_iterdir(item)
else:
yield item | 64,057 |
def load_polys(jsonfile):
"""load info of polygons(=puzzle state) from json file.
Args:
jsonfile (pathlib.Path): json file to be loaded
"""
try:
with jsonfile.open('r') as fi:
jsondata = json.load(fi)
except (IsADirectoryError, FileNotFoundError, json.JSONDecodeError):
... | 64,058 |
def make_tree_defs(mod_files_list):
"""get a list of 2-uple (module, list_of_files_which_import_this_module),
it will return a dictionary to represent this as a tree
"""
tree_defs = {}
for mod, files in mod_files_list:
node = (tree_defs, ())
for prefix in mod.split('.'):
... | 64,059 |
def verify_identifiers(identifiers, n_items):
"""Ensure that identifiers has a compatible length and that its elements
are unique"""
if identifiers is None:
return identifiers
identifiers = np.array(identifiers, copy=False)
# Check length for consistency
if len(identifiers) != n_items:... | 64,060 |
def image_get_class_cn_dict(cn_imagenet_class_path):
"""
获得分类的中文对照词典
:param cn_imagenet_class_path:
:return:
"""
fn = open(cn_imagenet_class_path, "r", encoding='UTF-8')
str_json = fn.read()
dic = json.loads(str_json)
fn.close()
return dic | 64,061 |
def reveal_type(value: _T) -> _T:
"""Inspect the inferred type of an expression.
Calling this function will make pyanalyze print out the argument's
inferred value in a human-readable format. At runtime it does nothing.
This is automatically exposed as a global during type checking, so in
code that... | 64,062 |
def f5_update_policy_method_command(client: Client, policy_md5: str, method_id: str,
method_name: str, act_as_method: str) -> CommandResults:
"""
Update allowed method from a certain policy..
Args:
client (Client): f5 client.
policy_md5 (str): MD5 hash of... | 64,063 |
def convertKerasType(dtype):
"""Convert a numpy type into a tensorflow type
"""
if dtype not in O.mapping.NP_TYPE_TO_TENSOR_TYPE:
logger.warning("Unknown data type %s is treated as float", str(dtype))
dtype = np.dtype('float32')
return O.mapping.NP_TYPE_TO_TENSOR_TYPE[dtype] | 64,064 |
def usage():
"""Show command usage."""
msg = ('\n\tUsage: '+sys.argv[0]+' config_file_name \n\n'
'\tExample: '+sys.argv[0]+' devices.cfg\n\n'
'\tOPTIONAL Values:\n'
'\t\tconfig_file_name ---> Name of the file that has remote devices access and command details, case sensitive\n'
'\... | 64,065 |
def get_file(c, key):
"""Get (print) a secret file"""
data = download_data(c, key, FILE)
c.run(f'printf $DATA | base64 -d', env={'DATA': data}) | 64,066 |
def do_ed_lines_mod_job(port_input_name: str, min_line_length: int, operator: str,
gradient_thr: int = 36, anchor_thr: int = 8, scan_interval: int = 1, line_fit_err_thr: int = 1,
max_edges: int = 5000, max_points_edge: int = 500, max_lines: int = 5000, max_points_line: ... | 64,067 |
def hess_smith(x_coord,y_coord,alpha,Re,npanel,batch_analyis):
"""Computes the incompressible, inviscid flow over an airfoil of arbitrary shape using the Hess-Smith panel method.
Assumptions:
None
Source: "An introduction to theoretical and computational
aerodynamics", ... | 64,068 |
def filter_folders_by_predicate(walk: OsWalk, predicate: WalkPredicate, abs_path: bool = False, prune: bool = False) -> OsWalk:
"""
Filters a walk's folder collection using the given predicate.
:param walk: The walk 'object' to filter
:param predicate: The condition to check; should take in the folder ... | 64,069 |
def extendScalarField(tetraMeshPath, meshVTK = None, threshold = None, meshNameType = '_withScalarField', recompute = False):
"""
Given two meshes, one superficial and another tetrahedral, extends all the scalar fields in the superficial mesh to the superficial using Laplace equation (Heat equation)
TODO:... | 64,070 |
def get_default_baseconf_settings_filenames():
"""Returns the filename string where the basic configuration will be read from.
:return: filename string
"""
return (_baseconf_settings_filename,_baseconf_settings_filename_comments) | 64,071 |
def sample_tag(user, name='main course'):
""" create and return a sample tag"""
return Tag.objects.create(user=user, name=name) | 64,072 |
def markUnexpectedSigmaPeaks(x, y, x_sigma, y_sigma, status, max_sigma, min_sigma, r_neighbors):
"""
For each peak, check if it has an unexpected sigma. If it does not mark
the peak for removal (by setting the status to ERROR) and the neighbors
as running.
"""
assert (x.flags['C_CONTIGUOUS']),... | 64,073 |
def cron_clean_view():
"""Clean-ups every outdated article or bias pair."""
return {"cleaned": clean_articles()} | 64,074 |
def disable_elements(window: sg.Window, elem_list: List[sg.Window]) -> None:
""" Take a list of element keys and disable the element.
Args:
window: The element representing the passed GUI window.
elem_list: The list of elements whose state is to be changed.
Returns:
None
"""
... | 64,075 |
def calculate_plane_histogram(plane, doseplane, dosegridpoints, maxdose, dd,
id, structure, hist):
"""Calculate the DVH for the given plane in the structure."""
contours = [[x[0:2] for x in c['data']] for c in plane]
# Create a zero valued bool grid
grid = np.zeros((dd['ro... | 64,076 |
def test_max_response_time():
"""
Test if the value and type of the "max_response_time" property is correct.
"""
cmd = ShdlcCmdSetBaudrate(baudrate=0x00000000)
assert type(cmd.max_response_time) is float
assert cmd.max_response_time == 0.05 | 64,077 |
def broadcast(send_from_nick, addr, msg_from_client, target='others'):
"""
Inputs
send_from_nick: (str) Display handle.
addr: (address) Sender's address
msg_from_client: (str)
target: (str) Options: 'others', 'self', 'all'
"""
msg = f'@{send_from_nick.decode()}: {msg_from... | 64,078 |
def test_align():
"""TimeSeries.insert_element() and TimeSeries.convert_deltas()
"""
# Test the case:
#
# +-----+-----+---
# | x | y |
# +-----+-----+---
# ^-t0 ^-t1
#
# yields
#
# +-----+-----+---
# | y-x | 0 |
# +-----+-----+---
# ^-t0 ^-t1
... | 64,079 |
def log_model(spark_model, artifact_path, conda_env=None, jars=None, dfs_tmpdir=None,
sample_input=None):
"""
Log a Spark MLlib model as an MLflow artifact for the current run. This uses the
MLlib persistence format, and the logged model will have the Spark flavor.
:param spark_model: Pip... | 64,080 |
def acorr(x, axis=-1, onesided=False, scale='none'):
"""Compute autocorrelation of x along given axis.
Parameters
----------
x : array-like
signal to correlate.
axis : int
axis along which autocorrelation is computed.
onesided: bool, optional
if True, only returns the ri... | 64,081 |
def jsonp(func):
"""
Decorator for the following JSON API functions for the connection test.
"""
def dec(request, *args, **kw):
resp = func(request, *args, **kw)
cb = request.GET.get('callback')
if not cb:
cb = ''
resp['Content-Type'] = 'application/javascrip... | 64,082 |
def vtkmatrix_to_numpy(matrix):
"""
Copies the elements of a vtkMatrix4x4 into a numpy array.
:param matrix: The matrix to be copied into an array.
:type matrix: vtk.vtkMatrix4x4
:rtype: numpy.ndarray
"""
m = np.ones((4, 4))
for i in range(4):
for j in range(4):
m[i,... | 64,083 |
def test_ridge_classifier_predict():
"""Test of `LinearClassifier` class with a prediction."""
lc = RidgeClassifier(learning_rate=0.1, iterations=1, standardize=True)
X = np.array([[0], [1]])
y = np.array([[0], [1]])
lc.fit(X, y)
assert np.equal(lc.predict(np.array([0])), np.array([0])) | 64,084 |
def PnCPjInvDyn(robot, q, qdot, qddot, s_jp, s_jd):
"""
q: np.array, qdot: np.array, qddot: np.array, s_jp: np.array, s_jd: np.array
"""
# print(qddot[0])
# print(qddot[1])
assert IsClose(qddot[0], qddot[1])
mass, mass_inv, b, g, lambda_i, jac_i_bar, null_i = UpdateRobotSystem(
rob... | 64,085 |
def load_model(str_filename, which_iteration=-1):
"""Load a previously saved model and its history from a file
"""
print("Loading model from %s" % str_filename)
data = torch.load(str_filename)
# Set the type for floats from the save
set_dtype(data['cfg']['dtype'])
# Reconstruct Geometry
new_geom = new_geome... | 64,086 |
def utcnow(cls):
"""[!91sgk] (disabled)"""
raise TypeError("UTCDateTime: 'utcnow()' is disabled. Use 'now()' instead.") | 64,087 |
def genera_le_permutazioni(lista):
"""generatore ricorsivo per la lista delle possibili permutazioni degli elementi in lista. Il contratto della ricorsione e di generare le permutazioni prefissando ciascuna di esse con gli elementi in history"""
if len(lista)==0:
yield ""
for first in lista:
lista_altri =... | 64,088 |
def Tbeam(
depth: RealNumber,
web_thickness: RealNumber,
flange_width: RealNumber,
flange_thickness: RealNumber,
) -> Dict[str, float]:
"""
Calculates the Centroid, Area, Moment of Inetia, and Section Modulus of a T beam.
The assumed orientation is with the depth along the y axis and th... | 64,089 |
def get_base_required_field_types():
""" Get field types for UI asset required fields.
2016-08-24: removed 'coordinates': 'floatlist',
2016-08-26" remove 'augmented': 'bool', 'Ref Des': 'string','hasDeploymentEvent': 'bool','remoteDocuments': 'list',
added 'editPhase' can have values: EDIT, STAGED, OPER... | 64,090 |
def check_instance_attribute_access_through_class(builder: IRBuilder,
expr: MemberExpr,
typ: Optional[ProperType]) -> None:
"""Report error if accessing an instance attribute through class object."""
if isinstanc... | 64,091 |
def list(
ctx: CLIContext,
status: str,
scaling_group: str | None,
filter_: str | None,
order: str | None,
offset: int,
limit: int | None,
) -> None:
"""
List agents.
(super-admin privilege required)
"""
fields = [
agent_fields['id'],
agent_fields['status'... | 64,092 |
def split_train_val(all_dir, train_dir, rate=5):
"""
将每个类别的数据按分割率进行分割,生成训练集和测试集数据。
:param all_dir: 分割的原始文件夹
:param train_dir: 输出的文件夹
:param rate: 分割率
:return: 无
"""
# 获取所有的子文件夹
dirs = subdir_list(all_dir)
# 排序
dirs = sorted(dirs)
# 如果没有结果文件夹则新建
if not os.path.exists(... | 64,093 |
def _index_p(es_client: elasticsearch.Elasticsearch, index_name: str) -> bool:
"""
Checks if the given index exists.
"""
indices = IndicesClient(es_client)
return indices.exists(index_name) | 64,094 |
def histogram(arg, nbins=None, binwidth=None, base=None, closed='left',
aux_hash=None):
"""
Compute a histogram with fixed width bins
Parameters
----------
arg : numeric array expression
nbins : int, default None
If supplied, will be used to compute the binwidth
binwidth... | 64,095 |
def load_cam_params(path):
"""Loads camera parameters from a JSON file.
:param path: Path to the JSON file.
:return: Dictionary with the following items:
- 'im_size': (width, height).
- 'K': 3x3 intrinsic camera matrix.
- 'depth_scale': Scale factor to convert the depth images to mm (optional).
"""
... | 64,096 |
def _create_new_wells(field_id: int, well_names: Set[str]) -> None:
"""Create new wells if not exists"""
return Well.objects.bulk_create(
[Well(name=well_name, field_id=field_id) for well_name in well_names], ignore_conflicts=True
) | 64,097 |
def _shell_lookup(args):
"""This function is called when the script is used from command line:
[jakni@nissen scripts]$ python unifetch.py -a A6XGL2 -ncis
Name: A6XGL2_HUMAN
Data class: Unreviewed
TaxID: 9606
Sequence: MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRRE [ ... ]
"""
... | 64,098 |
def get_feature_symbolic_learning(df, gp_config):
"""
Parameters
----------
df: pd.DataFrame,the input dataFrame.
gp_config: GPConfig object, the config object of gplearn.SymbolicTransformer.
Returns
-------
df_t: pd.DataFrame, df with the features of SymbolicTransformer trans.
... | 64,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.