content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _recover_forcei_rod(xb, dof_map, elem, prop):
"""get the static rod force"""
nid1, nid2 = elem.nodes
# axial
i11 = dof_map[(nid1, 1)]
i12 = dof_map[(nid1, 2)]
i13 = dof_map[(nid1, 3)]
i21 = dof_map[(nid2, 1)]
i22 = dof_map[(nid2, 2)]
i23 = dof_map[(nid2, 3)]
# torsion
... | b0365d5d65963c7d3d8313dcf4cee964d1a774d7 | 38,800 |
import os
def assign_segid_to_crashes(max_dist, usrap_segment_layer, input_crash_fc, out_gdb):
"""
This function first creates the Field mapping and then performs a
spatial join between Crash Feature Class and Segment Feature Class
"""
try:
add_formatted_message("Assigning {0} to crashes..... | 7d9fdfe9e3ceec98adcdead99d683920fadaf34e | 38,801 |
def create():
"""
Create a new DeviceModel.
Request:
{
'dm_name': 'Foo',
'df_list': [
{
'df_id': 12, // required
'df_parameter': [{}, ...] // required
'tags': [], // optional
},
... | 8de6c7a749bd2b46f947ce6fa02d0f3d33ecf381 | 38,802 |
def resize_image(img, min_side=800, max_side=1333):
"""
Resize an image such that the size is constrained to min_side and max_side.
Args
min_side: The image's min side will be equal to min_side after resizing.
max_side: If after resizing the image's max side is above max_side, resize until ... | 97e0355af5906132a8a84dbd6beb45e0b33fdaf0 | 38,803 |
def increase_by_1_list_comp(dummy_list):
"""
Increase the value by 1 using list comprehension
Return
------
A new list containing the new values
Parameters
----------
dummy_list: A list containing integers
"""
return [x+1 for x in dummy_list] | 9ad24064a7cf808cba86523e5b84fe675c6c128b | 38,804 |
def registered_root():
"""Return currently registered root"""
return _registered_root["_"] | d11d1e23faa3a63f84d8820b61b6ef8936f937fb | 38,805 |
def _is_conn_refused_exception(exceptionobj):
"""
<Purpose>
Determines if a given error number indicates that the remote
host has actively refused the connection. E.g.
ECONNREFUSED
<Arguments>
An exception object from a network call.
<Returns>
True if the error indicates the connection was... | ef833ce236a5fb697ec2ac35aec19240bd18757c | 38,806 |
import io
def _load_Xy(zipfile, csvfile, sep=',', header=None, engine='python',
na_values={'?'}, **kwargs):
"""Load a zippend csv file with targets in the last column and features in
the rest."""
with ZipFile(zipfile) as z:
with z.open(csvfile) as c:
s = io.StringIO(c.r... | 432f0201b6250bb08d61d0fbf0b0c29f25dda30c | 38,807 |
def pairwise(iterable):
"""
s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b) | e54f8d83c49b77f2219ed4a8f000bac07073e1f0 | 38,808 |
from typing import List
def get_pending_transfer_pairs(
transfers_pair: List[MediationPairState],
) -> List[MediationPairState]:
""" Return the transfer pairs that are not at a final state. """
pending_pairs = [
pair
for pair in transfers_pair
if pair.payee_state not in STATE_TRANS... | 660cf390299e614b1a19115005529b9c26a82ea8 | 38,809 |
def split(text: str, max_message_length: int = 4091) -> list:
""" Разделение текста на части
:param text: Разбиваемый текст
:param max_message_length: Максимальная длина разбитой части текста
"""
if len(text) >= max_message_length:
last_index = max(
map(
lambda s... | e54b7730705ed1a2143d7caa82b0f209081d6edf | 38,810 |
def apply_preconfig_to_existing(
self,
preconfig_id: str,
ne_pk: str,
) -> bool:
"""Apply preconfig to existing approved appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - appliancePreconfig
- POST
-... | 453b61b5eb83ea485e741cca9e2cec75d43bae2f | 38,811 |
def convert_quantiles_to_ci(ci, sm_concat, H, error_ci, coef_spline_smoothing=0):
"""
convert the computed quantiles for the normalized errors
into the quantiles of the errors by scaling back
with additional spline smoothing
"""
weights = np.ones((1,H))
weights_W = 1
q = list(set(ci... | 88404e2f43cf25713bffed54a6cdf024e2499ba0 | 38,812 |
def pythagoras(a, b):
"""Compute pythagoras.
Parameters
----------
a : float
length of one side of the triangle
b : float
length of second side
Returns
-------
c : float
length of the hypothenuse
"""
return np.sqrt(a**2 + b**2) | 5cfa96bb995d7bcd0c5b0193b5ba92e8b00c16b7 | 38,813 |
import itertools
def construct_target_sets_method_4(features, labels, ncl, n_samples, n_dim, final_features, dataset_name=None):
""" Construct the target sets: most confusion between classes. """
class_combinations = np.unique(labels)
normals = None
anomalies = None
# investigate each combinati... | 5f6ffdf70131ae11793836952e0dd1745d828cd6 | 38,814 |
def find_low_point_coords(arr: ArrayLike) -> list[list[int]]:
"""Return the low point locations in the input."""
arr_zeros = np.zeros(arr.shape)
# row[i+1] - row[i] > 0 => [row i+1] > row[i]
diff_down = np.diff(arr, 1, axis=0)
# row[i] - row[i+1] > 0 => row[i] > row[i+1]
diff_up = -1 * diff_d... | 8dc7f326ac0561657f8935a49ed46b3e5423cf09 | 38,815 |
import os
def save_config(config, path):
"""
Write the configuration file to ``path``.
"""
os.umask(0o77)
f = open(path, "w")
try:
return config.write(f)
finally:
f.close() | 8174cc17b97664a6253d906618cf1a45896c08b9 | 38,816 |
import unicodedata
def is_hw(unichr):
"""unichrが半角文字であればTrueを返す。"""
return not unicodedata.east_asian_width(unichr) in ('F', 'W', 'A') | 260d79199c8551b635fb343a72ffeb30e7707958 | 38,817 |
from typing import Optional
def view_experiments(query_id: Optional[int] = None, omic_id: Optional[int] = None):
"""View a list of all analyses, with optional filter by network id."""
experiment_query = manager.session.query(Experiment)
if query_id is not None:
experiment_query = experiment_query... | 9552fb23d31b781c507be71cefb9df4cc62b7d28 | 38,818 |
import itertools
def GenerateLegacyPrefixes(bitness, required_prefixes, optional_prefixes):
"""Produce list of all possible combinations of legacy prefixes.
Legacy prefixes are defined in processor manual:
operand-size override (data16),
address-size override,
segment override,
LOCK,
REP/REPE... | c622b7cb3b9217e7aed54237eaaa3a7e6018a6ba | 38,819 |
def cfg_path():
"""Returns a path of the project config file to read."""
if utils.is_local_dev_server() or utils.is_dev():
return 'realms-dev.cfg'
return 'realms.cfg' | 763351450972d379bc6025acef76ab311d5e17cc | 38,820 |
from datetime import datetime
def default_event_end(hour: int = DEFAULT_EVENT_END_HOUR) -> datetime:
"""Return next default start time."""
return next_x_hour(hour, default_event_start()) | 6aa5dc752d67c8ea61293da8e97981aa66b2633b | 38,821 |
def deletedup(xs):
"""Delete duplicates in a playlist."""
result = []
for x in xs:
if x not in result:
result.append(x)
return result | 0f36899c9ce2710564d5d5938b54edbdd64afd81 | 38,822 |
def _cell_version(cellname):
"""Gets the cell based treadmill root."""
admin_cell = admin.Cell(context.GLOBAL.ldap.conn)
cell = admin_cell.get(cellname)
version = cell.get('version')
if version is None:
raise Exception('Version is not defined for cell: %s')
root = cell.get('root')
... | bc112cbd9522802c4dbfc9985498a2ceed28e942 | 38,823 |
from typing import Any
def prettyStringRepr(s: Any, initialIndentationLevel=0, indentationString=" "):
"""
Creates a pretty string representation (using indentations) from the given object/string representation (as generated, for example, via
ToStringMixin). An indentation level is added for every open... | 0c25810f5bd559a8dda09a2ec07bf6ea18956716 | 38,824 |
def create_flow(blocks, name="AnonymousFlow", mode=MODE_CRITICAL, common={}):
"""Auxiliary function to create test flows on the spot."""
return type(name, (TestFlow,), {'mode': mode,
'common': common,
'blocks': blocks}) | 6957c39c1e00f5072674a2815df29eded827a827 | 38,825 |
import os
def execute_script_get_local_variables(script, folder=None,
filename="_temp_custom_run_script_.py",
check=True):
"""
Executes a script and returns the local variables.
@param script filename or code
@par... | e7cdb1fb120c730dd00b540dd6b28fe583338bbf | 38,826 |
def format_date_time(date_time: wx.DateTime) -> str:
"""Format the given datetime in a string."""
dt: wx.DateTime = date_time
d, mon, y = dt.GetDay(), dt.GetMonth() + 1, dt.GetYear()
h, m = pad_int_str(dt.GetHour()), pad_int_str(dt.GetMinute())
s = pad_int_str(dt.GetSecond())
str_out = f"{wx.Da... | f0cd93e267a6a5b8663a6b003fb542d5abd20059 | 38,827 |
import os
def replace_tail(path: str, search: str, replace: str) -> str:
"""
>>> replace_tail('/dir1/dir2/path.ext', '/dir1', '/dir2')
'dir2/dir2/path.ext'
>>> replace_tail('/dir1/dir2/path.ext', '/dir1/', '/dir2/')
'dir2/dir2/path.ext'
>>> replace_tail('/dir1/dir2/path.ext', '/dir3', '/dir2... | cc9cc5d808a2befa1427543b3a1f3f71d48d4d87 | 38,828 |
def parse_cencus_tract_info(rows):
""" Pass in multiple rows for a census tract to create CensusTractInfo
object
Demographics the folowing are derived from 'Visible Minority' section
East Asian (Chinese + South East Asian + Korea + Japanese + Fillipino)
Hispanic (Latin American)
... | 2bb5c173bfdf538234a438f7c5eaa062af8de174 | 38,829 |
from typing import List
from typing import Tuple
def match_points_to_regions(points: List[Tuple[float, float]], shapes_ds: pd.Series,
keep_outside: bool = True, distance_threshold: float = 5.) -> pd.Series:
"""
Match a set of points to regions by identifying in which region each po... | 8f1e368ed6af9d628cf2a96036355f7b90977db7 | 38,830 |
def GridSizer_GetCols3(sizer):
"""
Wrapper for wxGridSizer.GetColws()
With wx3 wxGridSizer.GetRows() and wxGridSizer.GetCols() "returns zero
if the sizer is automatically adjusting the number of rows depending
on number of its children."
@param sizer: Instance of wxGridSizer or a derived class... | a2b353353e424269126321c3ae64e024a8b14f9b | 38,831 |
def roi_align_nchw_ir(data, rois, num_rois, w_pc, pos_pc, pooled_size, spatial_scale, sample_ratio):
"""Hybrid routing fo ROI align operator in NCHW layout.
Parameters
----------
data : tvm.te.Tensor or numpy NDArray
4-D with shape [batch, channel, height, width]
rois : tvm.te.Tensor or nu... | e3ae01444590119174570a7495e7e90a1c29d04b | 38,832 |
def mux(car_state):
"""Returns car_pose to publish, given car_state."""
if car_state == CarState.START: return None
elif car_state == CarState.AUTO: return g['auto_car_pose']
elif car_state == CarState.MANUAL: return g['manual_car_pose'] | 91086eb497eb03afed0f071a8a977e696207d653 | 38,833 |
import logging
def update_log_level(debug: bool, level: str) -> str:
"""update log level"""
if debug is True:
level_num = logging.DEBUG
else:
level_num = logging.getLevelName(level)
settings.set('LOGLEVEL', logging.getLevelName(level_num))
return settings.LOGLEVEL | 318a06705b76f24fb16aaf8bc9c7c6b0f592224b | 38,834 |
def get_mapping(d):
"""
Reports fields and types of a dictionary recursively
:param object: dictionary to search
:type object:dict
"""
mapp=dict()
for x in d:
if type(d[x])==list:
mapp[x]=str(type(d[x][0]).__name__)
elif type(d[x])==dict:
mapp[x]=get_m... | 87722f1429a93a934af08cb68519576cfc2cd7b0 | 38,835 |
def tf_top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float("Inf"), min_tokens_to_keep=1):
"""
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (batch size, vocabulary size)
top_k (`int`, *optional*, defaul... | dd83ba9c46eb942e6054c459eac50d459e3f8627 | 38,836 |
def eval_fx(fx, stats):
"""Given fx and stats ('min', 'max', 'mean', 'std') return the result"""
_ = BNF().parseString(fx, parseAll=True)
val = evaluate_stack(exprStack[:], stats)
return val | 273fbafd92b45c0d1c77cc8ee9b1f552f083aacb | 38,837 |
def help(event):
"""Returns some documentation for a given command.
Examples:
!help help
"""
def prepare_doc(doc):
return doc.split('\n')[0]
plugin_manager = event.source_bot.plugin_manager
prendex = 'Available commands: '
if len(event.args) < 1:
return prendex +... | dbc2baed887df46e0d101d48a1a338760329679e | 38,838 |
def wordCount(wordListRDD):
"""Creates a pair RDD with word counts from an RDD of words.
Args:
wordListRDD (RDD of str): An RDD consisting of words.
Returns:
RDD of (str, int): An RDD consisting of (word, count) tuples.
"""
return (wordListRDD.map(lambda x: (x,1)).reduceByKey(lambd... | 1bb52a8d702cca68a91b4a172417224a07dea5d4 | 38,839 |
def parse_size(text):
"""Parse a size string to a structured type"""
match = SIZE_RE.match(text)
if not match:
return None
width = int(match.group('width'))
height = int(match.group('height'))
if 'rate' in match.groupdict():
framerate = float(match.group('rate'))
interlaced =... | 217d24b2a44a1ab4affeb0b3efc8794c4bdb7e19 | 38,840 |
def temporarily_as_user(setenv=True):
"""
Set effective user/group ID to the ordinary user (the one invoking the script).
An optional parameter "setenv=False" will skip setting user-related
environmental variables accordingly.
It can be used either as an ordinary function, or as a context manager
in "with" statem... | 4e230dab862b8a3ff9298137335dd3b1312f82e4 | 38,841 |
def encode_author(author):
"""
:param author:
:return:
"""
author = lxml.html.fromstring(author).text
if isinstance(author, str):
return unidecode.unidecode(remove_control_chars_author(to_unicode(author)))
return author | 58f584d19865ede0624ba674b20045b8e9b97097 | 38,842 |
import posixpath
def create_clowder_collection(session, url, collection, dryrun=False):
"""Create a Clowder collection.
Args:
session: http session
url: Clowder URL
collection: Clowder collection name
dryrun: Boolean. If true, no POST requests are made
Returns:
col... | d2645792a9834bdb853ea011bb23e44e3f95ba43 | 38,843 |
from typing import Optional
from typing import List
from typing import Dict
from typing import Callable
from typing import Type
from typing import Any
from typing import Tuple
def pait(
# param check
at_most_one_of_list: Optional[List[List[str]]] = None,
required_by: Optional[Dict[str, List[str]]] = None,... | 4f60318d06a6ebfff5d9d2040841c44dc9b99ebd | 38,844 |
def alpha_clipping(rectangle, line):
"""
Apply alpha-clipping of `line` according to `rectangle`.
Parameters
----------
rectangle : Rectangle
line : Line
Returns
-------
`None` or Line within rectangle
"""
a_min = 0.0
a_max = 1.0
outcode_p1 = rectangle.get_outcode(l... | 2f8f69ea7834aea91eea4f1b7e65eddbefac96a9 | 38,845 |
def create_spark_session():
"""
Create the entry point to programming Spark with the Dataset and DataFrame API.
The entry point into all functionality in Spark is the SparkSession class.
Instead of having a spark context, hive context, SQL context, now all of it is encapsulated in a Spark session.
S... | 533c611065083f8ebe1a87dd91f7ca7f18f1af2b | 38,846 |
import copy
import traceback
def model_gui(model,
sample=None,
data_dt=.01,
plot=plot_fit_diagnostics,
conditions=None,
verify=False):
"""Mess around with model parameters visually.
This allows you to see how the model `model` would be aff... | 221bbfab5a7efa41727f74ca8b57246787b675a5 | 38,847 |
def force_bytes(s, encoding='utf-8', errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first for performance reas... | 2a1f7f17789d472862c77128df90a4af669cade1 | 38,848 |
import random
def single_random_user(ev_room):
"""
Returns a single user name from users in a room
:param ev_room: Room to select users from
:return: A single user tuple
"""
return random.choice(GlobalVars.users_chatting[ev_room]) | aa2d0468091f09095d81ef8adf80b2f6c52f16dc | 38,849 |
def get_bploc_tuples(bp, source_map=None):
""" Returns a list of tuples (file, line) where a breakpoint was resolved. """
if not bp.IsValid():
return []
locs = []
for bploc in bp:
le_tupl = resolve_line_entry(bploc.GetAddress().line_entry, source_map)
if le_tupl[0] and le_tupl[1]... | 3e4e9433f12bcba94b1177d774009ec68058f08c | 38,850 |
def remplace_mot_entre_parentheses(texte: str):
"""
Les mots entre parenthèse représente le petite texte dans Animal Crossing.
Cela n'est pas prononcées.
"""
while '(' in texte and ')' in texte:
debut = texte.index("(")
fin = texte.index(")")
texte = texte[:debut] + "*" * ... | 30b2e86f56be6a4faee2f8c827c58d85ad62eb88 | 38,851 |
def main(token: str) -> int:
"""
Args:
token (str): bot access token
Return:
exit code of main script
NoneZero indicate a failure
"""
client = discord.Client()
@client.event
async def on_error(event, *args, **kwargs):
"""
Safely logout bot on event of... | b8614f88e06158a992384f0cdc83ec0564358197 | 38,852 |
def _threefry(
irb, key_buf, key_offset, counter_buf, counter_offset, out_buf, out_offset, out_shape
):
"""IRBuilder code for running Threefry
Parameters
----------
irb: IRBuilder
IRBuilder that this code will be generated for.
key_buf: BufferVar
Buffer to read the key from.
... | 66a150946bb1b7622321711d50af91babe3599bb | 38,853 |
def ussa_temp(altitude):
""" Compute reference temperature for a given altitude corresponding to the
US Standard Atmosphere.
Parameters
----------
altitude : float
Ambient altitude in kilometers; must lie in the range 0-50 km.
Returns
-------
Temperature at given altitude in K.... | 196902249f4d38bd14e6901c5341c6b7bf98df4f | 38,854 |
def get_scaled_cutout_basic_view(shp, p1, p2, scales):
"""
Like get_scaled_cutout_basic, but returns the view/slice to extract
from an image, instead of the extraction itself
"""
x1, y1 = p1[:2]
x2, y2 = p2[:2]
scale_x, scale_y = scales[:2]
# calculate dimensions of NON-scaled cutout
... | 5286465f2ccfb55f3cc6def7c1530857573861bb | 38,855 |
import numbers
def line_base(y, x, source_dataframe, width, height, description, title,
x_label, y_label, show_plot, color, colorbar_type, legend,
line_width, alpha, style, x_axis_type, y_axis_type, x_range,
y_range, fill_between, grid_visible, session, save_path):
""" On... | f83e35a6adeacfad6814456339ae8e679e11b4c0 | 38,856 |
import requests
from sys import stderr
def xml_download_retry(ena_accession):
"""
pulling xml record from ENA, some of the records take a longer time to connect, this retry set timeout to be 5 mins
:param ena_accession:
:return:
"""
try:
xml = ET.fromstring(requests.get("https://www.eb... | 787bb43565aa0733bbd270740d51c4cf93aee396 | 38,857 |
from typing import List
def check_data_for_invalid(data: List[int], preamble_size: int = 25) -> int:
"""Check the data for a number with an invalid sum.
Args:
data (List[int]): data from the data port
preamble_size (int; optional): the size of the preamble for data;
defaults to 25... | 1387c705e52245b495cf1c83415b35eb3d72fb85 | 38,858 |
def parseWeather(data: list) -> list:
""" take MetOffice weatherdata and return the first four future entries"""
forecast = []
whichday = 0
for day in data:
for entry in day['Rep']:
# The forecast is laggy for the current day, so we need to discard past entries
if ((whichday == 0) & (int(entry['... | 41e37fb4b3608f90417b3cb36ec81c5f6731b021 | 38,859 |
def process_file(filename):
"""
Process FITS file to get desired header info and image statistics
"""
outstr = ""
with fits.open(filename) as hdul:
hdr = hdul[0].header
if hdr['NAXIS'] == 3:
im = np.flipud(hdul[0].data[:, :, 0])
else:
im = hdul[0].data... | b80bc39446a8e0e93736619d82f2884d5bb2e88d | 38,860 |
def knapsack(v, w, n, W):
"""
Function solves 0/1 Knapsack problem
Function to calculate frequency of items to be added
to knapsack to maximise value
such that total weight is less than or equal to W
:param v: set of values of n objects,
:param w: set of weights of n objects,
first eleme... | 07537ab374f006a943a6ab19d90ee4cd580f9abf | 38,861 |
def get_stock_forms_by_case_id(case_ids):
"""Get a dict of form id sets by case id for the given list of case ids
This function loads Couch stock forms (even though they are
technically stored in SQL).
"""
form_ids_by_case_id = defaultdict(set)
for case_id, form_id in (
StockReport.obje... | 3a96fea179de3ce0d2c101e94cf191a378fc4aa9 | 38,862 |
def randint(low=0, high=None, shape=[1], dtype=None, name=None):
"""
:alias_main: paddle.randint
:alias: paddle.randint,paddle.tensor.randint,paddle.tensor.random.randint
This function returns a Tensor filled with random integers from the
"discrete uniform" distribution of the specified data type in the ... | 29763d4ed95401fa060267a3697af7f4986fb127 | 38,863 |
def variable_frequency(DataFrame, variable, sorted=False, ascending=False, limit=None, show_plot=False):
"""
Parameters
----------
DataFrame : pandas.DataFrame
DataFrame
variable : str
Variable to examine the freqeuncy.
sorted : bool, default False
ascending : bool, defa... | 86f622d2b3bccfb5f7966a6f879875441c4d0b24 | 38,864 |
def predict(examples,parameters):
"""
Compute the probability of being y=1 for all the `examples` given `parameters`.
Return a 1D array of probabilities.
"""
z = np.dot(examples,parameters)
return sigmoid(z) | ee122af0fff78959daee25b56dbc8ec7e9c1ce06 | 38,865 |
def less_generators(X):
"""
Reduce the generator matrix of the module defined by ``X``.
This is Algorithm 6.4 in [BC2012]_ and relies on the row syzygies of
the matrix ``X``.
EXAMPLES::
sage: from sage.geometry.hyperplane_arrangement.check_freeness import less_generators
sage: R.<... | b11b6084b9de0c67e101be82f7af858934de6d09 | 38,866 |
import os
def deploy_plain_bgp_config(duthost):
"""
Deploy bgp plain config on the DUT
Args:
duthost: DUT host object
Returns:
Pathname of the bgp plain config on the DUT
"""
bgp_plain_template_src_path = os.path.join(TEMPLATE_DIR, BGP_PLAIN_TEMPLATE)
bgp_plain_template_p... | 748cc3fa9dab8b6f4024324f01fd1c0e854175a1 | 38,867 |
def __normalize_request_parameters(post_body, query):
"""
Return a normalized string representing request parameters. This
includes POST parameters as well as query string parameters.
"oauth_signature" is not included.
:param post_body: The body of an HTTP POST request.
:type post_body: strin... | 2cd7e72530a461629dd5034665c09dd240734313 | 38,868 |
import os
def test_repo_dir(dir, name):
"""
Test an entered GitHub repository directory name.
"""
subdir = os.path.basename(dir)
return subdir != name | b8fdbcb82e53fd1079b611617b3acf534af25fe5 | 38,869 |
def reshape_to_grid(data_flat, coords, shape):
"""Given a flattened array of data with the corresponding Y and X coordinates and the desired grid shape, return the grid of desired shape with the data given. Assumes flattened array has a time dimension as first dimension.
:arg data_flat: 2d array of data. First... | 56072493aad94ee831d9a29a2ae784491c1b77f6 | 38,870 |
import random
def point_mutation(bitstring, mutation_rate):
"""
:param bitstring: '100011...' - 32 bit
:param mutation_rate: 0.08
:return:
"""
child = ""
for bit in bitstring:
if random() < mutation_rate:
child += "0" if bit == "1" else "1"
else:
chi... | ef9710d439ec37a0b250821f06a6499c8530175a | 38,871 |
import matplotlib.pyplot as _plt
from scipy.integrate import solve_ivp
def coupledHarmonicOscillator_nonlinear( N=500,
dt=0.1,
ICs={ 'y1_0': 0,
'x1_0': 1,
'y2_0': 0,
'x2_0': 0},
args={ 'f1': 45,
'f2': 150,
'm': 1,
... | 36921dce55bd8cbe10d55a480a538e9a16ae5cfa | 38,872 |
def filter_missing_value(keypoints_list, method='ignore'):
# TODO: impletemd 'interpolate' method.
"""Filter missing value in pose list.
Args:
keypoints_list: Estimate result returned by 2d estimator. Missing value
will be None.
method: 'ignore' -> drop missing value.
Return:
... | 051f12b3d1d7c97dd59ebacc455050fc7ec27d81 | 38,873 |
import re
def remove_punctuation(line):
"""
去除所有半角全角符号,只留字母、数字、中文
:param line:
:return:
"""
rule = re.compile(u"[^a-zA-Z0-9\u4e00-\u9fa5]")
line = rule.sub('', line)
return line | d63f355c5d48ec31db0412dd7b12474bf9d6dd6b | 38,874 |
import time
def CurrentTimeInSec():
"""Returns current time in fractional seconds."""
return time.time() | 3dc3bda89622ffdf0067d489c10f539cb6274e21 | 38,875 |
def pair(global_lut: dict, src: str, trace: Trace) -> str:
"""parsers a key value pair, returns the key"""
kv = src.split(Token.VALUE_SEPARATOR)
if len(kv) > 2:
# warn about assigning a value twice
# key = x = y
# in this case only the last value will be used
warn(Warn.MU... | e9012e524708147960ebd2327d9c10a98f3f110e | 38,876 |
def env_decode(value):
"""
Decodes an environment variable name or value that was returned by
get_env(for_subprocess=True)
:param value:
On Python 3, a unicode string, on Python 2, a byte string
:return:
A unicode string
"""
if not py2:
if not isinstance(value, str... | a317a4746cdae87a53a1d0a1b307b9fa29d6214a | 38,877 |
def disconnect():
"""This handler serves as a global disconnect procedure that will log a
user out no matter which provider they logged in with.
"""
if 'provider' in login_session:
if login_session['provider'] == 'google':
gdisconnect()
del login_session['gplus_id']
... | 0d7eaad5cc647c954655fe3fdb80556478587c8e | 38,878 |
import argparse
import sys
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use',
default=0, type=int)
parser.add_argument('--def', dest=... | 8e10383f9c64562265dd3640c19f23d265c66a68 | 38,879 |
import urllib
def DebugViewUrl(breakpoint):
"""Returns a URL to view a breakpoint in the browser.
Given a breakpoint, this transform will return a URL which will open the
snapshot's location in a debug view pointing at the snapshot.
Args:
breakpoint: A breakpoint object with added information on project... | 76b4d9f3483a89207dd7b3eb85e03751d2ead810 | 38,880 |
def hyperheader2dic(head):
"""
Convert a hypercomplex block header into a python dictionary.
"""
dic = dict()
dic["s_spare1"] = head[0]
dic["status"] = head[1]
dic["s_spare2"] = head[2]
dic["s_spare3"] = head[3]
dic["l_spare1"] = head[4]
dic["lpval1"] = head[5]
dic["rpva... | 3fd2611b52491e16a8402ba7a2755b723e13601d | 38,881 |
def convert_order_to_href(keystone_id, order_id):
"""Convert the tenant/order IDs to a HATEOS-style href."""
if order_id:
resource = 'orders/' + order_id
else:
resource = 'orders/????'
return utils.hostname_for_refs(keystone_id=keystone_id, resource=resource) | fa87d2e992df5be3e94ed60bf506da4ae282daa3 | 38,882 |
def pretty_struct(ctx, title, args, kwargs, sep=' :: '):
"""Pretty print a struct."""
kwargs = {f'{k}<<{sep}>>': v
for k, v in kwargs.items()}
return pp.pretty_call_alt(ctx, str(title), args, kwargs) | bf0e12c9eca187f3959d77b244c1c6625ee382b8 | 38,883 |
def Gerrity_score(contingency):
"""
Returns Gerrity equitable score given a contingency table
Author: Dougie Squire
Date: 12/05/2018
Parameters
----------
contingency : xarray DataArray
A contingency table of the form output from doppyo.skill.co... | 288aecd1581cbd71d167dbaab9c1b281146d8aba | 38,884 |
def parse_args():
"""
Parse and establish the arguments we take in on the CLI
"""
parser = ArgumentParser(description="Mirror a Red Hat mirror.")
# Programmatic Things
parser.add_argument("-b", "--base", dest="base",
help="The remote base URL of the OS you want to "
... | f3f1f12e2496533de7cfaa87d59c9a598f8d879a | 38,885 |
from datetime import datetime
import pytz
def get_course_assignments(course_key, user, include_access=False): # lint-amnesty, pylint: disable=too-many-statements
"""
Returns a list of assignment (at the subsection/sequential level) due dates for the given course.
Each returned object is a namedtuple wit... | 2efa2fa18921d4391f8aa2529c7801dba2df745d | 38,886 |
def ltl_tp(L, out = None):
"""
L.T @ L with a lower triangular matrix.
Parameters
----------
L : (np, ...) ndarray
Lower triangular matrix in packed storage.
out : (np, ...) ndarray
Output buffer. If None, this will be created.
If out = L, then in-place multiplication i... | 9294e316f0285906bcdf24af976fdf4e5f46ba90 | 38,887 |
def return_dictionary_list(lst_of_tuples):
""" Returns a dictionary of lists if you send in a list of Tuples"""
orDict = defaultdict(list)
# iterating over list of tuples
for key, val in lst_of_tuples:
orDict[key].append(val)
return orDict | c495aa209def87f947c7347d84941abecc6c39b2 | 38,888 |
from typing import Any
def force_bytes(
s: Any,
encoding: str = 'utf-8',
strings_only: bool = False,
errors: str = 'strict',
) -> bytes:
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is... | e990853108696879e360ca42bb108cc71d6f4f2d | 38,889 |
def delete_content():
"""
DESC : Fonction permettant de supprimer un contenu
"""
try:
compte_id, access = get_jwt_identity().split("+")
content_id = request.get_json().get("content_id")
if compte_id:
try:
CURSOR.execute("""
DEL... | 7c70d380f87e657c6ada02669e50b9587819717a | 38,890 |
def collect_nested(expr):
"""
Collect numeric coefficients, trascendental functions, and symbolic powers,
across all levels of the expression tree.
The collection gives precedence to (in order of importance):
1) Trascendental functions,
2) Symbolic powers,
3) Numeric coefficien... | 534cff29bbcc0dc6faa83a1fe9929ec176bebde1 | 38,891 |
def euler2(f2p, b, t, h, p):
"""
tuple b = boundary condition (x0, y0, y'0)
float h = step
int t = number of steps
lambda f2p = dy/dx
int p = significant digits after x values
"""
x = b[0]
y = b[1]
yp = b[2]
y2p = f2p(x, y, yp)
ret = [(x, y)] #list of tuples to be returned with x and ... | 67e390f0c21ba87d8aeec97920403c2d62678dc9 | 38,892 |
def Conv2D(in_channels, out_channels, kernel_size, dropout=0, weight_norm=False, **kwargs):
"""Weight-normalized Conv2d layer"""
m = nn.Conv2d(in_channels, out_channels, kernel_size, **kwargs)
nn.init.normal_(m.weight, mean=0, std=0.1)
nn.init.constant_(m.bias, 0)
if weight_norm:
return nn.u... | 43240086ef50cf3edc4bfcbf1fea422eac0f339d | 38,893 |
def get_profile():
"""Obtain the profile of the logged in user."""
user = util.user_from_jwt(request.get_json().get('token'))
if not user:
return api_error(m.USER_NOT_FOUND), 404
response = {
'username': user.username,
'name': user.name,
}
return api_success(**response... | 902f2c76fadb092d002de9cd16ec3e850be0ea9f | 38,894 |
import os
def check_file_size(origin, temp):
"""Compare the file size of original and re encoded file."""
origin_filesize = os.path.getsize(origin)
filesize = os.path.getsize(temp)
if origin_filesize < filesize:
Logger.info('Encoded movie is bigger than the original movie')
return Fals... | cda70bf22aadfbf80c1835c719e79b571bae0c2f | 38,895 |
import os
import shutil
def download_from(url : str, destination_file : str) -> str:
""" Downloads a file to the specified destination.
Keyword arguments:
url -- url of the file to download
destination_file -- path to the file to download to
Returns path to the downloaded... | b983cead6179a7c4cbcfa473d73c065b86471685 | 38,896 |
def parse_int(text: str) -> int:
"""
Takes in a number in string form and returns that string in integer form
and handles zeroes represented as dashes
"""
text = text.strip()
if text == '-':
return 0
else:
return int(text.replace(',', '')) | 1f49a2d75c2fadc4796456640e9999796fddfa93 | 38,897 |
def english_to_french(english_text):
"""
This Function Translates input text from English-French
"""
translate = language_translator.translate(
text = english_text,
model_id = 'en-fr').get_result()
french_text = translate['translations'][0]['translation']
return french_text | 0e9a5797b3299d4cd76fe2b5acfa3ca90efda7b8 | 38,898 |
def pred_transform(image, target):
"""
:param image: ndarray[H, W, C] RGB
:param target: None
:return: ndarray[H, W, C] RGB 0-255, None"""
image = resize_pad(image, image_size, False, 32, False, 114)[0]
return image, target | e742f0549b08c8dc2cb2f505c24c80653d0d4a50 | 38,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.