content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def profile(request):
"""
Update a User profile using built in Django Users Model if the user is logged in
otherwise redirect them to registration version
"""
if request.user.is_authenticated():
obj = get_object_or_404(TolaUser, user=request.user)
form = RegistrationForm(request.POST... | 225ac41ec6565e30f54ece3cad76b2a0770a319d | 3,653,006 |
def conj(Q):
"""Returns the conjugate of a dual quaternion.
"""
res = cs.SX.zeros(8)
res[0] = -Q[0]
res[1] = -Q[1]
res[2] = -Q[2]
res[3] = Q[3]
res[4] = -Q[4]
res[5] = -Q[5]
res[6] = -Q[6]
res[7] = Q[7]
return res | e0a6d67d322f2c939e2d8249983789222c96363d | 3,653,007 |
def benchmark_summary(benchmark_snapshot_df):
"""Creates summary table for a benchmark snapshot with columns:
|fuzzer|time||count|mean|std|min|25%|median|75%|max|
"""
groups = benchmark_snapshot_df.groupby(['fuzzer', 'time'])
summary = groups['edges_covered'].describe()
summary.rename(columns={'... | 5cdaa888adb47906659a249076c8a4acb27c6d1d | 3,653,008 |
def is_pio_job_running(*target_jobs: str) -> bool:
"""
pass in jobs to check if they are running
ex:
> result = is_pio_job_running("od_reading")
> result = is_pio_job_running("od_reading", "stirring")
"""
with local_intermittent_storage("pio_jobs_running") as cache:
for job in targ... | 0ed9daf39372ead913ad52d5c93426eeb06f74ed | 3,653,009 |
def encode(text, encoding='utf-8'):
"""
Returns a unicode representation of the string
"""
if isinstance(text, basestring):
if not isinstance(text, unicode):
text = unicode(text, encoding, 'ignore')
return text | 81d9d2d5cf920c0f15ffc5e50fb670b079ae1f90 | 3,653,010 |
def calculate_sparsity(df: pd.DataFrame) -> tuple:
"""Calculate the data sparsity based on ratings and reviews.
Args:
df ([pd.DataFrame]): DataFrame with counts of `overall` and `reviewText`
measured against total `reviewerID` * `asin`.
Returns:
[tuple]: Tuple of data sparsity ... | 53e6b2682b67ceb8bbb4f5a6857cdbd565321421 | 3,653,011 |
def char_fun_est(
train_data,
paras=[3, 20], n_trees = 200, uv = 0, J = 1, include_reward = 0, fixed_state_comp = None):
"""
For each cross-fitting-task, use QRF to do prediction
paras == "CV_once": use CV_once to fit
get_CV_paras == True: just to get paras by using CV
Returns
... | 51012cc870d9bcd1f86fe69534e26d7d365ad271 | 3,653,012 |
def create_tables_for_import(volume_id, namespace):
"""Create the import or permanent obs_ tables and all the mult tables they
reference. This does NOT create the target-specific obs_surface_geometry
tables because we don't yet know what target names we have."""
volume_id_prefix = volume_id[:volu... | 8e02e98031e4242e2e0d559750258d74180593db | 3,653,013 |
def org_repos(info):
"""
处理组织的仓库
:param info: 字典
:return: 两个列表,第一个包含字典(id,全名,url),第二个包含所用到的语言
"""
repo_info = []
languages = []
if info:
for repo in info:
temp = {"id": repo["id"], "full_name": repo["full_name"], "url": repo["url"], "language": repo["language"]}
... | 9d5633bf834845e1301e0fd383a57c42f2bd530c | 3,653,014 |
from typing import Union
from datetime import datetime
def year(yyyy_mm_dd: Union[str, datetime.date]) -> int:
"""
Extracts the year of a given date, similar to yyyy function but returns an int
>>> year('2020-05-14')
2020
"""
date, _ = _parse(yyyy_mm_dd, at_least="%Y")
return date.year | eb34fb578d5ec7130d5670332aa4bbb9aca186ac | 3,653,015 |
def getTypeLevel(Type):
"""Checks whether a spectral data type is available in the endmember library.
Args:
Type: the type of spectra to select.
Returns:
level: the metadata "level" of the group for subsetting. returns 0 if not found.
"""
for i in range(4):
level = i + 1
... | 6c26f7dc570b5a7f0cacdc1171ae733b005e7992 | 3,653,016 |
from typing import Union
def construct_creator(creator: Union[dict, str], ignore_email):
"""Parse input and return an instance of Person."""
if not creator:
return None, None
if isinstance(creator, str):
person = Person.from_string(creator)
elif isinstance(creator, dict):
pers... | 5306f288874f4d15d5823c34268321121909a3ad | 3,653,017 |
def _encode_query(items: dict, *, mask=False) -> str:
"""Encode a dict to query string per CLI specifications."""
pairs = []
for key in sorted(items.keys()):
value = _MASK if mask and key in _MASKED_PARAMS else items[key]
item = "{}={}".format(key, _quote(value))
# Ensure 'url' goes ... | 918f0aa4198367fb3889eb67bba622d272082af7 | 3,653,018 |
def spatial_shape_after_conv(input_spatial_shape, kernel_size, strides, dilation, padding):
""" This function calculates the spatial shape after conv layer.
The formula is obtained from: https://www.tensorflow.org/api_docs/python/tf/nn/convolution
It should be note that current function assumes PS is done ... | a7d924260feb478e44a9ec166fe4248b51632270 | 3,653,019 |
def sample_partition(dependency_tensor, null_distribution,
updates=100,
initial_partition=None
):
"""
Sample partition for a multilayer network with specified interlayer dependencies
:param dependency_tensor: dependency tensor
:param null_d... | d6c469054057f18ad1e7ab3abd96103e81931649 | 3,653,020 |
import re
def normalize_spaces(s: str) -> str:
"""
連続する空白を1つのスペースに置き換え、前後の空白を削除した新しい文字列を取得する。
"""
return re.sub(r'\s+', ' ', s).strip() | aac95ed5b77b5c65f9ce16cfa685d80c56f0e66f | 3,653,021 |
def power_iter(mat_g, error_tolerance=1e-6, num_iters=100):
"""Power iteration.
Args:
mat_g: the symmetric PSD matrix.
error_tolerance: Iterative exit condition.
num_iters: Number of iterations.
Returns:
eigen vector, eigen value, num_iters
"""
mat_g_size = mat_g.shape[-1]
def _iter_condit... | 11717fda8b3dedce94e9be3157a78d8d95e0e989 | 3,653,022 |
from typing import Union
from typing import Any
def _get_values_target_representation(
val: Union[str, Any],
target_representation: str,
conversion_type: str,
conversion_rate: float,
n_round: int,
split: bool,
input_symbol: str,
target_symbol: str,
) -> Any:
"""
Returns the val... | 188fe2da51a177fc743ee30c67807b46730a3a34 | 3,653,023 |
from typing import OrderedDict
def GetResidues(mol, atom_list=None):
"""Create dictrionary that maps residues to atom IDs:
(res number, res name, chain id) --> [atom1 idx, atom2 idx, ...]
"""
residues = OrderedDict()
if atom_list is None:
atom_list = range(mol.GetNumAtoms())
for aid... | 51f66cf9c3203573df5660205581fd0571826876 | 3,653,024 |
def BIC(y_pred, y, k, llf = None):
"""Bayesian Information Criterion
Args:
y_pred (array-like)
y (array-like)
k (int): number of featuers
llf (float): result of log-likelihood function
"""
n = len(y)
if llf is None:
llf = np.log(SSE(y_pred, y))
return np... | f070400f045b1e8f98b453b8d5f8661271b1969e | 3,653,025 |
def create_abstract_insert(table_name, row_json, return_field=None):
"""Create an abstracted raw insert psql statement for inserting a single
row of data
:param table_name: String of a table_name
:param row_json: dictionary of ingestion data
:param return_field: String of the column name to RETURNI... | 8b0a960178a0162b7a0c339682541f0f13520d85 | 3,653,026 |
def descsum_create(s):
"""Add a checksum to a descriptor without"""
symbols = descsum_expand(s) + [0, 0, 0, 0, 0, 0, 0, 0]
checksum = descsum_polymod(symbols) ^ 1
return s + '#' + ''.join(CHECKSUM_CHARSET[(checksum >> (5 * (7 - i))) & 31] for i in range(8)) | 52ce47b470dada282318cd23c61665adfb7554c3 | 3,653,028 |
def _get_header(key):
"""Return message header"""
try:
return request.headers[key]
except KeyError:
abort(400, "Missing header: " + key) | cbdf9928f6ce4c41145529c68039761eab65c3d0 | 3,653,029 |
def compute_solution(primes_list, triangle_sequence):
""" Auxiliary function to compute the solution to the problem.
"""
factorise_w_primes = partial(factorise, primes=primes_list)
all_factors = vmap(factorise_w_primes)(triangle_sequence)
# number of divisors = number of possible combinations of pri... | 5df3444b10a4ae316fab1c21c87e3187d4792f14 | 3,653,030 |
import platform
def key_description(character):
"""
Return the readable description for a key.
:param character: An ASCII character.
:return: Readable description for key.
"""
if "Windows" in platform.system():
for key, value in hex_keycodes.items():
if value == character:
... | 9ed5bd198898c2f5cf234cb0c46924286fa18e51 | 3,653,031 |
def combine_index(df, n1, n2):
"""將dataframe df中的股票代號與股票名稱合併
Keyword arguments:
Args:
df (pandas.DataFrame): 此dataframe含有column n1, n2
n1 (str): 股票代號
n2 (str): 股票名稱
Returns:
df (pandas.DataFrame): 此dataframe的index為「股票代號+股票名稱」
"""
return df.set_index(df[n1].st... | 645c62fdc7d8e541c9b55b5f1621d6c442ca683a | 3,653,033 |
def safe_get_stopwords(stopwords_language):
"""
:type stopwords_language: basestring
:rtype: list
"""
try:
return get_stopwords(stopwords_language)
except LanguageNotAvailable:
return [] | f6a32da469e59341aa9a928cac362b0075e5d792 | 3,653,034 |
def setup_mock_device(mock_device):
"""Prepare mock ONVIFDevice."""
mock_device.async_setup = AsyncMock(return_value=True)
mock_device.available = True
mock_device.name = NAME
mock_device.info = DeviceInfo(
MANUFACTURER,
MODEL,
FIRMWARE_VERSION,
SERIAL_NUMBER,
... | f39951f9109e5646d1e4cdd4782907cce5ee3a1c | 3,653,036 |
def convert(digits, base1, base2):
"""Convert given digits in base1 to digits in base2.
digits: str -- string representation of number (in base1)
base1: int -- base of given number
base2: int -- base to convert to
return: str -- string representation of number (in base2)"""
# Handle up to base 3... | 482e7207a27c6acfdaf088ef8195792f29d14452 | 3,653,039 |
def h(b, W ,X):
"""
This function implments the softmax regression hypothesis function
Argument:
b -- bias
W -- predictive weight matrix
X -- data matrix of size (numbers_examples, number_predictors)
Returns:
softmax(XW + b)
"""
return softmax( (X @ W) + b) | abca116d09993b310a70ddf80fcf0eea73b6d542 | 3,653,040 |
def get_random_points(N):
"""
- Takes number of parameters N
- Returns tuple (x1,x2), where x1 and x2 are vectors
"""
x1 = np.random.uniform(-1,1,N)
x2 = np.random.uniform(-1,1,N)
return (x1,x2) | e118d2dbbc472bfa31fa30ffe1fabbf625a9c924 | 3,653,041 |
def n_bit_color(clk, din, vga_signals, vga_ports):
"""
Maps n bit input, din, to n bit vga color ports
Ex: din=10010101, r=100, g=101, b=01
"""
blu = len(vga_ports.blu)
grn = len(vga_ports.grn) + blu
red = len(vga_ports.red) + grn
assert len(din) == red
@always(clk.posedge)
... | e760c21c0b87c54d5977e6ba29bed0f5dc20b6ab | 3,653,042 |
from typing import Tuple
from typing import Dict
def point_cloud_transform_net(point_cloud: nn.Variable, train: bool) -> Tuple[nn.Variable, Dict[str, nn.Variable]]:
"""T net, create transformation matrix for point cloud
Args:
point_cloud (nn.Variable): point cloud, shape(batch, number of points, 3)
... | 59a3a30ef874dd1ce47a0d9a369c9170b30ac4ea | 3,653,043 |
def posix_getpgid(space, pid):
""" posix_getpgid - Get process group id for job control """
try:
return space.newint(os.getpgid(pid))
except OSError, e:
space.set_errno(e.errno)
return space.newbool(False)
except OverflowError:
return space.newbool(False) | b01f0d363ce7f0937a52c824aefc0a262f739757 | 3,653,045 |
def on_display_disconnected():
"""Shortcut for registering handlers for ACTION_DISPLAY_DISCONNECTED events.
Functions decorated with this decorator will be called when push2-python loses connection with the Push2
display. It will have the following positional arguments:
* Push2 object instance
... | bfb4314e6da432193a0b1e9691ad60d0eb7de039 | 3,653,046 |
from typing import Union
from typing import Dict
from typing import Any
def parse_received_data(blockpage_matcher: BlockpageMatcher,
received: Union[str, Dict[str,
Any]], anomaly: bool) -> Row:
"""Parse a received field into a section of a ro... | 30a01d1b045d0f67e279cca34ade90aaf46b9c62 | 3,653,047 |
def get_filters():
""" Returns sidebar filters """
filters = {
'organisations': Organisation.objects.all(),
'topics': Topic.objects.all(),
'licenses': License.objects.all(),
'formats': Format.objects.all()
}
return filters | da137bbcd37d6504358e9e94a6722495bbc81d65 | 3,653,048 |
from xdsl.dialects.builtin import DenseIntOrFPElementsAttr, i32
import typing
from typing import List
from typing import Tuple
def irdl_op_builder(cls: typing.Type[OpT], operands: List,
operand_defs: List[Tuple[str, OperandDef]],
res_types: List, res_defs: List[Tuple[str, Resul... | 24c103897b040f2b4959b3d3c1642bc6eca6fda2 | 3,653,049 |
def _listify(single: st.SearchStrategy) -> st.SearchStrategy:
"""
Put the result of `single` strategy into a list
(all strategies should return lists)
"""
@st.composite
def listify_(draw):
return [draw(single)]
strategy = listify_()
strategy.function.__name__ = f"listified<{repr... | eb4efb742e2c465754e79ba979b69b412f6c066e | 3,653,050 |
def get_text(selector):
"""
Type the keys specified into the element, or the currently active element.
"""
if not get_instance():
raise Exception("You need to start a browser first with open_browser()")
return get_text_g(get_instance(), selector) | b2866c93b80dcf3c61b8330fb09e4af054937e0b | 3,653,051 |
from functools import partial
import time
import textwrap
def _eps(code, version, file_or_path, scale=1, module_color=(0, 0, 0),
background=None, quiet_zone=4):
"""This function writes the QR code out as an EPS document. The
code is drawn by drawing only the modules corresponding to a 1. They
are... | 65e3f4d69eea5aa0385c1b53693d164aa0f5db6d | 3,653,052 |
from typing import List
from typing import Dict
import click
def get_packager_targets(
targets: List[Target], connections: Dict[str, Connection], remote_api: ConnectionClient
) -> List[PackagerTarget]:
"""
Build targets for calling packager. Fetch and base64 decode connections by names using local man... | 1aac3748b2176f5f11ed8ed137f78d64bf01c112 | 3,653,054 |
def elina_texpr0_permute_dimensions(texpr2, dimperm):
"""
Permute dimensions of an ElinaTexpr0 following the semantics of an ElinaDimperm.
Parameters
----------
texpr2 : ElinaTexpr0Ptr
Pointer to the ElinaTexpr0 which dimensions we want to permute.
dimperm : ElinaDimpermPtr
Poin... | f9c60e6285bc4e934eddf0a0be0511f08a57f45d | 3,653,055 |
def rgb(red: int, green: int, blue: int, background: bool = False) -> Chalk:
"""Generate a new truecolor chalk from an RGB tuple.
Args:
red (int):
The intensity of red (0-255).
green (int):
The intensity of green (0-255).
blue (int):
The intensity of ... | d5c1e79cc1bf7ee37f1e1df17e9518ac0e11f02b | 3,653,056 |
def first(x: pd.Series) -> pd.Series:
"""
First value of series
:param x: time series
:return: time series of first value
**Usage**
Return series with first value of `X` for all dates:
:math:`R_t = X_0`
where :math:`X_0` is the first value in the series
**Examples**
Last v... | 1a2c856bdff7158ecd7512e43158427530cbc8e4 | 3,653,057 |
def simulate(iterations, graph_generator, graph_params, n_nodes, beta, rho, steps, n_infected_init, vacc=None):
"""Perform `iterations` simulations and compute averages. If vacc is not
None, run the simulation using the SIRV model, otherwise use SIR."""
# Initialize arrays for computing averages over simul... | 96eeb8be72ceb336d62f858337d983cc8f8d5a9d | 3,653,058 |
import urllib
import json
def lookup_location():
"""
Geolocation lookup of current position.
Determines latitude and longitude coordinates of the system's position
using the ipinfo.io service.
Returns:
Tuple (lat, lon) containing the latitude and longitude coordinates
associated ... | 5d654314aa8d53cbca2b488bb7c9eb3f1f9cf81a | 3,653,059 |
def _str_or_none(value):
"""Helper: serialize value to JSON string."""
if value is not None:
return str(value) | 7aa1550f71accaa4111386153b2c331e2ff076bc | 3,653,060 |
def create_song_graph_from_songs(songs: list[Song],
parent_graph: song_graph.SongGraph = None,
year_separation: int = 10) -> song_graph.SongGraph:
"""Create and return a song graph from a list of songs.
(Optional) Add a parent graph from a large... | 647eb1ce77cf0c596c2fabd41aa32062636ca8a4 | 3,653,061 |
def convert(secs):
"""Takes a time in seconds and converts to min:sec:msec"""
mins = int(secs // 60)
secs %= 60
msecs = int(round(((secs - int(secs)) * 1000)))
secs = int(secs)
return f'{mins} mins, {secs} secs, {msecs} msecs' | 70752f190f94d3bdb4cb3b562b6bf9d1c7d28479 | 3,653,062 |
def from_data(symbols, key_matrix, name_matrix, one_indexed=False):
""" z-matrix constructor
:param symbols: atomic symbols
:type symbols: tuple[str]
:param key_matrix: key/index columns of the z-matrix, zero-indexed
:type key_matrix: tuple[tuple[float, float or None, float or None]]
:param nam... | 5b3f98b98dca797223a95af967e9aaff311d24f8 | 3,653,063 |
def should_drop_from_right_deck(n_left: int, n_right:int, seed: int=None) -> bool:
"""
Determine whether we drop a card from the right or left sub-deck.
Either `n_left` or `n_right` (or both) must be greater than zero.
:param n_left: the number of cards in the left sub-deck.
:param n_right: the nu... | 42bbfc3c8a129f090b50c0979d95e53fd6d6a13f | 3,653,064 |
def EXPOSED(mu=1.0):
"""
matrix of exposed sites
Parameters
----------
mu: rate
"""
pis = np.array([0.088367,0.078147,0.047163,0.087976,0.004517,0.058526,0.128039,0.056993,0.024856,0.025277,0.045202,0.094639,0.012338,0.016158,0.060124,0.055346,0.051290,0.006771,0.021554,0.036718])
... | c203eb8affeddd4b2620836759acb35ae6f9114c | 3,653,066 |
async def rename_conflicting_targets(
ptgts: PutativeTargets, all_existing_tgts: AllUnexpandedTargets
) -> UniquelyNamedPutativeTargets:
"""Ensure that no target addresses collide."""
existing_addrs: set[str] = {tgt.address.spec for tgt in all_existing_tgts}
uniquely_named_putative_targets: list[Putativ... | 9ac25549de1fca5912104135b87a1a17f1cd43fe | 3,653,067 |
def outer2D(v1, v2):
"""Calculates the magnitude of the outer product of two 2D vectors, v1 and v2"""
return v1[0]*v2[1] - v1[1]*v2[0] | b1f80afa3b8537eb11d79b17d0f12903bec9387c | 3,653,068 |
from typing import Union
def get_item_indent(item: Union[int, str]) -> Union[int, None]:
"""Gets the item's indent.
Returns:
indent as a int or None
"""
return internal_dpg.get_item_configuration(item)["indent"] | a80997e8c2cfa76a76ff8d09c7308196f0572f86 | 3,653,069 |
def V_RSJ_asym(i, ic_pos, ic_neg, rn, io, vo):
"""Return voltage with asymmetric Ic's in RSJ model"""
if ic_pos < 0 or ic_neg > 0 or rn < 0:
#or abs(ic_neg/ic_pos) > 1.2 or abs(ic_pos/ic_neg) > 1.2 :
# set boundaries for fitting
#pass
v = 1e10
else:
v = np.zeros(len(i... | 5005beec6a90bf1a5054836f6f22dbe42dcda6f1 | 3,653,070 |
def h2_gas_costs(pipe_dist=-102.75, truck_dist=-106.0, pipeline=True, max_pipeline_dist=2000):
"""Calculates the transport cost of H2 gas. Requires as input the distance that H2 will be piped and
trucked."""
if max_pipeline_dist > pipe_dist > 400:
pipe = 0.0004 * pipe_dist + 0.0424
elif pipe_di... | 5b3623d33862038a9629349e8052e8214ddba51c | 3,653,071 |
from typing import Union
def number_to_words(input_: Union[int, str], capitalize: bool = False) -> str:
"""Converts integer version of a number into words.
Args:
input_: Takes the integer version of a number as an argument.
capitalize: Boolean flag to capitalize the first letter.
Returns... | 22c5f7c64354a76404150cdf888e3bc3582659f1 | 3,653,072 |
from typing import Dict
from typing import OrderedDict
def get_size_reduction_by_cropping(analyzer: DatasetAnalyzer) -> Dict[str, Dict]:
"""
Compute all size reductions of each case
Args:
analyzer: analzer which calls this property
Returns:
Dict: computed size reductions
... | ce1aad85d8f971cccc8cb0547b14be8074228261 | 3,653,073 |
import re
def getProxyFile(path):
"""
Opens a text file and returns the contents with any setting of a certificate file
replaced with the mitmproxy certificate.
"""
with open(path, "r") as fd:
contents = fd.read()
certReferences = re.findall("setcertificatesfile\(.*\)", contents, r... | c5c0d562e2b430b79b91b2a9ffd23f6d18320b6f | 3,653,074 |
def bytes_filesize_to_readable_str(bytes_filesize: int) -> str:
"""Convert bytes integer to kilobyte/megabyte/gigabyte/terabyte equivalent string"""
if bytes_filesize < 1024:
return "{} B"
num = float(bytes_filesize)
for unit in ["B", "KB", "MB", "GB"]:
if abs(num) < 1024.0:
... | cdeb228de80422f541c5fa682422d77a44d19ca2 | 3,653,075 |
def braf_mane_data():
"""Create test fixture for BRAF MANE data."""
return {
"#NCBI_GeneID": "GeneID:673",
"Ensembl_Gene": "ENSG00000157764.14",
"HGNC_ID": "HGNC:1097",
"symbol": "BRAF",
"name": "B-Raf proto-oncogene, serine/threonine kinase",
"RefSeq_nuc": "NM_00... | 7e62545147ef1a6f81c75e56d85f5ab8df3895e8 | 3,653,076 |
def import_class(path):
"""
Import a class from a dot-delimited module path. Accepts both dot and
colon seperators for the class portion of the path.
ex::
import_class('package.module.ClassName')
or
import_class('package.module:ClassName')
"""
if ':' in path:
m... | dcdf71a3bb665dae1fe5913e19be3a4c0aa3c5d3 | 3,653,078 |
import torch
def elastic(X, kernel, padding, alpha=34.0):
# type: (Tensor, Tensor, int, float) -> Tensor
"""
X: [(N,) C, H, W]
"""
H, W = X.shape[-2:]
dx = torch.rand(X.shape[-2:], device=kernel.device) * 2 - 1
dy = torch.rand(X.shape[-2:], device=kernel.device) * 2 - 1
xgrid = torch... | 580c9600cb4ddd77d114ae94303fc2c2a416cf17 | 3,653,079 |
def fixture_make_bucket(request):
"""
Return a factory function that can be used to make a bucket for testing.
:param request: The Pytest request object that contains configuration data.
:return: The factory function to make a test bucket.
"""
def _make_bucket(s3_stub, wrapper, bucket_name, reg... | bdfbbad1b80f43a1b81f5bf8f69db350128e3304 | 3,653,080 |
def get_member_struc(*args):
"""
get_member_struc(fullname) -> struc_t
Get containing structure of member by its full name "struct.field".
@param fullname (C++: const char *)
"""
return _ida_struct.get_member_struc(*args) | ac2c226725af8bde1510a6f7fd2fdb64a8c52d01 | 3,653,081 |
from datetime import datetime
def pop():
"""Check the first task in redis(which is the task with the smallest score)
if the score(timestamp) is smaller or equal to current timestamp, the task
should be take out and done.
:return: True if task is take out, and False if it is not the time.
"""
... | 0472d0bcffee84547d7ee400d547ecbb86e50e87 | 3,653,082 |
def xml_to_dictform(node):
""" Converts a minidom node to "dict" form. See parse_xml_to_dictform. """
if node.nodeType != node.ELEMENT_NODE:
raise Exception("Expected element node")
result = (node.nodeName, {}, []) # name, attrs, items
if node.attributes != None:
attrs = node.attribut... | 8fdc07070a32eb34c38e46cb12d23d367d71c606 | 3,653,083 |
def TranslateCoord(data, res, mode):
"""
Translates position of point to unified coordinate system
Max value in each direction is 1.0 and the min is 0.0
:param data: (tuple(float, float)) Position to be translated
:param res: (tuple(float, float)) Target resolution
:param mode: (TranslationMode) Work mode. Availa... | c89515692330ce02c0f6f371c16a9028c51e9bbe | 3,653,084 |
def _get_mutator_plugins_bucket_url():
"""Returns the url of the mutator plugin's cloud storage bucket."""
mutator_plugins_bucket = environment.get_value('MUTATOR_PLUGINS_BUCKET')
if not mutator_plugins_bucket:
logs.log_warn('MUTATOR_PLUGINS_BUCKET is not set in project config, '
'skipping c... | 31073e1fbaf817d63d02de93a2fc224bd2904dec | 3,653,085 |
from io import StringIO
def objectify_json_lines(path_buf_stream,
from_string=False,
fatal_errors=True,
encoding=_DEFAULT_ENCODING,
ensure_ascii=False,
encode_html_chars=False,
... | a3de3cd8f13c7a245573bd34944e67908dfd4786 | 3,653,086 |
def gll_int(f, a, b):
"""Integrate f from a to b using its values at gll points."""
n = f.size
x, w = gll(n)
return 0.5*(b-a)*np.sum(f*w) | d405e4c3951f9764077508fcdb73e000c107e4d4 | 3,653,087 |
def _get_remote_user():
"""
Get the remote username.
Returns
-------
str: the username.
"""
return input('\nRemote User Name: ') | 5f2bb67b5f55ec053a755c015755f488ab6d8c71 | 3,653,089 |
def nf_regnet_b4(pretrained=False, **kwargs):
""" Normalization-Free RegNet-B4
`Characterizing signal propagation to close the performance gap in unnormalized ResNets`
- https://arxiv.org/abs/2101.08692
"""
return _create_normfreenet('nf_regnet_b4', pretrained=pretrained, **kwargs) | 642ba43a132128a16273bb6cc76178b71be6beaf | 3,653,092 |
from typing import Tuple
def load_data_binary_labels(path: str) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Loads data from CSV file and returns features (X) and
only binary labels meaning (any kind of) toxic or not"""
df = pd.read_csv(path)
X = df.comment_text.to_frame()
y = df[config.LIST_CLASSES]... | e73b99b2d00d388298f9f6e2cdfca15f121a0238 | 3,653,093 |
from bs4 import BeautifulSoup
def parse(html_url):
"""Parse."""
html = www.read(html_url)
soup = BeautifulSoup(html, 'html.parser')
data = {'paragraphs': []}
content = soup.find('div', class_=CLASS_NAME_CONTENT)
for child in content.find_all():
text = _clean(child.text)
if c... | 226245618d220db00eb2f298aaf462c1c861c32b | 3,653,094 |
import logging
def get_tp_algorithm(name: str) -> GenericTopologyProgramming:
""" returns the requested topology programming instance """
name = name.lower()
if name == "uniform_tp":
return UniformTP()
if name == "joint_tp":
return JointTP()
if name == "ssp_oblivious_tp":
r... | 6f98613c13becf1ed85cb8a667fc35cfac86973f | 3,653,095 |
def get_first_job_queue_with_capacity():
"""Returns the first job queue that has capacity for more jobs.
If there are no job queues with capacity, returns None.
"""
job_queue_depths = get_job_queue_depths()["all_jobs"]
for job_queue in settings.AWS_BATCH_QUEUE_WORKERS_NAMES:
if job_queue_de... | a23bf9dcef39d1377a1d7cb2a37abbe1186fac0a | 3,653,096 |
def rotations(images, n_rot, ccw_limit, cw_limit):
"""
Rotates every image in the list "images" n_rot times, between 0 and cw_limit
(clockwise limit) n_rot times and between 0 and ccw_limit (counterclockwise
limit) n_rot times more. The limits are there to make sense of the data
augmentation. E.g: Rotating an... | b1ca7a609faa6ed8903424976b94b477a4798096 | 3,653,097 |
def num_range(num):
"""
Use in template language to loop through numberic range
"""
return range(num) | 7b66e4ffd264ea7b49850a9300c3a6c80282fce1 | 3,653,098 |
def datamodel_flights_column_names():
"""
Get FLIGHTS_CSV_SCHEMA column names (keys)
:return: list
"""
return list(FLIGHTS_CSV_SCHEMA.keys()) | 6e5edfa181e02955976602a289576eca307a13bc | 3,653,099 |
def create_tomography_circuits(circuit, qreg, creg, tomoset):
"""
Add tomography measurement circuits to a QuantumProgram.
The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography... | ab42a0b57ccd94f6ffbb64425473c3a90dd10888 | 3,653,100 |
def filter_background(bbox, bg_data):
"""
Takes bounding box and background geojson file assumed to be the US states, and outputs a geojson-like dictionary
containing only those features with at least one point within the bounding box, or any state that completely
contains the bounding box.
This te... | f06fe5efe1e3920d8b1092601a121e313da4eec4 | 3,653,101 |
def rename_columns(table, mapper):
""" Renames the table headings to conform with the ketos naming convention.
Args:
table: pandas DataFrame
Annotation table.
mapper: dict
Dictionary mapping the headings of the input table to the
stan... | c9c9228f4f477b8d5ade234964c2540fd20ddd09 | 3,653,102 |
from typing import Union
import json
def parse_tuple(s: Union[str, tuple]) -> tuple:
"""Helper for load_detections_csv, to parse string column into column of Tuples."""
if isinstance(s, str):
result = s.replace("(", "[").replace(")", "]")
result = result.replace("'", '"').strip()
resul... | ad568bfc8ccdf8440378e852daccaf2f24a7e2d0 | 3,653,104 |
import re
def clean(tweet):
"""
clean tweet text by removing links, special characters
using simple regex statements
Parameters
----------
tweet : String
Single Twitter message
Returns
-------
tokenized_tweet : List
List of cleaned tokens derived from the input Twitter messa... | fbfacb49f88638610fb071cb6b14d02dadf665e1 | 3,653,105 |
def predict(x, u):
"""
:param x: Particle state (x,y,theta) [size 3 array]
:param u: Robot inputs (u1,u2) [size 2 array]
:return: Particle's updated state sampled from the motion model
"""
x = x + motionModel(x, u) + np.random.multivariate_normal(np.zeros(3), Q)
return x | 7fe3e9fa42e1e74ac448a0139ca6dae8ff5388ad | 3,653,106 |
def plot_multiple(datasets, method='scatter', pen=True, labels=None, **kwargs):
"""
Plot a series of 1D datasets as a scatter plot
with optional lines between markers.
Parameters
----------
datasets : a list of ndatasets
method : str among [scatter, pen]
pen : bool, optional, default: T... | 85b41b719cb8d33884dd7364b3e0937100167c6a | 3,653,107 |
def _scale_enum(anchor, scales):
""" 列举关于一个anchor的三种尺度 128*128,256*256,512*512
Enumerate a set of anchors for each scale wrt an anchor.
"""
w, h, x_ctr, y_ctr = _whctrs(anchor) #返回宽高和中心坐标,w:16,h:16,x_ctr:7.5,y_ctr:7.5
ws = w * scales #[128 256 512]
hs = h * scales #[128 256 512]
anchor... | b0b8e9418b935daf2961fbd690a4ccf2b6bd6d7b | 3,653,108 |
import codecs
def metamodel_from_file(file_name, **kwargs):
"""
Creates new metamodel from the given file.
Args:
file_name(str): The name of the file with textX language description.
other params: See metamodel_from_str.
"""
with codecs.open(file_name, 'r', 'utf-8') as f:
... | 526a1876ed11aff2341133d061573ae9f3bfb1fe | 3,653,109 |
import sirepo.template
import copy
def _python(data):
"""Generate python in current directory
Args:
data (dict): simulation
Returns:
py.path.Local: file to append
"""
template = sirepo.template.import_module(data)
res = pkio.py_path('run.py')
res.write(template.python_so... | df0d2eae8155f1093dde02db73fd5185983d6847 | 3,653,110 |
def load_hosts_conf(path='/etc/hosts'):
"""parse hosts file"""
hosts = {}
try:
with open(path, 'r') as f:
for line in f.readlines():
parts = line.strip().split()
if len(parts) < 2:
continue
addr = ip_address(parts[0])
... | c6e2d1f34f5aa140a3bccfbd4d9791641cc75fff | 3,653,111 |
import random
def _waveform_distortion(waveform, distortion_methods_conf):
""" Apply distortion on waveform
This distortion will not change the length of the waveform.
Args:
waveform: numpy float tensor, (length,)
distortion_methods_conf: a list of config for ditortion method.
... | cca32854f3d72f381d40a5ca8802c29996413149 | 3,653,114 |
def _pad_returns(returns):
"""
Pads a returns Series or DataFrame with business days, in case the
existing Date index is sparse (as with PNL csvs). Sparse indexes if not
padded will affect the Sharpe ratio because the 0 return days will not be
included in the mean and std.
"""
bdays = pd.dat... | fde27dd928d3f0510f98fa4eba8f89f7d6b81922 | 3,653,115 |
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public... | 3a758340d1c13cc29f0013f3d2fec77c47099c02 | 3,653,116 |
def pair_sorter(aln):
"""Get the alignment name and attributes for sorting."""
return (
aln.name,
not aln.first_in_pair,
aln.unmapped,
aln.supplementary_alignment,
aln.secondary_alignment) | 217eac7c89a12f68f4c9fe324c4feb6c2a955d58 | 3,653,117 |
def project_to2d(
pts: np.ndarray, K: np.ndarray, R: np.ndarray, t: np.ndarray
) -> np.ndarray:
"""Project 3d points to 2d.
Projects a set of 3-D points, pts, into 2-D using the camera intrinsic
matrix (K), and the extrinsic rotation matric (R), and extrinsic
translation vector (t). Note that this ... | 5f9bc03ae0086649746651da4e5e8e1d870db6bd | 3,653,119 |
import copy
def uncontract_general(basis, use_copy=True):
"""
Removes the general contractions from a basis set
The input basis set is not modified. The returned basis
may have functions with coefficients of zero and may have duplicate
shells.
If use_copy is True, the input basis set is not ... | de6638ae34b4d6f0b3a467048683ac363f71f9c1 | 3,653,120 |
def read_sd15ch1_images(root_dir,
image_relative_path_seq,
resize=None,
color=False):
"""
WARNING
-------
- All images must have the same shape (this is the case for the frames, and all models but the
ones of the "01-origina... | 0d6efd2eac2762440ae532564e4f680a1f056d30 | 3,653,121 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.