id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
ffa5fabd1b59b099ec3c | def prepare_batch(harn, raw_batch):
img1, img2, label = raw_batch
inputs = harn.xpu.variables(img1, img2)
label = harn.xpu.variable(label)
batch = (inputs, label)
return batch | |
ffa6042cd9a89b0585c5 | def __init__(self,filename):
self.file = filename
with gzip.open(self.file) as f:
for line_no, line in enumerate(f):
if line.startswith(b'Data start time:'):
timestring = line.decode().split()[-2:]
self.startday = dt.datetime.... | |
ffa61872522a136c3b28 | def checkValidGeom(shp): | |
ffa62ee11170a0a679c8 | def ensure_state_in_qtable(self, state):
if state not in self.qtable:
self.qtable[state.get_copy()] = {action:0.0 for action in self.action_space} | |
ffa630629bc8af123cff | def setup(self):
pygame.init()
self.screen = pygame.display.set_mode(self.get_screen_dims(), 0, 32)
self.clock = pygame.time.Clock() | |
ffa6889c9526bfd3c04f | def get_coin_spend(self):
return 300 | |
ffa6e870daa1fe11c71d | def key_import(self, gpg, key_files, trust_level=None):
for file in key_files:
gpg.import_key(file)
if trust_level:
gpg.trust_key(file, trust_level) | |
ffa7416d68897d8f17cb | def test_root_not_404():
res = app.get('/')
assert "404" not in res.status | |
ffa764f5104e97492130 | def product():
categories = Category.query.all()
product_list = Product.query.all()
return render_template(
"dashboard/product/product.html",
categories=categories,
product_list=product_list
) | |
ffa77a2ba22d998fd358 | def _value(root, *tags: str, type_=None):
el = root
for tag in tags:
found = el.getElementsByTagName(tag)
if not found:
raise ValueError(f"Element not found in document: {tags!r}")
if len(found) > 1:
vs = "\n\t".join([_node_name(e) for e in found])
ra... | |
ffa77e3f9326c08ab82d | def gen_starting_values(dataset):
# Maximum trait value
global max_trait
max_trait = get_max_trait(dataset)
# Peak temperature
T_pk_start = get_T_pk(dataset, max_trait)
# Get only the subset of the dataset until the peak temperature.
dataset_up_to_peak = get_dataset_up_to_peak(dataset, T_... | |
ffa7848ae7a097c73bd9 | def QueryDocumentListFeed(self, uri):
return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString) | |
ffa796d3b339038c1d91 | def get_track_duration(self):
self.track_duration = float(self.request("duration ?"))
return self.track_duration | |
ffa799c79547a0560fce | def CleanBuildInfo(RawBuildInfo):
CleanedBuildInfo = ''
for char in RawBuildInfo:
if char == '\x00':
CleanedBuildInfo += ' '
else: CleanedBuildInfo += char
del RawBuildInfo
while CleanedBuildInfo[-1] == ' ':
CleanedBuildInfo = CleanedBuildInfo[:-1]
return CleanedB... | |
ffa79fa1513c18f847a4 | def install(ctx):
ctx.run(f"{PIPENV_PREFIX} python setup.py install") | |
ffa7ac9159a7c9f74e3f | def __call__(self, tensor):
net = tensor
if self.conv is not None:
net = self.conv(tensor)
_, h, w, ic = tensor.shape.as_list()
r = self.scale
f_h, f_w = math.floor(h * r), math.floor(w * r)
net = tf.reshape(net, [-1, w, h, r, r, self.out_ch])
net = ... | |
ffa7c01f9d1106cdb7ed | def reorderList(self, head: ListNode) -> None:
if not head: return
ltmp = []
cur = head
while cur: # into a list
ltmp.append(cur)
cur = cur.next
n = len(ltmp)
for i in range(n // 2):
ltmp[i].next = ltmp[n - 1 - i]
ltmp[... | |
ffa7dd8cbf9b4dbbe885 | def get_element(self, *locator):
WebDriverWait(self.driver, ELEMENT_FIND_TIMEOUT).until(
expected_conditions.presence_of_element_located(locator))
return self.driver.find_element(*locator) | |
ffa7e4240c0a27a65949 | def string_list(s):
return json.loads(s) | |
ffa7f5b9df80a89c454b | def verify() -> bool:
return check_witness(OWNER) | |
ffa7f903cd54c0565c50 | def __call__(self, i, t, var=None):
return self.eval_deriv(i, 0, t, var=var) | |
ffa83293165d8000c61e | def recognize_speech_from_mic(self):
# check that recognizer and microphone arguments are appropriate type
if not isinstance(self.recognizer, sr.Recognizer):
raise TypeError("`recognizer` must be `Recognizer` instance")
if not isinstance(self.microphone, sr.Microphone):
... | |
ffa83670da13b51bb1e3 | def np_rolling_mean(data, num_points, mode="reflect", axis=0):
return uniform_filter1d(data, size=num_points, axis=axis, mode=mode) | |
ffa878fc526649e68582 | def player2_inside(player2, score_box, win):
if player2.top < (win.top + score_box.bottom):
player2.top = win.top + score_box.bottom
if player2.bottom > win.bottom:
player2.bottom = win.bottom | |
ffa89679bc9cde6081a1 | def init_form(self, values=None):
if values:
values = values.copy()
values['lt'] = self.request.session['lt'][-1]
form_initial = {
'service': self.service,
'method': self.method,
'warn': (
self.warn or self.request.session.get("... | |
ffa8ae21083ffd1b8e5f | def pool_get_connection(self, timeout=3, retry_num=1):
try:
conn = self.pool.get(timeout=timeout)
logger.debug('get connection: {}'.format(conn))
# caller should the take care of the availability of the connection object from the pool
return conn
except qu... | |
ffa8b997d481135e99a9 | def forward(self, tensor: Tensor) -> Tensor: # type: ignore
if self.dim is not None:
return tensor.squeeze(dim=self.dim)
else:
return tensor.squeeze() | |
ffa8c8c4bdf6fe156f32 | def __create_full_matrix(self,n_qubits, base):
result = lil_matrix(base)
if n_qubits == 1 :
result = csc_matrix(result)
return result
else:
for i in range(n_qubits-1):
result = kron(result, base)
result = csc_matrix(re... | |
ffa8d6fc92adf302537c | def django_db_setup():
pass | |
ffa8efe4a31fd643b493 | def test_lock_before(self):
# Create a lock
m = DBMutex.objects.create(lock_id='lock_id')
# Try to acquire the lock. It should raise an exception
with self.assertRaises(DBMutexError):
with db_mutex('lock_id'):
raise NotImplementedError
# The lock shoul... | |
ffa8efec95ffe12536c7 | def binomial(trials, successProb):
return sum([bernoulli(successProb) for a in range(trials)]) | |
ffa9093839cfeb7f914c | def GetWaveletId(self):
return self.waveletId | |
ffa93fa6ba1411880a9a | def test_getting_a_specific_apikey(self):
response = self.client.get('/apikeys/1')
resp = json.loads(response.data.decode('utf-8'))
testutil.assertEqual(self, {
response.status_code: 200,
resp['status']: 200,
resp['message']: 'OK',
resp['apikey']['... | |
ffa9433e42a5c8dc179a | def _transform(self, df: DataFrame) -> DataFrame:
return self._transformer.transform(df) | |
ffa949c1bc720e235f70 | def _render(data):
if not data.get('status'):
data['status'] = 'success'
return Response(json.dumps(data), mimetype='text/json') | |
ffa95088382568cf5be3 | def get_route_data(route_url):
# get the climb description
text = ''
while text == '':
try:
text = requests.get(route_url).text
break
except:
print('too fast, sleeping...')
time.sleep(5)
print('finished sleeping')
contin... | |
ffa95ddf35798f667d6b | def ReadFiles(args):
if args.mode.startswith('delta'):
return ReadFilesDelta(args)
else:
return ReadFilesRaw(args) | |
ffa963e31b9816a622a0 | def setup_method(self):
self.hmc, self.hmc_resources = standard_test_hmc()
self.uris = (
(r'/api/storage-groups(?:\?(.*))?', StorageGroupsHandler),
(r'/api/storage-groups/([^/]+)', StorageGroupHandler),
)
self.urihandler = UriHandler(self.uris) | |
ffa96adf97e24c3ff8fa | def test_xi_p_02(test_case_4):
xi_p = test_case_4["eos"].xi_p(test_case_4["n_b"], gp.proton_singlet_CCDK)
assert np.abs((xi_p - test_case_4["xi_p"]) / xi_p) < TOL | |
ffa96dc2699128772bd3 | def on_key_press(self, key, modifiers):
self.game.on_key_pressed(key, modifiers) | |
ffa975e4fbdc7f590ca3 | def __str__(self):
printable_string = '\n{0!s:_^80}\n'.format('Owner Members Object Properties')
#
# retrievable methods
#
printable_string += '{0!s:40}\n'.format('Members')
printable_string += (' {0!s:<28}: {1!s:<50}\n'.format('user_name', self.user_name))
pri... | |
ffa99ed728e0c6bdfbf9 | def acquire_actions_and_apply(console_printer,
section,
file_diff_dict,
result,
file_dict,
cli_actions=None):
cli_actions = CLI_ACTIONS if cli_actions is None else cl... | |
ffa9f213e23804e2095d | def __init__(self, *args):
this = _idaapi.new_cnumber_t(*args)
try: self.this.append(this)
except: self.this = this | |
ffa9fdc211c1e799cf65 | def continue_video(self):
if self.is_paused == True:
print(f"Continuing video: {self.currently_playing.title}")
self.is_paused = False
elif self.is_playing == True:
print("Cannot continue video: Video is not paused")
elif self.currently_playing == None:
... | |
ffaa00f800f5799f4f1d | def parseHtmlTag(self, inlines):
m = self.match(reHtmlTag)
if m:
inlines.append(Block(t="Html", c=m))
return len(m)
else:
return 0 | |
ffaa18c1e2e9062871ab | def output_signature(self):
return _qbee_swig.qbee_deframer_sptr_output_signature(self) | |
ffaa2b40b254055c871f | def _get_all_props(self) -> Tuple:
props = []
for name, item in prp.__dict__.items():
if isinstance(item, (Property, BoundedProperty)):
props.append(item)
return props | |
ffaa38acca21fe12f51b | def competence(stochastic):
return 0 | |
ffaa518f7839e17b5e83 | def aggravate_sapairs(sa_dir, save_path):
files = os.listdir(sa_dir)
data = []
for fi in files:
if os.path.isdir(fi):
continue
with open(os.path.join(sa_dir, fi), 'rb') as f:
data += pickle.load(f)
with open(save_path, 'wb') as f:
pickle.dump(... | |
ffaa6c04daae3fe7c930 | def longest( t ):
nonlocal max_len
n = 1
if not t . is_leaf ():
for b in t . branches:
L = longest(b)
if b. label == t. label + 1:
n = max (n , L + 1)
max_len = max (n , max_len)
return n | |
ffaa6d742927a0069676 | def clone(self, *args):
return _osg.CompositeShape_clone(self, *args) | |
ffaa7d5d3bcec651e2ca | def feed_forward(self):
f_hat = self.model.feed_forward()
return f_hat | |
ffaa930c5f89ad226077 | def skip_default(self, field):
return False | |
ffaaabb0e6bab5836f1d | def __init__(self, port=50000, serverip='localhost'):
self.serverip = serverip
self.port = port
self.socket = None #use this variable as the client socket
#Initialize the socket | |
ffaab0fdfcbe1db67b3a | def get_binary_rep(n, num_digits):
result = ''
while n>0:
result = str(n%2) + result
# print(str(n%2))
n = n//2
if len(result) > num_digits:
raise ValueError('not enough digits')
for i in range(num_digits - len(result)):
result = '0' + result
... | |
ffaad683da104585b942 | def before_patch(self, req, resp, db_session, resource, *args, **kwargs):
ensure_modifiable(self.model, req.context['doc']) | |
ffaadcf945f043356663 | def assemble_combined_cluster_images(clusters):
roots = [cl for cl in clusters.values() if cl["parent"] == None]
reps, recs = [], []
for r in roots:
rep_li, rec_li = lineage_images(r)
reps.append(rep_li)
recs.append(rec_li)
return (
impr.join([impr.frame(img) for img in reps]),
impr.join([... | |
ffaaf671e33767676ffb | def beta_init(df, ds=None):
if ds is None:
ds = []
data = df + ds
t_N = max(data)
n = len(df)
term1 = np.array([np.log(t_N / t) for t in df])
beta1 = ((1 / n) * np.sum(term1)) ** (-1)
x_k... | |
ffaafff9b6ae0e251b40 | def apply_GCAL_training_sequence(model, time_factor):
model.warning("Modifying time functions to reproduce GCAL Gaussian sequence")
for sweeper in model.training_patterns.Retina.generators:
gaussian = sweeper.generator
for p in ['orientation', 'x', 'y']:
binary_op_or = gaussian.get_... | |
ffab05c6c51412f432e6 | def test_2dt_tracks():
data, properties = tracks_2d()
layer = Tracks(data, properties=properties)
assert layer.ndim == 3
assert np.all([np.all(ld == d) for ld, d in zip(layer.data, data)])
assert np.all(
[np.all(lp == p) for lp, p in zip(layer.properties, properties)]
) | |
ffab27332b68bb571a97 | def get_splits(split_dir):
train = read_split(os.path.join(split_dir, 'train.json'))
test = read_split(os.path.join(split_dir, 'test.json'))
val = read_split(os.path.join(split_dir, 'val.json'))
return train, test, val | |
ffab49564fef54132394 | def dteSixthModifiedHertzMindlinSpherePackEffectiveShearModulus( KhmMod, MuRef, Kref, scale = 1.0 ):
MuHmMod = []
MuHmMod = [scale * (MuRef/Kref) * k**pow + (1.0-scale) * MuRef for k in KhmMod]
return MuHmMod | |
ffab53ce7283d0081eab | def _formatparam(param, value=None, quote=1):
if value is not None and len(value) > 0:
if quote or tspecials.search(value):
value = value.replace('\\', '\\\\').replace('"', r'\"')
return f'{param}="{value}"'
else:
return f'{param}={value}'
else:
return... | |
ffab79d703bcfa064b26 | def is_ascii(self, s):
return s.encode("ascii", "ignore").decode("ascii") == s | |
ffab7bfdf603f0451f28 | def add(self, product, quantity=1, update_quantity=False):
# get product id
product_id = str(product.id)
# check if id is in dictionary
if product_id not in self.cart.keys():
self.cart[product_id] = {
'price' : str(product.price),
'quantity' ... | |
ffab7d21b00f4d9dec94 | def stiffSandEffectiveShearModulusHertzMindlinAtNewPorosity( originalPorosity,
newPorosity,
shearModulusHM,
grainBulkModulus,
grainShearModulus ):
Phi0 = originalPorosity
Phi = newPorosity
Mu_hm = shearModulusHM
K_s = grainBulkModulus
Mu_s = grainShearModulus
PhiR... | |
ffab8a1dce97e00eb1bd | def parseUnits(self, input):
quantity = self.convert(input)
units = ' '.join(str(quantity.units).split(' ')[1:])
return NumberService.parseMagnitude(quantity.item()) + " " + units | |
ffab93282f91bdf88ecb | def backward(self, top, propagate_down, bottom):
top_shape = top[0].shape
bottom[0].diff[...] = top[0].diff[...]
#sio.savemat(self._str + '.mat', {'data': bottom[0].data})
print '%s backward,diff:%.10f'%(self._str,top[0].diff.mean())
#print '%s backward,min:%.10f,max:%.10f,mean:%... | |
ffabb42336cdfbb38aab | def available_cores() -> int:
# https://htcondor.readthedocs.io/en/latest/users-manual/services-for-jobs.html#extra-environment-variables-htcondor-sets-for-jobs
condor_job_ad = os.environ.get("_CONDOR_JOB_AD")
if condor_job_ad:
try:
classad = dials.util.parse_htcondor_job_classad(pathli... | |
ffabdb67957e87dd91f9 | def contains(tree, key):
if get(tree, key):
return True
return False | |
ffabdd683d287eb1771c | def test_ensemblgenomes_genome_download_links(masking, ensembl):
mask = masking if masking != "unmasked" else "none"
for genome in ["Amel_HAv3.1", "ASM23943v1"]:
assert ensembl.get_genome_download_link(
genome, mask=mask, **{"version": 55}
) | |
ffabf56f6ca4e93cea4b | def worklist(self):
pending = default_worklist()
## TODO: group by type?
return dict(count=pending.count(), items=pending) | |
ffac24bc97767816f41d | def get_timezone(self): # real signature unknown; restored from __doc__
pass | |
ffac419f730a84d6ec2a | def utf8(value):
if not isinstance(value, binary_type) and not isinstance(value, text_type):
value = binary_type(value)
if isinstance(value, text_type):
return value.encode('utf-8')
else:
return value | |
ffac5cc0f9a9ada8ee8b | def is_discrete(self):
for i in range(len(self._types)):
if self._types[i] is True:
return False
return True | |
ffac5eb27f9bbc88b5d3 | def get_id_of_title(self, title:str) -> int:
self.cur.execute("SELECT page_id FROM page WHERE page_title='%s';" % title)
res = self.cur.fetchone()
return res[0] if res else None | |
ffac7271618a763c853a | def set_default_thresholds(self):
lo_thres = [o.meta.safe_energy_range[0] for o in self.obs_list]
hi_thres = [o.meta.safe_energy_range[1] for o in self.obs_list]
self.energy_threshold_low = lo_thres
self.energy_threshold_high = hi_thres | |
ffac7b49e8ccc8eb1a09 | def _execute(self, statement, consistency, parameters=None, results=False):
res = self.session.execute_async(
SimpleStatement(statement, consistency_level=consistency),
parameters=parameters,
)
try:
res = res.result() # force this thread to wait
exce... | |
ffac9ab5a1cac4e699dd | def _log_http_request(self, url, method, body, headers):
self.logger.debug('send: %s %s', method.upper(), url)
self._log_header_body("request", headers, body) | |
ffacc2839836d5f45c42 | def _write_csv(self):
raise NotImplementedError | |
ffad0ff7bb9c1f572784 | def test__parse_user__2():
user_id = 202301020003
guild_id = 202301020004
user = User.precreate(user_id)
guild_profile = GuildProfile(nick = 'sinker')
data = {
'user_id': str(user_id),
'member': {
**guild_profile.to_data(
defaults = True,
... | |
ffad1622e8f1d553d119 | def parse_return(self, match):
field = match.group(1).lower()
body = self.parse_body(startpos=match.end())
if field in ("rtype", "returntype"):
kind = " ".join(body)
self.doc.add_return_type(kind)
else:
self.doc.add_return(desc=body) | |
ffad162b030692ea49cf | def test_scheduler_start_date(self):
dag_id = 'test_start_date_scheduling'
dag = self.dagbag.get_dag(dag_id)
dag.clear()
self.assertTrue(dag.start_date > DEFAULT_DATE)
scheduler = SchedulerJob(dag_id,
num_runs=2)
scheduler.run()
... | |
ffad259407da54976f45 | def recursive_min(nested_nlis):
s_num = None
first_try = True # flag
for i in nested_nlis:
if type(i) == type([]):
val = recursive_min(i)
else:
val = i
if first_try or val < s_num:
s_num = val # basic case
first_try = False
... | |
ffad2d60dccc0920f75d | def test_not_authenticated(self):
response = self.client.get(missions_url)
self.assertEqual(403, response.status_code)
response = self.client.get(missions_id_url(args=[1]))
self.assertEqual(403, response.status_code) | |
ffad3242ae5301e1fed2 | def json(self):
return {
"id": self.id,
"name": self.title,
"goal_id": self.goal_id
} | |
ffad3a080467c018e3ba | def has_vertex(self, vid: base.VertexID) -> bool:
return vid in self._forward | |
ffad3a9de3b107e7a0f7 | def _check_parametrize_names(
self, node: ast.Call, names: ast.AST
) -> Optional[bool]:
multiple_names: Optional[bool] = None
if isinstance(names, ast.Str):
if ',' in names.s:
self.error_from_node(
ParametrizeNamesWrongType, node, expe... | |
ffad6bf7c2ea340fe474 | def base_url(self):
return "{0}://{1}:{2}".format(
self._protocol,
self._host,
self._port) | |
ffad73d96bd5ec1d2206 | def posterior(prior, likelihood, observation):
prior_f = 1 - prior
features_true = 1
features_false = 1
for i in range(len(observation)):
if observation[i]:
features_true *= likelihood[i][True]
features_false *= likelihood[i][False]
else:
features_true... | |
ffad8967d672a1dc8d6d | def find_nearest_node(self, target):
nodes = np.array(self.nodes)
# Find start coordinate on skeleton
dist_array = np.linalg.norm(nodes - target, ord=2, axis=1)
i_min_dist = np.argmin(dist_array)
nearest_node = tuple(nodes[i_min_dist])
return nearest_node | |
ffad9f64be823d5340c3 | def provider(self) -> Optional[str]:
return pulumi.get(self, "provider") | |
ffadae3668dbe63cf220 | def get_field(self, table_name, field_info):
field_params = OrderedDict()
field_notes = []
with self.connection.cursor() as cursor:
primary_key_column = self.connection.introspection.get_primary_key_column(
cursor, table_name
)
try:
f... | |
ffadb920388447827d5b | def train_linear_svr(dataset):
svm_m = MultiOutputRegressor(LinearSVR())
svm_m.fit(dataset.train_x, dataset.train_y)
return svm_m | |
ffadd3abce9cd7575f91 | def test_redacted_string_050():
original_string = "at 60 characters. this is an even longer string than normal."
expected = "*******************************************************rmal."
# a negative unmask length should result in the default unmask length
long_unmask_len = -5
redacted = RedactedS... | |
ffade51b8d95fbf66e70 | def fetch_youtube_url(search_term):
YOUTUBE_DEV_KEY = getenv('YOUTUBE_DEV_KEY')
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=YOUTUBE_DEV_KEY,
cache_discovery=False)
log.info(u"Searching for {}".format(search_term))
search_response = ... | |
ffadf230fdcb7a12fe54 | def err(msg):
LOGGER.error(msg) | |
ffadfab1ed03dd4e9703 | def read_data(path):
data = pd.read_csv(path)
return data | |
ffae0410ce1e6759cd7d | def get_entropy(data):
entropy = 0
seen = list()
for x in data:
if x not in seen:
seen.append(x)
p_x = float(data.count(x)) / len(data)
if p_x > 0:
entropy += - p_x * math.log(p_x, 2)
return entropy | |
ffae50eccba755041377 | def _build_graph(self):
self._creat_placeholders()
logits = self._create_logits()
self._create_ctc_loss(logits)
self._create_optimizer()
self._create_eval(logits) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.