id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
00a2faa3d337dae25f8d | async def mastermind(self, ctx, difficulty='easy'):
current_game = None
for game in self.active_games:
if game.player == ctx.author:
current_game = game
break
if current_game:
await current_game.print_to_ctx(
ctx,
... | |
00a3014c29dede8c48eb | def group_tweets_by_state(tweets,find_state):
# A dictionary of state names and lists of closest tweets.
tweets_per_state = {}
for tweet in tweets:
# The state name is not in the dictionary.
if find_state(tweet) not in tweets_per_state:
# Assign a new key - state name to the dict... | |
00a3070e5bc160f5180d | def append(self, label, information):
self[label] = information | |
00a3289532218dc55e0d | def add_class(field, class_attr):
return field.as_widget(attrs={'class': class_attr}) | |
00a336905fb046e312d4 | def form_valid(self, form):
backend = MongoEngineBackend()
user = backend.authenticate(
username=self.request.POST['username'],
password=self.request.POST['password']
)
login(self.request, user.get_user())
# login(self.request, form.get_user())
ret... | |
00a3506ed323f12f3403 | def tuple_add(t1, t2):
return tuple(map(sum, zip(t1, t2))) | |
00a3507ceb3f54cfc0a8 | def reset_device_manager():
devices.gamepads = []
devices.keyboards = []
devices.mice = []
devices.microbits = []
devices._post_init() | |
00a35ab3c70f02acd090 | def setUp(self):
self.httpObj = HTTPClass() | |
00a364794c1d93313f1f | def view(diffs):
diffl = []
path = ''
def view_plain(dict4view, path):
"""Check and print dictionary in plain format.
Checks if value of the dictionary was updated, removed or added:
if it was removed prints info about it,
if it was added prints info about it,
if it... | |
00a36aefa10f7a40a076 | def test_duplicate_unicode_codepoints(self):
self.assertFalse(bool(self.validation_state & 0x400000)) | |
00a36f561c95329ce892 | def device_info(self):
return self._device.device_info | |
00a38864b3bd070f9dcf | def split(string):
return [letter for letter in string] | |
00a3b6b9d15177d185b2 | def compare_colors(N=36, compare_with="tab20", show=True):
import matplotlib.cm
import matplotlib.colors
import matplotlib.pyplot as plt
colors_distinctipy = distinctipy.get_colors(
N, exclude_colors=[(1, 1, 1), (0, 0, 0)], return_excluded=False
)
cmap = matplotlib.cm.get_cmap(compare_... | |
00a3c9dc1075dc749fb0 | def show_ref_table(self):
radius = self.radii[self.ref_band][0] #any radius will do
jds = self.jds[self.ref_band]
df = self.data[self.ref_band][radius][jds[self.ref_frame]]
return df | |
00a3ca756e56fa891d3e | def get_of_code(self, code):
raise NotImplementedError | |
00a3ddd802642ce919bf | def __lt__(self, other):
# first check the type
if not isinstance(other, MPolynomialIdeal):
return False
# the ideals may be defined w.r.t. to different term orders
# but are still the same.
R = self.ring()
S = other.ring()
# separate next two tests t... | |
00a400c9174f7cfb0406 | def asignaPersonaComoAlumno(self, persona): | |
00a41da8d05c0b0f6c9f | def parameter_combinations(cls):
return cls.generate_parameter_combinations({'proportion': [0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0],
'n_components': [3]}) | |
00a4286478087fe1f724 | def media_channel(self):
if self.media_content_type == MEDIA_TYPE_CHANNEL:
return self._channels.get(self._tv.channel_id)
return None | |
00a4294b48ee8b92bff1 | def read_byte_data(self, addr, register):
return self.regs[register] | |
00a42beec443f072b121 | def _compress_content(self, content):
zbuf = StringIO()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
zfile.write(content.read())
zfile.close()
content.file = zbuf
return content | |
00a4556514f3f3f77185 | def get_top_tokens(text_collection, n, stopwords):
return [] | |
00a473ced929abfaa981 | def loss(self, source='records'):
if source == 'records':
if self.stream is not None:
import_optional_dependency('pandas_xyz')
return self.activity.records[::-1].xyz.z_gain_threshold()
elif source == 'summary':
if 'loss' in self.summary.index:
return self.summary['loss']
... | |
00a477fbf50752ff6a98 | def check_gradients(self, outputs=None, atol=1e-5, rtol=1e-3):
delta = 1e-3
n_steps = self.unroll * 2
feed = self._fill_feed(
n_steps, {n: np.zeros((self.minibatch_size, n_steps, n.size_out))
for n in self.tensor_graph.invariant_inputs},
{p: np.zer... | |
00a4787bd6ae1d02d3a0 | def get_num_bp(bt):
return int(np.sum([i.length for i in bt])) | |
00a4896ffff15cad9463 | def get_distance(self, other_point):
return math.sqrt((other_point.x - self.x)**2 + (other_point.y - self.y)**2) | |
00a4a7d7794a2c4d98c6 | def build_aggregation(self, aggregation_level, time_step_delta):
if aggregation_level == None:
aggregation_level = "00"
self.set_time_step_delta(time_step_delta)
self.set_aggregation(aggregation_level + \
self.time_step_delta.get_time_step_level_str() + \... | |
00a4d12410e905209740 | def _text(self, *args, **kw):
return self._create('text', args, kw) | |
00a4db462b44585031bd | def ricker():
def time(t, s=1.):
s = jnp.atleast_2d(jnp.asarray(s)).T
# The normalization term 2 / (sqrt(3 s) pi^{1/4})
A = 2 / (jnp.sqrt(3 * s) * (jnp.pi**0.25))
# square the scale s^2
wsq = s**2
# t^2
xsq = t**2
# the modulation term (1 - t^2/a^2)
... | |
00a4ed55f0981886bd36 | def constantX(value):
return theano.tensor.constant(np.asarray(value,
dtype=theano.config.floatX)) | |
00a4fdbc7d1dcd6a9478 | def get_antpos_ecef(antpos, lon):
import pyuvdata.utils as uvutils
ecef = uvutils.ECEF_from_rotECEF(antpos, lon)
return ecef | |
00a4fdeb7f495b886948 | def forward(self, decode_out):
return self.fc1(self.dropout1(decode_out)) | |
00a50502fd682a2e4ca0 | def datastore_import(file) -> None:
with sqlite3.connect(DB_FILE) as connection:
initialize_tables(connection)
with open(file, 'r') as f:
data = json.load(f)
import_data(data, connection) | |
00a512639b3b8a68c7f4 | def climatology_check(time_series, clim_table, group_function):
grouped_data = time_series.groupby(group_function)
vals = [(g, clim_table.get(grp_val)) for (grp_val, g) in grouped_data]
# Should speed up processing of climatologies.
pool = multiprocessing.Pool()
chunks = pool.map(_process_time_chunk... | |
00a54362c92af0dbd49e | def startSession(self):
self._debug("Starting session with %s (no action)" % (self.server)) | |
00a570aac2b971b63c66 | def calc_y(self):
return sin(radians(self.yaw)) * self.radius | |
00a598a4547f3b084596 | def roundup_to_hundred(a,b):
return math.ceil( (max(a,b)) / 100) * 100 | |
00a5afa0663fa6843bc7 | def __thrustTorqueDeriv(self, Np, Tp, dNp_dX, dTp_dX, dNp_dprecurve, dTp_dprecurve,
r, precurve, presweep, precone, Rhub, Rtip, precurveTip, presweepTip):
Tb = np.array([1, 0])
Qb = np.array([0, 1])
Npb, Tpb, rb, precurveb, presweepb, preconeb, Rhubb, Rtipb, precurvetipb, presweepti... | |
00a5bf990c70126b74cb | def do_rmp(self, _):
sg.set_platoon(None)
sg.LOG("Platoon removed") | |
00a605857a5d46300dd0 | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
smappee_base = hass.data[DOMAIN][config_entry.entry_id]
entities = []
for service_location in smappee_base.smappee.service_locations.values():
for actuator_id... | |
00a6066b226314e7e7b6 | def compute_derivative(self, r, dr):
if r.requires_grad == False:
r.requires_grad = True
with torch.enable_grad():
kernel = self.forward(r)
ker_grad = self._grads(kernel, r)
return ker_grad.unsqueeze(1) * dr | |
00a6406d5d0d7dc75170 | def get_sensors(self):
return self.impedance_head.sensor_set | |
00a66a42c8473c278f82 | def _create_service(self):
if not self.sms.check_hosted_service_name_availability(self.service_name).result:
raise Exception("Name host is not available")
request = self.sms.create_hosted_service(self.service_name,
self.service_name,... | |
00a683832ac04db344d8 | def packitem_maybe_inplace(self, w_obj, w_arg, w_value):
w_modified = w_obj.packitem_maybe_inplace(self, w_arg, w_value)
return w_modified | |
00a6a94e1e99e83a3e50 | def violationsInHighestAndLowestPCs(periods):
connection = sqlite3.connect("inspection.db")
cursor = connection.cursor()
#Get postal codes with highest and lowest violations first(for lowest I choose 1 in many results)
command = """
SELECT i.FacilityZip, COUNT(*) as CountedViolation
... | |
00a6ae598a34475cd2dc | def checks(): | |
00a6bce45cbdb31ad4c6 | def process_tick(self):
pass | |
00a6c8cd042998530ceb | def __init__(self):
self.usage = """
%s input.experiment=experimentname input.run_num=N input.address=address
format.file_format=cbf format.cbf.detz_offset=N
%s input.experiment=experimentname input.run_num=N input.address=address
format.file_format=pickle format.pickle.cfg=path
"""%(libtbx.env.dispatcher_nam... | |
00a6c9ca3d32a9a1da4a | def enqueue(self, el):
self._queue.append(el) | |
00a6de9d24b356f8c713 | def check_queues(self):
did_work = False
for queue in self.receive_queues:
if not queue.empty():
did_work = True
msg = queue.get_nowait()
if not isinstance(msg, tuple):
raise ValueError(f'expected msg from receive... | |
00a6ed698a403a9c3e65 | def confusion_matrix(self, test_labels, class_classifications):
confusion_matrix = [[0 for k in range(self.n_clusters)]
for i in range(self.n_clusters)]
for label, classif in zip(test_labels, class_classifications):
confusion_matrix[label][classif] += 1
... | |
00a701c21d8e01a42194 | def setProperties(self, obj):
self.Type = "ReinforcementDimensioning"
if not hasattr(obj, "ParentDrawingView"):
obj.addProperty(
"App::PropertyLink",
"ParentDrawingView",
"ReinforcementDimensioning",
QT_TRANSLATE_NOOP(
... | |
00a70603d9b1e99b5aa1 | def test_reboot(self):
assert self.instance.time_rebooted is TIME_IN_PAST
assert self.instance.reboot_count == 0
self.instance.reboot()
assert self.inst.was_rebooted
assert self.instance.time_rebooted is not TIME_IN_PAST
assert self.instance.reboot_count == 1
# C... | |
00a739487efa367005e7 | def toutes_combinaisons(s):
lis=[]
for i in product(*[[0,1]]*s):
ch1=''
for j in range(len(i)):
ch1+=str(i[j])
lis.append(ch1)
return(lis) | |
00a758026089658900cc | def on_key_press(self, key, modifiers):
# if key == arcade.key.UP:
# self.player.change_y = self.movespeed
#elif key == arcade.key.DOWN:
# self.player.change_y = -self.movespeed
if key == arcade.key.A:
self.player.change_x = -self.movespeed
self... | |
00a795cd9cdf38a7bad8 | def collectOutput(self,finishedJob, output, options=None):
evaluation = finishedJob.getEvaluation()
outputDict = evaluation[1]
if self.cvScore is not None:
output.addRealization(outputDict)
else:
cvIDs = {self.cvID: np.atleast_1d(range(len(utils.first(outputDict.values()))))}
outputDic... | |
00a7af1ef87e29fb6875 | def get_user_name():
import getpass
user = getpass.getuser()
return user | |
00a7cd3ba4ec2b72c955 | def test():
import pytest
rv = pytest.main(["project/tests", "--verbose"])
exit(rv) | |
00a7fab63293b8d1ba20 | def processAlgorithm(self, parameters, context, feedback):
# Retrieve the feature source and sink. The 'dest_id' variable is used
# to uniquely identify the feature sink, and must be included in the
# dictionary returned by the processAlgorithm function.
alignment = self.parameterA... | |
00a81074414c8b63d74b | def create_default_credentials() -> credentials.Credentials:
# We can not use "gcloud auth application-default login" here because
# we use "gcloud app deploy" to deploy a Django app to app-engine. It
# requires "gcloud auth login".
command = ['gcloud', 'auth', 'login', '-q']
su... | |
00a821a46c2dda603d29 | def isRunnnig(self):
response = None
url = baseUrl+"/status"
try:
response = urllib.request.urlopen(url, timeout=5)
if str(response.getcode()).startswith("2"):
return True
else:
return False
except URLError:
... | |
00a82714a7ceed73087f | def question_to_vec(question, embeddings, dim):
# Hint: you have already implemented exactly this function in the 3rd assignment.
########################
#### YOUR CODE HERE ####
########################
count = 0
Q2V = np.zeros(dim)
for tok in question.split():
if tok... | |
00a857ecc04a71c8ee36 | def get_user_profile(self, username):
if username:
res = self.api.user(username)
else:
res = self.api.me()
return GithubConnector.build_profile(res) | |
00a85e8626120baa1abe | def numba_color2gray(image_array):
return _conversion(image_array).astype("uint8") | |
00a85edb11a75a4dbf3d | def add(self, state, action, reward, next_state, done):
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e) | |
00a8714a33b723da0318 | def get_magnitude(self):
return math.sqrt(self.x**2 + self.y**2) | |
00a88ad68b8de7414e20 | def test_list(self):
outputAssert = self.buildingTests(["3", "3", "20", "100", "1", "14", "5", "999", "20", "15"])
self.assertEqual(outputAssert[0][10], outputAssert[1][1], f"El resultado debería ser: \"{outputAssert[1][2]}\"") | |
00a892b8b00079f6ca74 | def coords( self ):
return self.x, self.y | |
00a89eaad6935eed97d7 | def to_full_name(author):
full_name = "{last_name}, {first_name} {middle_name}".format(
**defaultdict(str, {k: v.title() for k, v in author.items()})
)
return full_name.strip() | |
00a8db4376eb0bcf64e1 | def create(self, req, body):
if (body is None or not body.get('snapshot') or
not isinstance(body['snapshot'], dict)):
raise exc.HTTPUnprocessableEntity()
if 'display_name' in body['snapshot']:
body['snapshot']['name'] = body['snapshot'].pop('display_name')
... | |
00a8e525632ca9b17431 | def pixel_clock(self):
return self._block[9] * 10 | |
00a8f943fcf7cd49b550 | def tokenize(text):
#normalize
text = re.sub(r"[^a-zA-Z0-9]", " ",text.lower())
#tokenize
token_words=word_tokenize(text)
#remove stopwords from the token words
Stopwords=stopwords.words('english')
token_words = [w for w in token_words if w not in Stopwords]
#lemmatize each token wor... | |
00a918bacd6499793be8 | def cloud_download(self, local_dir='/tmp/'):
if self.path is None:
# Nothing to see here (possibly raise exception?)
return
if not os.path.exists(self.path):
try:
import cottoncandy as cc
except ImportError:
print("File ({})... | |
00a9227ca6f66041afcb | def insert_after(list, new, key):
if list == ():
return ()
else:
head, tail = list
if head == key:
return (head, (new, tail))
else:
return (head, insert_after(tail, new, key)) | |
00a95ab7f402c1f3c42c | def parse_file_info(filename):
with open(filename, 'r') as document:
all_files_info_list = []
pattern_chains_info = re.compile("c(\d+)n(\d+)")
lines = document.readlines()
lines = [line.strip() for line in lines]
for line in lines:
file_info_dict = {}
... | |
00a95c306ba60586befd | def problem(self, results):
if results.results[0].state == nagiosplugin.Unknown:
return results.results[0].hint
ret = ['%s is %.2f hours old' % (r.metric.name, r.metric.value)
for r in results if r.state != nagiosplugin.Ok]
return 'Snapshot %s' % ', '.join(ret) | |
00a96d9ce8d0a9135d53 | def truncate(self):
return self.client.post("{}/truncate".format(self.url)) | |
00a9701481b93680b1ec | def test_internet_down(self, logs, socket_patch):
connection = CheckInternetConnection()
self.assertFalse(connection.connected())
self.assertTrue(socket_patch.called)
self.assertRegex(logs.output[0],
'No Internet connection. Check your Internet connection and '
... | |
00a989c31354ed3ad362 | def disassemble(self, offset, size):
for i in DCode(self.CM, offset, size, self.get_buff()[offset:offset + size]).get_instructions():
yield i | |
00a993f4ebfa36805227 | def _set_scaling_months(self,
months):
self.months = months | |
00a9c37473837caace10 | def _drop_columns(self, column_names, cursor):
cursor.drop_columns(self.table_name, column_names) | |
00a9e56127ee356f057b | def build_model(self, input_dim):
model = Sequential()
model.add(Bidirectional(
LSTM(32, return_sequences=True), input_shape=input_dim))
model.add(Dropout(0.1))
model.add(Bidirectional(LSTM(16)))
model.add(Dense(self.n_class, activation="softmax"))
model.com... | |
00a9e9ff9314d7c5cc00 | def hit_rate(self):
if (self.INSTRUCTIONS != 0):
return self.PRIVATE_ACCESSES/self.INSTRUCTIONS
else:
return 0 | |
00a9ffc8f8263c6e68e1 | def input_definition(self, input_definition):
self._input_definition = input_definition | |
00aa0d2827cd980cd0cf | def count(self):
return self.size() | |
00aa107ada2f08821ef6 | def drawText(surface, text, color, rect, font, aa=False, bkg=None):
rect = Rect(rect)
y = rect.top
lineSpacing = 0
# get the height of the font
fontHeight = font.size('Tg')[1]
# Split by newline.
sp_text = text.split('\n')
# Loop through text.
for text in sp_text:
#... | |
00aa233eade56a4c2116 | def set_mod_paths(self, mod_paths=None):
# make sure we don't have the same path twice, using nub
if mod_paths is None:
# no paths specified, so grab list of (existing) module paths from $MODULEPATH
self.mod_paths = [p for p in nub(curr_module_paths()) if os.path.exists(p)]
... | |
00aa262f9c808e0d0a9f | def ai_sticks_to_take(self):
return random.choice(self.content) | |
00aa3e1cf26e7044118c | def scoreEvaluationFunction(currentGameState):
return currentGameState.getScore() | |
00aa4001c4e1d8ceafe0 | def extract(self, corpus):
# logging.info("\tWe are in\n")
all_substructures = []
arc_information = {}
id_to_doc_mapping = {}
debug_number_iterator = 0
# logging.info("\tWe are starting\n")
for doc in corpus:
# if debug_number_iterator % 100 == 0: l... | |
00aa4517543c88f0af71 | def _download_and_open_image(local_filepath, url):
if not os.path.exists(local_filepath):
_mkdir_unless_exists(os.path.dirname(local_filepath))
with contextlib.closing(urllib.urlopen(url)) as url_handle:
with open(local_filepath, 'wb') as file_handle:
shutil.copyfileobj(fsrc=url_handle, fdst=fil... | |
00aa532c47bc65ecbe1b | def load_input_file(file_path):
word_to_paraphrases_dict = {}
word_to_k_dict = {}
with open(file_path, 'r') as fin:
for line in fin:
target_word, k, paraphrases = line.split(' :: ')
word_to_k_dict[target_word] = int(k)
word_to_paraphrases_dict[target_word] = para... | |
00aa6656497795dc0ea3 | def test_clean_neither_set(self):
self.assertIsNone(self.pE_run.clean()) | |
00aa688197690e00a1ea | def get_example_search_queries(self):
res = run_sql("""SELECT example.body FROM example
LEFT JOIN collection_example on example.id=collection_example.id_example
WHERE collection_example.id_collection=%s ORDER BY collection_example.score""", (self.id,))
return [query[0] for query in res] | |
00aa6a1af2fb665a3d7d | def create(cls, **kwargs):
cls(owner=users.get_current_user(), **kwargs).save() | |
00aa7893e7810e159682 | def attach_cluster(cluster_id: str) -> None:
if not os.path.isdir(__CLUSTERS_PATH):
raise Exception("INTERNAL ERROR: Missing clusters directory: {}".format(__CLUSTERS_PATH))
for name in os.listdir(__CLUSTERS_PATH):
cluster_path = os.path.join(__CLUSTERS_PATH, name)
if not os.path.isdir(c... | |
00aa8112d6e14e577f22 | def __call__(self, *args) -> float:
return self.eval(*args) | |
00aacda09e4f2c9a2fdb | def test_update(self):
new_name = 'new_test_name'
is_updated = self.way.update(name=new_name)
self.assertTrue(is_updated)
way = Way.objects.get(id=self.way.id)
self.assertEqual(way.name, new_name) | |
00aae2163850f69bb0f8 | def is_empty(self):
return self.num_logs == 0 | |
00aae9840b533dc1465e | def _fit_decision_sets(self, XTrain, yTrain):
num_outer_idx = 2
# know which class is majority
majority = np.argmax(np.bincount(yTrain))
all_classes = np.unique(yTrain) # all classes in y
# sample size is variable. Therefore we will always maintain this sample size as maximum s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.