content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_new_listing(old_listing):
"""Get the new listing."""
try:
fetched_listing = requests.get(cfg['api_url']).json()['product']
except requests.exceptions.RequestException:
return old_listing
else:
old_item_ids = {old_item['productId'] for old_item in old_listing}
new_... | 35,000 |
def tracks(lonp, latp, fname, grid, fig=None, ax=None, Title=None):
"""
Plot tracks as lines with starting points in green and ending points in
red.
Args:
lonp,latp: Drifter track positions [time x ndrifters]
fname: Plot name to save
"""
if fig is None:
fig = plt.figure... | 35,001 |
def parse_numpy():
"""Yield a function to parse Numpy docstrings.
Yields:
A parser function.
"""
yield from parser(numpy) | 35,002 |
def setup_logging(root_folder, log_level=None, env_key="LOG_CFG"):
"""Setup logging configuration
"""
default_path = root_folder + '/logging.yaml'
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
... | 35,003 |
def create_user(engine: create_engine, data: dict) -> Union[User, None]:
"""
Function for creating row in database
:param engine: sqlmodel's engine
:param data: dictionary with data that represents user
:return: Created user instance or nothing
"""
logging.info('Creating an user')
user =... | 35,004 |
def _densify_2D(a, fact=2):
"""Densify a 2D array using np.interp.
:fact - the factor to density the line segments by
:Notes
:-----
:original construction of c rather than the zero's approach
: c0 = c0.reshape(n, -1)
: c1 = c1.reshape(n, -1)
: c = np.concatenate((c0, c1), 1)
... | 35,005 |
def conf_paths(filename) -> list:
"""Get config paths"""
home = os.path.expanduser('~')
paths = [path.format(home=home, filename=filename) for path in
PATH_TEMPLATES]
return paths | 35,006 |
def get_neighbor_edge(
graph: srf.Alignment,
edge: tuple[int, int],
column: str = 'z',
direction: str = 'up',
window: Union[None, int] = None,
statistic: str = 'min'
) -> Union[None, tuple[int, int]]:
"""Return the neighboring edge having the lowest minimum value
Parameters:
gra... | 35,007 |
def show_comparison(x_coordinates: np.ndarray, analytic_expression: callable, numeric_solution: [dict, np.ndarray],
numeric_label: str = "Numeric Solution", analytic_label: str = "Analytic Solution",
title: str = None, x_label: str = None, y_label: str = None, save_file_as: str =... | 35,008 |
async def fixt_db(fixt_redis_client):
"""Actual fixture for requests working with db."""
await start_gino()
yield
await stop_gino() | 35,009 |
def has_master(mc: MasterCoordinator) -> bool:
""" True if `mc` has a master. """
return bool(mc.sc and not mc.sc.master and mc.sc.master_url) | 35,010 |
def sz_margin_details(date='', retry_count=3, pause=0.001):
"""
获取深市融资融券明细列表
Parameters
--------
date:string
明细数据日期 format:YYYY-MM-DD 默认为空''
retry_count : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
... | 35,011 |
def delay_slot_insn(*args):
"""
delay_slot_insn(ea, bexec, fexec) -> bool
Helper function to get the delay slot instruction.
@param ea (C++: ea_t *)
@param bexec (C++: bool *)
@param fexec (C++: bool *)
"""
return _ida_idp.delay_slot_insn(*args) | 35,012 |
def decode_argument(params, word_embeddings, argument_extractors):
"""
:type params: dict
:type word_embeddings: nlplingo.embeddings.WordEmbedding
:type argument_extractors: list[nlplingo.nn.extractor.Extractor] # argument extractors
"""
if len(argument_extractors) == 0:
raise RuntimeErr... | 35,013 |
def pairwise_radial_basis(K: numpy.ndarray, B: numpy.ndarray) -> numpy.ndarray:
"""Compute the TPS radial basis function phi(r) between every row-pair of K
and B where r is the Euclidean distance.
Arguments
---------
K : numpy.array
n by d vector containing n d-dimensional points.
... | 35,014 |
def low_index_subgroups(G, N, Y=[]):
"""
Implements the Low Index Subgroups algorithm, i.e find all subgroups of
``G`` upto a given index ``N``. This implements the method described in
[Sim94]. This procedure involves a backtrack search over incomplete Coset
Tables, rather than over forced coinciden... | 35,015 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the sensor platform."""
client = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT]
coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATO... | 35,016 |
def test_cli_direct_task_ansible_21_min(capsys):
"""
Test cli direct task
"""
ansible_galaxy_cli.main('aci-ansible-galaxy direct')
out, err = capsys.readouterr()
assert err == '' # nosec
assert 'Usage: ansible-galaxy' in out | 35,017 |
def ifft_complex(fft_sig_complex) -> np.ndarray:
"""
Compute the one-dimensional inverse discrete Fourier Transform.
:param fft_sig_complex: input array, can be complex.
:return: the truncated or zero-padded input, transformed along the axis
"""
ifft_sig = np.fft.ifft(fft_sig_complex)
fft_p... | 35,018 |
def merge_eopatches(*eopatches, features=..., time_dependent_op=None, timeless_op=None):
""" Merge features of given EOPatches into a new EOPatch
:param eopatches: Any number of EOPatches to be merged together
:type eopatches: EOPatch
:param features: A collection of features to be merged together. By ... | 35,019 |
def plot_each_ring_mean_intensityc( times, mean_int_sets, xlabel= 'Frame',save=False, *argv,**kwargs):
"""
Plot time dependent mean intensity of each ring
"""
num_rings = mean_int_sets.shape[1]
fig, ax = plt.subplots(figsize=(8, 8))
uid = 'uid'
if 'uid' in kwargs.keys():
... | 35,020 |
def parse_args():
"""Parse cli arguments."""
parser = argparse.ArgumentParser(description="Java project package name changer.")
parser.add_argument("--directory", default=".", type=str, help="Working directory.")
parser.add_argument(
"--current",
required=True,
type=str,
... | 35,021 |
def dispos(dra0, decd0, dra, decd):
"""
Source/credit: Skycat
dispos computes distance and position angle solving a spherical
triangle (no approximations)
INPUT :coords in decimal degrees
OUTPUT :dist in arcmin, returns phi in degrees (East of North)
AUTHOR :a.p.martinez... | 35,022 |
def bind_port(sock, host=HOST):
"""Bind the socket to a free port and return the port number. Relies on
ephemeral ports in order to ensure we are using an unbound port. This is
important as many tests may be running simultaneously, especially in a
buildbot environment. This method raises an exception... | 35,023 |
def node_to_html(node: Union[str, NodeElement, list]) -> str:
"""
Convert Nodes to HTML
:param node:
:return:
"""
if isinstance(node, str): # Text
return escape(node)
elif isinstance(node, list): # List of nodes
result = ''
for child_node in node:
resu... | 35,024 |
def cli(
topology: PathLike,
trajectory: List[str],
reference: PathLike,
outfile: PathLike,
logfile: PathLike,
step: int,
mask: str,
tol: float,
verbose: bool,
) -> None:
"""Align a trajectory to average structure using Kabsch fitting."""
start_time: float = time.perf_counter... | 35,025 |
def cuda_reshape(a, shape):
""" Reshape a GPUArray.
Parameters:
a (gpu): GPUArray.
shape (tuple): Dimension of new reshaped GPUArray.
Returns:
gpu: Reshaped GPUArray.
Examples:
>>> a = cuda_reshape(cuda_give([[1, 2], [3, 4]]), (4, 1))
array([[ 1.],
... | 35,026 |
async def test_multiple_store_function_race_condition(
db: sqlalchemy.orm.Session, async_client: httpx.AsyncClient
):
"""
This is testing the case that the retry_on_conflict decorator is coming to solve, see its docstring for more details
"""
await tests.api.api.utils.create_project_async(async_clie... | 35,027 |
def test_ep_basic_equivalence(stateful, state_tuple, limits):
"""
Test that EpisodeRoller is equivalent to a
BasicRoller when run on a single environment.
"""
def env_fn():
return SimpleEnv(3, (4, 5), 'uint8')
env = env_fn()
model = SimpleModel(env.action_space.low.shape,
... | 35,028 |
def test_styles(patch_click, message, kwargs, supported):
""" Test to ensure the ClickLogger is sytling messges correctly """
# uses click.style to make the expected formatted string
if supported:
expected_output = click.style(message, **kwargs)
else:
expected_output = message
# log... | 35,029 |
def _find_crate_root_src(srcs, file_names=["lib.rs"]):
"""Finds the source file for the crate root."""
if len(srcs) == 1:
return srcs[0]
for src in srcs:
if src.basename in file_names:
return src
fail("No %s source file found." % " or ".join(file_names), "srcs") | 35,030 |
def decode_check(string):
"""Returns the base58 decoded value, verifying the checksum.
:param string: The data to decode, as a string.
"""
number = b58decode(string)
# Converting to bytes in order to verify the checksum
payload = number.to_bytes(sizeof(number), 'big')
if payload and sha256d... | 35,031 |
def rotate(origin, point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
"""
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) *... | 35,032 |
def get_users_info(token, ids):
"""Return a response from vk api users.get
:param token: access token
:param ids: users ids
:return: dict with users info
"""
args = {
'user_ids': ids,
'fields': 'city,bdate,connections,photo_200',
'access_token': token,
'v': set... | 35,033 |
def train_aggressive(batch, kl_coef=1, teacher_forcing=1, max_iter=20):
"""
Train the encoder part aggressively
:param batch: *first* batch of data, each entry correspond to a word.
:param kl_coef: weight of KL divergence term in loss.
:param teacher_forcing: rate of teacher forcing, default=1.... | 35,034 |
def _receive_release_rq(event):
"""Standard logging handler for receiving an A-RELEASE-RQ PDU."""
pass | 35,035 |
def create_consistencygroup(ctxt,
host='test_host@fakedrv#fakepool',
name='test_cg',
description='this is a test cg',
status='available',
availability_zone='fake_az',
... | 35,036 |
def hex(generator):
"""
Decorator for transactions' and queries generators.
Allows preserving the type of binaries for Binary Testing Framework.
"""
prefix = 'T' if generator.__name__.lower().endswith('tx') else 'Q'
print('{}{}'.format(prefix, binascii.hexlify(generator().SerializeToString()).d... | 35,037 |
def test_verify_file(monkeypatch, capsys):
"""
.
"""
device = Device()
device.set("device", "/dev", "Device Serial", "ABCDEF", 1)
file_obj = File()
file_obj.set_properties("test", "path", "abc")
file_obj.set_security("644", "owner", "group")
file_obj.device_name = device.device_name... | 35,038 |
def ndigit(num):
"""Returns the number of digits in non-negative number num"""
with nowarn(): return np.int32(np.floor(np.maximum(1,np.log10(num))))+1 | 35,039 |
def data_store_folder_unzip_public(request, pk, pathname):
"""
Public version of data_store_folder_unzip, incorporating path variables
:param request:
:param pk:
:param pathname:
:return HttpResponse:
"""
return data_store_folder_unzip(request, res_id=pk, zip_with_rel_path=pathname) | 35,040 |
def privateDataOffsetLengthTest10():
"""
Offset doesn't begin immediately after last table.
>>> doctestFunction1(testPrivateDataOffsetAndLength, privateDataOffsetLengthTest10())
(None, 'ERROR')
"""
header = defaultTestData(header=True)
header["privOffset"] = header["length"] + 4
header[... | 35,041 |
def meanncov(x, y=[], p=0, norm=True):
"""
Wrapper to multichannel case of new covariance *ncov*.
Args:
*x* : numpy.array
multidimensional data (channels, data points, trials).
*y* = [] : numpy.array
multidimensional data. If not given the autocovariance of *x*
will... | 35,042 |
def nasnet_6a4032(**kwargs):
"""
NASNet-A 6@4032 (NASNet-A-Large) model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
... | 35,043 |
def start_mining():
"""
Start the mining process.
Get query, or use standard.
Execute mining.
"""
query = raw_input("input search query, press enter for standard. \n")
if query == '':
# all tweets containing one of the words and not 'RT'
query = "Finance OR Investment OR Econ... | 35,044 |
def get_character_card(character_id, preston, access_token):
"""Get all the info for the character card.
Args:
character_id (int): ID of the character.
preston (preston): Preston object to make scope-required ESI calls.
access_token (str): Access token for the scope-required ESI calls.
... | 35,045 |
def expand_ALL_constant(model, fieldnames):
"""Replaces the constant ``__all__`` with all concrete fields of the model"""
if "__all__" in fieldnames:
concrete_fields = []
for f in model._meta.get_fields():
if f.concrete:
if f.one_to_one or f.many_to_many:
... | 35,046 |
def add_image_profile_row(form):
"""
Generates html component of configuration dropdowns
"""
_label = LABEL(SPAN('Template:', ' ', SPAN('*', _class='fld_required'), ' '))
select = SELECT(_name='image_profile', _id='request_queue_image_profile')
idx=1
for imageprofile in getImagePr... | 35,047 |
def generate_all_documents(course, timestamps):
"""A generator for all docs for a given course.
Args:
course: models.courses.Course. the course to be indexed.
timestamps: dict from doc_ids to last indexed datetimes. An empty dict
indicates that all documents should be generated.
... | 35,048 |
def server(user, password):
"""A shortcut to use MailServer.
SMTP:
server.send_mail([recipient,], mail)
POP3:
server.get_mail(which)
server.get_mails(subject, sender, after, before)
server.get_latest()
server.get_info()
server.stat()
Parse mail:
... | 35,049 |
def get_rackspace_token(username, apikey):
"""Get Rackspace Identity token.
Login to Rackspace with cloud account and api key from environment vars.
Returns dict of the token and tenant id.
"""
auth_params = {
"auth": {
"RAX-KSKEY:apiKeyCredentials": {
"username"... | 35,050 |
def calculate_hessian(model, data, step_size):
"""
Computes the mixed derivative using finite differences mathod
:param model: The imported model module
:param data: The sampled data in structured form
:param step_size: The dx time step taken between each
:returns: mixed derivative
"""
hessian = pd.... | 35,051 |
def get_quarterly_income_statements(symbol):
"""
Returns quarterly IS for the past 5 yrs.
"""
df = query_av(function="INCOME_STATEMENT", symbol=symbol, datatype='quarterlyReports')
return df | 35,052 |
def BRepBlend_HCurve2dTool_IsPeriodic(*args):
"""
:param C:
:type C: Handle_Adaptor2d_HCurve2d &
:rtype: bool
"""
return _BRepBlend.BRepBlend_HCurve2dTool_IsPeriodic(*args) | 35,053 |
def moveZeroesB(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nonzeroes = [x for x in nums if x != 0]
if nonzeroes and len(nonzeroes) < len(nums):
nums[:len(nonzeroes)] = nonzeroes
nums[len(nonzeroes):] = [0] * (len(nums) - len(nonzeroes)) | 35,054 |
def plot_signle_affinity_map(name, origin_affinity_map_index_onepatch, softmax=False):
"""prob_vect_index: [vc_dict_size, kernel, kernel]
"""
vc_dict_size, kernel, kernel = origin_affinity_map_index_onepatch.shape
origin_affinity_map_index_onepatch = origin_affinity_map_index_onepatch.view(vc_dict_size,... | 35,055 |
def ParagraphEditor(TargetDocument, Keyword, Value, OutputFile):
"""
**TargetDocument: str of the location and file name
**Keyword: list of the keyword that will be replaced
**Value: list of the desired value
**OutputFile: str of the location and file name (replaces files with the same name)
... | 35,056 |
def HLRBRep_SurfaceTool_OffsetValue(*args):
"""
:param S:
:type S: Standard_Address
:rtype: float
"""
return _HLRBRep.HLRBRep_SurfaceTool_OffsetValue(*args) | 35,057 |
def update_cv_validation_info(test_validation_info, iteration_validation_info):
"""
Updates a dictionary with given values
"""
test_validation_info = test_validation_info or {}
for metric in iteration_validation_info:
test_validation_info.setdefault(metric, []).append(iteration_validation_... | 35,058 |
def epoch_to_datetime(epoch: str) -> datetime:
"""
:param epoch:
:return:
"""
return datetime.datetime.fromtimestamp(int(epoch) / 1000) | 35,059 |
def calculate_log_odds(
attr: Tensor,
k: float,
replacement_emb: Tensor,
model,
input_emb: Tensor,
attention_mask: Tensor,
prediction: Tensor,
) -> float:
"""
Log-odds scoring of an attribution
:param attr: Attribution scores for one sentence
:param k: top-k value (how many ... | 35,060 |
async def wallet_config(
context: InjectionContext, provision: bool = False
) -> Tuple[Profile, DIDInfo]:
"""Initialize the root profile."""
mgr = context.inject(ProfileManager)
settings = context.settings
profile_cfg = {}
for k in CFG_MAP:
pk = f"wallet.{k}"
if pk in settings:... | 35,061 |
def nodePreset(atr="string",ctm="string",delete="[name, string]",ex="[name, string]",ivn="string",ls="name",ld="[name, string]",sv="[name, string]"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/nodePreset.html
-----------------------------------------
nodePreset is NOT undoable... | 35,062 |
def parse_ini(path):
"""Simple ini as config parser returning the COHDA protocol."""
config = configparser.ConfigParser()
try:
config.read(path)
return True, ""
except (
configparser.NoSectionError,
configparser.DuplicateSectionError,
configparser.DuplicateOptionE... | 35,063 |
def setup_logging(args):
"""Setup logging handlers based on arguments
"""
handler = logging.StreamHandler()
handler.setFormatter(LOG_FORMAT)
if args.debug:
handler.setLevel(logging.DEBUG)
elif args.quiet:
handler.setLevel(logging.WARNING)
else:
handler.setLevel(loggin... | 35,064 |
def number_of_positional_args(fn):
"""Return the number of positional arguments for a function, or None if the number is variable.
Looks inside any decorated functions."""
try:
if hasattr(fn, "__wrapped__"):
return number_of_positional_args(fn.__wrapped__)
if any(p.kind == p.VAR_... | 35,065 |
def run_tests(args=None):
"""This can be executed from within an "if __name__ == '__main__'" block
to execute the tests found in that module.
"""
if args is None:
args = []
sys.exit(main(list(args) + [__import__('__main__').__file__])) | 35,066 |
def complete_charges():
"""
Update the state of all charges in progress.
"""
for charge in Charge.objects.filter(state=Charge.CREATED):
charge.retrieve() | 35,067 |
def check_space(space):
""" Check the properties of an environment state or action space """
if isinstance(space, spaces.Box):
dim = space.shape
discrete = False
elif isinstance(space, spaces.Discrete):
dim = space.n
discrete = True
else:
raise NotImplementedErr... | 35,068 |
def finish_work(state):
"""Move all running nodes to done"""
state.progress.done = state.progress.done | state.progress.running
state.progress.running = set()
return state | 35,069 |
def show_submit_form(context, task, user, redirect, show_only_source=False):
"""Renders submit form for specified task"""
context["task"] = task
context["competition_ignored"] = user.is_competition_ignored(task.round.semester.competition)
context["constants"] = constants
context["redirect_to"] = red... | 35,070 |
def getkey(key="foo"):
"""
Returns the latest version of the key on the hosts specified
"""
row = re.compile(r'version ([\d\.]+), value: (.*)', re.I)
data = execute(_getkey, key)
table = []
for host, line in data.items():
match = row.match(line)
if match is None:
... | 35,071 |
def index_of_masked_word(sentence, bert):
"""Return index of the masked word in `sentence` using `bert`'s' tokenizer.
We use this function to calculate the linear distance between the target
and controller as BERT sees it.
Parameters
----------
sentence : str
Returns
-------
int
... | 35,072 |
def _get_headers():
"""Get headers for GitHub API request.
Attempts to add a GitHub token to headers if available.
Returns:
dict: The headers for a GitHub API request.
"""
headers = {}
github_token = os.getenv(env.GH_TOKEN, None)
if github_token is not None:
headers['Author... | 35,073 |
def vgg19(down=8, bn=False, o_cn=1, final='abs'):
"""VGG 19-layer model (configuration "E")
model pre-trained on ImageNet
"""
model = VGG(make_layers(cfg['E'], batch_norm=False), down=down, o_cn=o_cn, final=final)
model.load_state_dict(model_zoo.load_url(model_urls['vgg19']), strict=False)
r... | 35,074 |
def get_short_link_from_vk(login: str, password: str, link: str) -> str:
"""
Функция для получения короткой ссылки используя сервис vk.
"""
from vk_auth__requests_re import auth
session, rs = auth(login, password)
# Страница нужна чтобы получить hash для запроса
rs = session.get('https://... | 35,075 |
def student_list(request):
"""
List all students, or create a new student.
"""
if request.method == 'GET':
students = Student.objects.all()
serializer = StudentSerializer(students, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer ... | 35,076 |
def get_model_features(url, chromedriver):
"""For given model url, grab categories and tags for that model"""
try:
BROWSER.get(url)
time.sleep(5)
cats = BROWSER.find_elements_by_xpath("//section[@class='model-meta-row categories']//ul//a")
cats = [cat.text for cat in cats]
... | 35,077 |
def sent2labels(sent):
"""
Extracts gold labels for each sentence.
Input: sentence list
Output: list with labels list for each token in the sentence
"""
# gold labels at index 18
return [word[18] for word in sent] | 35,078 |
def get_course_id_from_capa_module(capa_module):
"""
Extract a stringified course run key from a CAPA module (aka ProblemBlock).
This is a bit of a hack. Its intended use is to allow us to pass the course id
(if available) to `safe_exec`, enabling course-run-specific resource limits
in the safe exe... | 35,079 |
def find_free_box_id() -> str:
"""
limits = prog_info["limits"] if "limits" in prog_info else {}
Returns is of the first available sandbox directory. Searched for
non-existing directories in /tmp/box.
"""
# Search for free id in EXEC_PATH
ids = [True for i in range(MAX_CONCURRENT_EXEC)]
... | 35,080 |
def _gershgorin_circles_test(expr, var_to_idx):
"""Check convexity by computing Gershgorin circles without building
the coefficients matrix.
If the circles lie in the nonnegative (nonpositive) space, then the matrix
is positive (negative) definite.
Parameters
----------
expr : QuadraticExp... | 35,081 |
def generate(env):
"""
Add Builders and construction variables for CUDA compilers to an Environment.
"""
# create builders that make static & shared objects from .cu files
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CUDASuffixes:
# Add this suffix to the lis... | 35,082 |
def make_papers(
*,
n_papers: int,
authors: AuthorList,
funders: FunderList,
publishers: PublisherList,
fields_of_study: List,
faker: Faker,
min_title_length: int = 2,
max_title_length: int = 10,
min_authors: int = 1,
max_authors: int = 10,
min_funders: int = 0,
max_f... | 35,083 |
def test_pid_downarrow4():
"""
"""
d = bivariates['boom']
pid = PID_downarrow(d)
assert pid[((0,), (1,))] == pytest.approx(0.20751874963942218, abs=1e-4)
assert pid[((0,),)] == pytest.approx(0.45914791702724433, abs=1e-4)
assert pid[((1,),)] == pytest.approx(0.33333333333333348, abs=1e-4)
... | 35,084 |
def parse_cypher_file(path: str):
"""Returns a list of cypher queries in a file. Comments (starting with "//") will be filtered out and queries needs to be seperated by a semilicon
Arguments:
path {str} -- Path to the cypher file
Returns:
[str] -- List of queries
"""
def chop_comm... | 35,085 |
def del_method():
"""del: Cleanup an item on destroy."""
# use __del__ with caution
# it is difficult to know when the object will be actually removed
context = ""
class _Destroyable:
def __del__(self):
nonlocal context
context = "burn the lyrics"
item = _Dest... | 35,086 |
def DevoilerConversation(vals,elements):
"""Reveal hidden discussion topic"""
#location id, conversation id
#basically, set a variable
#location id and/or conversation id might be expressions
vals["postcode"] = "set convo_hidden_%s_%s false\n"%(elements[0],elements[1]) | 35,087 |
def main():
"""
Main program
"""
conn = pycovenantsql.connect(**DB_CONFIG)
with conn.cursor() as cursor:
# Create a new table
sql_create_table = """
CREATE TABLE IF NOT EXISTS `users` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`created_at` DATETIME NOT... | 35,088 |
def plot_planar_polar_positions(filename):
"""Process data as x vs y"""
x = []
y = []
with open(filename) as data_file:
odom_data = csv.reader(data_file)
for row in odom_data:
x.append(float(row[0]) * cos(float(row[1])))
y.append(float(row[0]) * sin(float(row[1]))... | 35,089 |
def sample_user(email="test@local.com", password="testpass"):
"""Create a sample User"""
return get_user_model().objects.create_user(email, password) | 35,090 |
async def test_vec_add(dut):
""" Test Vector Adder """
# Create a 10us period clock on port clk
clock = Clock(dut.clk_i, 10, units="us")
cocotb.fork(clock.start())
# Reset system
await FallingEdge(dut.clk_i)
dut.rst_n_i <= 0
dut.data0_i <= np2bv(np.zeros(shape=DUT_VECTOR_SIZE, dtype=np.... | 35,091 |
def _precedence(match):
"""
in a dict spec, target-keys may match many
spec-keys (e.g. 1 will match int, M > 0, and 1);
therefore we need a precedence for which order to try
keys in; higher = later
"""
if type(match) in (Required, Optional):
match = match.key
if type(match) in (t... | 35,092 |
def main(argv):
"""
The main method of the program. It is responsible for:
- Managing the server and request handler
- Spawning the GA instance
- Starts the interface or parses command-line arguments
And finally returns the exit code
"""
controller = SATController.... | 35,093 |
def experiment_set_reporting_data(connection, **kwargs):
"""
Get a snapshot of all experiment sets, their experiments, and files of
all of the above. Include uuid, accession, status, and md5sum (for files).
"""
check = CheckResult(connection, 'experiment_set_reporting_data')
check.status = 'IGNO... | 35,094 |
def display2D(data,show=None,xsize=None,ysize=None,pal=None):
"""display2D(data,show=None,xsize=None,ysize=None) - create color image object
from 2D list or array data, and the color palette is extracted from 'pal.dat',
if show=1 specified by default a 300x300 window shows the data image
xsize, ysize override th... | 35,095 |
def read_port_await_str(expected_response_str):
"""
It appears that the Shapeoko responds with the string "ok" (or an "err nn" string) when
a command is processed. Read the shapeoko_port and verify the response string in this routine.
If an error occurs, a message.
:param expected_response_str: ... | 35,096 |
def doify(f, *, name=None, tock=0.0, **opts):
"""
Returns Doist compatible copy, g, of converted generator function f.
Each invoction of doify(f) returns a unique copy of doified function f.
Imbues copy, g, of converted generator function, f, with attributes used by
Doist.enter() or DoDoer.enter().
... | 35,097 |
def deserialize(config, custom_objects=None):
"""Inverse of the `serialize` function.
Args:
config: Optimizer configuration dictionary.
custom_objects: Optional dictionary mapping names (strings) to custom
objects (classes and functions) to be considered during deserialization.
Returns:
... | 35,098 |
def unquote_to_bytes(string):
"""unquote_to_bytes('abc%20def') -> b'abc def'."""
# Note: strings are encoded as UTF-8. This is only an issue if it contains
# unescaped non-ASCII characters, which URIs should not.
if isinstance(string, str):
string = string.encode('utf-8')
res = string.split(... | 35,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.