id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
ffbff262443386280077 | def convert_labelling(file_handle, original_file_name):
# read each line in the file
ignore_flag = 1
for line in file_handle:
# remove trailing spaces
line = str(line).strip()
# ignore the first line
if ignore_flag > 0:
ignore_flag -= 1
continue
... | |
ffc00bbe8f2991114cd8 | def is_own_group(user, group):
if group is None:
return False
return user.group == group | |
ffc01aabfd7a00f77ee7 | def do_tr(self, attr):
params = dict(attr)
try:
if 'tCenter' in params['class']:
# Of course we won't store current_item on first <tr class="tCenter"> seen.
if self.tr_counter != 0:
# We only store current_item if to... | |
ffc02415a435e12c6dd6 | def del_aux(s, k, Omega):
p = s[k]
j = k + 1
while (j < len(s)) and (pseudo_angle(Omega, p, s[j]) == 0):
j = j + 1
return j | |
ffc04d50ee0e2b271737 | def test_put(self):
url = reverse('alias-detail', args=(self.alias_1.id,))
data = {'alias': 'alias_5',
'target': self.alias_1.target,
'start': f'{timezone.now()}',
'end': f'{timezone.now() + timedelta(days=2)}'
}
json_data = json.du... | |
ffc09bf9a9585f065cc6 | def calculate_prob(lines, replacement_selection_list):
probs = []
for line in zip(lines, replacement_selection_list):
tmp = 1.0 * np.exp(
self.privacy_epsilon * line[0][1] / (
2 * self.mapping_range * line[1][1]))
... | |
ffc09e6078a47fcb3660 | def rotation_matrix(self):
return np.asarray(
pybullet.getMatrixFromQuaternion(self.ee_orientation)) | |
ffc0c2cc25744711eb93 | def getting_urls_from_sitemap(doc="products-sitemap.xml", tag_name="loc"):
with open(doc) as sitemap:
sitemap_soup = BeautifulSoup(sitemap, "lxml")
urls = sitemap_soup.find_all(tag_name)
all_urls = []
for url in urls:
all_urls.append(url.string)
# code to write urls to separa... | |
ffc0c37e517c9cd11143 | def _request(self, url: str, method: str, **kwargs) -> requests.Response:
# Obtain an OpenID Connect (OIDC) token from metadata server or
# using service account.
google_open_id_connect_token = id_token.fetch_id_token(
google.auth.transport.requests.Request(), self.client_id)
... | |
ffc0d6f92bfc7ef531fe | def yearly_view():
# User reached route via GET
if request.method == "GET":
# Set the year to the current year
reqYear=date.today().strftime("%Y")
# User reached route via POST
else:
# Set the year base on the form
reqYear=request.form.get("year")
# Query the datab... | |
ffc0f87f00e50288baab | def module(self) -> Optional[cst.Module]:
wrapper = self.wrapper
if wrapper is None:
return None
return wrapper.module | |
ffc1007cb1a2fd43de2a | def _analyze(self):
self.sim_setup_name = self.renderer.initialize_eigenmode(**self.setup)
self.renderer.analyze_setup(self.sim_setup_name)
self.compute_convergences() | |
ffc117a28e7b5facc96a | def topo_sort2(self):
# Add dummy dependency between leaf nodes to guarantee their order.
new_nodes = deepcopy(self.nodes)
for n, (parents, _) in new_nodes.items():
if n[2].isnumeric() and n[0] != 0:
left_leaf = (n[0] - 1, n[1] - 1, str(int(n[2]) - 1))
new_nodes[left_leaf][1].add(n)
... | |
ffc11b511cb152e6692c | def virtual_position(self):
return self.Position(self._virtual_row, self._virtual_col) | |
ffc14ce124e4e4aadbeb | def get_file_at_url(url, path, referer=None):
log("(url : %s, path : %s)" % (url, path))
try:
with urlopen_wrapper(url, referer) as response:
content_type = response.info().get("Content-Type", "").split("/")
assert 1 <= len(content_type) <= 2
if len(content_type) == 2... | |
ffc16667eed26858124a | def update_display(self):
self.display_update_period = self.settings['refresh_period']
if self.settings['measure']:
length = self.image_gen.frame_num.val
self.settings['progress'] = (self.frame_index +1) * 100/length
if hasattr(self, 'img'):
... | |
ffc1b6cb3582bc89a0db | def add_asset(self, file, filename, type=None, metadata=None, bucket_name=""):
try:
fp = io.BytesIO(file)
except TypeError as e:
logger.error(e)
raise
try:
meta = json.loads(metadata)
except ValueError as e:
logger.error(e)
raise
if bucket_name == "... | |
ffc1bf5b1440b0fc9202 | def display_all_occurences(word, locations, output='default.html', all_tooltips=True):
locations.sort()
word_coords = [WordCoord(w) for w in locations]
visual = HTMLVisualization(word)
while word_coords:
same_doc = 0
curr_doc = word_coords[0].get_doc()
for coord in word_coords:
... | |
ffc1d3d7d51cae46c549 | def get_number_of_nodes():
return int(get(cs.ODIN_CONF, cs.MAIN_SECTION, cs.NUMBER_OF_NODES)) | |
ffc1ed12829be5e8b9e1 | def __game_is_finished(self):
is_finish = False
if self.ship_lifes == 0:
self._screen.show_message('LOSE',
"You've got out of lives. Good luck next time!" +
"\nYour score: " + str(self.user_points))
is_finish = True
el... | |
ffc21135f39d67dad9aa | def _compute_sliceindex(self, descriptor):
args = []
values = []
ordered = sorted(self.parameter_list.keys())
for name in ordered:
vals = self.get_parameter(name)['values']
args.append(name)
values.append(vals)
index = 0
for element in ... | |
ffc24970ca3f240fcc3c | def test_identifier(self):
ident = IdentifierLocalIF(DATA)
self.assertEqual(ident.evaluate({ "requester": "192.168.1.1" }), False)
self.assertEqual(ident.evaluate({ "requester": "127.0.0.1" }), True) | |
ffc28b73724f6a113338 | def update(self):
self._polygon = self.create_polygon() | |
ffc29aaeff892dacb23d | def validate_params(module, aws):
return | |
ffc2b4d61d8e288607b4 | def _DidCrunchFail(returncode, stderr):
return returncode != 0 or stderr | |
ffc2ba3e2f999b70bdc5 | def mean_magnitude(self):
#if self.magnitude is None:
# self.calc_magnitude()
#
#return np.mean(self.magnitude)
return 0 | |
ffc2c778cacc298cd69a | def task(self):
#pass
update_photo_moments_in_cache() | |
ffc2d42996211f34dda5 | def test_object_to_jsonable(
test_object: TestObject,
path: str = "") -> MutableMapping[str, Any]:
res = dict() # type: Dict[str, Any]
if test_object.product_id is not None:
res['product_id'] = test_object.product_id
if test_object.capacity is not None:
res['capacity'] = t... | |
ffc2d6726909e970aee4 | def test_compact_single_sided_range_enum(self):
dist = self.compact(VARS)
self.helper_generate_single_sided_range_int_enum(dist) | |
ffc2d6f0cf415494bb6f | def pipelines_by_affinity():
primitives = DSBoxPrimitives()
policy = AffinityPolicy(primitives)
policy.set_symetric_affinity(primitives.get_by_name('Descritization'),
primitives.get_by_name('NaiveBayes'), 10)
policy.set_symetric_affinity(primitives.get_by_name('Normaliz... | |
ffc3072a46be4a02f93e | def PageView(y):
parser = wp.PageView()
offset = 0
while True:
url = "http://%s.igem.org/wiki/index.php?title=Special:PopularPages&limit=5000&offset=%s" % (y, offset)
handle = urllib.request.urlopen(url)
html = handle.read()
if b"There are no results for this report." in html... | |
ffc30e2d7fb21c986f12 | def create_story(description):
client = RequestManager()
body = {
'name': commons.get_unique_name(description)
}
client.set_method('POST')
client.set_endpoint("/projects/{0}/stories".format(ProjectHelper.project_id))
client.set_body(json.dumps(body))
r... | |
ffc323f469b383d387d8 | def fee(self, fee):
self._fee = fee | |
ffc33808239b3fc03c3d | def simple_runner():
return run | |
ffc36b36ee86113a5da7 | def ban_ip(ip):
command = 'iptables -A INPUT -s {} -j DROP'.format(ip)
subprocess.call(command.split()) | |
ffc3800d0ddabb49e380 | def test_signup(self):
data = {
'email': 'testusersignup@cultidate.com',
'username': 'testusersignup',
'password': '12345678+',
'first_name': 'name',
'last_name': 'surname',
'bio': 'MyBio',
'city': 'Istanbul',
'is_co... | |
ffc3afbf7f009075954c | def status(self, args):
import onlinelab.core.runtime
settings = self._configure(args)
onlinelab.core.runtime.status(settings) | |
ffc3d59403f23eae5cd2 | def error_from_error_field(error_field):
if error_field["code"] != -32000:
return UnexpectedJSONError(error_field)
elif isinstance(error_field["data"], list):
# Special handling for config commit errors, as the data field is a
# list.
if not all(d["type"] == "config_commit_error... | |
ffc3e0f578be0eb6da85 | def get(url):
response = urllib.request.urlopen(url)
data = response.read()
data = data.decode("utf-8")
data = json.loads(data)
return data | |
ffc40dbb14c70397c7e3 | def scattering(x_2d,
y_2d,
var_2d,
scale=1,
alpha=1.0,
color=None,
cmap=general_cmap,
marker='o',
zorder=1,
title=None,
xlabel='Abscissa',
ylabel='Ordinate... | |
ffc41d067fcc2a0c8efd | def trip_stats(df):
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
total_secs = df['Trip Duration'].sum()
dt = datetime(1,1,1) + timedelta(seconds=int(total_secs))
print("Total travel time is {} seconds which is equivalent to {} days, {} hours, "... | |
ffc4306c59395f6cf1f1 | def process_song_data(spark, input_data, output_data):
# get filepath to song data file
song_data = input_data + 'song_data/*/*/*/*.json'
# read song data file
df = spark.read.json(song_data)
# extract columns to create songs table
songs_table = df.select('song_id', 'title', 'artist_id', ... | |
ffc4590eb99b6e100826 | def subsequence(needle, haystack):
for i in xrange(len(haystack) - len(needle) + 1):
if needle == haystack[i:i + len(needle)]: return i | |
ffc45b04a2efc9e11228 | def moit(struct):
inertial_tensor = np.zeros((3,3))
geo = struct.get_geo_array()
ele = struct.elements
mass = np.array([atomic_masses_iupac2016[atomic_numbers[x]] for x in ele])
### First center molecule
total = np.sum(mass)
com = np.sum(geo*mass[:,None], axis=0)
com = com / t... | |
ffc45b9f5cfd97a9c08a | def _connect(self) -> None:
connect_event = ProfileEvent(
ProfileEventType.CONNECT, ProfileTimestamp())
conduits, peer_dims, peer_locations = self.__manager.request_peers()
self._communicator.connect(conduits, peer_dims, peer_locations)
self._settings_manager.base = self.... | |
ffc4991c54e9084a4176 | def call(self, feat, order, window):
p = self.config
with tf.name_scope('delta_delta'):
delta_delta = py_x_ops.delta_delta(
feat,
order,
window)
return delta_delta | |
ffc4ab8b2ce2c9ced6a9 | def __call__(self, *args, **kwargs):
return self.time(*args, **kwargs) | |
ffc4b865517350297dc5 | def delete(name):
ret = {"name": name, "changes": {}, "comment": "", "result": True}
if name in __reg__:
del __reg__[name]
return ret | |
ffc4c670eec5107ee2d9 | def list_2_int(listInt):
return reduce(lambda x, y : (x << 8) + y, listInt) | |
ffc4d0afe6029de5268a | def db():
session.begin_nested()
yield
session.remove() | |
ffc50058cb07ff0e8b59 | def WriteToDotFile(self, filename: str) -> None:
with open(filename, "w") as dotFile:
print("digraph snailfish_numbers {", file=dotFile)
for line in self.DotRepresentation():
print(line, file=dotFile)
print("}", file=dotFile) | |
ffc530cf9a944b3c1bca | def is_unlimited(self):
return self.remaining_hits is None | |
ffc53b944da8e3d20e0c | def pseudosample(x):
#
BXs=[]
for k in range(len(x)):
ind=random.randint(0,len(x)-1)
BXs.append(x[ind])
return BXs | |
ffc547f412a18e9ddd27 | def linear_interpolate(x1, y1, x2, y2, x):
return y1 if np.isclose(x1,x2) else y1 + (x-x1)*(y2-y1)/(x2-x1) | |
ffc5710abab5ce9ae6d7 | def _get_response(url):
time_first_attempt = time.time()
response = requests.get(url, headers={'User-agent': 'idk_just_let_me_dl_this'})
while response.status_code != 200:
response = requests.get(url)
print(time.time() - time_first_attempt)
if time.time() - time_first_attempt > 10:... | |
ffc58d329cbed1d6149e | def ReadFasta(aPath):
fr = open(aPath)
dictOfsequences = {}
seqID = ''
seq = ''
flag = 0
for line in fr:
if '>' in line:
if flag != 0:
dictOfsequences[seqID] = seq
seq = ''
seqID=line.replace('\n','')
flag += 1
e... | |
ffc595020baa8321ad83 | def check_files_exist(filenames):
for filename in filenames:
if filename is not None:
check_file_exists(filename) | |
ffc5b0b5ea6ef5d13405 | def getUser(self):
try:
return self.user
except:
pass
self._authorize()
return self.user | |
ffc5bdf98acf97bd4454 | def test_cylinder_initialization():
# setting up test params
start = np.random.rand(3)
direction = 5 * np.random.rand(3)
direction_norm = np.linalg.norm(direction)
direction /= direction_norm
normal = np.array((direction[1], -direction[0], 0))
base_length = 10
base_radius = np.random.uni... | |
ffc5cf85b27ee88307a5 | def get_morgan_fingerprint(self, radius=3, n_bits=None):
if n_bits is None:
return AllChem.GetMorganFingerprint(self.mol, radius)
else:
return AllChem.GetMorganFingerprintAsBitVect(self.mol, radius, \
nBits=n_bits) | |
ffc5d675cbe1b8a1746f | def experiment(self):
return self._experiment | |
ffc5e5658fa74529187d | def df(self):
return self._df.loc[self.in_training(self._hashes)] | |
ffc5fbcf9d0ddbb5b7fa | def import_cleaned_geometries_from(self, othercleaner):
for feature_id, shape in othercleaner.geom.items():
self._add_feature_with_new_shape(
othercleaner.feature_from_id(feature_id), shape) | |
ffc60922a6006911dffd | def GetWindowMenu(self): | |
ffc62de961469a238469 | def count_lines(input_file):
check_file_readable(input_file)
n = 0
with open(input_file, 'r') as istream:
for _ in istream:
n += 1
return n | |
ffc6304113c8c9354fcb | def delete_unfingerprinted_songs(self):
d = self.songs.delete().where(self.songs.c[SQLACDatabase.FIELD_FINGERPRINTED] == False)
with self.Engine.connect() as c:
c.execute(d) | |
ffc6389ec2bd3cbf1a76 | def __call__(self, ctx, engine):
assert(isinstance(ctx, dict))
assert(x.name in ctx for x in self._params)
# retrieve op func from active TagEnvs
op_func = engine.get_operator(self.op)
# get values from data
values = self.get_params(ctx)
# perform action op with d... | |
ffc640595b6ca1b0391d | def _register(callback, content_type_list):
for ct in content_type_list:
pre_save.connect(
callback,
sender=ct.model_class(),
dispatch_uid=ct.model
) | |
ffc66da00c598ec08d2f | def is_valid_file(parser, arg):
if not os.path.isfile(arg):
parser.error("The file %s does not exist!" % arg)
else:
return arg
return None | |
ffc68801618b0849a627 | def read_temporal_profile(path):
started = False
data = []
cats = []
with open(path, encoding="latin") as prof:
for l in prof:
splitted = l.split(";")
if splitted[0] == "1":
started = True
if started:
if splitted[1] == "F1":
... | |
ffc6b2322ae98ed5802a | def _SaveCulpritInCompileFailures(compile_failures, culprit_commit):
culprit_entity = Culprit.GetOrCreate(
gitiles_host=culprit_commit.gitiles_host,
gitiles_project=culprit_commit.gitiles_project,
gitiles_ref=culprit_commit.gitiles_ref,
gitiles_id=culprit_commit.gitiles_id,
commit_positi... | |
ffc6bec409fd00e0271d | def help_command(update: Update, context: CallbackContext) -> None:
update.message.reply_text('Help!') | |
ffc6ce750f4e14976cf2 | def media_next_track(self):
self.send_req_ircc(self.get_command_code("Next")) | |
ffc6f5669c9aef8249b8 | def get_init_state(self):
raise NotImplementedError | |
ffc75172ba51923ed710 | def format(self):
self.code_lines = []
line_checkers = [
self.fix_trailing_whitespace,
self.fix_indentation,
self.fix_heading,
self.fix_narrative_paragraph,
]
self.block_method = self.format_block
self._apply(line_checkers)
... | |
ffc75450f0fad1ef742c | def minimum_elevation_degrees(self) -> pulumi.Output[Optional[float]]:
return pulumi.get(self, "minimum_elevation_degrees") | |
ffc768c81c673a058b88 | def standard_attrs(cls):
return SourceClip._provides_attrs + super().standard_attrs() | |
ffc7a0d08e52530d8356 | def _unpause_vm():
self.compute_ops.unpause_vm(instance) | |
ffc7aedf3e1c99ed955c | def get_search_query(self):
return self.search_use_q and self.request.GET.get('q', '') or None | |
ffc7b4ac06e9f46a0572 | def generate_df_for_n_weeks(weeks, dataset, prj_id, beginning, end):
BQ = get_biqquery_service()
daily_pdt_reco_df = pd.concat([
add_week_to_df(get_gbq_query_results(
BQ,
get_weekly_information.format(
date_start=beginning,
date_end... | |
ffc7c0d169c427acf89c | def get_strength(self):
return self._strength | |
ffc7e15d9f0a3367fe18 | def initGui(self):
icon_path = ':/plugins/TestPlugin/icon.png'
self.add_action(
icon_path,
text=self.tr(u'TestPlugin'),
callback=self.run,
parent=self.iface.mainWindow())
# will be set False in run()
self.first_start = True | |
ffc8602c0e3392782d52 | def __repr__(self):
return f'Annotation([{", ".join([feat.__repr__() for feat in self._features])}])' | |
ffc8695f66ab82069452 | def make_companion_xml(name, line, destination):
if line == 'Overview':
with open(prepare_file('html/' + name + ".xml", destination), 'a') as target:
target.write('<html filename="' + name + '" display_name="' + line + '"/>')
else:
filename = line.split()[-1][2:-1].rsplit('/', 1)... | |
ffc86a7e1cb8478ed1a1 | def __iter__(self):
for name in self.list():
yield name | |
ffc870429bdabfcc8614 | def parent_uri(self):
return self._parent_uri | |
ffc8708a1a435100cf47 | def testSetupQuestion(self):
response = self.client.get(reverse("setup_question"), {},
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertTemplateUsed(response, "first-login/question.html")
try:
json.loads(response.content)
except ValueError:
self.fail... | |
ffc878367b0e7f783618 | def get_device_for_nbs_volume(dom):
free_slot, free_dev = _find_free_dev_and_pcislot(dom)
if free_slot is None or free_dev is None:
return None
target_dev = '/dev/' + free_dev
real_path = ('/dev/nbs/xd' + _slot_to_disk(free_slot))
return {'mountpoint': target_dev,
'real_path': r... | |
ffc892dcf4f5a85732b9 | def solveSudoku(self, board: List[List[str]]) -> None:
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
def get_related_cells(target_cell):
target_grid_index = target_cell[0] // 3 * 3 + target_cell[1] // 3
... | |
ffc8acac0171f5f8a662 | def enable_hash_discard(self):
if self.hashlabel is None:
raise DatasetUsageError("Can't enable hash discard without hashlabel")
if self._started != 1:
raise DatasetUsageError("Call enable_hash_discard after set_slice")
self._mkwritefuncs(discard=True) | |
ffc8b11ddf2090197692 | def pathendswith(path, *end):
if len(end) > len(path):
return False
for a, b in zip(path[-len(end):], end):
if type(b)==type:
if type(a)!=b:
return False
elif type(b)==int:
if a != b:
return False
elif type(a)==int:
... | |
ffc8ebbe8b94472f6a75 | async def set(self, ctx, role_name: str):
role_name = role_name.lower()
def check(msg):
return msg.author == message.author and msg.content == "confirm"
if role_name not in self.roles:
await ctx.send("Role `{}` is not removable.".format(role_name))
return
... | |
ffc8ff5c6e9ca7199389 | def disconnect(self):
with suppress(AttributeError):
self.serial.close()
self.reader_thread = None | |
ffc93054ea75f1f41473 | def get_features(self):
return self.features_out | |
ffc9537aebeaa47f00e1 | def step(self) -> None:
self.optimizer.step() | |
ffc965d57894267f9cfd | def select_action(policy, state):
state = torch.from_numpy(state).long().unsqueeze(0)
state = torch.zeros(3,9).scatter_(0,state,1).view(1,27)
pr = policy(Variable(state))
m = torch.distributions.Categorical(pr)
action = m.sample()
log_prob = torch.sum(m.log_prob(action))
return action.data[... | |
ffc969652add70cce499 | def _find_path(self, map, xStart, yStart, radius):
currentX = xStart
currentY = yStart
lastX = xStart
lastY = yStart
waypoints = []
allpoints = []
# 0 -> No / 1 -> Top / 2 -> Bottom / 3 -> Left / 4 -> Right / Top Left -> 5 / Top Right -... | |
ffc9698c1be588d47c1e | def save_dataframe(df:pd.DataFrame, filename:str):
df.to_csv(filename, index=False) | |
ffc9a200f544cacfa4bb | def test_add_proposition(self):
response = self.client.post('/propositions/', {'title': 'Moon is square'}, format='json')
assert response.data['title'] == 'Moon is square'
assert response.data['truthvalue'] == True
# Assert 201 Created as status
assert response.status_code == 201... | |
ffc9b1a0cfa23f45a4fd | def main():
filename = input('filename?\n')
print(report_distribution(count_words(filename))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.