id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
001203528bf457a56049 | def file_changes_reloader():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
path = sys.argv[1] if len(sys.argv) > 1 else "templates/"
path_to_metrics = sys.argv[1] if len(sys.argv) > 1 else "metrics/"
event_handler ... | |
0012042aff988de3d3d2 | def test_reversible_encoding():
text = "For the glory for mankind"
encoder = Encoder([text])
coded = encoder.encodetext(text)
decoded = encoder.decodeindexes(coded)
print("Original text: %s" % text)
print("Encoded text: " + str(coded))
print("Decoded text: %s" % decoded)
assert text == ... | |
00121717804c37654b36 | def format_kml_placemark_description(placemarkdict):
starttag = "<![CDATA["
newlinetag = "<br />\n"
endtag = "]]>"
descriptionlist = []
descriptionlist.append(starttag)
for item in placemarkdict:
if isinstance(placemarkdict[item], dict):
descr... | |
00122b9ee0911d27b9e7 | def process_file(file_name):
result = []
try:
with open(file_name, 'r+') as logfile:
print("Opening: %s" % file_name)
execution_start_time = time.time()
for line in logfile:
result.append(_tokenize_line(line))
execution_end_time = time.... | |
00122d1058fa22a298c7 | def build_graph(self, graph, inst_name, port_nets):
self.add_graph_edges(graph, port_nets) | |
001268d02223a387fc89 | def lower(parameters: ARRAY_FLOAT) -> float:
lower_bound = float(parameters[2])
return lower_bound | |
00127b6da776eb780270 | def load(self, symbols=None, df=True, from_csv=True):
if isinstance(symbols, str):
symbols = [symbols]
pricing_data = {}
for symbol in symbols:
if from_csv:
data_df = pd.read_csv(self._output_path(symbol))
date_col = self.column_names[0]
... | |
00127dbc3d298ab4a4ee | def _validate_text(self, odbc_cursor):
return "valid" | |
00128abcd72caa868760 | def tuple_avg_rec(aList):
newList = []
if (len(aList) == 1):
newList.append((sum(aList[0]))/(len(aList[0])))
else:
newList.append((sum(aList[0]))/(len(aList[0])))
newList.extend(tuple_avg_rec(aList[1:]))
return newList | |
00129073798ec0996c1c | def create_gui(self):
masterframe = ttk.Frame(self)
masterframe.grid(column=0, row=0, sticky=tk.NSEW)
masterframe.rowconfigure(99, weight=1)
self.book = ttk.Notebook(masterframe)
self.book.grid(column=0, row=0, sticky=tk.NSEW)
self.materials = MaterialsTab(self.book, s... | |
00129f671257e4d0dd7c | def hey(sentence):
bob = SpeechSorter(sentence)
if bob.gibberish():
return "Fine. Be that way!"
elif bob.yelling():
return "Woah, chill out!"
elif bob.question():
return "Sure."
else:
return "Whatever." | |
0012aa73077fa85266fd | def get_candidate_files(self):
return self._git_ls_files(["ls-files", "--cached"]) | |
0012b86c525b705f7a27 | def remove(table, id_=None):
# your code
id_ = ui.get_inputs(['id'], "Give id:")[0]
common.remove(table, id_) | |
0012d3a0c89f7f4adacf | def wc(file_):
with open(file_,"r") as count_file:
cfile = count_file.read()
linecount = len(cfile.splitlines())
wordcount = len(cfile.split())
charcount = len(cfile)
return f"{linecount} {wordcount} {charcount} {file_}" | |
0012d8ee6d653abe625f | def associate_project_with_quality_profile(self, project, language, qualityProfile): | |
00130e4a78ee85e3e33d | def test_get_many(self):
p = Post(type='tweet', id='1234')
p2 = Post(type='post', id='2345')
self.engine.save([p, p2])
ret = self.engine.get(Post,
[{'uid': 'tweet:1234', 'score': 0},
{'uid': 'post:2345', 'score': 0}])
... | |
00131312ee379c10a618 | def _create_course_with_access_groups(self, course_location, user=None, store=ModuleStoreEnum.Type.split):
course = CourseFactory.create(
org=course_location.org,
number=course_location.course,
run=course_location.run,
default_store=store
)
self._a... | |
001336a503719e250d58 | def path_to_local_file_uri(path):
path = pathname2url(path)
if path == posixpath.abspath(path):
return "file://{path}".format(path=path)
else:
return "file:{path}".format(path=path) | |
00134f8dddc7a2ff4a85 | def relative_rate(self):
return _sdesign_swig.zybo_fft_sptr_relative_rate(self) | |
00136ebcf5cb5eb1d2c1 | def axesNames(cls):
return tuple(['Y', 'X']) | |
001381f1f759aad5bc7d | def ask_task_user(update, context):
query = update.callback_query
query.answer()
reply_markup = None
task = context.user_data.get(consts.CURR_TASK)
if task is not None:
keyboard = []
reply_markup = None
# There's only one user in private chats
if query.message.chat.... | |
0013ac00dc45d1aca86f | def parse_for_field(response, field = ""):
lines = response.split("\r\n")
map = {}
map["body"] = lines[-1]
map["top"] = lines[0]
map["method"] = lines[0].split(' ')[0]
map["url"] = lines[0].split(' ')[1]
map["http_version"] = lines[0].split(' ')[2][5:]
for i in range(1, len(lines) - 1):... | |
0013b3ad74709a00a35d | def corp_income(revenue, expenditure, income, loss):
if (revenue >= expenditure):
income = revenue - expenditure
loss = 0
else:
loss = -(revenue - expenditure)
income=0
return (income, loss) | |
0013cd78faf3dfda22a3 | def _is_done(self, state=None):
raise NotImplementedError | |
0013fc931fbbe91b82b6 | def estimate_fundamental_matrix(points_a, points_b):
###########################################################################
# TODO: YOUR FUNDAMENTAL MATRIX ESTIMATION CODE HERE
###########################################################################
num = points_a.shape[0]
A = np.zeros((num,... | |
00143106b530522656bb | def _interpolate(format):
def matchorfail(text, pos):
match = tokenprog.match(text, pos)
if match is None:
raise _ItplError(text, pos)
return match, match.end()
namechars = "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
chunks = []
po... | |
001463baeec11ec88953 | def delay(self, seconds, func, *args, **kwargs):
now = time.time() # Note: this is before the lock
with self._lock:
self._delay_call.append(DelayedFunc(now, seconds, func, args, kwargs))
self.ensure_running() | |
001498f6d8c3018653ba | def main(_):
model_exists = utilities.check_model_exists(args.ckpt)
if not model_exists:
raise ValueError("Model not found")
network_params, dataloader_params, training_params = configure_parameters()
print("=======dataloader_params: {}".format(dataloader_params))
network, dataloader, traini... | |
0014a9fa7e727831d1e0 | def _assert_set_with_options(self, test_cases):
category, existing_key, cases = test_cases
msg = "Failed in: {}".format(category)
if existing_key:
self.redis.set('key', 'value')
for (key, value, expected_result), config in cases:
# set with creation mode and... | |
0014ae884b0948223831 | def __init__(self, parallel_corpus):
self.pc = parallel_corpus
self.build_vocab(parallel_corpus)
self.build_dictionaries() | |
0014ba6bae7c6996907b | def _day_rule_matches(self, rule, dt):
if dt.weekday() == 4:
sat = dt + datetime.timedelta(days=1)
if super(SiteHolidays, self)._day_rule_matches(rule, sat):
return True
elif dt.weekday() == 0:
sun = dt - datetime.timedelta(days=1)
if super... | |
0014bf4124a5fe41c6b7 | def getLastPhotoID():
db = sqlite3.connect('db/main.db')
curs = db.cursor()
curs.execute('''SELECT max(id) FROM photo''')
return curs.fetchone()[0] | |
0014d0c161bb4882f6b4 | def add(self, product, quantity):
print("funcion añadir del carrito")
print("id producto " + str(product.id))
print("cantidad " + str(quantity))
product_id = str(product.id)
if product.id not in self.cart: # esto no funciona
print("el producto no esta en el carrito"... | |
0014d1ad037eccb018cf | def makebctmat(self):
self.bctmat = np.zeros((len(self.G.nodes()),len(self.G.nodes())))
nodeIndices = dict(zip(self.G.nodes(), range(len(self.G.nodes()))))
for nn,x in enumerate(self.G.nodes()):
for y in self.G.edge[x].keys():
try:
self.bctmat[nn,n... | |
0014e71f4db6d682f8cc | def simple_hash(int_list, prime1, prime2, prime3):
result = 0
for integer in int_list:
result += ((result + integer + prime1) * prime2) % prime3
return result | |
0014ed897966a3ad8259 | def test_1_qubit_identities(self):
# T*X*T = X
elem1 = CNOTDihedral(1)
elem1.phase(1, 0)
elem1.flip(0)
elem1.phase(1, 0)
elem2 = CNOTDihedral(1)
elem2.flip(0)
self.assertEqual(elem1, elem2,
'Error: 1-qubit identity does not hold')
... | |
0014f5eb01d985d5ef2f | def home():
return render_template("index.html") | |
0014f7c5a43376e4fd91 | def sort(src, flags, dst=None): # real signature unknown; restored from __doc__
pass | |
0014f985651842e60752 | def float_to_dyna(f):
return int(f * math.pow(10, DECIMAL_PLACES)) | |
001503e136820640156a | def bits(tensor: tf.Tensor, bitsize: Optional[int] = None,) -> list:
with tf.name_scope("bits"):
bitsize = bitsize or (tensor.dtype.size * 8)
the_bits = [
tf.bitwise.bitwise_and(tf.bitwise.right_shift(tensor, i), 1)
for i in range(bitsize)
]
return the_bits
... | |
00151e32e93fe67134bf | def summary(self):
total = self.stop - self.start
s = "%s duration: %0.2f\n" % (self.name, total)
prev = ("start", self.start)
for tick in self.ticks:
s += (" %s => %s" % (prev[0], tick[0])).ljust(30) + "... %0.2fs\n" % (tick[1] - prev[1])
prev = tick
s ... | |
00152e12bfe751c51692 | def test_reionize3():
assert standardize_smiles('C1=C(C=C(C(=C1)O)C(=O)[O-])[S](O)(=O)=O.[Na+]') == 'O=C(O)c1cc(S(=O)(=O)[O-])ccc1O.[Na+]' | |
001535fb288a6a152a49 | def home():
search_form = SearchForm()
page = request.args.get('page', 1, type=int)
reports = Report.query.order_by(Report.date_posted.desc()).paginate(
page=page, per_page=100)
latest_reports = get_latest_reports()
return render_template('home.html', title="Market Report List",
... | |
0015456ee00fdddd0a1f | def testParseOptions(self):
test_artifacts_path = self._GetTestFilePath(['artifacts'])
self._SkipIfPathNotExists(test_artifacts_path)
test_file_path = self._GetTestFilePath(['testdir'])
self._SkipIfPathNotExists(test_file_path)
yara_rules_path = self._GetTestFilePath(['rules.yara'])
self._Skip... | |
00154890f020404dba33 | def data_process(self, data):
pass | |
0015502bf8eaa3298cc3 | def contains_point(self, pt):
# (my_x, my_y) = (self.corner.x, self.corner.y)
# my_width = self.width
# my_height = self.height
# (x, y) = (pt.x, pt.y)
# return ( x >= my_x and x< my_x + my_width and y >= my_y and y < my_y + my_height)
return (
self.corn... | |
001551cd610394e0d6d0 | def set(self, key, **kwargs):
return self._redis_client.set(key, **kwargs) | |
00157fcf87c623e5c946 | def _extract_kwargs(cls, kwargs):
return dict([(p, kwargs.pop(p, None))
for p in cls._method_parameters]) | |
0015f5ca1ebf6317a9c5 | def m_step(stats, n_samples):
(
zeroeth_order_statistics,
first_order_statistics,
average_min_distance,
) = (0, 0, 0)
for zeroeth_, first_, average_ in stats:
zeroeth_order_statistics += zeroeth_
first_order_statistics += first_
average_min_distance += average... | |
0015f8d4892e34a5c7b8 | def _get_test_db_name(self):
if self.connection.settings_dict["TEST"]["NAME"]:
return self.connection.settings_dict["TEST"]["NAME"]
return TEST_DATABASE_PREFIX + self.connection.settings_dict["NAME"] | |
00160ce8ea6427531653 | def print_list(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
return "" | |
00160ea53aea23c77197 | def get_article_text(article):
title = body = ""
if article.title is not None:
title = ' '.join(article.title.text.split()) + ". "
if article.body is not None:
body = ' '.join(article.body.text.split())
return title + body | |
00160fbe236911a5bf28 | def type(self, type):
allowed_values = ["Unknown", "SSD", "HDD", "NVRAM"] # noqa: E501
if self.local_vars_configuration.client_side_validation and type not in allowed_values: # noqa: E501
raise ValueError(
"Invalid value for `type` ({0}), must be one of {1}" # noqa: E501
... | |
00166293eeb73626ab3b | def get_epoch_current_time():
epoch = time.time()*1000
return int(epoch) | |
001694f9a81137eb5c40 | def n_classes(self):
return self.n_labels | |
0016ba8079b8378171c8 | def _enhance_element_tree(self):
setattr(self, "tag", self.element_tree.tag)
for root_child in list(self.element_tree):
if root_child.tag != 'link':
if len(self.element_tree.findall(root_child.tag)) > 1:
setattr(self, root_child.tag, self.element_tree.fin... | |
0016d7900f8cfc5a1b28 | def LoadDesignVariables(main):
GeometricParameters = main['ANSYS']['DesignProperties']
ODesign = main['ANSYS']['oDesign']
for part, parameter in GeometricParameters.items():
for SubparmeterName, SubparmeterValue in parameter.items():
if SubparmeterName in ['Embrace', 'Pf', 'Iph', '... | |
0016de460c0274248e24 | def start_date(self):
return self.tc_entries[0].entrytime \
if len(self.tc_entries) > 0 else None | |
0016ed9dd85cbf85e0f5 | def parse_feature(self, feature_key, lines):
... | |
0017202c3a0075b82905 | def _get_interacting_pairs(symbs, mols, symbs4inter):
symbs4inter = tuple(sorted(symbs4inter))
pairs = []
for mol1, mol2 in itertools.combinations(mols, 2):
for atms in itertools.product(mol1, mol2):
if tuple(sorted(symbs[i] for i in atms)) == symbs4inter:
pairs.append... | |
00172aa62cac8d702cef | def perform(self, context: LaunchContext) -> Text:
from ..utilities import perform_substitutions
name = perform_substitutions(context, self.name)
if 'anon' + name not in context.launch_configurations:
context.launch_configurations['anon' + name] = self.compute_name(name)
re... | |
00173c4c5109bd65eb29 | def validate(model, criterion, gpu=True):
testing_loader = dataloaders['testing']
device = torch.device("cuda:0" if gpu else "cpu")
model.to(device)
model.eval()
model.to(device)
correct = 0
total = 0
for inputs, labels in iter(testing_loader):
inputs, labels = inputs.to(device)... | |
00174ce6932b9608fd83 | def estimate_coverage(self, verbose = True):
#TODO proper bootstrap calculations
np = len(self.keys)
#remove landmarks from potential candidates
candidates = self.keys.difference(set(self.landmarks.keys()))
nc = min(len(candidates),100)
test_keys = random.choice(candidate... | |
001759dc0fe02e8acdc6 | async def test_sensor_bad_value(hass: HomeAssistant, setup_comp_2) -> None:
assert hass.states.get(ENTITY).state == STATE_ON
_setup_sensor(hass, None)
await hass.async_block_till_done()
assert hass.states.get(ENTITY).state == STATE_UNAVAILABLE | |
001762b9f2ea35bf141a | def test_count_words_with_numbers():
from TechLurker.searching import count_words
sentance = "The number of the day is 4"
counts = count_words(sentance)
assert counts.get('4') == 1 | |
0017c5a0ea1b9b410a6f | def service_search(request):
if request.method == 'POST':
# get Search Key data from search form
search_value = request.POST.get('search_value')
print("========================")
# Get all requirements in SERVICE status
if request.user.has_perm('customer.customer_view_others... | |
0017d0bf2622e131237c | def bounds(self):
if self._bounds is None:
self._bounds = self.polygon.bounds
return self._bounds | |
0017d4f9477082b7977a | def add(request):
context = RequestContext(request)
if request.method == 'POST':
form = CategoryForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print form.errors
else:
form = CategoryForm()
return render_to_response('rango/add_category.html', {'form': for... | |
0017e2c77dd5f409733e | def __choose_from_alternatives__(self, alternatives) -> int:
raise NotImplementedError | |
0017f07c9fbf67647508 | def set_loc(self, (x, y)):
self.loc = (x, y) | |
0017f14f3bdbaab3e5db | def rotation(thetax, thetay, thetaz):
sx, cx = np.sin(thetax), np.cos(thetax)
sy, cy = np.sin(thetay), np.cos(thetay)
sz, cz = np.sin(thetaz), np.cos(thetaz)
X = np.array([[1, 0, 0],
[0, cx, -sx],
[0, sx, cx]])
Y = np.array([[cy, 0, sy],
[0, 1, 0... | |
001828d6fe2cf98c6859 | def gui_start():
# Set windows properties.
WINDOW.title("Question answering System")
WINDOW.minsize(width=900, height=600)
WINDOW.maxsize(width=1300, height=600)
# Create 3 frames (for article_list - run_button - text_area ) with border = 1 & 3-D effects = sunken.
list_frame = tk.Fram... | |
00182ec740fc1456b89c | def countwordtokens(counters):
# sum the counts
return sum(counters, Counter()) | |
001843b69fcd346503d7 | async def _post(self, **kwargs) -> dict:
async with self.session.post(self.url, headers=self.headers, **kwargs) as resp:
resp = await resp.json()
log.info(resp)
return resp | |
0018508eaf48a79f83fe | def _swim(self, k):
while k > 1 and self._greater(k//2, k):
self._exch(k, k//2)
k = k//2 | |
0018562ffd75d939fe01 | def does_strict_dominate(g1, g2, delta1, delta2):
dim = len(g1)
is_sdom = True
for i in range(dim):
if g2[i] + delta2[i] <= g1[i] - delta1[i]:
is_sdom = False
return is_sdom | |
001873e999f9e948f6f5 | def get_csrf(self):
return self.csrf | |
00187da6aa673fb4c74f | def get_attrs(self):
out = []
for attr in dir(self):
if ((attr[0] == '_' and attr not in self._keep_attrs) or
callable(getattr(self, attr))):
continue
out.append(attr)
return out | |
0018802effc2ec675b20 | def testUnicodeHeaderValues(self):
self._messageTest(self.messageWithUnicode, self.assertUnicodeHeaderValues) | |
001886cb5fdb059e3f30 | def get_missing_oids(): | |
00188893e2a5f27267fe | def dbExists():
return os.path.exists("data/metadata.db") | |
00188d87cbe29bcc6fa8 | def channel_test(self) -> discord.Channel:
return self._ch_test | |
001891164b2909d783c1 | def isOutOfMemory(self, **kwargs):
return False | |
0018adfe1bcefb8794e6 | def init_notebook():
from IPython.display import display, Javascript, HTML
# todo: ideally you don't want user interactions done this way:
# they result in spamming of JavaScript "objects" and when nbconverting,
# this will result in a huge number of output_javascript elements.
def my_send... | |
0018b81e50d95b807b0a | def show_state(self):
raise NotImplementedError('Subclasses must implement abstract methods') | |
0018d31bcbf950d95b5d | def write_defmap(mass, pixscale, z_lens, sample_fits, ra_off=0, dec_off=0):
D_d = cosmo.angular_diameter_distance(z_lens)
npix = mass.shape[0]
pix_area = pixscale**2
center = int(npix / 2)
image_radius = center * pixscale
y, x = np.mgrid[-1 * image_radius:image_radius:1j * npix, -1 * image_radiu... | |
00194fc53444eadc7168 | def IsFile(self):
return self.type == 'file' | |
001968de9771c28889ea | def addtolist(integer, lst):
lst.append(integer) | |
0019791c0ea4add1caaa | def change_current_view(self, target_view, asset_id=False):
self.session["current_view"] = target_view
if target_view == "dashboard":
self.session["current_settlement"] = None
if asset_id:
asset = ObjectId(asset_id)
self.session["current_asset"] = asset
... | |
00197c270e04e7837416 | def set_player_data(user, player):
if c.player_collection.find_one({"_id": user.id}) is None:
c.player_collection.insert_one({"_id": user.id})
for player_data in player.__dict__:
if "character" not in player_data:
c.player_collection.find_one_and_update({"_id": user.id}, {"$set"... | |
00197eb1e8b1de9ca70b | def niceblock(text,newlines=False):
return re.sub('\n([\t])+',(' ' if not newlines else '\n'),re.sub('^\n([\t])+','',text)) | |
0019873edfed2614fdd7 | def setup(self, stage=None):
data_path = self.args.get("train_glob", "/pvc/output/processing")
train_base_url = data_path + "/train"
val_base_url = data_path + "/val"
test_base_url = data_path + "/test"
train_count = self.get_num_files(train_base_url)
val_count = self.... | |
0019cdda993b250198cf | def get_html_file_path(self, filename):
return path.join(self.html_folder, filename) | |
0019cedcc1f38d621e75 | def make_out_file():
now = datetime.datetime.now()
date_time = now.strftime("%Y%m%d_%H%M")
print ('\n config_file: config_' + date_time + '.conf')
return ('config_' + date_time + '.conf') | |
0019d31ab61bf6bbdbf4 | def comment_count_difference(word):
count_with_word = comment_count(posts_with_word(word))
count_without_word = comment_count(posts_without_word(word))
average_with_word = average(count_with_word)
average_without_word = average(count_without_word)
delta = average_with_word - average_without_word
... | |
0019e0a3ab26b2576a61 | def __str__(self):
return '%s (%s)' % (self.book,self.chapterId) | |
0019f80e7c9b11b9d195 | def test_breadth_traversal_02():
from graph import Graph
empty_graph = Graph()
assert empty_graph.breadth_traversal('A') == []
assert empty_graph.breadth_traversal('') == [] | |
0019f82af06c75bb0f9e | def openSceneInOS(self):
pcu.openWithOS(os.path.dirname(pm.sceneName())) | |
001a0269df9091439d06 | def test_project_wizard():
python_project_template.utils.setup_logging()
proj = python_project_template.project.Project(test=True)
_raw_input_set([
# Title
"My Title",
# Package
"my_title",
# Authors
"Author1",
"yes",
"Author2",
"no",
# Description
"a description",
... | |
001a15ad19339fc5949b | def write_data_to_disk(self):
if not self.mcmc_runs:
logger.info("No data to write to disk")
return
# Close Parquet writer used to write data for outputs / derived outputs.
self.db.close()
with Timer("Writing calibration data to disk."):
# Write para... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.