id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
fff00412ff739025f4fd | def hub(self) -> Optional[pulumi.Input['ResourceIdArgs']]:
return pulumi.get(self, "hub") | |
fff00cf40b2cb3d2d861 | def test_attr_name(self):
self.assertIs(type(self.model1.name), str)
self.assertEqual(self.model1.name, "Holberton")
self.assertIs(type(self.model2.name), str)
self.assertEqual(self.model2.name, "Betty") | |
fff01d03690074f590e9 | def build_document(self, document):
raise NotImplementedError() | |
fff03617e8b19d851daa | def get(self, request, pk):
logs1 = WorkoutLog.objects.filter(
profile=request.profile,
workout_day__exercise=pk,
).all()
logs2 = CustomWorkoutLog.objects.filter(
profile=request.profile,
workout_day__exercise=pk,
).all()
result = [... | |
fff06c39334f48a451b0 | def classifier(self):
module = Net(self.nn_config)
if self.nn_config['cuda'] and tr.cuda.is_available():
module.cuda()
for epoch in range(self.nn_config['epoch']):
with open(self.nn_config['report_filePath'],'a+') as f:
f.write('\nepoch:{}\n'.format(epoch)... | |
fff07b242ac96a52c2d7 | def parse(data, dtype: DataType = None) -> DataFrame: | |
fff0bfa1196a75e0d8ff | def _key_to_filename(self, key):
digest = md5hex(key)
return os.path.join(self._dir, digest[-2:], digest[:-2]) | |
fff0dc02985cc04d2769 | def plt_column_box_plot(column, df):
fig, ax = plt.subplots()
plt.xlabel('Column')
plt.ylabel('Values')
df.boxplot(column, ax=ax)
fig.savefig('output\\{}_box_plot.png'.format(column)) | |
fff0e33bad38213d6202 | def render(self, filename=None, stop_on_close=True):
if filename is None:
drawnow.drawnow(self.update_drawnow, stop_on_close=stop_on_close)
else:
rgb_arr = self.get_rgb()
plt.imshow(rgb_arr, interpolation='nearest')
plt.savefig(filename) | |
fff0e4f856642a0f7e38 | def _compute_invoice(self):
inv_obj = self.env['account.invoice']
for rec in self:
rec.count_inv = inv_obj.search_count([('transport_student_id',
'=', rec.id)]) | |
fff0f15ae66fd3d6f5bb | def get_instructions():
instructions = {}
for f, t in doc_files.items():
instructions_from_file(f, t, instructions)
return instructions | |
fff100d87c46fed46ac4 | def info_msg(self, msg1, *args ):# {{{
self.msg1 = msg1
self.args = args
if args:
# Printing the first message:
print self.WHITE + "[" + self.YELLOW + "INFO" + self.YELLOW + "] " + \
msg1 + \
self.WHITE,
# Printing var ... | |
fff123109060f5b3f895 | def test_all_contributors(client):
contributors = client.contributors(PROJECT_ID)
assert contributors.project_id == PROJECT_ID
assert contributors.items[0].user_id == 20181 | |
fff123ded7900b5f1773 | def sample_delay(self, *args, **kwargs):
return _trellis_swig.pccc_decoder_combined_ci_sptr_sample_delay(self, *args, **kwargs) | |
fff13b37fcb920823ca4 | def bootstrap_np(data, boots=1000):
to_return = np.empty([boots, data.shape[0]])
sys_index = 0
total = 0
for system in data:
for boot in range(boots):
for sample in range(system.shape[0]):
total += system[np.random.randint(0, system.shape[0])]
to_ret... | |
fff1666b41543acc3d9b | def remove_from_favorites(self, name):
pass | |
fff16e9446cdcdb7a1b8 | def pass_stats(data, outcomes, key, filters = []):
# Check that the key exists
if key not in data.columns.values :
print "'{}' is not a feature of the Titanic data. Did you spell something wrong?".format(key)
return False
# Return the function before visualizing if 'Cabin' or 'Ticket'
... | |
fff176c0612580eed1dc | def get_percent_values_by_range(bg_values, lower_threshold: int, upper_threshold: int, round_val=2):
calc_low_thresh, calc_upper_thresh = _validate_input(lower_threshold, upper_threshold)
results = round(np.where((bg_values <= calc_upper_thresh) & (bg_values >= calc_low_thresh), 1, 0).sum()/bg_values.size*100, ... | |
fff18b97de1002387a00 | def create_mokawes_command(self, fastq, pannumber):
# call function to build nexus fastq paths - returns tuple for read1 and read2 and samplename
fastqs = self.nexus_fastq_paths(fastq)
# build dictionary of pan number specific/relevant bedfile to be used in command
bedfiles = self.nexus_... | |
fff196a7de815d813b56 | def create_box(self):
raise NotImplementedError() | |
fff1ad92145bdcbc0978 | def _subsample(self, inputs, stride, scope=None):
if stride == 1:
return inputs
else:
return self._max_pool(inputs, 3, stride, scope) | |
fff1b0789037f91049fc | def unique_id(self):
return _blocks_swig0.annotator_alltoall_sptr_unique_id(self) | |
fff1b2e99e618e23c000 | def create_url(path, dcnm_hostname=dcnm_hostname):
return "https://%s/rest%s" % (dcnm_hostname, path) | |
fff1dca0da8ca1234487 | def chord_counter(chords):
times = 0
for key, val in notelist.items():
key = re.sub('7|sus4|sus|add9|/[A-Z][#b]|/[A-Z]', '', key)
for chord in chords:
if chord == key:
times += 1
else:
pass
return tim... | |
fff1e01354e602e511c4 | def should_prune(name):
in_whitelist = not pruning_params.white_list or any(
e in name for e in pruning_params.white_list)
in_blacklist = any(e in name for e in pruning_params.black_list)
if pruning_params.white_list and not in_whitelist:
return False
elif in_blacklist:
return False... | |
fff1e5fd55a83e592225 | def render(self, context, template = None , path = '', string = '', tid = ''):
if (path or string or tid) and not template:
template = self.get_template(path, string, tid)
return template.render(**context) | |
fff20046a56c4c8ee91d | def open(self):
global availability
self.set_nodelay(True)
ClientWebSocketHandler.clients.add(self)
if availability:
message = '1'
else:
message = '0'
self.write_message(message)
logging.info('[' + self.request.host + '] New client') | |
fff2251e57b9a79ba028 | def get_course_id(canvas_obj, course_name):
# Create a user object
user = canvas_obj.get_user(USER_ID)
# Get the users's courses
user_courses = user.get_courses(enrollment_status='active', state='published')
for course in user_courses:
# Test for the give course name in the user's ... | |
fff22fffb723ad85ad91 | def format_date(self, date):
d = datetime.now()
d = d.strftime("%Y %m %d %H")
if(re.search("T", date)):
d = " ".join(
[date.split("T")[0].replace("-", " "),
date.split("T")[1].split(":")[0]])
return d | |
fff23d791e98fb3a7a76 | async def backup(self):
timestamp = datetime.utcnow().strftime(BACKUP_TIMESTAMP_FORMAT)
source_path = self._path
backup_path = self._path.with_suffix(f".backup.{timestamp}{self._path.suffix}")
self._log.warning(
f'Backing up database from "{source_path}" to "{backup_path}>"'
... | |
fff23da404ceb8148389 | def calPRD(X_rec, X_orig):
ERR = X_rec - X_orig
prd = np.average(LA.norm(ERR,axis=1)/LA.norm(X_orig,axis=1))*100
return prd | |
fff24f30b94b089087bb | def get_document_tokens(self, idx, p=None):
return normalize(tokenize(self.get_tokens(idx))) | |
fff283b1f7952bddeaf2 | def parse_unit(units):
# if units is not a list, put it in a list
units = units if isinstance(units, list) else [units]
unit_str = ''
for unit in units:
unit_name = unit.get('Name')
unit_power = unit.get('@power')
if not unit_str == '':
unit_str += '.'
if un... | |
fff29a32a5966a041ffb | def path_state(self):
node, path_back = self, []
while node:
path_back.append(node.state)
node = node.parent
return list(reversed(path_back)) | |
fff2b1b64f376abb7bd9 | def is_too_many_files(self):
return self._tag == 'too_many_files' | |
fff2d91984e5b47f7e99 | def shortestPath(graph,start,end):
final_distances,predecessors = Dijkstra(graph,start,end)
path = []
cost = 0.0
try:
cost = final_distances[end]
except Exception, e:
cost = NOT_CONNECTED
while 1:
path.append(end)
if end == start: break
end = predecessors[end]
path.reverse()
return path, cos... | |
fff2e43b73f718d34c17 | def Spatial_Reference(epsg, return_string=True):
srs = osr.SpatialReference()
srs.ImportFromEPSG(epsg)
if return_string:
return srs.ExportToWkt()
else:
return srs | |
fff2f8af11e096654123 | def normalize(self):
return self._normalize | |
fff31913995d5e7b75c0 | def addSafeSpaces(self):
# print("ADDING them safespaces")
if self.inBounds(self.n + 1, self.m)and not self.visited(self.n + 1, self.m):
self.makeSafe(self.n + 1, self.m)
#self.safespaces.add((self.n + 1, self.m))
if self.inBounds(self.n - 1, self.m):
self.mak... | |
fff329487b9a12ed9ccf | def _get_camera_object_by_addr(camera_addr):
camera = ThreadsafeCameraObject()
port_info_list = gp.PortInfoList()
port_info_list.load()
idx = port_info_list.lookup_path(camera_addr)
camera.set_port_info(port_info_list[idx])
return camera | |
fff3324fda173b3f10eb | def _find_mergeable(interpretation):
if not MERGE_STRATEGY:
return None
idx = _INCACHE.bisect_left(interpretation)
nobs = len(interpretation.observations)
nfoc = len(interpretation.focus)
nunint = len(interpretation.unintelligible)
nabs = len(interpretation.abstracted)
mergeable = in... | |
fff33dbe2301d9ec5bc8 | def get(self, label_id):
return {
'error': 'Not implemented'
}, 501 | |
fff3528a74271e373ca4 | def __init__(self, boundary: tuple, shape: tuple):
assert isinstance(boundary, tuple) and isinstance(shape, tuple)
self.boundary = boundary
self.shape = shape
self.num_cells = shape[0] * shape[1]
self.cell_length = (boundary[2] - boundary[0]) / shape[0]
self.cel... | |
fff3b47e05f1be19037a | def reset(self):
#Resets the grid to be the right size, with 0's as values
#Grid is a list of lists.
grid = []
for dummy_i in range(self._rows):
grid.append([])
for dummy_j in range(self._columns):
grid[dummy_i].append(0)
self._grid = grid... | |
fff3b68845841c63beab | def chunk(self):
raise NotImplementedError | |
fff420ee5b5e84af198b | def damage(self, damage: int):
self.health -= damage
if self.health <= 0:
self.destroy() | |
fff426dbaa32513c9e51 | def media_items(self): | |
fff43d1ac36a7cc9d71c | def LaminateLayerTemplateNew(deck, laminate, id, name, color, add_elements, remove_elements, mat, ply, t, theta, nip, sout, type, tmanuf, dvpreln, mapped_data, mapped_thickness, mapped_orientation, rosette, a, sync_name, layer_type): | |
fff43f8836aa01a556b9 | def conditional_prob(self, label, datapoint):
sum = 0.0
for i in range(self.CLASSES):
sum += np.exp(np.matmul(np.transpose(self.theta[:,i]),datapoint[:]))
return np.exp(np.matmul(np.transpose(self.theta[:,label]),datapoint[:]))/sum | |
fff44ed873adc2693c1a | def attachment_upload_command(client: Client, args: Dict[str, Any]) -> CommandResults:
file_entry = args.get('file')
file_name = demisto.dt(demisto.context(), f"File(val.EntryID=='{file_entry}').Name")
if not file_name: # in case of info file
file_name = demisto.dt(demisto.context(), f"InfoFile(va... | |
fff46a683cfb7cf85011 | def majorana_form(self):
hermitian_part = self.combined_hermitian_part
antisymmetric_part = self.antisymmetric_part
# Compute the Majorana matrix using block matrix manipulations
majorana_matrix = numpy.zeros((2 * self.n_qubits, 2 * self.n_qubits))
# Set upper left block
... | |
fff47eed5028a84836e9 | def get_all_likes(post):
likes = Like.query.filter_by(post_id=post).all()
if likes:
return likes_schema.jsonify(likes)
return abort(404) | |
fff49e55eb1af7984581 | def set_language_token(self, language_token):
self.language_token = language_token | |
fff4a20079e388172c6a | def run(self):
while not self.done:
self.run_n(100) | |
fff4ae016b019644af49 | def decoderModel(prevBeamStatesTuple, prevBeamSymbols):
sampleCount, beamCount = prevBeamSymbols.shape
vocabLen = self.symbolsTensor.shape[0]
bigSampleCount = sampleCount * beamCount
(prevGruOutput, prevGruState) = prevBeamStatesTuple
# nodeInfoPropagatedExpa... | |
fff4e67f1583e9fb6fbc | def convn_h2a(hexstr):
asciistr = binascii.b2a_hex(hexstr)
return asciistr | |
fff504f5c43fd665ec2f | def __sub__(self, other):
newObj = self.clone()
if isinstance(other, G1DConnections):
for i in xrange(len(newObj)):
(newObj[i])[2] -= (other[i])[2]
else:
for i in xrange(len(newObj)):
(newObj[i])[2] -= other
return newObj | |
fff526b1dc808b9d4302 | def delete_vdc(self):
if self.resource is None:
self.resource = self.client.get_resource(self.href)
return self.client.delete_linked_resource(self.resource,
RelationType.REMOVE, None) | |
fff529b8d230e4e80702 | def _print_results_header(self):
print("\033[94m"+"Summary\n"+"-"*32+"\033[0m")
print("Subroutine: {}".format(self.mc_sample.__name__))
print("Num Runs: {:2.1e}".format(self.num_runs))
print("-"*32+'\n') | |
fff532b9f523f5258b5c | def parse_xml(self, file):
date = datetime(2000, 1, 1, 0, 0, 0)
device_id = ""
payload = ""
with open(file) as xml_file:
xml = xml_file.read()
xml_file.close()
root = etree.fromstring(xml)
for sub_element in root:
if(sub_element.tag[30... | |
fff532c8f0b3d22335d0 | def queue_state(self):
return self.jobqueue.state() | |
fff549b8972641d7cb60 | def setUpParty (self) :
self._party.append(Person("Iowa Smith"))
self._party.append(Person("Dorthy"))
self._party.append(Person("Larry Fills"))
self._party.append(Person("Laureen Kraft"))
self._party.append(Person("Jeb the Forest Man")) | |
fff55db807f822b83627 | def set_bass_enhancement(self, alpha):
self._bass_enhancement = alpha | |
fff574001299ed9620fe | def get_shortest_path_between(self, origin, destination, distances=None):
origin, destination = str(origin), str(destination)
if not self.is_vertex(origin) or not self.is_vertex(destination):
raise ValueError("Non-existent vertex. Add it first and try again.")
if distances is None:... | |
fff57761e8f2fd590e7b | def cli():
if os.geteuid() != 0:
click.echo("Root privileges are required for this operation")
sys.exit(1) | |
fff580399c2b3b5cbd02 | def pointRadialDistance(lat1, lon1, bearing, distance):
rlat1 = deg2rad(lat1)
rlon1 = deg2rad(lon1)
rbearing = deg2rad(bearing)
rdistance = distance / rEarth # normalize linear distance to radian angle
rlat = asin( sin(rlat1) * cos(rdistance) + cos(rlat1) * sin(rdistance) * cos(rbearing) )
if ... | |
fff5912fa571f4ea5e57 | def load_themes(self):
json_data = importlib.resources.read_text('ttkbootstrap', 'themes.json')
settings = json.loads(json_data)
for theme in settings['themes']:
if theme['name'] not in self.theme_names():
settings = ThemeSettings(
name=theme['name... | |
fff596cfba94c7bf025b | def get_name(self):
return self.name | |
fff5b983e770586d8e16 | def get_participants(self):
return self.participants_group.user_set.all() | |
fff5c332eade160ea52e | def get_country(self):
doc = self._request("user.getInfo", True)
return Country(_extract_data(doc, "country"), self.network) | |
fff62a650a85a3cc60c0 | def covariance(self) -> np.ndarray:
if not self._is_memoized('_covariance'):
self._covariance = (
(self._metrics2.get_metric('ds') - self._metrics2.get_metric('mean'))
* (self._metrics1.get_metric('ds') - self._metrics1.get_metric('mean'))
).mean()
... | |
fff63dd0480ba19b55d7 | def initialize_sparse_array():
row = np.zeros(1)
col = np.zeros(1)
dat = np.zeros(1)
return scipy.sparse.coo_matrix((dat, (row, col))) | |
fff644bd4db89f553b45 | def mel_spectogram(
sample_rate,
hop_length,
win_length,
n_fft,
n_mels,
f_min,
f_max,
power,
normalized,
norm,
mel_scale,
compression,
audio,
):
audio_to_mel = transforms.MelSpectrogram(
sample_rate=sample_rate,
hop_length=hop_length,
win_... | |
fff667a425a15d750d3c | def configure(self):
self.config.render()
if self.config.has_changed():
msg = "Configuring {}".format(self)
hookenv.status_set("maintenance", msg)
hookenv.log(msg)
with self.config.open() as config_file:
self.send_request("configure", met... | |
fff66ca88586c5982ef0 | def graph(request, short_iri):
iri_no_prefix = short_iri.replace("flont:", "")
full_iri = ontology.FLONT_IRI + iri_no_prefix
existing = flont.apps.ontology.search(iri=full_iri)
if len(existing) == 0:
raise Http404("Resource '%s' not found." % full_iri)
node = existing[0]
is_individual = ... | |
fff6795aacd9ba4a7471 | def arrayToGLType( self, value ):
result = ARRAY_TO_GL_TYPE_MAPPING.get( value._type_ )
if result is not None:
return result
raise TypeError(
"""Don't know GL type for array of type %r, known types: %s\nvalue:%s"""%(
value._type_, list(ARRAY_TO_GL_TY... | |
fff67b08cb4c1f2b9e02 | def display_methods(self, tests=None):
print
print "Methods",
if tests:
print "used by tests {0!s}".format(tests),
print "in the Timings Database:"
print
for method in self.methods_in_tests(tests):
print ' {0!s}'.format(method) | |
fff6a9e7497e71be1ee4 | def to_dataframe(self, event_name: str) -> pandas.DataFrame:
return pandas.DataFrame(self[event_name]) | |
fff6c76632d56902910e | def create_account():
return render_template('create_account.html') | |
fff6cbb5d460cd027cb9 | def get_labels(self, path_to_input):
print("***GET_LABELS", file=sys.stderr)
xml_tree = XML.parse(path_to_input)
root = xml_tree.getroot()
for instruction in root.iter("instruction"):
print(instruction.attrib["opcode"] == "LABEL")
if instruction.attrib["opcode"] =... | |
fff6e555408f634032ef | def userTyping(self, message):
pass | |
fff6fd72399f069ee3b9 | def _singleValueFormatter(self, param_name, value):
return urlencode({param_name: value}) | |
fff7106036603253c668 | def list_verified_urls(self):
site_list = self.service.sites().list().execute()
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry'] \
if s['permissionLevel'] != 'siteUnverifiedUser' \
and s['siteUrl'][:4] == 'http']
return verified_sites_urls | |
fff71b8a0e1c68172d1b | def corner(self):
margin_of_error = 1.7
if (self.x < (self.game.window_width / 4) * margin_of_error):
if (self.y < (self.game.window_height / 4) * margin_of_error):
return self.game.TOP_LEFT_CORNER #top left
elif (self.y > (self.game.window_height * (3 / 4)) * (1 ... | |
fff727439e8d0b8da337 | def __init__(self, name, age):
self.name = name
self.age = age | |
fff7483a99fc8c0ca63a | def batch_ranges(x, batch_size):
size = len(x)
num_batches = int(ceil(size / float(batch_size)))
return [(i * batch_size, min(size, (i + 1) * batch_size))
for i in range(num_batches)] | |
fff76c8dba840cab1010 | def plot_track(x_b3, y_b3, x_b2, y_b2, x_b1, y_b1, output_filename):
from matplotlib import pyplot
figure = pyplot.figure(figsize=(10, 10))
pyplot.rcParams.update({'font.size': 30})
plot = figure.add_subplot(1, 1, 1)
ax = pyplot.gca()
ax.minorticks_on()
ax.locator_params(nbins=3)
x_labe... | |
fff781122f02a611f359 | def infer(data, num_inferences=1):
pass | |
fff789ed23b649cce23e | def test_init_unit(self):
reading = EnergyReading(self.energy_reading)
assert reading.unit == 'kWh' | |
fff791953c255645d5d5 | def calc_water_order_parameter(trj_file, gro_file, cutoffs, dim=2, filepath=''):
if dim == 0:
normal_vector = [1, 0, 0]
elif dim == 1:
normal_vector = [0, 1, 0]
else:
normal_vector = [0, 0, 1]
trj_str = f'{filepath}/{trj_file}'
gro_str = f'{filepath}/{gro_file}'
univers... | |
fff7a44ccd464cfdbbb8 | def run(self) -> None:
while self._running:
for event in pygame.event.get():
# check if the user is trying to exit
if event.type == pygame.QUIT:
self._running = False
# check for a grid square being selected
if even... | |
fff7af367457150c2e4a | def __find_mean_circles(img_gray):
rads = []
x = []
y = []
for par in np.linspace(1.1, 50, 40):
circles = cv2.HoughCircles(img_gray, cv2.HOUGH_GRADIENT, par, 1500,
param1=50, param2=30, minRadius=200,
maxRadius=0)
# p... | |
fff7b93ed34ee1465e11 | def _prep_for_multiprocessing(self):
pass | |
fff7ebedf34635cfb9a0 | def _get_keyboard( self, default="", heading="", hidden=False ):
keyboard = xbmc.Keyboard( default, heading, hidden )
keyboard.doModal()
if ( keyboard.isConfirmed() ):
return unicode( keyboard.getText(), "utf-8" )
return default | |
fff80db75fd85ef75120 | def svg(self, scale_factor=1.):
return "\n".join([g.svg(scale_factor) for g in self]) | |
fff82acc4695c018625d | def within_bounds(n, minn, maxn):
return minn <= n <= maxn | |
fff82caafd87f3bf7d0a | def display_help(webpage='', section=''):
if not webpage:
link = URL_WIKISTRING + URL_MANUAL_PAGE + EXTENSION
else:
link = URL_WIKISTRING + webpage + EXTENSION
if section:
link = link + '#' + section
display_url(link) | |
fff83f5343a071df47a9 | def empty(self) -> bool: | |
fff84ee3241480ff3e3a | def is_qualified_url(self):
if self.is_inline():
return False
result = urlparse(self.name)
return bool(result.netloc) | |
fff864bf593a86576504 | def get_function(tosca_tpl, node_template, raw_function):
if is_function(raw_function):
if isinstance(raw_function, dict):
func_name = list(raw_function.keys())[0]
if func_name in function_mappings:
func = function_mappings[func_name]
func_args = list(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.