id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
00517389dbb019321bc5 | def UpdateColumnsOrder(self, order): | |
00517f4fd21a3731409a | def _to_ndim(self, arg) -> np.array:
if arg is not None:
arg = np.array(arg).flatten()
if np.isscalar(arg) or arg.size == 1:
arg = np.repeat(arg, repeats=self.ndim)
elif arg.size != self.ndim:
raise ValueError(
f"All input a... | |
005187a6468c2e7786cf | def test_administrator_can_comment_in_community_post_with_disabled_comments(self):
user = make_user()
admin = make_user()
headers = make_authentication_headers_for_user(admin)
community = make_community(admin)
user.join_community_with_name(community_name=community.name)
... | |
0051a709a280f8ee972c | def isFile(self):
raise NotImplementedError | |
0051a7c582bf901ea9c9 | def get_slice_start_width(
self, node: ast.Slice,
symbolic_bindings: symbind_mod.SymbolicBindings) -> Tuple[int, int]:
return self._top()._slices[node].bindings_to_start_width[symbolic_bindings] | |
0051ea1899c1334e9618 | def _esiste(self, *args):
return os.path.exists(self._percorso(*args)) | |
0051f2951416cb290fca | def subcloud_destroy(context, subcloud_id):
return IMPL.subcloud_destroy(context, subcloud_id) | |
005205fd230cea258665 | def save(self, *args, **kwargs):
if not self.order_number:
self.order_number = self._generate_order_number()
super().save(self, *args, **kwargs) | |
005206d84c9b73648426 | def get_falling_block_position(self):
return self.__model.falling_block_position | |
00520fae8d5a3cdded8c | def SGD_train():
# YOUR TRAINING CODE GOES HERE
# Define parameters passed to MLP()
n_inputs = len(train_x[0])
n_hidden = list(map(int, DNN_HIDDEN_UNITS_DEFAULT.split()))
n_classes = len(train_t[0])
# Define a MLP Object
mlp = MLP(n_inputs, n_hidden, n_classes)
# train
p... | |
00521a6855e0f5875d09 | def test_filename(self):
f = _find_file('example1')
self.assertEqual(f, join(DIR_FF1, 'example1')) | |
00522e0af5d983bbbec5 | def tasks(self):
return self.__tasks | |
00524c142a3dd7638975 | def get_nonce(self):
return self.content['nonce'] | |
00525d34955d48f02105 | def __repr__(self):
return "SQLite3-based key:value database stored in '%s'"%self._file | |
00525f513ec483f988d1 | def main(root):
#return 0 <= max_depth(root) - min_depth(root) < 2
return 0 <= depth(root, False) - depth(root, True) < 2 | |
0052696aa022ee0abc92 | def crunchKNavList():
queryurl = u'https://wdq.wmflabs.org/api?q=string[1248:"%s"]' \
u'+AND+CLAIM[373]&props=373,1248,1472'
i = 0
props = {'P373': [], 'P1248': [], 'P1472': []}
while i < len(kNavList):
# Split up into 10 uuid chunks
ks = '",1248:"'.join(kNavList.keys()[i:... | |
0052905a2c9a54e526b7 | def top_n(distributions, n=5):
if not n:
n = len(distributions)
return sorted(distributions, key=lambda y: y[1], reverse=True)[:n] | |
005293cd21c65189ceef | def tokenize_one_example(self, example):
index, q_id, question, context, answer_list, answer_start = example
context = context.replace('\'\'', '\" ').replace(r'``', '\" ')
context_tokens = SQuADDataTokenizer._word_tokenize_spacy(context) if self._use_spacy else \
SQuADDataTokenizer.... | |
0052c4bc11e2e6079582 | def is_pair(self) :
values = [0]*13
for c in self.cards :
values[c.value]+=1
pair = False
for i in values :
if i==3 :
return False
if i==2 :
if pair :
return False
else :
... | |
0052def895ea0b0748ef | def zoom(image, upperLeftX, upperLeftY, lowerRightX, lowerRightY, factor):
width = factor*(lowerRightX-upperLeftX)
height = factor*(lowerRightY-upperLeftY)
newImg = cImage.EmptyImage(width,height)
for x in range(image.getWidth()):
if x >= upperLeftX and x < lowerRightX:
for y in ran... | |
0052ebf63897b7723d10 | def from_ebounds(cls, hdu):
if hdu.name != "EBOUNDS":
log.warning(
"This does not seem like an EBOUNDS extension. " "Are you sure?"
)
header = hdu.header
unit = header.get("TUNIT2")
low = hdu.data["E_MIN"]
high = hdu.data["E_MAX"]
... | |
00530058348adeabd010 | def count(self):
query = {'returnCountOnly': 'true'}
return self.get(query)['count'] | |
00531fc3f45213d37ec3 | def dfs (grafo,origen=None):
visitados=[]
pila=[]
pila.append(origen)
while pila:
# Saco un nodo de la pila
origen = pila.pop(0)
#print("levanto: "+origen)
visitados.append(origen)
# Apilo todos sus hijos que no hayan sido visitados
adyacente... | |
0053264cb53ea817cbda | def help_how_are_you(self):
print_say("Jarvis will inform you about his status.", self) | |
005344c7ae777ab0790d | def place_no_id_get(city_id):
city = storage.get("City", city_id)
if city is None:
abort(404)
all_places = []
for place in city.places:
all_places.append(place.to_dict())
return jsonify(all_places) | |
005363d1d7748a7ce39e | def createScenarioDataFiles(self, scenario: str) -> None:
assert self.arcProjDir is not None
arcTxtInOutDir = os.path.join(self.arcProjDir, r'Scenarios\{0}\TxtInOut'.format(scenario))
qTextInOutDir = os.path.join(self.qProjDir, r'Scenarios\{0}\TxtInOut'.format(scenario))
if not os.path.i... | |
005385b93045980fa6b8 | def extra_inits(self):
... | |
005393dfa683d2068b39 | def test_verify_claim_set_failure_claims_unexpected_and_missing(self):
# Create a new instance variable in the object by assigning to it. This instance variable will automatically
# become a claim. When calling the verify method on this object, this should cause the expected failure if the
# cl... | |
0053ba3f55222d201ee1 | def Gf(E,H,H_el,V,eta=1.e-7):
lel = len(H_el)
rel = len(H) - lel
S1 = SE(E,H_el,V.T.conj(),eta=eta)
S2 = SE(E,H_el,V,eta=eta)
invG = np.diag(np.ones((len(H),))*(E+1j*eta)) - H
invG[:lel,:lel] -= S1
invG[rel:,rel:] -= S2
G = la.inv(invG)
return G,S1,S2 | |
0053d7cdd9f4d5e4a2e3 | def getAffineTransform(self, coord1, coord2):
pts1 = coord1[0:3].astype(np.float32)
pts2 = coord2[0:3].astype(np.float32)
print(cv2.getAffineTransform(pts1, pts2))
return cv2.getAffineTransform(pts1, pts2) | |
0054159bc6c31af3395e | def _event_delayed_req(self, session, process_fields, req_flags):
msg = self.xmpp.Message();
msg['from'] = self.sessions[session]['to'];
msg['to'] = self.sessions[session]['from'];
msg['started']['seqnr'] = self.sessions[session]['seqnr'];
msg.send();
if self.thre... | |
00542a3050cec48af9ad | def solution(A): # O(N)
occurrences = {} # O(1)
for count, value in enumerate(A): # O(N)
if isinstance(value, int): # O(1)
if value... | |
005452b39f88a277dbb8 | def set_connections(self):
for n in self.molecular_graph:
atom = self.atoms[n]
connections = self.molecular_graph.predecessors(n)
atom.messages = connections | |
005459298b8741b1a54a | def delete_blob(self, container_name, filename):
try:
self._service.delete_blob(container_name, filename)
print(f"Successful: {filename} deleted")
except Exception as e:
print(e) | |
00546ee9b3b9b8072651 | def embedding_fn(self, x):
with tf.name_scope("presoftmax_linear"):
batch_size = tf.shape(x)[0]
length = tf.shape(x)[1]
x = tf.reshape(x, [-1, self.params["hidden_size"]])
logits = tf.matmul(x, self.embedding_table, transpose_b=True)
return tf.reshape... | |
0054948a649426ed22c1 | def record():
p = pyaudio.PyAudio()
#stream = p.open(format = form_1,rate = samp_rate,channels = chans, \
# input_device_index = dev_index,input = True, output=True, \
# frames_per_buffer=chunk)
stream = p.open(format=form_1,
channels=chans,
... | |
00549f3843d558dc1f67 | def altitude(self):
self._send_command(_SCD4X_GETALTITUDE, cmd_delay=0.001)
self._read_reply(self._buffer, 3)
return (self._buffer[0] << 8) | self._buffer[1] | |
0054a6f48c6191cd5285 | def train_experience_replay(self, batch_size):
# if batch_size > len(self.memory):
# return
idx = np.arange(batch_size)
if self.with_per:
tree_idx, minibatch = self.buffer.sample(batch_size)
else:
minibatch = random.sample(... | |
0054ab6b75f10d1a7e45 | def test_real_model(self, model, name):
assert get_model_name(model()) == name | |
00550b4e0002f41d3f0c | def __getitem__(self, object):
# check for previously unknown object
if object not in self.parents:
self.parents[object] = object
self.weights[object] = 1
return object
# find path of objects leading to the root
path = [object]
root = self.parents[object]
while root != path[-1]:
path.append(ro... | |
00550fdf4ccb4364ea55 | def _applyPatches(self, patchdir="./patches"):
if not os.path.exists(patchdir):
logging.debug("no patchdir")
return
if not ("PATH" in os.environ and
[p for p in os.environ["PATH"].split(":")
if os.path.exists(os.path.join(p,"patch"))]):
... | |
00552025f50d6af79195 | def getRandom(self) -> int:
return random.choice(tuple(self.el)) | |
00552ced8bd3d2a2babb | def __init__(self, database_config):
self.config = database_config | |
005545b4f7327e69435a | def when_unknown(self, callback):
#NOTE: this is the main hook point for auto discovery and registration
self.unknown_cb = callback | |
005551b65102162df66f | def log_event(self, event, payload=None):
return self | |
00557297399ef04b1e0f | def clean(self):
s = self.name
file = self.name
opening_brackets = ['(', '[', '<', '{']
closing_brackets = [')', ']', '>', '}']
for i in range(len(opening_brackets)):
b = opening_brackets[i]
c = closing_brackets[i]
while b in s:
... | |
00559332d24b76c6ead0 | async def _exists(self, key):
with await self._connect() as redis:
exists = await redis.exists(key)
return True if exists > 0 else False | |
0055a40d1eb38054eaef | def test_valid_token_provided_password_required(self):
with app.test_client() as client:
s = Serializer(app.config['SECRET_KEY'], expires_in=60)
tok = s.dumps({
'email': CommonRequests.sign_up_credentials["email"]})
self.password_change["password"] = ''
... | |
0055b1fc93967f472907 | def create_padding_mask(seq):
seq = tf.cast(tf.math.equal(seq, 0), tf.float32)
# add extra dimensions so that we can add the padding
# to the attention logits.
return seq[:, tf.newaxis, tf.newaxis, :] # (batch_size, 1, 1, seq_len) | |
0055c9779c2196535c61 | def load_model(name):
# type: (str) -> Optional["SasviewModel"]
# Remember the models that are loaded so they are only loaded once. While
# not strictly necessary (the models will use identical but different model
# info structure) it saves a little time and memory for the usual case
# where models... | |
0055dbad3e2b8609a0e3 | def next(self):
i=self.nextPointPos()
if i> -1:
self.curr =i
col=self.p.col[i]
row = self.p.row[i]
if self.topleft is True:
col = col - self.boxsize / 2
row = row - self.boxsize / 2
return [col,row]
retur... | |
0055dcc76acf2c4a3071 | def split(self,time):
i,u = self.getSegment(time)
if time < 0:
return self.constructor()(),self.constructor()()
if time <= self.times[0]:
#split before start of trajectory
return self.constructor()([time],[self.milestones[0]]),self.constructor()([time]+self.times,[self.milestones[0]]+self.milestones)
i... | |
0055dcd0a24e009d736e | async def create_control_policy_with_options_async(
self,
request: resource_manager_20200331_models.CreateControlPolicyRequest,
runtime: util_models.RuntimeOptions,
) -> resource_manager_20200331_models.CreateControlPolicyResponse:
UtilClient.validate_model(request)
query = {... | |
0055fe279fbe9e88fded | def sequence_mask(sequence: torch.LongTensor,
end_symbol_id: int) -> torch.ByteTensor:
b_sz, seq_len = sequence.size()
end_symbols = (sequence == end_symbol_id)
pattern = end_symbols.cumsum(dim=1) >= 1
lens = (1 - pattern).sum(dim=1)
final_lens = lens + 1
... | |
00561f856ff643782124 | def _getQuery(self, request):
q = Conference.query()
inequality_filter, filters = self._formatFilters(request.filters)
# If exists, sort on inequality filter first
if not inequality_filter:
q = q.order(Conference.name)
else:
q = q.order(ndb.GenericPropert... | |
00563cd00727c60168e5 | def __setitem__(self, i, v):
for j in range(4):
self.array[i*4+j] = v[j] | |
005641137be0b31b4cb5 | def check_used(port):
# Create a TCP socket
address = '127.0.0.1'
s = socket.socket()
try:
s.connect((address, port))
s.close()
# print "port %s is used" % port
return True
except socket.error, e:
# print "port %s is available" % port
return False | |
0056486b377afc525462 | def test_stop_start_router(self):
# Create admin account
account = Account.create(
self.api_client,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup_accounts.append(account)
physical_network, shared_vlan = get_free_vlan(
... | |
00564dbd3ff6c619b050 | def legal_contracts(self):
legal_bids = []
if self.declared_contract == 0:
for i in range(self.highest_bidding_contract.num, self.CARDS_IN_HAND + 1):
legal_bids.append(i)
else:
for i in range(self.CARDS_IN_HAND + 1):
legal_bids.append(i)
... | |
00564ffa84cfa1401177 | def actions(self):
return self._actionlist | |
005668e49283ffb0af7b | def highlight_text(text, **kwargs):
return click.style("{}".format(text), fg="blue", bold=False, **kwargs) | |
0056762436376ad76bb8 | def get_raw_payload(record) -> dict:
assert record is not None
return record if isinstance(record, dict) else json.loads(record) | |
005691d9e0d4b387d07b | def delete_user(username):
if 'username' not in session or username != session['username']:
form.username.errors = ["You are not authorized here."]
return redirect ('/login')
user = User.query.get(username)
db.session.delete(user)
db.session.commit()
session.pop('username')
re... | |
0056940a89ebc74d538f | def reader(path):
parser = etree.XMLParser(remove_blank_text=True)
return etree.parse(path, parser=parser) | |
0056b55db069d1333117 | def is_str(value):
return isinstance(value, str) | |
0056bc5ed23d4064884e | def test_storage_group_performance_function(self):
category = pc.SG
id_tag = pc.SG_ID
key_func = self.perf.get_storage_group_keys
metrics_func = self.perf.get_storage_group_stats
self.run_performance_test_asserts(category, id_tag, key_func,
... | |
0056be967236bc158be5 | def get_user_ranking(self, request):
users = User.query().order(-User.score)
return RankForms(items=[user.to_ranking_form() for user in users]) | |
0056f6b6b05fce0ee91e | def getInterfaceStatuses():
ipOutput = runIpLink()
outputLines = ipOutput.split('\n')
matchedInterfaces = matchInterfaces(outputLines)
interfaceNames = map(lambda x: (x.group('interface'),
x.group('status')), matchedInterfaces)
return interfaceNames | |
0056ffa0a595650f85af | def calculate_velocity(self,c, t):
return 5 * c[0] * t**4 + 4 * c[1] * t**3 + 3 * c[2] * t**2 + 2 * c[3] * t + c[4] | |
00571c46f1e355877c8e | def test_temperature_forecast():
lat, lon = lookup_location()
forecast = SMHIForecast(lat, lon)
t_0 = (forecast.time[1] - forecast.reference_time).total_seconds() / 3600
t_1 = (forecast.time[5] - forecast.reference_time).total_seconds() / 3600
hours = np.linspace(t_0, t_1, randint(2, 20))
temp... | |
005736596af6b998ad1e | def calibrate_data(self,data):
this_obsid = int(self.getObsID(data))
# Get Gain Calibration Factors
nfeeds = len(self.feeds)
self.cal_factors = np.zeros((nfeeds,len(self.rrl_qnumbers),21))
for iqno in range(len(self.rrl_qnumbers)):
for ifeed,feed_num in enumerate(se... | |
005737630b128fc2da3b | def add_arguments(self) -> None:
pass | |
00577788ddb013889fcb | def evaluate(next_month, prediction):
next_month *= 0.1
prediction *= 0.1
plt.figure(1)
for i in range(len(next_month)):
plt.plot(next_month[i][0:24], label='next month')
plt.plot(prediction[i][0:24], label='prediction')
plt.legend()
plt.show() | |
0057792a741b1276e564 | def support_switch(func):
def wrapper(*args, **kwargs):
arguments = ""
for i in args:
arguments = f"{arguments}{str(i)}, "
for key, value in kwargs.items():
arguments = f"{arguments}{str(key)} = {str(value)}, "
func_name = func.__name__
python_code = ... | |
0057b8b8f3be305d7d3d | def idle_seconds():
return default_scheduler.idle_seconds | |
0057cfff16f268b6d2fe | def _is_valid_maze(dim_val, char_list):
return ( isinstance(dim_val, int) and
isinstance(char_list, list ) and
pow(dim_val,2) == len(char_list)
) | |
0057d05516283b9b2d72 | def _make_pdf_pdftk(fields, src_pdf, basename, flatten=False):
# Create the actual FDF file
fdfname = basename + '.fdf'
fdf = forge_fdf("", fields, [], [], [])
fdf_file = open(fdfname, "wb")
fdf_file.write(fdf)
fdf_file.close()
# Build the final flattened PDF documents
dest_pdf = ba... | |
0057ebdee3148e86a578 | def wait_until_attached(self, timeout=120):
raise NotImplementedError() | |
005831248add2876b6ce | def double(x):
return x ** 2 | |
00584af335721dd4dde2 | def open_connections(self) -> None:
try:
self.mysql_connection = mysql.connect(user=self._db_user, password=self._db_pass, database=self._db_name)
self.cursor = self.mysql_connection.cursor()
except mysql.Error as err:
logger.exception(f'open_connections: {err}') | |
00584f31b547889e2f8d | def get_url(self):
return '%s?nid=%s' % (self.url, self.id) | |
0058696ce374f140fefe | def Viterbi(all_possible_hidden_states,
all_possible_observed_states,
prior_distribution,
transition_model,
observation_model,
observations):
# TODO: Write your code here
num_time_steps = len(observations)
w = [None] * num_time_steps
... | |
00589348a95820638f44 | def load_module(self, module_path):
return self.load(runpy.run_module(module_path)) | |
0058b25b5a7811a28562 | def click_bot_popup(mybrowser, mytrain):
url_train = 'https://www.zugfinder.net/en/train-' + mytrain
sleep(2.0)
mybrowser.get(url_train)
sleep(2.0)
my_tr = mybrowser.find_element_by_id("2021-09-15")
my_tr.find_element_by_tag_name("td").click()
sleep(1.0)
mybrowser.find_element_by_link_te... | |
00592bc84c820f61869b | def test_output_txt(self, setup):
setup["test_obj"].slot = SlotW15(
Zs=6, W0=10e-3, W3=30e-3, H0=5e-3, H1=20e-3, H2=50e-3, R1=15e-3, R2=10e-3
)
setup["widget"] = PWSlot15(setup["test_obj"])
assert setup["widget"].w_out.out_slot_height.text() == "Slot height: 0.075 [m]" | |
0059445ec0c240c20261 | def iterate_fields(fields, schema):
schema_dict = {val["name"]: val for val in schema}
for field_id, properties in fields.items():
if "group" in schema_dict[field_id]:
for _field_sch, _fields in iterate_fields(
properties, schema_dict[field_id]["group"]
):
... | |
005957c2fe19cc9b46e4 | def setMetaData(obj, key_or_params, value=None, namespace=None):
if value is None:
for key, value in key_or_params.items():
if namespace:
key = "%s_%s" % (namespace, key)
obj.setMetaData(key, value)
else:
if namespace:
key = "%s_%s" % (namespa... | |
00596a96dbd34ddf7ba2 | def _is_installed(self):
# Check xsnoed
sys = os.uname()[0]
return self._system.file_exists('xsnoed', self.get_install_path()) | |
00596dfdff0552d537a8 | def parse_grib(self, grbs, message, grib_info):
grbs.seek(message)
grb_list = grbs.read(28)
tensor = np.zeros((23, 33, 28))
for lvl in range(len(grb_list)):
data, lats, lons = grb_list[lvl].data(lat1=41,lat2=52)
# [-6° ... -0.5° ]+[0° ... 10.5°[
# [35... | |
00597ddb3de22bf4854a | def checkToolpath(self, operations):
return bool() | |
00598a59128e95fc1ef4 | def max_backoff_duration(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "max_backoff_duration") | |
0059a8229a45ed91457a | def drawPolygon(self, image):
cv.polylines(image, [self.polygon_points], 1, (255, 255, 0), 3) | |
0059bb8ef1d91245aa16 | def serialise(self):
client_address = self.client.address
date = self.date.strftime("%d %b %Y")
invoice_number = self.number
return dict(client_address = client_address,
signatory = self.client.account.signatory,
bill_unit = self.client.bill_unit,
... | |
0059c69dfccb1e76adc1 | def match_any(seq, f_seq, pred):
f_sequence = [k for k in seq if f_seq(k)]
return _any(f_sequence, pred) | |
0059dca0bdf9460769df | def get_short_date_string(self):
return self.date.strftime('%d/%m/%y') | |
005a07bea128ac5d76f5 | def get_density_map(self):
count_map = self.get_count_map()
if np.sum(count_map) == 0:
return count_map
return count_map / self.total | |
005a40a068ba7c2a5aea | def strip_to_predicate(recipe):
return [(ot, [x.split('(')[0] for x in anns]) for ot, anns in recipe] | |
005a50514ea7e584d9bf | def test_get_user(self):
client = TestClient(APP)
# To get a CSRF cookie
response = client.get("/")
csrftoken = response.cookies["csrftoken"]
# Login
payload = dict(csrftoken=csrftoken, **self.credentials)
client.post(
"/public/login/",
j... | |
005a574e798f65366fe2 | def pc_work_time_var(self):
return _transmit_nodes_swig.howto_ekf2_ff_sptr_pc_work_time_var(self) | |
005a60d0bac7fd2244b1 | def is_inside(self, point, entity):
if isinstance(point,Atom): x, y, z = point.coord[0], point.coord[1],\
point.coord[2]
#~ print "garnice: sb_xmin: " + str(entity.xmin)
#~ print "atom: [" + str(x) + ", " + str(y) + ", " + str(z) + "]"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.