content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def encode(number, base):
"""Encode given number in base 10 to digits in given base.
number: int -- integer representation of number (in base 10)
base: int -- base to convert to
return: str -- string representation of number (in given base)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <= ... | 19,800 |
def Print(string, color, highlight=False):
"""
Colored print
colorlist:
red,green
"""
end="\033[1;m"
pstr=""
if color == "red":
if highlight:
pstr+='\033[1;41m'
else:
pstr+='\033[1;31m'
elif color == "green":
if highlight:
... | 19,801 |
def _parse_constants():
"""Read the code in St7API and parse out the constants."""
def is_int(x):
try:
_ = int(x)
return True
except ValueError:
return False
with open(St7API.__file__) as f_st7api:
current_comment = None
seen_comments = ... | 19,802 |
def verify_outcome(msg, prefix, lista):
"""
Compare message to list of claims: values.
:param prefix: prefix string
:param lista: list of claims=value
:return: list of possible strings
"""
assert msg.startswith(prefix)
qsl = ["{}={}".format(k, v[0]) for k, v in parse_qs(msg[len(prefix) ... | 19,803 |
def equationMaker(congruency=None, beat_type=None, structure=None, n=None, perms=None, catch = False):
"""
Function to create equation stimuli, like in Landy & Goldstone, e.g. "b + d * f + y"
required inputs:
congruency: 'congruent' or 'incongruent'
beat_t... | 19,804 |
def get_deadline_delta(target_horizon):
"""Returns number of days between official contest submission deadline date
and start date of target period
(14 for week 3-4 target, as it's 14 days away,
28 for week 5-6 target, as it's 28 days away)
Args:
target_horizon: "34w" or "56w" indicating whe... | 19,805 |
def perform_tensorflow_model_inference(model_name, sample):
""" Perform evaluations from model (must be configured)
Args:
model_name ([type]): [description]
sample ([type]): [description]
Returns:
[type]: [description]
"""
reloaded_model = tf.keras.models.load_model(model_n... | 19,806 |
def check_ntru(f, g, F, G):
"""Check that f * G - g * F = 1 mod (x ** n + 1)."""
a = karamul(f, G)
b = karamul(g, F)
c = [a[i] - b[i] for i in range(len(f))]
return ((c[0] == q) and all(coef == 0 for coef in c[1:])) | 19,807 |
def total_price(id: int):
"""Calculates the total price for the order
Args:
id (int): The order ID
Returns:
[int]: Total price
"""
loop = asyncio.get_event_loop()
order_data = loop.run_until_complete(fetch_data(id)) | 19,808 |
def RaiseCommandException(args, returncode, output, error):
"""Raise an exception whose message describing a command failure.
Args:
args: shell command-line (as passed to subprocess.call())
returncode: status code.
error: standard error output.
Raises:
a new Exception.
"""
message = 'Command ... | 19,809 |
def edit_user(user_id):
"""
TODO: differentiate between PUT and PATCH -> PATCH partial update
"""
user = User.from_dict(request.get_json())
user.id = user_id
session_id = request.headers.get('Authorization', None)
session = auth.lookup(session_id)
if session["user"].role != Role.admin:... | 19,810 |
def Search_tau(A, y, S, args, normalize=True, min_delta=0):
"""
Complete parameter search for sparse regression method S.
Input:
A,y : from linear system Ax=y
S : sparse regression method
args : arguments for sparse regression method
normalize : boolean. Normalize co... | 19,811 |
def get_entry_accounts(entry: Directive) -> list[str]:
"""Accounts for an entry.
Args:
entry: An entry.
Returns:
A list with the entry's accounts ordered by priority: For
transactions the posting accounts are listed in reverse order.
"""
if isinstance(entry, Transaction):
... | 19,812 |
def default_evade():
"""
A catch-all method to try and evade suspension from Linkedin.
Currenly, just delays the request by a random (bounded) time
"""
sleep(random.uniform(0, 0)) | 19,813 |
def enter_fastboot(adb_serial, adb_path=None):
"""Enters fastboot mode by calling 'adb reboot bootloader' for the adb_serial provided.
Args:
adb_serial (str): Device serial number.
adb_path (str): optional alternative path to adb executable
Raises:
RuntimeError: if adb_path is invalid or adb e... | 19,814 |
def thesaurus_manager_menu_header(context, request, view, manager): # pylint: disable=unused-argument
"""Thesaurus manager menu header"""
return THESAURUS_MANAGER_LABEL | 19,815 |
def create_compiled_keras_model():
"""Create compiled keras model."""
model = models.create_keras_model()
model.compile(
loss=tf.keras.losses.sparse_categorical_crossentropy,
optimizer=utils.get_optimizer_from_flags('client'),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
return mo... | 19,816 |
def extraerWrfoutSerie(file_paths, latlong_estaciones, par, run):
""" extrae de los arechivos wrfout listados en file_paths
para la posicion (x, y) toda la serie de la variable
seleccionada"""
print(f'Processing: {file_paths}')
try:
wrf_temp = Dataset(file_paths)
except OSError:
... | 19,817 |
def top_mods(max_distance, top_n, min_len, stored_json):
"""Check top packages for typosquatters.
Prints top packages and any potential typosquatters
Args:
max_distance (int): maximum edit distance to check for typosquatting
top_n (int): the number of top packages to retrieve
min_l... | 19,818 |
def train_sedinet_cat(SM, train_df, test_df, train_idx, test_idx,
ID_MAP, vars, greyscale, name, mode, batch_size, valid_batch_size,
res_folder):
"""
This function trains an implementation of SediNet
"""
##================================
## create trainin... | 19,819 |
def query_top_python_repositories(stars_filter: Optional[str] = None): # FIXME: set stars_filter = None
"""
stars_filter examples:
>7
<42
42..420
"""
log.info("Querying top popular Python GitHub repositories...")
gql = GQL(endpoint=endpoint, headers=headers)
gql.load_query(... | 19,820 |
def psycopg2_string():
"""
Generates a connection string for psycopg2
"""
return 'dbname={db} user={user} password={password} host={host} port={port}'.format(
db=settings.DATABASES['default']['NAME'],
user=settings.DATABASES['default']['USER'],
password=settings.DATABASES['defaul... | 19,821 |
def get_phase_relation(protophase: np.ndarray, N: int = 0) -> np.ndarray:
"""
relation between protophase and phase
Parameters
----------
protophase : np.ndarray
N : int, optional
number of fourier terms need to be used
Returns
-------
np.ndarray
... | 19,822 |
def handle_articlepeople(utils, mention):
"""
Handles #articlepeople functionality.
Parameters
----------
utils : `Utils object`
extends tweepy api wrapper
mention : `Status object`
a single mention
Returns
-------
None
"""
urls = re.findall(r'(https?://[^\s... | 19,823 |
def bak_del_cmd(filename:Path, bakfile_number:int, quietly=False):
""" Deletes a bakfile by number
"""
console = Console()
_bakfile = None
bakfiles = db_handler.get_bakfile_entries(filename)
if not bakfiles:
console.print(f"No bakfiles found for {filename}")
return False
if n... | 19,824 |
def train_test_submissions(submissions=None, force_retrain_test=False,
is_parallelize=None):
"""Train and test submission.
If submissions is None, trains and tests all submissions.
"""
if is_parallelize is not None:
app.config.update({'RAMP_PARALLELIZE': is_paralleliz... | 19,825 |
def fetch_county_data(file_reference):
"""The name of this function is displayed to the user when there is a cache miss."""
path = file_reference.filename
return (pd
.read_csv(path)
.assign(date = lambda d: pd.to_datetime(d.date))
) | 19,826 |
def preston_sad(abund_vector, b=None, normalized = 'no'):
"""Plot histogram of species abundances on a log2 scale"""
if b == None:
q = np.exp2(list(range(0, 25)))
b = q [(q <= max(abund_vector)*2)]
if normalized == 'no':
hist_ab = np.histogram(abund_vector, bins = b)
if ... | 19,827 |
def exp_rearrangement():
"""Example demonstrating of Word-Blot for pairwise local similarity search on
two randomly generated sequencees with motif sequences violating
collinearity :math:`S=M_1M_2M_3, T=M'_1M'_1M'_3M'_2` where motif pairs
:math:`(M_i, M'_i)_{i=1,2,3}` have lengths 200, 400, 600 and are ... | 19,828 |
def package_install_site(name='', user=False, plat_specific=False):
"""pip-inspired, distutils-based method for fetching the
default install location (site-packages path).
Returns virtual environment or system site-packages, unless
`user=True` in which case returns user-site (typ. under `~/.local/
... | 19,829 |
def unregisterExcept(func):
"""
Un-registers a function from the except hook queue.
Look at the sys.displayhook documentation for more information.
:param func | <callable>
"""
try:
_excepthooks.remove(weakref.ref(func))
except (AttributeError, ValueError):
pass | 19,830 |
def atlas_slice(atlas, slice_number):
"""
A function that pulls the data for a specific atlas slice.
Parameters
----------
atlas: nrrd
Atlas segmentation file that has a stack of slices.
slice_number: int
The number in the slice that corresponds to the fixed image
for r... | 19,831 |
def enviar_cambio_estado(request):
"""
Cambio de estado de una nota técnica y avisar
por email al personal de stib
"""
if request.method == "POST" or request.POST.get("nota_tecnica"):
try:
nota_tecnica = get_object_or_404(NotasTecnicas, pk=request.POST.get("nota_tecnica"))
... | 19,832 |
def ha_inpgen(filename, outfile, is_list, ref, interface):
""" Input generator for (Quasi-)Harmonic Approximation calculations.
This command requires a file (FILENAME) that will be read to provide the
input data for the input generation.
"""
outbase = os.path.splitext(filename)[0]
if isins... | 19,833 |
def post_auth_logout(): # noqa: E501
"""Logout of the service
TODO: # noqa: E501
:rtype: None
"""
return 'do some magic!' | 19,834 |
async def head(url: str) -> Dict:
"""Fetch headers returned http GET request.
:param str url:
The URL to perform the GET request for.
:rtype: dict
:returns:
dictionary of lowercase headers
"""
async with aiohttp.request("HEAD", url) as res:
response_headers = res.headers... | 19,835 |
def send_recv_packet(packet, iface=None, retry=3, timeout=1, verbose=False):
"""Method sends packet and receives answer
Args:
packet (obj): packet
iface (str): interface, used when Ether packet is included
retry (int): number of retries
timeout (int): timeout to receive ... | 19,836 |
def delete_by_image_name(image_name):
"""
Delete Image by their name
"""
Image.query.filter_by(image_name=image_name).delete()
db.session.commit() | 19,837 |
def node_vectors(node_id):
"""Get the vectors of a node.
You must specify the node id in the url.
You can pass direction (incoming/outgoing/all) and failed
(True/False/all).
"""
exp = Experiment(session)
# get the parameters
direction = request_parameter(parameter="direction", default="... | 19,838 |
def newFlatDict(store, selectKeys=None, labelPrefix=''):
"""
Takes a list of dictionaries and returns a dictionary of 1D lists.
If a dictionary did not have that key or list element, then 'None' is put in its place
Parameters
----------
store : list of dicts
The dictionaries would be e... | 19,839 |
async def get_races(
db: Any, token: str, raceplan_id: str
) -> List[Union[IndividualSprintRace, IntervalStartRace]]:
"""Check if the event has a races."""
races = await RacesService.get_races_by_raceplan_id(db, raceplan_id)
if len(races) == 0:
raise NoRacesInRaceplanException(
f"No ... | 19,840 |
def _reshape_vectors(v1, v2, axis, dim, same_shape=True):
""" Reshape input vectors to two dimensions. """
# TODO v2 as DataArray with possibly different dimension order
v1, axis, _, _, _, _, coords, *_ = _maybe_unpack_dataarray(
v1, dim, axis, None, False
)
v2, *_ = _maybe_unpack_dataarray(... | 19,841 |
def yaml_load(data: str) -> Any:
"""Deserializes a yaml representation of known objects into those objects.
Parameters
----------
data : str
The serialized YAML blob.
Returns
-------
Any
The deserialized Python objects.
"""
yaml = yaml_import(raise_error=True)
re... | 19,842 |
def _get_current_branch():
"""Retrieves the branch Git is currently in.
Returns:
(str): The name of the current Git branch.
"""
branch_name_line = _run_cmd(GIT_CMD_GET_STATUS).splitlines()[0]
return branch_name_line.split(' ')[2] | 19,843 |
def PGAN(pretrained=False, *args, **kwargs):
"""
Progressive growing model
pretrained (bool): load a pretrained model ?
model_name (string): if pretrained, load one of the following models
celebaHQ-256, celebaHQ-512, DTD, celeba, cifar10. Default is celebaHQ.
"""
from models.progressive_gan ... | 19,844 |
def compare_environment(team_env, master_env, jenkins_build_terms ):
"""
compare the versions replace compare_environment
Return types
1 - Matches Master
2 - Does not match master. Master is ahead(red)
3 - branch is ahead (yellow)
:param team_env:
:param master_env:
:param jenkins_bu... | 19,845 |
def _runge_kutta_step(func,
y0,
f0,
t0,
dt,
tableau=_DORMAND_PRINCE_TABLEAU,
name=None):
"""Take an arbitrary Runge-Kutta step and estimate error.
Args:
func: Function t... | 19,846 |
def _create_serialize(cls, serializers):
"""
Create a new serialize method with extra serializer functions.
"""
def serialize(self, value):
for serializer in serializers:
value = serializer(value)
value = super(cls, self).serialize(value)
return value
serialize._... | 19,847 |
def confusion_matrix(y_true, y_pred, labels=None):
"""Compute confusion matrix to evaluate the accuracy of a classification
By definition a confusion matrix cm is such that cm[i, j] is equal
to the number of observations known to be in group i but predicted
to be in group j.
Parameters
-------... | 19,848 |
def dialect_selector(s):
"""Return a dialect given it's name."""
s = s or 'ansi'
lookup = {
'ansi': ansi_dialect
}
return lookup[s] | 19,849 |
def main():
"""
"Neither agreeable nor disagreeable," I answered. "It just is."
--- ALDOUS HUXLEY
"""
bg_1()
bg_2()
bg_4()
bg_3()
bg_5()
bg_6()
bg_7()
bg_8()
bg_9()
bg_10()
bg_11()
bg_12()
bg_13()
bg_14()... | 19,850 |
def dump(line, index):
""" Command for printing the last item in stack """
global stacks
global current_stack
checkStack(1, line, index)
line = line.strip().split(' ')
line.pop(0) # Removing the command itself
line = ' '.join(line)
if len(line) == 0:
ending = ''
else:
... | 19,851 |
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn) | 19,852 |
def bf(x):
""" returns the given bitfield value from within a register
Parameters:
x: a pandas DataFrame line - with a column named BF_NUMBER which holds the definition of given bit_field
reg_val: integer
Returns:
--------
res: str
the bit field value from within the register
"""... | 19,853 |
def get_mean_brightness(
frame: np.ndarray,
mask: Union[
np.ndarray,
None,
] = None,
) -> int:
"""Return the mean brightness of a frame.
Load the frame, calculate a histogram, and iterate through the bins until half or more of the pixels have been counted.
Args:
`frame`... | 19,854 |
def ban_sticker(msg, sticker_id):
"""
Банит стикер\n
:param msg:\n
:param sticker_id:\n
"""
with DataConn(db) as conn:
cursor = conn.cursor()
sql = 'SELECT * FROM `banned_stickers` WHERE `chat_id` = %s AND `sticker_id` = %s'
cursor.execute(sql, (msg.chat.id, sticker_id))
... | 19,855 |
def rearrange(s):
"""
Args:
s
Returns:
[]
"""
if not can_arrange_palindrome2(s):
return []
m = {}
for c in s:
if c in m:
m[c] += 1
else:
m[c] = 1
middle = ""
for k in m:
if m[k] % 2 == 0:
m[k] /= 2... | 19,856 |
def get_org_memberships(user_id: str):
"""Return a list of organizations and roles where the input user is a member"""
query = (
model.Session.query(model.Group, model.Member.capacity)
.join(model.Member, model.Member.group_id == model.Group.id)
.join(model.User, model.User.id == model.M... | 19,857 |
def standardize_concentration(df, columns, unit="nM"):
"""Make all concentrations match the given unit.
For a given DataFrame and column, convert mM, uM, nM, and pM concentration
values to the specified unit (default nM). Rename the column to include
({unit}).
Parameters
----------
d... | 19,858 |
def setup(hass, config):
""" Setup the Visonic Alarm component."""
from visonic import alarm as visonicalarm
global HUB
HUB = VisonicAlarmHub(config[DOMAIN], visonicalarm)
if not HUB.connect():
return False
HUB.update()
# Load the supported platforms
for component in ('sensor',... | 19,859 |
def moreparams():
""" Read list of json files or return one specific for specific time """
hour_back1 = request.args.get('hour_back1', default=1, type=int)
hour_back2 = request.args.get('hour_back2', default=0, type=int)
object_of_interest = request.args.get('object_of_interest', type=None)
#print(... | 19,860 |
def generate_http_request_md_fenced_code_block(
language=None,
fence_string='```',
**kwargs,
):
"""Wraps [``generate_http_request_code``](#generate_http_request_code)
function result in a Markdown fenced code block.
Args:
fence_string (str): Code block fence string used wrapping the cod... | 19,861 |
def test_detectors_with_stats(test_video_file):
""" Test all detectors functionality with a StatsManager. """
for detector in [ContentDetector, ThresholdDetector, AdaptiveDetector]:
vm = VideoManager([test_video_file])
stats = StatsManager()
sm = SceneManager(stats_manager=stats)
... | 19,862 |
def confident_hit_ratio(y_true, y_pred, cut_off=0.1):
"""
This function return the hit ratio of the true-positive for confident molecules.
Confident molecules are defined as confidence values that are higher than the cutoff.
:param y_true:
:param y_pred:
:param cut_off: confident value that defi... | 19,863 |
def onion(ctx, port, onion_version, private_key, show_private_key, detach):
"""
Add a temporary onion-service to the Tor we connect to.
This keeps an onion-service running as long as this command is
running with an arbitrary list of forwarded ports.
"""
if len(port) == 0:
raise click.Us... | 19,864 |
def determine_if_pb_should_be_filtered(row, min_junc_after_stop_codon):
"""PB should be filtered if NMD, a truncation, or protein classification
is not likely protein coding (intergenic, antisense, fusion,...)
Args:
row (pandas Series): protein classification row
min_junc_after_stop_codon (... | 19,865 |
def sma(other_args: List[str], s_ticker: str, s_interval: str, df_stock: pd.DataFrame):
"""Plots simple moving average (SMA) over stock
Parameters
----------
other_args: List[str]
Argparse arguments
s_ticker: str
Ticker
s_interval: str
Data interval
df_stock: pd.Data... | 19,866 |
def calculate_shortest_path(draw_func, grid, start, end):
"""https://en.wikipedia.org/wiki/A*_search_algorithm"""
count = 0
open_set = queue.PriorityQueue()
open_set.put((0, count, start))
open_set_hash = {start}
came_from = {}
# g_score: Distance from start to current node
g_score = {... | 19,867 |
def _get_hashed_id(full_name: str, name_from_id: MutableMapping[int,
str]) -> int:
"""Converts the string-typed name to int-typed ID."""
# Built-in hash function will not exceed the range of int64, which is the
# type of id in metadata artifact proto... | 19,868 |
def find_adjustment(tdata : tuple, xdata : tuple, ydata : tuple,
numstept=10,numstepx=10,tol=1e-6) -> tuple:
"""
Find best fit of data with temporal and spatial offset in range. Returns
the tuple err, dt, dx.
Finds a temporal and spatial offset to apply to the temporal and spatial
locatio... | 19,869 |
def get_params():
"""Loads ./config.yml in a dict and returns it"""
with open(HERE/'config.yml') as file:
params = yaml.load(file)
return params | 19,870 |
def parse_args(args, repo_dirs):
"""
Extract the CLI arguments from argparse
"""
parser = argparse.ArgumentParser(description="Sweet branch creation tool")
parser.add_argument(
"--repo",
help="Repository to create branch in",
choices=repo_dirs,
required=False,
)
... | 19,871 |
def simplify():
"""Our standard simplification of logic routine. What it does depende on the problem size.
For large problems, we use the &methods which use a simple circuit based SAT solver. Also problem
size dictates the level of k-step induction done in 'scorr' The stongest simplification is done if
... | 19,872 |
def update_location(new_fix):
"""Update current location, and publishes map if it has been a while"""
g['fix'] = new_fix
if published_long_ago(): publish_map() | 19,873 |
def test_arr_to_mat_double_small():
"""Test arr_to_mat."""
sample = np.asarray(
np.random.normal(size=(3, 3)), dtype=np.float64, order='F'
)
flag = carma.arr_to_mat_double(sample, False)
assert flag == 0, test_flags[flag] | 19,874 |
def check_args(args):
"""Checking user input
"""
pass | 19,875 |
def get_textgrid(path_transcription):
"""Get data from TextGrid file"""
data = textgriddf_reader(path_file=path_transcription)
text_df = textgriddf_df(data, item_no=2)
sentences = textgriddf_converter(text_df)
return sentences | 19,876 |
def accessible_required(f):
"""Decorator for an endpoint that requires a user have accessible or read permission in the
given room. The function must take a `room` argument by name, as is typically used with flask
endpoints with a `<Room:room>` argument."""
@wraps(f)
def required_accessible_wrappe... | 19,877 |
def make_erb_cos_filters_nx(signal_length, sr, n, low_lim, hi_lim, sample_factor, padding_size=None, full_filter=True, strict=True, **kwargs):
"""Create ERB cosine filters, oversampled by a factor provided by "sample_factor"
Args:
signal_length (int): Length of signal to be filtered with the generated
fi... | 19,878 |
def ecr_repo_permission_policy_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:
"""[ECR.3] ECR repositories should be have a repository policy configured"""
response = describe_repositories(cache)
myRepos = response["repositories"]
for repo in myRepos:
repoArn = ... | 19,879 |
def t_COMMENT(t):
"""
//.*
"""
pass | 19,880 |
def button_ld_train_first_day(criteria, min_reversal_number):
"""
This function creates a csv file for the LD Train test. Each row will be the first day the animal ran the
test. At the end, the function will ask the user to save the newly created csv file in a directory.
:param criteria: A widget ... | 19,881 |
def analyze_video(file, name, api):
"""
Call Scenescoop analyze with a video
"""
args = Namespace(video=file, name=name, input_data=None, api=True)
scene_content = scenescoop(args)
content = ''
maxframes = 0
for description in scene_content:
if(len(scene_content[description]) > maxframes):
con... | 19,882 |
def validategeojson(data_input, mode):
"""GeoJSON validation example
>>> import StringIO
>>> class FakeInput(object):
... json = open('point.geojson','w')
... json.write('''{"type":"Feature", "properties":{}, "geometry":{"type":"Point", "coordinates":[8.5781228542328, 22.87500500679]}, "crs... | 19,883 |
def encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):
"""
Build and train an encoder-decoder model on x and y
:param input_shape: Tuple of input shape
:param output_sequence_length: Length of output sequence
:param english_vocab_size: Number of unique English ... | 19,884 |
def close_to_cron(crontab_time, time_struct):
"""coron的指定范围(crontab_time)中 最接近 指定时间 time_struct 的值"""
close_time = time_struct
cindex = 0
for val_struct in time_struct:
offset_min = val_struct
val_close = val_struct
for val_cron in crontab_time[cindex]:
offset_tmp = v... | 19,885 |
def remove_stop_words(words_list: list) -> list:
""" Remove stop words from strings list """
en_stop_words = set(stopwords.words('english'))
return [w for w in words_list if str(w).lower not in en_stop_words] | 19,886 |
def build_jerry_data(jerry_path):
"""
Build up a dictionary which contains the following items:
- sources: list of JerryScript sources which should be built.
- dirs: list of JerryScript dirs used.
- cflags: CFLAGS for the build.
"""
jerry_sources = []
jerry_dirs = set()
for sub_di... | 19,887 |
def min_geodesic_distance_rotmats_pairwise_tf(r1s, r2s):
"""Compute min geodesic distance for each R1 wrt R2."""
# These are the traces of R1^T R2
trace = tf.einsum('...aij,...bij->...ab', r1s, r2s)
# closest rotation has max trace
max_trace = tf.reduce_max(trace, axis=-1)
return tf.acos(tf.clip_by_value((m... | 19,888 |
def project_to_2D(xyz):
"""Projection to (0, X, Z) plane."""
return xyz[0], xyz[2] | 19,889 |
def Geom2dInt_Geom2dCurveTool_D2(*args):
"""
:param C:
:type C: Adaptor2d_Curve2d &
:param U:
:type U: float
:param P:
:type P: gp_Pnt2d
:param T:
:type T: gp_Vec2d
:param N:
:type N: gp_Vec2d
:rtype: void
"""
return _Geom2dInt.Geom2dInt_Geom2dCurveTool_D2(*args) | 19,890 |
def osm_nodes(raw_elements: List[ELEMENT_RAW_TYPE]) -> Generator[Node, None, None]:
"""Converts dictionaries to Node class instances.
Returns a generator so use results in a for loop or convert to list.
Expects dictionary structure as returned by Overpass API."""
for element in raw_elements:
ta... | 19,891 |
def _content_length_rewriter(state):
"""Rewrite the Content-Length header.
Even though Content-Length is not a user modifiable header, App Engine
sends a correct Content-Length to the user based on the actual response.
If the response status code indicates that the response is not allowed to
contain a body,... | 19,892 |
def notfound(request):
"""
Common notfound return message
"""
msg = CustomError.NOT_FOUND_ERROR.format(request.url, request.method)
log.error(msg)
request.response.status = 404
return {'error': 'true', 'code': 404, 'message': msg} | 19,893 |
def l2norm(a):
"""Return the l2 norm of a, flattened out.
Implemented as a separate function (not a call to norm() for speed)."""
return np.sqrt(np.sum(np.absolute(a)**2)) | 19,894 |
def create_container(request):
""" Creates a container (empty object of type application/directory) """
storage_url = get_endpoint(request, 'adminURL')
auth_token = get_token_id(request)
http_conn = client.http_connection(storage_url,
insecure=settings.SWIFT_INSEC... | 19,895 |
def check_all_data_present(file_path):
"""Checks the data exists in location file_path"""
filenames = [
"t10k-images-idx3-ubyte",
"t10k-labels-idx1-ubyte",
"train-images-idx3-ubyte",
"train-labels-idx1-ubyte",
]
data_path = os.path.join(file_path, "data")
return tu... | 19,896 |
def get_searchable_models():
"""
Returns a list of all models in the Django project which implement ISearchable
"""
app = AppCache();
return filter(lambda klass: implements(klass, ISearchable), app.get_models()) | 19,897 |
def _worker_within(
worker_id,
global_t_nulls,
spotwise_t_nulls,
df_filt,
perms,
kernel_matrix,
null_corrs_filt,
keep_indices,
verbose=10,
compute_spotwise_pvals=False
):
"""
This function computes the test statistic on a chunk ... | 19,898 |
def create_updated_alert_from_slack_message(payload, time, alert_json):
"""
Create an updated raw alert (json) from an update request in Slack
"""
values = payload['view']['state']['values']
for value in values:
for key in values[value]:
if key == 'alert_id':
cont... | 19,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.