id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
ff9d15ba8b3fcd19f2bf | def cat_detector(tensor: np.array) -> bool:
prediction = ResNet50_predict_labels(tensor)
# 281 to 287 are dogs in ImageNet, if the predicted label is in this range
# return True
return (prediction <= 287) & (prediction >= 281) | |
ff9d2a5f7cacdee2511c | def test_staff_no_permission(self):
self.client.login(email='staff@email.com', password='staffpass')
self.assertFalse(self.staffuser.has_perm(USER_LIST_PERM))
response = self.client.get(USER_LIST_URL)
self.assertEqual(response.status_code, HTTPStatus.FORBIDDEN) # 403
self.asser... | |
ff9d2fa4562bbf3db746 | def load_json(self):
if self.json_path:
if os.path.exists(self.json_path):
with open(self.json_path, encoding='utf-8') as f:
data = json.load(f)
self.load_data(data)
print("{} {}(s) loaded from json file \"{}\"".format(
... | |
ff9d4cf16843ff18907f | def CosineSimilarity(text1, text2):
if isinstance(text2, list):
cos = dict()
for i in range(len(text2)):
targetText = text2[i].lower()
sourceText = text1.lower()
vec1 = [sourceText, targetText]
vec2 = count_vect.fit_transform(vec1)
tfidf = ... | |
ff9d56457ee46a88aecb | def pixel_at(index, bpp, pixel_transform, bitmap):
row_index, pixel_index = convert_to_2d(bitmap, bpp, index)
# print(f'row_index:{row_index}, pixel_index:{pixel_index}, index:{index}')
selected_row = bitmap[row_index]
selected_pixel = selected_row[pixel_index * bpp:(pixel_index + 1) * bpp]
if pixe... | |
ff9d5d2096b2c27932aa | def get_num_of_ipus_in_device(ipu_device, device="cpu"):
g = ops.Graph()
with g.as_default():
with ops.device(device):
cfg_op = gen_ipu_ops.ipu_get_num_devices(ipu_device)
with session_lib.Session(graph=g) as sess:
return sess.run(cfg_op) | |
ff9da1fd915dd84239a7 | def test_verify_failure_invalid_signature(self):
easyjwt_creation = EasyJWT(self.key)
token = easyjwt_creation.create()
key = 'invalid-' + self.key
with self.assertRaises(InvalidSignatureError):
easyjwt_verification = EasyJWT.verify(token, key)
self.assertIsNone... | |
ff9dcdf356b890f099f3 | async def create(self, ctx, type : str, time : str, limit : str, *, name : str):
guild = ctx.guild
author = ctx.author
if guild not in self.voice_users:
self.voice_users[guild] = list()
self.voice_channels[guild] = list()
if guild no... | |
ff9dfc1a144172a0ca90 | def output(id):
return Server.output(id) | |
ff9e466f52a73584715d | def _clear_data_plots(self, display_pts=1000):
#Initializing variables for plotting
self.out_voltages = np.ones(display_pts) * self._curr_output_voltage
self.measured_powers = np.ones(display_pts) * self._last_power
# Check that setpoint is reasonable, otherwise set error to 0
s... | |
ff9e750dea7d6fee986a | def blank_screen(switch):
if switch == True:
square1.setAutoDraw(False)
square2.setAutoDraw(False)
square3.setAutoDraw(False)
fixation.setAutoDraw(False)
else:
square1.setAutoDraw(True)
square2.setAutoDraw(True)
square3.setAutoDraw(True)
fixation.setAutoDraw(True) | |
ff9e761317269a30fc28 | def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
stream_slice = stream_slice if stream_slice is not None else []
file_... | |
ff9e8847a631860309ea | def str2long(s):
if type(s) not in (types.StringType, types.UnicodeType):
raise ValueError, 'the input must be a string'
l = 0L
for i in s:
l <<= 8
l |= ord(i)
return l | |
ff9e8e1b0137a3240157 | def exchange_rate_details(self, exchange_rate_details):
self._exchange_rate_details = exchange_rate_details | |
ff9edc18d9c86299a5a4 | def test_contact_view_add(self):
response = self.client.get('/contact/add/')
self.assertEqual(response.context['action'], 'add')
self.assertEqual(response.status_code, 200)
response = self.client.post('/contact/add/',
data={'phonebook_id': '1', 'contac... | |
ff9eeae9a0c026919950 | def test_stack():
stack = m.Stack()
stacklist = [i for i in range(15)]
for e in stacklist:
stack.push(e)
assert stack.isEmpty() == False
for i in reversed(range(15)):
last = stack.pop()
assert last == i
assert stack.isEmpty() == True | |
ff9ef9256f30d14ada22 | def set_session(aws_access_key_id=None,
aws_secret_access_key=None,
aws__session_token=None,
region_name=None,
profile_name=None,
boto_session=None):
global __session, __resource
__session = boto_session if boto_session is not None ... | |
ff9f023b3f3c7387fb53 | def categoriesJSON():
categories = Category.query.all()
return jsonify(CAtegory=[i.serialize for i in categories]) | |
ff9f083da003e5f0019a | def train(self, mode: bool = True) -> "ICMPolicy":
self.policy.train(mode)
self.training = mode
self.model.train(mode)
return self | |
ff9f5ea8333257adbfca | def distance_between(self, n1: T, n2: T) -> float: | |
ff9f60e5bd096ad15d63 | def _send(self, request: Request):
pass | |
ff9f64f7367e97596aaa | def add_wall(self, x0, y0, x1, y1):
self._walls.append(Wall(x0, y0, x1, y1)) | |
ff9f75968ee7e78d9c0e | def get_all_apis(self):
try:
paged_results = self.repository.services.list(
max_results=self.DEFAULT_MAX_RESULTS)
flattened_results = api_helpers.flatten_list_results(paged_results,
'services')
excep... | |
ff9f7609d68fd0b155da | def gen_index_combs(self, x):
return np.array(np.meshgrid(x[0], x[1])).T.reshape(-1, 2) | |
ff9f8d095962f2cbf1ee | def _process_request(self, request):
request = self._deserialize(request)
lookup = request.get("lookup", "")
if lookup == "":
pass
elif lookup == "rename":
changes = self._rename(
request["file"],
int(request["start"]),
... | |
ff9faab7a8d46a8f2ee7 | def sort(self):
self.entities.sort(key=lambda e: e.fitness, reverse=True) | |
ff9fb2ef0643c09c909c | def load(self):
raise NotImplementedError(
"Config %s can't load data from source" % ConfigBase
) | |
ff9fc07a05cea9531eff | def test_purge_expired_report_data_on_date(self):
report_period_table_name = OCP_REPORT_TABLE_MAP["report_period"]
cleaner = OCPReportDBCleaner(self.schema)
with schema_context(self.schema):
# Verify that data is cleared for a cutoff date == billing_period_start
first_p... | |
ff9fc09565e0f7eb7bb7 | def name(self) -> str:
return self.device.name or self.device.model | |
ff9fc1c3c5daf0c71282 | def check_description(self, description):
return f"{self.exit_value} {description}" | |
ff9fc5481cd112a2fe72 | def addMember(self, data):
self.create(data=data) | |
ff9fc620227b0abee982 | def update(self):
while not self._stopped:
if self._stream is not None and self._stream.isOpened():
(self.grabbed, self._frame) = self._stream.read()
if self.grabbed:
self._fps.update()
self.last = datetime.datetime.now()
time.sleep(0.01)
else:
self.connect()
time.sleep(0.01)
... | |
ff9fd1d7e413bb1d559c | def _get_data(self):
self.train_df = pd.read_csv('./risk_models/data/train.csv')
self.val_df = pd.read_csv('./risk_models/data/val.csv')
self.test_df = pd.read_csv('./risk_models/data/test.csv') | |
ff9fe301ae0c26efecf9 | def set_currency(self, currency):
if currency is not None and not isinstance(currency, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: currency EXPECTED TYPE: str', None, None)
self.add_key_value('Currency', currency) | |
ffa00aa0bdb3f458f0fe | def test_gs_path_only_bucket_with_trailing_slash(self):
bucket, subfolder = parse_remote_uri("gs://sample_bucket/", "gs")
self.assertTupleEqual((bucket, subfolder), ("sample_bucket", "")) | |
ffa01cbfc2de43faabee | def _initialise_net(self): | |
ffa0368548c33036b20a | def issubset(self, other):
return self.union(other) == other | |
ffa03b4060d0ccfc9fe6 | def SetRequiredNumberOfOverlappingPixels(self, _arg: 'unsigned long long const') -> "void":
return _itkMaskedFFTNormalizedCorrelationImageFilterPython.itkMaskedFFTNormalizedCorrelationImageFilterISS2IF2_SetRequiredNumberOfOverlappingPixels(self, _arg) | |
ffa040f814c03b0492c8 | def test_limits(client):
for i in range(100):
badge = client.post("/api/event/1/badge", json={
"legal_name": "Test User {}".format(i)
}).json
assert(badge['legal_name'] == "Test User {}".format(i))
badges = client.get("/api/event/1/badge", query_string={"limit": 10}).json
... | |
ffa05726e08d87fbe0ab | def _exists(self, model_name, fields):
return self._get_id(model_name, fields) is not None | |
ffa0849bbc836a7fb5ad | def is_list(thing):
return isinstance(thing, types.ListType) | |
ffa0ae8563c56c181ddf | def normalize_username(self, username):
username = username.split('@')[0].lower()
username = self.username_map.get(username, username)
return username | |
ffa0b8426a3b29ebc593 | def _convert_time(self):
s = map(str, self.time)
T = []
for t in s:
y = t[0:4]
m = t[4:6]
d = t[6:8]
h = t[8:]
h = int(float(h) * 24.)
mi = str(int(((float(t[8:]) * 24. - h)*60.)))
h = str(int(h))
tn ... | |
ffa0cc80c73d16663e27 | def semantic_similarity(sentence_1, sentence_2, info_content_norm):
words_1 = nltk.word_tokenize(sentence_1)
words_2 = nltk.word_tokenize(sentence_2)
joint_words = set(words_1).union(set(words_2))
vec_1 = semantic_vector(words_1, joint_words, info_content_norm)
vec_2 = semantic_vector(words_2, joint... | |
ffa0d6a98341d04bcf11 | def load_graph(filename):
with tf.gfile.GFile(filename, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='') | |
ffa0dfe162e45c530d0d | def _matrix2dict(matrix, etype=False):
n = len(matrix)
adj = {k: {} for k in range(n)}
for k in range(n):
for j in range(n):
if matrix[k, j] != 0:
adj[k][j] = {} if not etype else matrix[k, j]
return adj | |
ffa0f1062481331e7338 | def __init__(self, system, temperature, pressure=None):
# Initialize.
self.system = None # the System object governing the potential energy computation
self.temperature = None # the temperature
self.pressure = None # the pressure, or None if not isobaric
sel... | |
ffa0f3a3f9faad535ff7 | def get_volume_to_manage(self, aggregate_name, volume_name):
query = {
'name': volume_name,
'fields': 'name,aggregates.name,nas.path,name,type,style,'
'svm.name,qos.policy.name,space.size',
'aggregates.name': aggregate_name
}
response =... | |
ffa0f6b304752764c286 | def setPermission(self, request):
pass | |
ffa105cf4a05744a18ec | def language_code(self):
if self._language_code:
return self._language_code
return get_language() | |
ffa14f7a08a4f816537c | def calculnf(trajets,total):
for trajet in trajets:
if stations[trajet[1]] != 0:
stations[trajet[1]].calculI(trajet[0],trajet[2])
for station in stations:
if station != 0:
station.attribution(total)
#c'est le (maigre) prix a payer de notre implementation initiale en vecteur
return None | |
ffa152ceb54f55517158 | def find_one(self,table,field_list,**query_dict):
start_sql = 'SELECT '
sql = ''
query_sql = ''
for field in field_list: start_sql += field + ','
start_sql = start_sql[0:-1] + ' FROM %s WHERE ' % (table)
try:
if not query_dict: query_sql = '*'
els... | |
ffa156ca47b9d0d6584a | def add_user(self, auth_type, user_id, **data):
raise NotImplementedError() | |
ffa1574db73526a29655 | def display_initial_screen():
global menu_present, withdrawal_prompt, another_trans_prompt, \
initial_screen, deposit_options_prompt, deposit_prompt, \
acct_balance_displayed
initial_screen = True
menu_present = False
withdrawal_prompt = False
deposit_prompt = False
anoth... | |
ffa16172eebb6b5d67a9 | def __get_type__(self, param):
if isinstance(param, dbTableColumn):
if param.__data__['type'] in ['INTEGER']:
return 'int'
elif param.__data__['type'] in ['VARCHAR', 'TEXT']:
return 'str'
elif param.__data__['type'] in ['REAL']:
return 'float'
else:
return 'dbTableColumn'
else:... | |
ffa17b4c63580af951f3 | def _is_setup(self):
return True | |
ffa1b50c135f4602530a | def create_multiple_gaussian_map(coords_uv, output_size, sigma, valid_vec=None):
with tf.name_scope('create_multiple_gaussian_map'):
sigma = tf.cast(sigma, tf.float32)
assert len(output_size) == 2
s = coords_uv.get_shape().as_list()
coords_uv = tf.cast(coords_uv, ... | |
ffa1df76f1713e6d2fc1 | def turn_off(self, **kwargs):
self.magichome.turn_off() | |
ffa2151bf8ea6d59dcd2 | def users_list(self, **kwargs):
return self.call_api_get("users.list", kwargs=kwargs) | |
ffa23bbbcbe13ea70023 | def fibonacci(num):
first = 1
second = 2
fibo_list = []
for i in range(num):
fibo_list.append(first)
new = first + second
first = second
second = new
return print(fibo_list) | |
ffa25c62d732044ee100 | def get_image_metadata_item(self, image_id, key):
resp, body = self.get("images/%s/metadata/%s" % (str(image_id), key))
body = json.loads(body)
self.validate_response(schema.image_meta_item, resp, body)
return resp, body['meta'] | |
ffa26e79557911b9cd6b | def entra_dados_aluno():
nome = raw_input('O seu nome [primeiro último]: ')
data_nascimento = raw_input('A sua data de nascimento [aaaa/mm/dd]: ')
numero_aluno = raw_input('O seu número de aluno: ')
ano_curso = raw_input('Qual o seu ano de curso [1-5]: ')
return nome,data_nascimento,numero_aluno, an... | |
ffa2774d853f247214c1 | def is_known_attribute(attribute):
return attribute in C.DICT_EXPECTED_TYPES_ATTR | |
ffa297cff130c964ceae | def reverse(head):
cur, pre = head, None
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre | |
ffa2bd3cd71bafdc41a3 | def get_name_from_common( self, common_name ):
return Taxonomy.objects.filter( taxa_from_common__common__name = common_name ) | |
ffa2d50deca1b194b2ad | def alter_object(self, instance, request, url_args, url_kwargs):
return instance | |
ffa2e5fa90bfbf39e11f | def visualise(image, spectrum, title='', title_img='', title_spec='', cmap='gray'):
plt.figure(figsize=(18, 5))
plt.subplot(121)
plt.imshow(image, cmap=cmap)
plt.title(title_img)
plt.subplot(122)
plt.imshow(np.log(abs(spectrum)), cmap=cmap)
plt.title(title_spec)
plt.suptitle(title)
p... | |
ffa30723a49e21122b42 | def GetSurfaceCoordinates(self):
pass | |
ffa32731b746fbade586 | def test_add_numbers(self):
self.assertEqual(add(3, 4), 7) | |
ffa3488573a9ab665585 | def update(self):
c = 0
for file in self.update_gen(): c += 1
return c | |
ffa34e50d00fa3b8fa14 | def kl(mu, logvar):
kld = 0.5 * torch.sum(mu.pow(2) + logvar.exp() - logvar - 1)
return kld | |
ffa36de5dfbbb14455de | def accept_mimetypes(self):
return parse_accept_header(self.environ.get("HTTP_ACCEPT"), MIMEAccept) | |
ffa36e3c64a4eb292057 | def upgrade_history(self) -> pulumi.Output[Sequence['outputs.UpgradeHistoryEntryResponse']]:
return pulumi.get(self, "upgrade_history") | |
ffa3cedf4a45ed1f3176 | def send_put_request(url, data, **params):
if 'api_key' not in params.keys():
params['api_key'] = builtins.API_KEY
params['request_type']= "PUT"
return send_request(url, data, **params) | |
ffa3f28df3be646411bc | def layer(layer_type : str):
__initialize()
return __layers.get(layer_type) | |
ffa40634435a4834d450 | def train(self):
self.emission_model(self.train_data)
self.transition_model(self.train_data) | |
ffa409cdc41434d3cdb8 | def get_total(self):
#If the species is Christmas melon the base price is multiplied by 1.5
Christ_mas = 1
if self.species == "Christmas melon":
Christ_mas = 1.5
qty_charge = 0
#For internation orders if there is less than 10 melons, there is a 3 dollar charge
... | |
ffa42e7fd653b704d054 | def standardize(self):
board=self.find_standard_form()
self.duplicate(board) | |
ffa43fa1efea59916369 | def get_field_from_field(self, field1, field2 , value, tablename="ingredients"):
sql = "SELECT %s FROM %s WHERE %s = ?" % (field1, tablename, field2)
res = sql_query (self.conn, sql, (value, ))
return res | |
ffa450282d4f7e3a703b | def __init__(self, start_callback, stop_callback):
self.sample = None
self.after = None
self.start_callback = start_callback
self.stop_callback = stop_callback
self.cur_file = None | |
ffa47bf4ff3f0dd34e46 | def index( self, value ):
pos = 0
curr = self.head
while not curr == None :
if curr.data == value:
return pos
pos += 1
curr = curr.next
raise ValueError( str( value ) + " is not present in the list" ) | |
ffa492cf7e61ed4e322a | def transform(self, X):
cols = list(set(self.features_to_drop) & set(X.columns))
df = X.drop(columns=cols)
return df | |
ffa49acfbd6a0d020ee4 | def list_builds(yolo_file=None, **kwargs):
client.YoloClient(yolo_file=yolo_file).list_builds(**kwargs) | |
ffa4b082a0c004ec71a2 | def __init__(self):
self.new = Load("Feudalism Simulation", True)
self.log.tracktext("Now Loading")
self.board = self.new.initialize()
self.log.tracktext("Loading done")
cont = 1
while cont == 1:
cont = self.cycle()
self.log.track_popup_only("Simulatio... | |
ffa4f9eb82ca27d17c1c | def __init__(self, engine: Connectable):
self._session_factory = sessionmaker(bind=engine)
self._scoped_session = scoped_session(
session_factory=self._session_factory,
scopefunc=get_concurrent_identity
) | |
ffa504061ae096467ba6 | def __call__(self,*args,**kwargs):
self._log.append((self._method,args,kwargs))
return getattr(self._obj,self._method)(*args,**kwargs) | |
ffa51e6214783adf0029 | def get_first_monday(dates):
return 7%dates[0].weekday() | |
ffa54a56e5e62c158728 | def delete(self):
logger.debug('Deleting job {name} for {label}'.format(name=self.job_name, label=self.species_name))
if self.server != 'local':
ssh = SSHClient(self.server)
logger.debug('deleting job on {0}...'.format(self.server))
ssh.delete_job(self.job_id)
... | |
ffa54e3625aa684e0336 | def test_builder15(self):
builder = Builder(build_cmd='/bin/echo', su_cmd=None, foo='bar')
exp_cmd = ['/bin/echo', '--foo', 'bar']
self.assertEqual(builder.cmd(), exp_cmd) | |
ffa55948fad8cdd25dc3 | def __init__(self, namespace, table_name='beaker_cache', **params):
OpenResourceNamespaceManager.__init__(self, namespace)
def make_cache():
table_dict = dict(created=db.DateTimeProperty(),
accessed=db.DateTimeProperty(),
... | |
ffa58e24c673632ee766 | def opposite(color):
# TODO You have to write this | |
ffa5a12b938860c8639c | def construct_imports(variables, imports):
result = {}
for i in imports:
kv = i.split('=', 1)
if len(kv) != 2:
print 'Invalid value for --imports: %s. See --help.' % i
sys.exit(1)
result[kv[0]] = expand_template(kv[1], variables, result)
return result | |
ffa5b99280d47301aca2 | def is_float_equivalent(f1,f2,places=4):
_str_func = 'is_float_equivalent'
#zeroCheck
l_zeros = [-0.0,0.0,-2e-20]
if round(f1,places) in l_zeros and round(f2,places) in l_zeros:
log.debug("|{0}| >> zero match: {1}|{2}".format(_str_func,f1,f2))
return True
f1_rounded =... | |
ffa5c37e7957f469e61a | def addLayer(self, *args):
pass | |
ffa5cc3449d0577ea0b2 | def final_time():
return 10 | |
ffa5d43fb79555166b5c | def __batch_gradient_descent__(self, X_train, y_train, weights, dim,
L2, batch_size, random_seed, learning_rate, max_iter, verbose):
if batch_size == None:
batch_size = X_train.shape[0]
opt_weights = weights[:]
grad = weights[:]-weights[:]
... | |
ffa5edeb9f77ccb62548 | def __init__(self, data):
self.data = pd.read_csv(data) | |
ffa5ee4514f4535e98ee | def _level(self, level):
if level is None:
return INFO
elif level.lower() == 'notset' or level.lower() == 'off':
return NOTSET
elif level.lower() == 'debug' or level.lower() == 'd':
return DEBUG
elif level.lower() == 'info' or level.lower() == 'i':
... | |
ffa5f6ca25e8ab60881d | def formShowImg(image, predictions, _map, counter):
prediction = np.asarray(to_categorical_4d_reverse(predictions, _map), dtype=np.uint8)[0]
print(np.shape(prediction))
prediction = cv2.cvtColor(prediction, cv2.COLOR_RGB2BGR)
# ---------------------------------------------------------------------------... | |
ffa5f77e20663e0ca2d5 | def numBands(self):
return self.energies.shape[-1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.