id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
004949ae8667a64bac6c | def add_hero(self, Hero):
self.heroes.append(Hero) | |
0049750a4ff66ef87acb | def construct_deck(number_of_decks=1):
deck = []
royals = ["K", "Q", "J"]
ace = "A"
for i in range(0,4*number_of_decks):
for i in range(2,11):
deck.append(i)
for royal in royals:
deck.append(royal)
deck.append(ace)
return deck | |
004982d8cd9531030cca | def test_get_path(self):
# Add / to the end
base_path = '%s%s' % (self.base_path, os.path.sep)
# Construct the script
script = TestScript(base_path, self.rand_str(), self.rand_str())
self.assert_equal(self.base_path, script.get_path(''))
self.assert_equal(os.path.join(s... | |
00498fcc44a6ee6401f3 | def genR(G):
l = G.number_of_edges()
n = G.number_of_nodes()
# Generate directed graph with n nodes and l links
# G = nx.generators.random_graphs.gnm_random_graph(n,l, seed = s)
# Edges to Links dictionary
edg2link = {}
ind = 0
for edg in G.edges_iter():
edg2link... | |
0049a428c901e9fa4dbd | def stripface(n, x0, y0, z0, w, h):
# Rectangular strips in the x-y plane.
x_new = x0
xy_strip_set = []
for i in range(n):
xy= [ [ x_new, y0, z0, 1.0 ], [ x_new+w, y0, z0, 1.0 ], [ x_new+w, y0+h, z0, 1.0 ], [ x_new, y0+h, z0, 1.0 ] ]
xy_mat = np.matrix(xy)
xy... | |
0049b47829805e34d4a2 | def mergeSort(arr):
if len(arr)>1:
mid = len(arr)//2
lefthalf = arr[:mid]
righthalf = arr[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
lenleft = len(lefthalf)
lenright = len(righthalf)
while i < lenleft and j < len... | |
0049c8a8422132c71be6 | def offset(self, par) :
return self._shaped_array_(par, self.pyda.pixel_offset(par), gu.PIXEL_OFFSET) | |
004a21e8e4d87a7a9081 | def __str__(self):
states_str = "states = \n["
for state_row in self.channel_configs:
states_str += str(state_row) + ',\n'
states_str = states_str[:-2] + ']\n'
matrix_str = "matrix([\n"
for row in self.matrix:
matrix_str += '['
matrix_str += '... | |
004a2b1b36deb7d86084 | def __init__(self, host, port=DEFAULT_PORT):
self._host = host
self._port = port | |
004a40337980c12c2dd8 | def generate_two_fake_datasets(self):
t_0 = self.model.parameters.t_0
delta_t = self.n_tE * self.model.parameters.t_E
times = np.arange(t_0-delta_t, t_0+delta_t, self.dt)
self.data_1 = self.generate_dataset(
self.f_source_1, self.f_blend_1, times)
self.data_2 = self... | |
004a478a893485b3dd1e | def useragent(self) :
try :
return self._useragent
except Exception as e:
raise e | |
004a55447f7000c69c8a | def __contains__(self, key):
return key in self.nodes | |
004a7242c43ceb8d3376 | def test_b(self):
return | |
004a8df97f6b9aadb6f3 | def BBox_FromExtents(xmin, ymin, zmin, xmax, ymax, zmax):
s = BRepPrimAPI_MakeBox(gp_Pnt(xmin, ymin, zmin),
gp_Pnt(xmax, ymax, zmax)).Shape()
ais_bbox = AIS_Shape(s)
ais_bbox.SetDisplayMode(AIS_WireFrame)
return ais_bbox | |
004a975dc28f70348dd4 | def main_2d_plot(syzes, crossovers, fig=None, ax=None):
if fig is None:
fig = plt.figure()
if ax is None:
ax = fig.add_subplot(1, 1, 1)
ax.set_xlabel("system size")
ax.set_ylabel("crossover time")
ax.set_title("Crossover time as a function of system size scatter plot")
ax.scatte... | |
004a9aa97795938ab9f5 | def output(self) -> bool:
return self.and_gate.output | |
004a9e07b827229eed7e | def save_dict_to_json(self, dic):
file_path = pathlib.Path.cwd().parent.joinpath('res', self.dst_json_path)
with open(file_path, 'w'):
json.dump(dic, file_path)
pass | |
004aad02fd1be085fbb2 | def is_public(self):
return False | |
004ac7931709fa440a88 | def has_user(self, user): | |
004ac915d6e269748af4 | def switch(self,a,b,f=None,t=None):
# copy shelf
h = self.copy()
# switch all books
for n,i in enumerate(h):
h[n] = i.switch(a,b,f,t)
return h | |
004adef4568f1c70e582 | def test_factorial_api_with_post(self):
response = self.client.post(self.FACTORIAL_API_ENDPOINT+"/4")
assert response.status_code == 405
assert response.json == "POST method is not allowed. Please use only GET http method." | |
004ae8e72f457fcbcd85 | def _get_client():
return client.ClientV1(api_version=INSPECTOR_API_VERSION,
inspector_url=CONF.inspector.service_url,
session=_get_inspector_session()) | |
004afa571afd28ece042 | def isprintable(self, *args, **kwargs): # real signature unknown
pass | |
004b04d0705574bb173f | def __init__ (self, label, word, lang, greek_mode, w, c, s):
self.label = label
self.word = word
self.lang = lang
self.term = None
self.greek_mode = greek_mode
self.w = w
self.c = c
self.s = s | |
004b33ca8f59f56ff821 | def getStrips(seq):
deltas = [seq[i+1] - seq[i] for i in xrange(len(seq)-1)]
increasing = list()
decreasing = list()
start = 0
for i, diff in enumerate(deltas):
if (abs(diff) == 1) and (diff == deltas[start]):
continue
if (start > 0):
if deltas[start] == 1:
... | |
004b33f8a5313643f698 | def disable_attention_slicing(self):
# set slice_size = `None` to disable `attention slicing`
self.enable_attention_slicing(None) | |
004b39344e55e98ad175 | def tray_icon_activated(reason):
if reason == QSystemTrayIcon.Trigger:
self.show() | |
004b3b1ada1af4b5a6bd | def make_tilegrid():
group = displayio.Group()
sprite_sheet, palette = adafruit_imageload.load("/tilesheet-2x.bmp",
bitmap=displayio.Bitmap,
palette=displayio.Palette)
grid = displayio.TileGrid(sprite_sh... | |
004b54ee954669f749e3 | def next_test_batch(self):
batch = []
for traj in self.test_tups:
random.shuffle(traj)
for data in traj:
action = data['action']
if(self.precompute):
state = data['feature']
else:
... | |
004b5bdf0321c222c704 | def launch(lti=lti):
# example of getting lti data from the request
# let's just store it in our session
session['full_name'] = request.form.get('lis_person_name_full')
# Write the lti params to the console
app.logger.info(json.dumps(request.form, indent=2))
session['guid'] = request.form.get... | |
004b9f54784e8dd89d47 | def sort_rows(rows, column=1, highest_first=True):
return sorted(rows,
key=itemgetter(column),
reverse=highest_first) | |
004ba7b2fc5f931e3dbc | def setup_layers(self, params):
in_layer = tf.placeholder(
"float",
name="input",
shape=[None, params.in_size]
)
coeff = tf.Variable(tf.ones([params.in_size, 1]), name="coeff")
intercept = tf.Variable(tf.zeros([1,]), name="intercept")
out_... | |
004babc5bdae58dcfe83 | def assure_directory_exists(path, is_file=False):
if is_file:
path = os.path.dirname(path)
#END handle file
if not os.path.isdir(path):
os.makedirs(path)
return True
return False | |
004bceb99b64ab44c069 | def main():
import nltk, re, pprint # I don't know if these are all necessary to import
from nltk import word_tokenize # but I put them here just in case
from urllib import request
from bs4 import BeautifulSoup
url = "https://yle.fi/uutiset/18-89760"
url_decoded = request.... | |
004bd8bcb8c5dbbb3916 | def delete(self, key):
_unimplemented(__name__) | |
004bdfa3fa4646337f77 | def squarea(self,a):
self.alpha = self.alpha*a | |
004c404ef934cff1f25e | def CopyToStatTimeTuple(self):
if self.timestamp is None:
return None, None
return self.timestamp, None | |
004c654e470549d47059 | def calc_gradient(self, X: np.ndarray, y: np.ndarray) -> np.ndarray:
pass | |
004c76f264f3b1214401 | def retrieve_all_tracks_from_playlist(playlist_id):
fields = "tracks.items.track.id, tracks.next"
response_json = sp.playlist(playlist_id, fields=fields)[func_dict.tracks]
return_df = pd.json_normalize(response_json[func_dict.items])
while response_json[func_dict.nextt]:
response_json = spotify... | |
004c7ddf27b977968c15 | def do_POST(self):
self.server.helper.getLogger().ddebug("Handling POST request from another probe")
contentLength = self.headers.get("content-length")
# read content
args = self.rfile.read(int(contentLength))
# convert from bytes to string
args = ... | |
004c9028f033e81705bb | def basemap_latlon(self, func, *args, latlon=True, **kwargs):
return func(*args, latlon=latlon, **kwargs) | |
004c904e386c868755cf | def _check_symbol_matches_synopsis_name(self, docstring, cursor, loc, symbol):
if symbol != cursor.name:
if len(difflib.get_close_matches(symbol, [cursor.name], n=1)):
mess = f"Docstring name '{symbol}' does not match symbol. Assuming you meant '{cursor.name}'"
patch = Patch(loc, cursor.name)... | |
004ca417419421991f94 | def set_crosshairs(self, state):
self.frame.set_crosshairs(state) | |
004ca9ff2b0ef5f00b16 | def generate_events(raw, duration=60):
num_events = raw.n_times / raw.info['sfreq'] / duration
events = np.zeros(shape=(int(num_events), 3), dtype=int)
for idx, event in enumerate(events):
event[0] = idx * raw.info['sfreq'] * duration
event[1] = 0
event[2] = 60053
return events | |
004caf5a2094e88e4589 | def n_optimization(self):
return len(self._inds['opt']) | |
004cca04d5040310c3a5 | def get_droplets():
data = handle_url('/droplets/')
return data['droplets'] | |
004ce0bb28caea06be79 | def main():
# Instantiate a dummy authorizer for managing 'virtual' users
authorizer = DummyAuthorizer()
# Define a new user having full r/w permissions and a read-only
# anonymous user
# authorizer.add_user(environ['FTP_USER'],
# environ['FTP_PASS'],
# ... | |
004d229ef9bb7936cceb | def codegenerator(modname, prefix, grammar):
parser = GrakoGrammarGenerator(prefix, filename=modname)
model = parser.parse(grammar)
code = pythoncg(model)
module = imp.new_module(modname)
exec_(code, module.__dict__)
sys.modules[modname] = module
return module | |
004d2bd2ace38c36e660 | def _get_external_resources(self):
content = {}
element = self._validate_name + '.html'
element_files = {
'root': { # the root directory
'index.html': self.external_links['index'],
element: self.external_links['seed_element'], # seed-element
... | |
004d49f45fccfdce76bc | def action_type(self) -> pulumi.Output[str]:
return pulumi.get(self, "action_type") | |
004d4f530f2ab4dc2edd | def getFiles(folderpath):
return glob.glob(os.path.join(folderpath, "*.json")) | |
004d519d88a40ce4893a | def convert_to_int_seqs(path, field, token2int,
delimiter='|', maxlen=float('inf')):
int_seqs = []
for line in open(path):
elements = line.strip().split(delimiter)
token_list = elements[field].split()
int_seq = convert_to_int_seq(token_list, token2int, maxlen)
int_seq... | |
004d54b16efd07d8b962 | def get(cache_key):
packed_value = cache.get(cache_key)
if not packed_value:
return None
value, refresh_time, refreshed = packed_value
if (datetime.datetime.now() > refresh_time) and not refreshed:
# Store the stale value while the cache revalidates for another
# MINT_DELAY secon... | |
004d6373f668fb4283ac | def test_already_event_exist(self):
registration(self)
self.client.post(
'/create-event',
data=json.dumps(self.event),
content_type='application/json',
headers={
'Authorization': authorization(self)
})
res = self.client.... | |
004d653ea018e90be075 | def pearson_dist(x, y):
return np.sqrt(2 * (1 - pearson(x, y))) | |
004d809b5d1565752192 | def still_playing():
return True # TODO add win/lose conditions | |
004d81075ded28d6971a | def test_03_call(self):
toSucceed = DummyEventClass()
toSucceed.name = 'toSucceed'
toSucceed.event = self.setValInt
toSucceed.event2 = self.setValIntRetInt
#
toFail = DummyEventClass()
toFail.name = 'toFail'
toFail.event = self.throwawayInt
toFail.... | |
004d84dc710386721d0b | def show_plot_widget(self):
selection = self.plt_optns.currentText()
if selection == 'Axis Aligned Slice Plot':
AxisSlicePltW(self.parent, self, self.plot_ref)
if selection == 'Axis Aligned Projection Plot':
AxisProjectionPltW(self.parent, self, self.plot_ref)
if... | |
004d96ee7070f12e4733 | def get_all_masks(n_tokens, max_subset_size):
masks = []
for subset_size in range(1, max_subset_size + 1):
index_combos = itertools.combinations(range(n_tokens), subset_size)
for indices_to_allow in index_combos:
mask = np.zeros(n_tokens)
mask[np.array(indices_to_allow)] ... | |
004dbbd9a7bdf098dd5b | def remove_stop_words(self):
self.pipe.remove_stop_words() | |
004dbc9f3bbfed5a4f26 | def LoadPowerImage(fname,wl=None,inttime=None):
if wl == None: wl = input('Enter wavelength (nm):')
if inttime == None: inttime = input('Enter Integration Time (ms):')
if os.path.splitext(fname)[-1] == '.fit': image = LoadFITS(fname)
elif os.path.splitext(fname)[-1] == '.TIF': image = LoadTiff(fname)
#image = ... | |
004dc816e4178050df24 | def load_dict(self, strFileName):
temp = file(strFileName, 'r').read()
self.dictProbTable = eval(temp)
self.MLincomplete = False
return | |
004dde5847badcf394e2 | def __del__(self):
self.log_file.flush()
self.log_file.close() | |
004de9f7826617ab5892 | def is_cluster(self, n):
return np.any(self.mx[n] == 1) | |
004df6a22ff5b322570a | def make_datetime_struct(time_str):
fmt = "%Y %m %d %H %M %S"
time_struct = datetime.datetime.strptime(' '.join(re.split('-|:|\ ', time_str)), fmt)
return time_struct | |
004df7a9b3f88be734b5 | def Schoof():
pass | |
004e0ae6b179873db30b | def __str__(self):
raise NotImplementedError | |
004e0e8f4b14428ac2af | def arguments(
argv: List[str] = None,
flag_name_converter: Callable[[Path], str] = None,
):
return Arguments(
argv=argv,
flag_name_converter=flag_name_converter
) | |
004e5836aec21270d0ae | def batch_loss(self, batch):
fX, y = self.embed(batch)
distances = self.pdist(fX)
# sample triplets
triplets = getattr(self, "batch_{0}".format(self.sampling))
anchors, positives, negatives = triplets(y, distances)
# compute loss for each triplet
losses = self.... | |
004e7850676566c58bdd | def scrapeInfo(self, html):
return | |
004e7c057b289a5bcbe8 | def containerize_command(self, command): | |
004ea20e319a1e0c4c08 | def get_config_data():
data = {}
with open (CONFIG_FILE_PATH, 'r') as f:
data = json.load(f)
return data | |
004ec647544f0322db36 | def read_distance(self):
return self._robot.read_distance() | |
004ed9c532588402ccd2 | def info():
return "" | |
004ede48028de3eb6726 | def _pad(tensor, tformat, seq_lens, val):
assert tformat in ["a*bs*t*v", "bs*t*v"], "invalid tformat"
bs_ids = range(tensor.shape[_bsdim(tformat)])
for _bs in bs_ids:
first_nan_t = seq_lens[_bs]
if first_nan_t < tensor.shape[_tdim(tformat)]:
if tformat in ["a*bs*t*v"]:
... | |
004ef656d75296670056 | async def get_stock_exchange_stream(self):
try:
subsr_id = await self.__get_subscription_id(STOCK_EXCHANGE)
return self.stream_stub.GetStockExchangeUpdates(subsr_id, metadata=self.__getmd_for_bot())
except Exception as e:
error_traceback = ''.join(traceback.format_tb(... | |
004f115d98c23f08eb79 | def __init__(self):
self._solver_list = ["hyperopt",
"optunity",
"optuna",
"randomsearch",
"quasirandomsearch",
"gridsearch"] | |
004f2fd992dc4a66ad70 | async def call(self, event, data=None, to=None, sid=None, namespace=None,
timeout=60, ignore_queue=False):
if to is None and sid is None:
raise ValueError('Cannot use call() to broadcast.')
if not self.async_handlers:
raise RuntimeError(
'Cannot... | |
004f3989c3d9f847e8f8 | def map(self, f):
return self.bind(
lambda x: self.ret(f(x))
) | |
004f43ab343b07aa3e90 | def split_timestamp(msg: str) -> Tuple[str, Optional[int]]:
try:
m = TIMESTAMP_REGEX.match(msg)
mainmsg = m.group(1)
timestamp = int(m.group(2))
return mainmsg, timestamp
except (TypeError, AttributeError, ValueError):
return msg, None | |
004f4fcfe28641f9c3b8 | def _update_reward_variables(self):
subtask_step = self._subtask_step
self._leg, self._table = self._recipe["recipe"][subtask_step]
self._leg_site, self._table_site = self._site_recipe[subtask_step][:2]
if len(self._site_recipe[subtask_step]) == 3:
self._leg_table_angle = se... | |
004f96057caabc36bad6 | def fixture_loader():
return load_fixture | |
004fabba1cdfe198ae29 | def validate(self):
if self.dialogType == "bid": return self.isBidLegal()
elif self.dialogType == "trump": return self.isTrumpLegal()
elif self.dialogType == "bidtrump": self.isBidTrumpLegal()
else: return 1 | |
004fbfc17b558371116a | def test_well_search_gps(self):
lat_long_box = {'start_corner': '48.418466095707046,-123.36755990982056', 'end_corner': '48.41493417062313,-123.36180925369264'}
wells = Search.well_search('', '', '', '', lat_long_box)
self.assertEqual(wells.count(), 2) | |
004fc05c1004b4493d70 | def fill_with_space_to_length(string_to_fill, new_length, align='left'):
delta = new_length - len(string_to_fill)
if delta > 0:
if align == 'left':
return string_to_fill + ' ' * delta
return ' ' * delta + string_to_fill
return string_to_fill | |
004fe10ad75feb248652 | def model_id_to_vertices_and_triangles(self, model_id):
if model_id in self.raw_models:
data = self.raw_models[model_id]
elif model_id in car_id2name:
data = self.raw_models[car_id2name[model_id]]
else:
raise KeyError(model_id)
vertices = np.array(dat... | |
004fea8478e02cd52b84 | def bootstrap(input_x, input_y, sample_size):
l = len(input_x)
# generate our up-sample index
upsample_idx = np.random.choice(range(l), sample_size)
# with these indices, extract the corresponding observations
output_x = input_x[upsample_idx]
output_y = input_y[upsample_idx]
return output_x... | |
005043366a851c0702c1 | async def onreact_add(self, ctx, message: discord.Message, emoji, role: discord.Role):
try:
emoji = await commands.EmojiConverter().convert(ctx, emoji)
except commands.BadArgument:
if emoji not in emoji_module.UNICODE_EMOJI:
await ctx.send("I do not have access to... | |
005054134378b9b594fb | def visualize_configurations(args):
# Data
data = np.loadtxt(args.data)
print(data)
# Plot parameters
figsize = 250
dpi = 100
trimfrac = 0.4
figsizeextra = round_up_to_even(figsize * (1 + trimfrac))
figsizeextra_inch = figsizeextra / dpi
# Plotting
plt.figure... | |
00509ab51611ace1b33c | def set_game_results(self):
opponents = [0, 1, 2, 3]
opponents.remove(self.game_player_id)
if self.game['kind'] == 'sauspiel':
team_mate = self.get_team_mate() | |
0050aa0f1cd2450eeac8 | def __init__(self):
self.home_root = self._getHome()
self.scratch_root = self._getScratch() | |
0050ab1b8e7c9f08d223 | def check_reboot(): | |
0050bd814957ca6721d1 | def set_constants(cls, constants):
cls.constants = constants | |
0050c0c3e4cbb3e972ed | def test_knn(self) -> None:
# Creating data
fd_train_basis, fd_test_basis, y_train_basis = _create_data_basis()
fd_train_grid, fd_test_grid, y_train_grid = _create_data_grid()
# Test KNN method with basis representation, n_neighbours=3 and
# uniform kernel
knn_basis = Ke... | |
0050da3d4d66a13890c4 | def verify_expected(expected):
def advection_verify(claw):
from clawpack.pyclaw.util import check_diff
import numpy as np
q0=claw.frames[0].state.get_q_global()
qfinal=claw.frames[claw.num_output_times].state.get_q_global()
if q0 is not None and qfin... | |
0050e9385beef7770d0e | def get_logon_challenge(self, username, password):
pak = DataBuffer()
pak.insert_string(username)
pak.insert_string(password)
self.send_packet(BNLS_LOGONCHALLENGE, pak)
pid, pak = self.receive_packet()
if pid != BNLS_LOGONCHALLENGE:
return None
retur... | |
0050fde09cbbd58e9c1b | def stash(self, payload):
# Pause a specific process, if we have a key in our payload
key = payload['key']
if self.queue.get(key) is not None:
if self.queue[key]['status'] == 'queued':
self.queue[key]['status'] = 'stashed'
answer = {'message': 'Process... | |
0051254cb8a0c4d3b5a7 | def new(self, obj):
key = str(obj.__class__.__name__ + "." + obj.id)
self.__objects[key] = obj.to_dict() | |
00513504998b5ac026c9 | def _assertOutput(self, expected_files):
for root, dirs, files in os.walk(self.workdir, topdown=False):
for name in files:
self.assertTrue(name in expected_files)
self.assertTrue(os.stat(os.path.join(root, name)).st_size > 0) | |
005170d82d8da3178998 | def GenerateNthFibonacci(n: int):
return phi**n/rt5 - (1-phi)**n/rt5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.