content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def __generate_linear_plot_func(
cloudpair: tuple[Cloud, Cloud],
ax: Axes,
distance: list[float],
y: list[float],
color: str,
series_name: str,
semilogy: bool,
) -> Callable[[Optional[int]], list[PathCollection]]:
"""
:return function that actually does the plotting. We do this becau... | 76,500 |
def get_id_set(id_set_path: str) -> dict:
"""
Parses the content of id_set_path and returns its content.
Args:
id_set_path: The path of the id_set file
Returns:
The parsed content of id_set
"""
with open(id_set_path, 'r') as id_set_file:
id_set = json.load(id_set_file)
... | 76,501 |
async def update_recipe_category(category: str, new_category: CategoryIn, session: Session = Depends(generate_session)):
""" Updates an existing Tag in the database """
try:
return db.categories.update(session, category, new_category.dict())
except Exception:
raise HTTPException(status.HTTP... | 76,502 |
def get_station_id(pool, latitude, longitude, station_type) -> str:
"""
Retrieve station id
:param pool: database connection pool
:param latitude:
:param longitude:
:param station_type: StationEnum: which defines the station type
such as 'CUrW', 'WRF'
:return: str: station id, if station... | 76,503 |
def lambda_handler(event, context):
"""Lambda function""" | 76,504 |
def get_bgp_summary(
device, address_family=None, vrf=None, rd=None, all_summary=False
):
""" Get neighbors from show bgp summary command
Args:
device ('obj'): Device object
address_family ('str'): address family
vrf ('str'): vrf name
all_summary ('bool')... | 76,505 |
def give_stats(list_of_scores, list_of_dates, selected_date, over_all):
"""returning the stats of a list of scores"""
if not over_all:
total = 0
ctr = 0
best = 9999
worst = 0
for score in list_of_scores:
if score[0].text == list_of_dates[selected_date].text:
... | 76,506 |
def initialize(
backends=(
"libturbojpeg.so.0", # for Ubuntu
"turbojpeg.dll", # for Windows
"/opt/libjpeg-turbo/lib64/libturbojpeg.0.dylib", # for Mac OS X
)):
"""Loads the shared library if it was not loaded yet.
Parameters:
backends: tuple of shared library ... | 76,507 |
def get_swt(
sig: Union[pd.DataFrame, pd.Series],
wavelet: Optional[str] = None,
depth: Optional[int] = None,
timing_mode: Optional[str] = None,
output_mode: Optional[str] = None,
) -> Union[pd.DataFrame, Tuple[pd.DataFrame, pd.DataFrame]]:
"""
Get stationary wt details and smooths for all a... | 76,508 |
def get_structure_AlN():
"""Set up AlN primitive cell
Al N
1.0
3.1100000000000000 0.0000000000000000 0.0000000000000000
-1.5550000000000000 2.6933390057696038 0.0000000000000000
0.0000000000000000 0.0000000000000000 4.9800000000000000
Al N
2 2
... | 76,509 |
def _tail(filename, starting_lines=10):
"""
A generator for reading new lines off of the end of a file. To start with,
the last `starting_lines` lines will be read from the end.
"""
f = open(filename)
current_size = os.stat(filename).st_size
_seek_to_n_lines_from_end(f, starting_lines)
... | 76,510 |
def transpose(transform, df, dicts):
"""Transposes the given dataframe"""
df = df.reset_index().set_index('index').T.reset_index()
df.columns = df.iloc[0]
return (df[1:], dicts) | 76,511 |
def wizard_xy_df(run, channel_i=None, result_block="sigproc_v1", **kwargs):
"""
Wizard to explore sigprocv2 data as a function of the stage
Audience:
Trained technicians.
Goal:
Allow user to see:
Any anomalies that are occuring as a result of the stage position
"""
... | 76,512 |
def autostart():
"""call autostart scripts"""
home = os.path.expanduser('~/.config/qtile/autostart.sh')
subprocess.call([home]) | 76,513 |
def test_2_8_type_check():
"""
Tests type check validation failure with traceback alteration.
"""
with pytest.raises(Exception) as excinfo:
msg_override = "Incorrect (<Sample Key>) YAML value."
type_check(value=1, required_type=str, tb_remove_name="test_2_8_type_check", msg_override=msg_... | 76,514 |
def getrecursionlimit(): # real signature unknown; restored from __doc__
"""
getrecursionlimit()
Return the current value of the recursion limit, the maximum depth
of the Python interpreter stack. This limit prevents infinite
recursion from causing an overflow of the C stack and crashing Pytho... | 76,515 |
def format_label_value(*values):
"""
Construct a label value.
If multiple value components are provided, they are joined by underscores.
"""
return '_'.join(values) | 76,516 |
def get_ticker_from_user():
"""
This function prompts a user for an input, and returns it as the ticker
:return:
"""
logging.info('Prompting user to enter a ticker symbol')
print('Note: Data up to 1 month from today will be fetched from Yahoo Finance')
return raw_input('Enter a Symbol Ticker... | 76,517 |
def get_failed_info(res):
"""获取失败用例信息"""
intf_summary_list, full_summary_list = res
failed_intf_dic = {}
for system_dic in intf_summary_list:
if system_dic['failCaseNum'] == 0:
continue
for intf_dic in system_dic['children']:
if intf_dic['failCaseNum'] == 0:
... | 76,518 |
def delete(targets, branch_name):
"""
delete command: delete target associated with <branch_name> local branch
Returns the updated targets dict
"""
if branch_name not in targets:
logging.error('No such deploy target: {0}'.format(branch_name))
return targets
print 'You are about t... | 76,519 |
def _singularity_prefix(
singularity_cmd=DEFAULT_SINGULARITY_COMMAND,
sudo=DEFAULT_SUDO,
sudo_cmd=DEFAULT_SUDO_COMMAND,
**kwds
):
"""Prefix to issue a singularity command."""
command_parts = []
if sudo:
command_parts.append(sudo_cmd)
command_parts.append(singularity_cmd)
retu... | 76,520 |
def build_in_mem_cube(gene_ids, cube_index, other_attrs, cube_sum, cube_nnz):
"""
Build the cube in memory, calculating the gene expression value for each combination of attributes
"""
logger.info("Building in-mem cube")
# Count total values so we can allocate buffers once
total_vals = 0
fo... | 76,521 |
def set_country(request, response, country_code):
"""Set region instance."""
info = get_cookie(request)
if country_code and Country.objects.filter(country=country_code):
info["country_code"] = country_code
set_cookie(request, response, info)
return True
else:
return Fals... | 76,522 |
def filter_from_strings(filter_strings: Union[str, Sequence[str]]) -> StringFilter:
"""Create a string filter from a sequence of input strings.
Each string in the sequence can have the following format:
- `ALL`: Accept all strings.
- `NONE`: Accept no strings.
- `<regex>` or `+<regex>`: Include str... | 76,523 |
def get_data_train_in_candidates():
""" Return artificial datasets when train_in_candidates = True """
sent_idx_to_idx = {}
# Manually set alias map
alias2wpids = {
'alias1': [["Q1", 10], ["Q4", 6]],
'multi word alias2': [["Q2", 5], ["Q1", 3], ["Q4", 2]],
'alias3': [["Q1", 30]]... | 76,524 |
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
http://docs.python.org/3.4/library/itertools.html#itertools-recipes
"""
return next(filter(pred, iterable), default) | 76,525 |
def _fHN(phi, const, lamb, omega, alpha, beta, gamma, S, K, t, r, real=True):
"""
real=True to return fstarHN, real=False to return fHN
"""
# Internal Function:
# Model Parameters:
gamma = gamma + lamb + 1 / 2
lamb = -1 / 2
sigma2 = (omega + alpha) / (1 - beta - alpha * gamma ** 2)
... | 76,526 |
def test_11(pc):
"""add_transceiver with valid sendEncodings should succeed"""
encodings = [
webrtc.RtpEncodingParameters(
active=False, max_bitrate=1337, max_framerate=30, rid="foo", scale_resolution_down_by=2.0
)
]
init = webrtc.RtpTransceiverInit(send_encodings=encodings)
... | 76,527 |
def build_season_div(num, nomen, season):
""" Build the string for the HTML div representing an entire season """
txt = SEASON_START % {'season': str(num), 'name': nomen}
for episode_num in sorted(season.keys()):
txt += build_episode_row(season[episode_num])
txt += SEASON_END
return txt | 76,528 |
def create_batch_groups(test_groups, batch_size):
"""Return batch groups list of test_groups."""
batch_groups = []
for test_group_name in test_groups:
test_group = test_groups[test_group_name]
while test_group:
batch_groups.append(test_group[:batch_size])
test_group =... | 76,529 |
def _random_menu(update, context): # pylint: disable=unused-argument
"""Present the user the comic options"""
comics = database_query("SELECT name FROM sources")
buttons = [InlineKeyboardButton(f"{name}", callback_data=name) \
for name in itertools.chain.from_iterable(comics)]
buttons_grouped =... | 76,530 |
def forwards(apps, schema_editor):
"""
Change all Play objects into Work objects, and their associated
data into WorkRole and WorkSelection models, then delete the Play.
"""
Play = apps.get_model("spectator_events", "Play")
Work = apps.get_model("spectator_events", "Work")
WorkRole = apps.ge... | 76,531 |
def debug_off():
"""Turn off logging of the requests module."""
http.client.HTTPConnection.debuglevel = 0
LOGGER.setLevel(logging.WARNING).setPropagate(False) | 76,532 |
def process_single(path, save=True):
"""
Process single image segment
"""
# Parse file name
name = parse_name(path)
if save: print(f"{name.full}:")
# Get file fields
header, data = load_hrit(path)
# Get image properties from HRIT header
h, v, bpp = get_image_properties(hea... | 76,533 |
def pr_hr_series():
"""Return hourly time series."""
def _pr_hr_series(values, start="1/1/2000"):
coords = pd.date_range(start, periods=len(values), freq=pd.DateOffset(hours=1))
return xr.DataArray(
values,
coords=[coords],
dims="time",
name="pr",... | 76,534 |
def calculate_derivative(contour_points, target_index):
""" Calculates derivative.
Calculates the derivative of the current point(contour_points[target_index])
and returned it.
Args:
contour_points:: [RPoint, RPoint, ...]
RContour's points(RPoint objects) to be derivative.
... | 76,535 |
def test_started_after_assigned_and_scheduled():
"""
Started occurs after both assigned and scheduled.
"""
state = {
TaskEventType.CREATED,
TaskEventType.ASSIGNED,
TaskEventType.SCHEDULED,
}
# already created
assert_that(TaskEventType.CREATED.may_transition(state), ... | 76,536 |
def _get_timeout(value):
"""
Turn an input str or int into a float timeout value.
:param value: the input str or int
:type value: str or int
:raises ValueError:
:returns: float
"""
maximum_dbus_timeout_ms = 1073741823
# Ensure the input str is not a float
if isinstance(value, ... | 76,537 |
def addScriptTestsTo(TestClassFactory, tests):
"""Add all the tests to the test class"""
TestClass = TestClassFactory()
for idx in range(len(tests)):
setattr(TestClass, "test%d" % idx, getScriptTestMethod(tests[idx]))
return TestClass | 76,538 |
def _latest_snapshot_path(experiment_name):
"""Return the latest pkl file"""
return osp.join(DATA_DIR, "%s.latest" % (experiment_name)) | 76,539 |
def lambda_handler(evt, ctx):
"""AWS Lambda entrypoint"""
try:
return awsgi.response(app, evt, ctx)
except Exception as err:
print(f'{err}')
return {
'statusCode': 500,
'body': json.dumps({
'message': 'internal server error',
})
} | 76,540 |
def get_next_pid(custom_xml):
"""Get highest pid from XML file."""
maxPid = 0
e = xml.fromstring(custom_xml)
for prop in e:
if 'pid' in prop.keys():
thisPid = int(prop.get('pid'))
if maxPid < thisPid:
maxPid = thisPid
return str(maxPid + 1) | 76,541 |
def pad_input_ids_msmarco(input_ids, max_length,
pad_on_left=False,
pad_token=0):
"""An original padding function that is used only for MS MARCO data."""
padding_length = max_length - len(input_ids)
padding_id = [pad_token] * padding_length
if padding... | 76,542 |
def batch_iter(data, batch_size, shuffle):
"""
each data item is a tuple of lables and text
"""
n_batches = int(np.ceil(len(data) / batch_size))
indices = list(range(len(data)))
if shuffle: np.random.shuffle(indices)
for i in range(n_batches):
batch_indices = indices[i * batch_size... | 76,543 |
def get_child_context(xml_node: XmlNode, parent_node: Node,
_: RenderingContext) -> RenderingContext:
"""Return"""
return RenderingContext({
'parent_node': parent_node,
'node_globals': InheritedDict(parent_node.node_globals),
'xml_node': xml_node
}) | 76,544 |
def generate_map(lat, lon):
"""
Generate a map object for a given set of latitude and longtitude
"""
distances = _distance_from_coordinates(lat, lon)
# Sort distances in ascending order
sorted_distances = sorted(distances)
split_distances = sorted_distances[:2 * app.config["NUM_OF_HOTSPOTS"]... | 76,545 |
def test_check_007():
""" Font designer field in METADATA.pb must not be 'unknown'. """
from fontbakery.specifications.googlefonts import (com_google_fonts_check_007 as check,
family_metadata)
good = family_metadata("data/test/merriweather/")
print('Test PASS... | 76,546 |
def error_message(page_user) -> None:
"""I should see the error message."""
p_action = UpdateUserAction(_page=page_user)
assert p_action.has_failed() is True | 76,547 |
def build_grid_ds_tf(sorted_keys, num_cells, batch_size, name=None):
""" Method to build a fast access data structure for point clouds.
Creates a 2D regular grid in the first two dimension, saving the first and
last index belonging to that cell array.
Args:
sorted_keys: An `int` `Tensor` of shape `[N]`, t... | 76,548 |
def check_class(module_name, class_name, packages=None, pip_args=None):
"""
Checks whether a class is present in the specified module and (tries to) install if packages have been provided.
:param module_name: the module to check
:type module_name: str
:param class_name: the name of the class to che... | 76,549 |
def create_group(opp, name):
"""Create a new person group.
This is a legacy helper method. Do not use it for new tests.
"""
data = {ATTR_NAME: name}
opp.services.call(DOMAIN, SERVICE_CREATE_GROUP, data) | 76,550 |
def getsyncat(word):
"""Returns a list of all syntactic categories of the word as strings or an empty list if no results."""
syncats = ', '.join(list(SYNCAT_ORDER.values()))
tup = (word.upper(),)
c.execute('''SELECT {0} FROM syncat WHERE word=?'''.format(syncats), tup)
result = c.fetchone()
re... | 76,551 |
def pin_to_core(worker):
"""
Worker is a handle to a remote Ray actor with a `run_fn` method.
"""
resource_ids = ray.get(worker.run_fn.remote((lambda: ray.get_resource_ids())))
cpu_idx = resource_ids["CPU"][0][0]
ray.get(worker.run_fn.remote((lambda: psutil.Process().cpu_affinity([cpu_idx])))) | 76,552 |
def prompt_for_instances(ecs_instances, asg_contents, scale_down=False, sort_by="launch_time"):
"""
sorts the instances into an order that tries not to cause an AZ imbalance
when removing instances. Also, prompts the user if there are issues.
@param ecs_instances: list of ECSInstance() objects
@para... | 76,553 |
def classifier_extra_metrics(features, labels, predictions):
"""Returns extra metrics to use with classifier."""
if 'logistic' in predictions:
return {
'my_mean_prediction':
tf.compat.v1.metrics.mean(predictions['logistic']),
'my_mean_age':
tf.compat.v1.metrics.mean(featu... | 76,554 |
def getAnswer(x,input_string):
"""Iegūst mainīgajam x vērtību 1 vai 2, parādot tekstu input_string.
Ja ievadīta nepareiza vērtība, tad tiek paradīta kļūdas ziņa."""
while True:
try:
x = int(input(input_string))
if x < 1:
raise ValueError
elif x > 2:
r... | 76,555 |
def test_instantiation():
"""test the instantiation of a escpos-printer class and basic printing"""
instance = printer.Dummy()
instance.text('This is a test\n') | 76,556 |
def get_model_version_uri(project_id: int, model_id: Text, version: Text) -> Text:
"""Get model version URI.
Args:
project_id {int}: project id
model_id {Text}: model id (name)
version {Text}: model version
Returns:
Text: path to model package for model version
"""
p... | 76,557 |
def _depc_factory(name, cache_dir):
"""DependencyCache factory for the examples
Args:
name (str): name of the cache (e.g. 'annot')
cache_dir (str): name of the cache directory
"""
cache_dpath = HERE / cache_dir
controller = DummyController(cache_dpath)
depc = DependencyCache(
... | 76,558 |
def nx_to_pandas(g):
"""
Convert directed multigraph stored as NetworkX MultiDiGraph into Pandas DataFrame.
Parameters
----------
g : networkx.MultiDiGraph
Directed multigraph to convert.
Returns
-------
df_node : pandas.DataFrame
Node attributes. The NetworkX identifie... | 76,559 |
def get_case_properties(patient, importer):
"""
Returns case name and dictionary of case properties to update
Raises ConfigurationError if a value cannot be deserialized using
the data types given in a column mapping.
"""
name_columns = importer.name_columns.split(' ')
case_name = ' '.join(... | 76,560 |
def review_log(request, type, ctype_id, obj_id):
"""
Display list of record changes and allow user to select status (approved/not approved)
"""
current_user = request.user
log_list = LogEntry.objects.filter(content_type_id=ctype_id, object_id=obj_id)
if type == 'user':
# exclude chang... | 76,561 |
def left2right_decode(
symbols_to_logits_fn,
start_symbols,
context_BxU_dict,
batch_size,
max_decode_len,
vocab_size,
top_p,
temperature,
beam_size = 1,
beam_start = 5,
beam_alpha = 0.6,
beam_min = 0,
beam_max = -1,
eos_id = 1,
):
"""left to right decode.
N... | 76,562 |
def test_empty_graph(graph_empty):
""" this test check to see if empty graph contains a value.
"""
assert graph_empty.has_vert('foo') is False | 76,563 |
def encode_key(
key: str, value: Optional[Union[int, float, str]] = None, value_type: str = "str"
) -> bytes:
"""Encode given header key to a bytes string.
Parameters
----------
key : str
header key
value : Optional[Union[int, float, str]], optional
value of the header key, by d... | 76,564 |
def loads(*args, **kwargs):
""" calls json.loads """
return json.loads(*args, **kwargs) | 76,565 |
def windows_create_static_package(input_hat_binary_path, output_hat_path, hat_file, quiet=True):
"""Creates a Windows static .lib HAT package from a static .obj HAT package"""
# Confirm that this is a static hat library
_, extension = os.path.splitext(input_hat_binary_path)
if extension != ".obj":
... | 76,566 |
def hashIter(bytesiter, hasher, ashexstr=True):
"""Will hash the blockIter generator and return digest"""
for block in bytesiter:
hasher.update(block)
return hasher.hexdigest() if ashexstr else hasher.digest() | 76,567 |
def parse(code, delimiter=' '):
"""Return the result of the RPN calculation of the `code` string or list.
Supported operatorations are
* +, -, *, mult, /, div, //, idiv, pow, %, mod
* sin, cos, tan, asin, acos, atan, sqrt, sqr, abs, exp
Args:
code (str|list):
string of ... | 76,568 |
def get_session(autocommit=True, expire_on_commit=False, use_slave=False):
"""Helper method to grab session."""
facade = _create_facade_lazily()
return facade.get_session(autocommit=autocommit,
expire_on_commit=expire_on_commit,
use_slave=use_slave... | 76,569 |
def test_basicdataset_export_round_trip(public_client):
"""
Test basic dataset round tripping to file.
"""
with temp_directory():
result = BasicCollectionResult.from_server(
client=public_client,
dataset_name="OpenFF Gen 2 Opt Set 1 Roche",
spec_name="default... | 76,570 |
def test_141_parseWind_nonstd():
"""Check parsing of nonstandard wind groups."""
def report(wind_group):
"""(Macro) Return Metar object from parsing the given wind group."""
return Metar.Metar(sta_time + wind_group)
assert report("OOOOOKT").wind_speed.value() == 0
assert report("OOOOOK... | 76,571 |
def query_aisc_shapes(shape=None, metric=False, version=None):
"""
Queries the AISC steel shape database and returns a list of the shape
names in the specified shape category.
Parameters
----------
shape : str
The shape for which names will be returned. If None, all shape names
... | 76,572 |
def upload_avatar():
"""保存图片"""
# 提取参数
req_data = request.files.get("image")
# 校验参数
if not req_data:
return jsonify(errno=RET.PARAMERR, errmsg="请选择图片文件")
# 保存图片
file_data = req_data.read()
try:
filename = upload_image(file_data)
except Exception as e:
current... | 76,573 |
def get_roster_alltime(team_id, start_year=START_YEAR, end_year=END_YEAR):
"""Return the roster file of team with matching id."""
try:
return urlopen(ROSTER_ALLTIME_URL.format(team_id, start_year, end_year))
except HTTPError:
raise ValueError('Could not find a roster for a team with that id.... | 76,574 |
def test_check_datetime():
"""Test if check_datetime throws an exception if an improperly formatted datetime is found."""
a = {
'start': '2016-12-30T11:30:00Z',
}
check_datetime('upsert_event', a, ('start',))
a = {
'start': '2016-12-30T11:30:00+4506',
}
with pytest.raises(PyC... | 76,575 |
def induced_subgraph(G, nbunch):
"""Returns a independent deep copy subgraph induced on nbunch.
The induced subgraph of a graph on a set of nodes N is the
graph with nodes N and edges from G which have both ends in N.
Parameters
----------
G : NetworkX Graph
nbunch : node, container of nod... | 76,576 |
def get_calib_images(calib_img_paths, calib_img_names, resimgs=False):
"""Reads and returns images used for calibration."""
calibImages = []
calibImgNames = []
for calib_img_path, calib_img_name in zip(calib_img_paths, calib_img_names):
calibImage = cv2.imread(calib_img_path)
if ca... | 76,577 |
def test(testpath, import_models=True, verbose=False):
"""
Run doctests in web2py environment. testpath is formatted like:
a tests all controllers in application a
a/c tests controller c in application a
a/c/f test function f in controller c, application a
Where a, c and f are applica... | 76,578 |
def test_RepartitionedHybridTopologyFactory_energies():
"""
Test whether the difference in the nonalchemical zero and alchemical zero states is the forward valence energy. Also test for the one states.
"""
from perses.tests.test_topology_proposal import generate_atp
from openmmforcefields.generato... | 76,579 |
def make_image(imagePath, detections):
"""
returns "image": a numpy array representing an image, compatible with scikit-image
"""
image = io.imread(imagePath)
logger.info("*** "+str(len(detections))+" Results, color coded by confidence ***")
imcaption = []
for detection in detections:
... | 76,580 |
def html_chemname_format(name):
"""
Format a chemical formula to display subscripts and superscripts in HTML
(e.g., Plotly plots)
Example, "CH3COO-" becomes "CH<sub>3</sub>COO<sup>-</sup>"
Parameters
----------
name : str
A chemical formula.
Returns
-------
... | 76,581 |
def from_shape_and_word(shape, word):
"""
Returns the ribbon corresponding to the given ribbon shape and
word.
EXAMPLES::
sage: import sage.combinat.ribbon as ribbon
sage: ribbon.from_shape_and_word([2,3],[1,2,3,4,5])
[[1, 2], [3, 4, 5]]
"""
pos = 0
r = []
for l... | 76,582 |
def dcm_to_hvdict(
unique_id,
slice_paths,
patient_name='',
mri_type = '',
segmentation_info=None,
seg_label_info=None,
visualization_parameters_override=None
):
"""
Given a list of dcm file names, creates a dehydrated version of an hv object as a dict.
Slices with blank segmenta... | 76,583 |
def normalize(X, Y=None):
"""
Normalise X and Y according to the mean and standard deviation of the X values only.
"""
# # It would be possible to normalize with last rather than mean, such as:
# lasts = np.expand_dims(X[:, -1, :], axis=1)
# assert (lasts[:, :] == X[:, -1, :]).all(), "{}, {}, {}... | 76,584 |
def import_maplight_from_json_view(request):
"""
Take data from Test XML file and store in the local Voting Info Project database
"""
# If person isn't signed in, we don't want to let them visit this page yet
if not request.user.is_authenticated():
return redirect('/admin')
import_mapli... | 76,585 |
def create_app():
"""
Function Construct the core application for the flask
"""
app = Flask(__name__)
CORS(app)
app.config.from_object('config.Config')
"""
Initializing the sqlalchemy db with the app
"""
db.init_app(app)
"""
Creating the app context
""... | 76,586 |
def move_polygons(polygons, from_grid, to_grid=None):
"""
A function that moves polygons to the origin bounding box (0, 250, 250, 250)
"""
if(to_grid):
x_displacement = (from_grid // 10) - (to_grid // 10)
y_displacement = (from_grid % 10) - (to_grid % 10)
else:
x_displacemen... | 76,587 |
def get_output_template(config: Dict, software: Union[PlacementSoftware, AlignmentSoftware],
extension: str, **kwargs) -> str:
"""
Creates a name template of .{extension} output files produced by specific software.
Used to produce .tree, .align etc. file name templates. Stored in the... | 76,588 |
def create_tf_strings_model():
"""
A model that concatenates two input strings
"""
g = tf.Graph()
with g.as_default():
with tf.name_scope("some_namespace"):
x = tf.placeholder(tf.string, name="in_x")
y = tf.placeholder(tf.string, name="in_y")
# Assigned t... | 76,589 |
def get_numeric_project_id(gcloud, project_id):
"""Get the numeric project ID."""
project_info = json.loads(
gcloud.run('projects', 'describe', project_id, '--format=json'))
return project_info['projectNumber'] | 76,590 |
def vstran(d1: np.ndarray, d2: np.ndarray) -> tuple:
"""calculate variance stabilized weights
Calculation of variance stabilized weights which describes in paper
in section "Variance stabilized weights"
Parameters
----------
d1 : np.ndarray
1d ndarray of diagonal elements
d2 : np.n... | 76,591 |
def send_real_person_status(status=None, channel=None):
"""Send the status of the person to the websocket.
:param status: the current status of the RealPerson, will fetch the status automatically
:param channel: an outgoing reply channel, defaults to the entire group
"""
if channel is None:
... | 76,592 |
def count_local_minmax(A):
"""
Count local max and min
@author Akafael
"""
n = len(A)
# Trivial Solution
if n <= 1:
return 1
# Calculate the diff
B = []
count = 0
isRising = False
isFalling = False
for i in range(1, n - 1):
B.append(A[i + 1] - A[i]... | 76,593 |
def ensure_directory(path):
"""Ensure that the parent directory of `path` exists"""
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname) | 76,594 |
def fitness(individual,target):
"""
individual : the individual to evaluate (a list)
target : the target sum the individuals are aiming for
"""
sum = reduce(add,individual,0)
return abs(target-sum) | 76,595 |
def dynamic_gru(input,
size,
param_attr=None,
bias_attr=None,
is_reverse=False,
gate_activation='sigmoid',
candidate_activation='tanh',
h_0=None,
origin_mode=False):
"""
:api_attr: Static... | 76,596 |
def purpleStraightLine(l):
"""Draws a purple straight line. Args: Length of line."""
pencolor("#cc00ff")
for pixels in range(l):
forward(1) | 76,597 |
def create_schema(name: str) -> str:
"""Function for generating create schema statements
:param str name: The name of the schema
:return: Create statement
:rtype: str
"""
statement = f"CREATE SCHEMA {name}"
return statement | 76,598 |
def sec_validation_correctness():
"""
Determine the actual status of each process to compare with simulation results and understand the accuracy of
multiple blockchain validations
"""
# Each validator has 85% accuracy of correct secondary validation
# Array that tabulates validation status of ea... | 76,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.