body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
1f25df9cc4ad5aef833db5d066fe61924110c6682c1c60b9709ed1fe306ec612 | def _separable_approx2(h, N=1):
' returns the N first approximations to the 2d function h\n whose sum should be h\n '
return np.cumsum([np.outer(fy, fx) for (fy, fx) in _separable_series2(h, N)], 0) | returns the N first approximations to the 2d function h
whose sum should be h | gputools/separable/separable_approx.py | _separable_approx2 | tlambert03/gputools | 89 | python | def _separable_approx2(h, N=1):
' returns the N first approximations to the 2d function h\n whose sum should be h\n '
return np.cumsum([np.outer(fy, fx) for (fy, fx) in _separable_series2(h, N)], 0) | def _separable_approx2(h, N=1):
' returns the N first approximations to the 2d function h\n whose sum should be h\n '
return np.cumsum([np.outer(fy, fx) for (fy, fx) in _separable_series2(h, N)], 0)<|docstring|>returns the N first approximations to the 2d function h
whose sum should be h<|endoftext|> |
27fb3a8d27c5958201c98f6ea08f3e694eacaf5c7db2ad3190b12f3a6a0ca5ea | def _separable_series3(h, N=1, verbose=False):
' finds separable approximations to the 3d kernel h\n returns res = (hx,hy,hz)[N]\n s.t. h \x07pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])\n\n FIXME: This is just a naive and slow first try!\n '
(hx, hy, hz) = ([], [], [])
res = h.copy()
... | finds separable approximations to the 3d kernel h
returns res = (hx,hy,hz)[N]
s.t. h pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])
FIXME: This is just a naive and slow first try! | gputools/separable/separable_approx.py | _separable_series3 | tlambert03/gputools | 89 | python | def _separable_series3(h, N=1, verbose=False):
' finds separable approximations to the 3d kernel h\n returns res = (hx,hy,hz)[N]\n s.t. h \x07pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])\n\n FIXME: This is just a naive and slow first try!\n '
(hx, hy, hz) = ([], [], [])
res = h.copy()
... | def _separable_series3(h, N=1, verbose=False):
' finds separable approximations to the 3d kernel h\n returns res = (hx,hy,hz)[N]\n s.t. h \x07pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])\n\n FIXME: This is just a naive and slow first try!\n '
(hx, hy, hz) = ([], [], [])
res = h.copy()
... |
fdac818e7bbcd366ba8e7eb93a262dbf7656d0e0ac4973a8389c8552bd1e807e | def _separable_approx3(h, N=1):
' returns the N first approximations to the 3d function h\n '
return np.cumsum([np.einsum('i,j,k', fz, fy, fx) for (fz, fy, fx) in _separable_series3(h, N)], 0) | returns the N first approximations to the 3d function h | gputools/separable/separable_approx.py | _separable_approx3 | tlambert03/gputools | 89 | python | def _separable_approx3(h, N=1):
' \n '
return np.cumsum([np.einsum('i,j,k', fz, fy, fx) for (fz, fy, fx) in _separable_series3(h, N)], 0) | def _separable_approx3(h, N=1):
' \n '
return np.cumsum([np.einsum('i,j,k', fz, fy, fx) for (fz, fy, fx) in _separable_series3(h, N)], 0)<|docstring|>returns the N first approximations to the 3d function h<|endoftext|> |
ef72023021582cc035cc4fa3a8d81d7ba4eb4cde5faa34b151a8ba9d108ae84d | def separable_series(h, N=1):
'\n finds the first N rank 1 tensors such that their sum approximates\n the tensor h (2d or 3d) best\n\n returns (e.g. for 3d case) res = (hx,hy,hz)[i]\n\n s.t.\n\n h \x07pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])\n\n Parameters\n ----------\n h: nda... | finds the first N rank 1 tensors such that their sum approximates
the tensor h (2d or 3d) best
returns (e.g. for 3d case) res = (hx,hy,hz)[i]
s.t.
h pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])
Parameters
----------
h: ndarray
input array (2 or 2 dimensional)
N: int
order of approximation
Return... | gputools/separable/separable_approx.py | separable_series | tlambert03/gputools | 89 | python | def separable_series(h, N=1):
'\n finds the first N rank 1 tensors such that their sum approximates\n the tensor h (2d or 3d) best\n\n returns (e.g. for 3d case) res = (hx,hy,hz)[i]\n\n s.t.\n\n h \x07pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])\n\n Parameters\n ----------\n h: nda... | def separable_series(h, N=1):
'\n finds the first N rank 1 tensors such that their sum approximates\n the tensor h (2d or 3d) best\n\n returns (e.g. for 3d case) res = (hx,hy,hz)[i]\n\n s.t.\n\n h \x07pprox sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])\n\n Parameters\n ----------\n h: nda... |
b9d3ae0c656900ca787053e83aba3f79567e44d9f512817db3f79906930ceb9a | def separable_approx(h, N=1):
'\n finds the k-th rank approximation to h, where k = 1..N\n\n similar to separable_series\n\n Parameters\n ----------\n h: ndarray\n input array (2 or 2 dimensional)\n N: int\n order of approximation\n\n Returns\n -------\n all N apprxoimat... | finds the k-th rank approximation to h, where k = 1..N
similar to separable_series
Parameters
----------
h: ndarray
input array (2 or 2 dimensional)
N: int
order of approximation
Returns
-------
all N apprxoimations res[i], the i-th approximation | gputools/separable/separable_approx.py | separable_approx | tlambert03/gputools | 89 | python | def separable_approx(h, N=1):
'\n finds the k-th rank approximation to h, where k = 1..N\n\n similar to separable_series\n\n Parameters\n ----------\n h: ndarray\n input array (2 or 2 dimensional)\n N: int\n order of approximation\n\n Returns\n -------\n all N apprxoimat... | def separable_approx(h, N=1):
'\n finds the k-th rank approximation to h, where k = 1..N\n\n similar to separable_series\n\n Parameters\n ----------\n h: ndarray\n input array (2 or 2 dimensional)\n N: int\n order of approximation\n\n Returns\n -------\n all N apprxoimat... |
163b21ffa8db61a92f02adab8635443fa213ad8bd7eab3f6779ea1b3664bba12 | def get_issues_without_due_date(connection):
'Fin Issues where we need to set due_date value'
query = 'SELECT id FROM issues WHERE status IN :statuses AND due_date IS null'
return connection.execute(sa.text(query), statuses=STATUSES).fetchall() | Fin Issues where we need to set due_date value | src/ggrc/migrations/versions/20190412_84c5ff059f75_set_due_date_for_fixed_and_depricated_.py | get_issues_without_due_date | MikalaiMikalalai/ggrc-core | 1 | python | def get_issues_without_due_date(connection):
query = 'SELECT id FROM issues WHERE status IN :statuses AND due_date IS null'
return connection.execute(sa.text(query), statuses=STATUSES).fetchall() | def get_issues_without_due_date(connection):
query = 'SELECT id FROM issues WHERE status IN :statuses AND due_date IS null'
return connection.execute(sa.text(query), statuses=STATUSES).fetchall()<|docstring|>Fin Issues where we need to set due_date value<|endoftext|> |
04b9f3db00ccc73d4b28d7a5f237039ec71f5f863b763a103b6136fb19deaae6 | def get_revision_due_date(con, issue_id):
'Fund due_date value in related revision'
query = "SELECT content, created_at FROM revisions WHERE resource_type = 'Issue' AND resource_id = :id ORDER BY id DESC"
all_revisions = con.execute(sa.text(query), id=issue_id)
result = None
last_status = None
f... | Fund due_date value in related revision | src/ggrc/migrations/versions/20190412_84c5ff059f75_set_due_date_for_fixed_and_depricated_.py | get_revision_due_date | MikalaiMikalalai/ggrc-core | 1 | python | def get_revision_due_date(con, issue_id):
query = "SELECT content, created_at FROM revisions WHERE resource_type = 'Issue' AND resource_id = :id ORDER BY id DESC"
all_revisions = con.execute(sa.text(query), id=issue_id)
result = None
last_status = None
for rev in all_revisions:
if (not ... | def get_revision_due_date(con, issue_id):
query = "SELECT content, created_at FROM revisions WHERE resource_type = 'Issue' AND resource_id = :id ORDER BY id DESC"
all_revisions = con.execute(sa.text(query), id=issue_id)
result = None
last_status = None
for rev in all_revisions:
if (not ... |
1622720df8bc0abf91c1e03d02865576725065783f0a57d49a15ddb10d608f12 | def upgrade():
'Upgrade database schema and/or data, creating a new revision.'
connection = op.get_bind()
issues_for_update = get_issues_without_due_date(connection)
issues_ids = [issue['id'] for issue in issues_for_update]
for issue_id in issues_ids:
due_date = get_revision_due_date(connect... | Upgrade database schema and/or data, creating a new revision. | src/ggrc/migrations/versions/20190412_84c5ff059f75_set_due_date_for_fixed_and_depricated_.py | upgrade | MikalaiMikalalai/ggrc-core | 1 | python | def upgrade():
connection = op.get_bind()
issues_for_update = get_issues_without_due_date(connection)
issues_ids = [issue['id'] for issue in issues_for_update]
for issue_id in issues_ids:
due_date = get_revision_due_date(connection, issue_id)
set_due_date(connection, issue_id, due_d... | def upgrade():
connection = op.get_bind()
issues_for_update = get_issues_without_due_date(connection)
issues_ids = [issue['id'] for issue in issues_for_update]
for issue_id in issues_ids:
due_date = get_revision_due_date(connection, issue_id)
set_due_date(connection, issue_id, due_d... |
25eb65cb2baefeaff9ce12a6638cc9c687d20f629c8691da947804dff60199e8 | def downgrade():
'Downgrade database schema and/or data back to the previous revision.'
raise NotImplementedError('Downgrade is not supported') | Downgrade database schema and/or data back to the previous revision. | src/ggrc/migrations/versions/20190412_84c5ff059f75_set_due_date_for_fixed_and_depricated_.py | downgrade | MikalaiMikalalai/ggrc-core | 1 | python | def downgrade():
raise NotImplementedError('Downgrade is not supported') | def downgrade():
raise NotImplementedError('Downgrade is not supported')<|docstring|>Downgrade database schema and/or data back to the previous revision.<|endoftext|> |
1586f3ebb7740132e8b5d4cf628a6afd1c53939eff485661daeb5c604d3b1789 | def earth_distance(pos1, pos2):
'Taken from http://www.johndcook.com/python_longitude_latitude.html.'
(lat1, long1) = pos1
(lat2, long2) = pos2
degrees_to_radians = (pi / 180.0)
phi1 = ((90.0 - lat1) * degrees_to_radians)
phi2 = ((90.0 - lat2) * degrees_to_radians)
theta1 = (long1 * degrees_... | Taken from http://www.johndcook.com/python_longitude_latitude.html. | workshops/util.py | earth_distance | r-gaia-cs/swc-amy | 0 | python | def earth_distance(pos1, pos2):
(lat1, long1) = pos1
(lat2, long2) = pos2
degrees_to_radians = (pi / 180.0)
phi1 = ((90.0 - lat1) * degrees_to_radians)
phi2 = ((90.0 - lat2) * degrees_to_radians)
theta1 = (long1 * degrees_to_radians)
theta2 = (long2 * degrees_to_radians)
c = (((sin(... | def earth_distance(pos1, pos2):
(lat1, long1) = pos1
(lat2, long2) = pos2
degrees_to_radians = (pi / 180.0)
phi1 = ((90.0 - lat1) * degrees_to_radians)
phi2 = ((90.0 - lat2) * degrees_to_radians)
theta1 = (long1 * degrees_to_radians)
theta2 = (long2 * degrees_to_radians)
c = (((sin(... |
4c1f801cc9d746c79489c4df1c8c0de47c039a917ca6db36b7b1119d33e9e17d | def upload_person_task_csv(stream):
'Read people from CSV and return a JSON-serializable list of dicts.\n\n The input `stream` should be a file-like object that returns\n Unicode data.\n\n "Serializability" is required because we put this data into session. See\n https://docs.djangoproject.com/en/1.7/t... | Read people from CSV and return a JSON-serializable list of dicts.
The input `stream` should be a file-like object that returns
Unicode data.
"Serializability" is required because we put this data into session. See
https://docs.djangoproject.com/en/1.7/topics/http/sessions/ for details.
Also return a list of fields... | workshops/util.py | upload_person_task_csv | r-gaia-cs/swc-amy | 0 | python | def upload_person_task_csv(stream):
'Read people from CSV and return a JSON-serializable list of dicts.\n\n The input `stream` should be a file-like object that returns\n Unicode data.\n\n "Serializability" is required because we put this data into session. See\n https://docs.djangoproject.com/en/1.7/t... | def upload_person_task_csv(stream):
'Read people from CSV and return a JSON-serializable list of dicts.\n\n The input `stream` should be a file-like object that returns\n Unicode data.\n\n "Serializability" is required because we put this data into session. See\n https://docs.djangoproject.com/en/1.7/t... |
e7c8d42fba7cf97e28e99e3db4193ebb2056f6dbd0e290fdbb62634f761cd6eb | def verify_upload_person_task(data):
'\n Verify that uploaded data is correct. Show errors by populating ``errors``\n dictionary item. This function changes ``data`` in place.\n '
errors_occur = False
for item in data:
errors = []
event = item.get('event', None)
if event:
... | Verify that uploaded data is correct. Show errors by populating ``errors``
dictionary item. This function changes ``data`` in place. | workshops/util.py | verify_upload_person_task | r-gaia-cs/swc-amy | 0 | python | def verify_upload_person_task(data):
'\n Verify that uploaded data is correct. Show errors by populating ``errors``\n dictionary item. This function changes ``data`` in place.\n '
errors_occur = False
for item in data:
errors = []
event = item.get('event', None)
if event:
... | def verify_upload_person_task(data):
'\n Verify that uploaded data is correct. Show errors by populating ``errors``\n dictionary item. This function changes ``data`` in place.\n '
errors_occur = False
for item in data:
errors = []
event = item.get('event', None)
if event:
... |
b292523a1dece95f277620c18638cb0d3a86154763ad6e585ff34276833b45d1 | def create_uploaded_persons_tasks(data):
'\n Create persons and tasks from upload data.\n '
if any([row.get('errors') for row in data]):
raise InternalError('Uploaded data contains errors, cancelling upload')
persons_created = []
tasks_created = []
with transaction.atomic():
fo... | Create persons and tasks from upload data. | workshops/util.py | create_uploaded_persons_tasks | r-gaia-cs/swc-amy | 0 | python | def create_uploaded_persons_tasks(data):
'\n \n '
if any([row.get('errors') for row in data]):
raise InternalError('Uploaded data contains errors, cancelling upload')
persons_created = []
tasks_created = []
with transaction.atomic():
for row in data:
try:
... | def create_uploaded_persons_tasks(data):
'\n \n '
if any([row.get('errors') for row in data]):
raise InternalError('Uploaded data contains errors, cancelling upload')
persons_created = []
tasks_created = []
with transaction.atomic():
for row in data:
try:
... |
ebcee3b5878a4143c5a46fb858cf0618d35c7cc981c6740c3819361819d95afb | def create_username(personal, family):
'Generate unique username.'
stem = ((normalize_name(family) + '.') + normalize_name(personal))
counter = None
while True:
try:
if (counter is None):
username = stem
counter = 1
else:
co... | Generate unique username. | workshops/util.py | create_username | r-gaia-cs/swc-amy | 0 | python | def create_username(personal, family):
stem = ((normalize_name(family) + '.') + normalize_name(personal))
counter = None
while True:
try:
if (counter is None):
username = stem
counter = 1
else:
counter += 1
... | def create_username(personal, family):
stem = ((normalize_name(family) + '.') + normalize_name(personal))
counter = None
while True:
try:
if (counter is None):
username = stem
counter = 1
else:
counter += 1
... |
03759732926be232300efc18809c48f0041b3519aeb9a6d824b3167d2ca10d81 | def normalize_name(name):
'Get rid of spaces, funky characters, etc.'
name = name.strip()
for (accented, flat) in [(' ', '-')]:
name = name.replace(accented, flat)
return name.lower() | Get rid of spaces, funky characters, etc. | workshops/util.py | normalize_name | r-gaia-cs/swc-amy | 0 | python | def normalize_name(name):
name = name.strip()
for (accented, flat) in [(' ', '-')]:
name = name.replace(accented, flat)
return name.lower() | def normalize_name(name):
name = name.strip()
for (accented, flat) in [(' ', '-')]:
name = name.replace(accented, flat)
return name.lower()<|docstring|>Get rid of spaces, funky characters, etc.<|endoftext|> |
160e9806d43c9b12f63247f5804003a93aa4907edf095fd2ee830254ef48794a | def train(train_dataloader, query_dataloader, retrieval_dataloader, arch, feature_dim, code_length, num_classes, dynamic_meta_embedding, num_prototypes, device, lr, max_iter, beta, gamma, mapping, topk, evaluate_interval):
'\n Training model.\n\n Args\n train_dataloader, query_dataloader, retrieval_dat... | Training model.
Args
train_dataloader, query_dataloader, retrieval_dataloader(torch.utils.data.dataloader.DataLoader): Data loader.
arch(str): CNN model name.
code_length(int): Hash code length.
device(torch.device): GPU or CPU.
lr(float): Learning rate.
max_iter(int): Number of iterations.
... | lthNet.py | train | butterfly-chinese/long-tail-hashing | 6 | python | def train(train_dataloader, query_dataloader, retrieval_dataloader, arch, feature_dim, code_length, num_classes, dynamic_meta_embedding, num_prototypes, device, lr, max_iter, beta, gamma, mapping, topk, evaluate_interval):
'\n Training model.\n\n Args\n train_dataloader, query_dataloader, retrieval_dat... | def train(train_dataloader, query_dataloader, retrieval_dataloader, arch, feature_dim, code_length, num_classes, dynamic_meta_embedding, num_prototypes, device, lr, max_iter, beta, gamma, mapping, topk, evaluate_interval):
'\n Training model.\n\n Args\n train_dataloader, query_dataloader, retrieval_dat... |
cdf907274e6955859636f039b6d362fa76254762c93e3f32b0ee965af4a4bb00 | def generate_code(model, dataloader, code_length, num_classes, device, dynamic_meta_embedding, prototypes):
'\n Generate hash code\n\n Args\n dataloader(torch.utils.data.dataloader.DataLoader): Data loader.\n code_length(int): Hash code length.\n device(torch.device): Using gpu or cpu.\n\... | Generate hash code
Args
dataloader(torch.utils.data.dataloader.DataLoader): Data loader.
code_length(int): Hash code length.
device(torch.device): Using gpu or cpu.
Returns
code(torch.Tensor): Hash code. | lthNet.py | generate_code | butterfly-chinese/long-tail-hashing | 6 | python | def generate_code(model, dataloader, code_length, num_classes, device, dynamic_meta_embedding, prototypes):
'\n Generate hash code\n\n Args\n dataloader(torch.utils.data.dataloader.DataLoader): Data loader.\n code_length(int): Hash code length.\n device(torch.device): Using gpu or cpu.\n\... | def generate_code(model, dataloader, code_length, num_classes, device, dynamic_meta_embedding, prototypes):
'\n Generate hash code\n\n Args\n dataloader(torch.utils.data.dataloader.DataLoader): Data loader.\n code_length(int): Hash code length.\n device(torch.device): Using gpu or cpu.\n\... |
74cbb516a069aae8fac68a4016c1999022c058269a7b51e7c2377fa43129d099 | def generate_prototypes(model, dataloader, num_prototypes, feature_dim, device, dynamic_meta_embedding, prototypes_placeholder):
'\n Generate prototypes (visual memory)\n\n Args\n dataloader(torch.utils.data.dataloader.DataLoader): Data loader.\n code_length(int): Hash code length.\n devi... | Generate prototypes (visual memory)
Args
dataloader(torch.utils.data.dataloader.DataLoader): Data loader.
code_length(int): Hash code length.
device(torch.device): Using gpu or cpu.
Returns
code(torch.Tensor): prototypes. | lthNet.py | generate_prototypes | butterfly-chinese/long-tail-hashing | 6 | python | def generate_prototypes(model, dataloader, num_prototypes, feature_dim, device, dynamic_meta_embedding, prototypes_placeholder):
'\n Generate prototypes (visual memory)\n\n Args\n dataloader(torch.utils.data.dataloader.DataLoader): Data loader.\n code_length(int): Hash code length.\n devi... | def generate_prototypes(model, dataloader, num_prototypes, feature_dim, device, dynamic_meta_embedding, prototypes_placeholder):
'\n Generate prototypes (visual memory)\n\n Args\n dataloader(torch.utils.data.dataloader.DataLoader): Data loader.\n code_length(int): Hash code length.\n devi... |
5a1385edd81fa2ea3a3fc7b2fe6d4934d11f126a3c86f6631b83e6765790f058 | def roc_auc(predictions, target):
'\n This methods returns the AUC Score when given the Predictions\n and Labels\n '
(fpr, tpr, thresholds) = metrics.roc_curve(target, predictions)
roc_auc = metrics.auc(fpr, tpr)
return roc_auc | This methods returns the AUC Score when given the Predictions
and Labels | Jigsaw-Multilingual-Toxic-Comment-Classification/train-by-lstm.py | roc_auc | NCcoco/kaggle-project | 0 | python | def roc_auc(predictions, target):
'\n This methods returns the AUC Score when given the Predictions\n and Labels\n '
(fpr, tpr, thresholds) = metrics.roc_curve(target, predictions)
roc_auc = metrics.auc(fpr, tpr)
return roc_auc | def roc_auc(predictions, target):
'\n This methods returns the AUC Score when given the Predictions\n and Labels\n '
(fpr, tpr, thresholds) = metrics.roc_curve(target, predictions)
roc_auc = metrics.auc(fpr, tpr)
return roc_auc<|docstring|>This methods returns the AUC Score when given the Predi... |
df06cdef78bb1d30663d76123313c03910bd17ae413b5f570b10ecedaa4af8c3 | def __init__(self, exception: Exception, plugin_name: str=None, entry_point: EntryPoint=None):
'Initialize FailedToLoadPlugin exception.'
self.plugin_name = plugin_name
self.original_exception = exception
self.entry_point = entry_point | Initialize FailedToLoadPlugin exception. | src/valiant/plugins/exceptions.py | __init__ | pomes/valiant | 2 | python | def __init__(self, exception: Exception, plugin_name: str=None, entry_point: EntryPoint=None):
self.plugin_name = plugin_name
self.original_exception = exception
self.entry_point = entry_point | def __init__(self, exception: Exception, plugin_name: str=None, entry_point: EntryPoint=None):
self.plugin_name = plugin_name
self.original_exception = exception
self.entry_point = entry_point<|docstring|>Initialize FailedToLoadPlugin exception.<|endoftext|> |
dcf311029fd7fe46fbdb97f49b2c90a8dfc3796c03a5bbda33045df1828108ca | def __str__(self):
'Format our exception message.'
return f"Failed to load plugin '{self.plugin_name}' due to {self.original_exception}. Entry point is: {self.entry_point}. sys.path is: {sys.path}" | Format our exception message. | src/valiant/plugins/exceptions.py | __str__ | pomes/valiant | 2 | python | def __str__(self):
return f"Failed to load plugin '{self.plugin_name}' due to {self.original_exception}. Entry point is: {self.entry_point}. sys.path is: {sys.path}" | def __str__(self):
return f"Failed to load plugin '{self.plugin_name}' due to {self.original_exception}. Entry point is: {self.entry_point}. sys.path is: {sys.path}"<|docstring|>Format our exception message.<|endoftext|> |
1e9e36aae44db3f23d44efb0c623213e7370adf7fe66317427665a89273848d9 | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.ProcessProposal = channel.unary_unary('/protos.Endorser/ProcessProposal', request_serializer=peer_dot_fabric__proposal__pb2.SignedProposal.SerializeToString, response_deserializer=peer_dot_fabric__proposal__respo... | Constructor.
Args:
channel: A grpc.Channel. | bddtests/peer/fabric_service_pb2_grpc.py | __init__ | memoutng/BlockchainTesteo | 1 | python | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.ProcessProposal = channel.unary_unary('/protos.Endorser/ProcessProposal', request_serializer=peer_dot_fabric__proposal__pb2.SignedProposal.SerializeToString, response_deserializer=peer_dot_fabric__proposal__respo... | def __init__(self, channel):
'Constructor.\n\n Args:\n channel: A grpc.Channel.\n '
self.ProcessProposal = channel.unary_unary('/protos.Endorser/ProcessProposal', request_serializer=peer_dot_fabric__proposal__pb2.SignedProposal.SerializeToString, response_deserializer=peer_dot_fabric__proposal__respo... |
66f1f8a224faff68eebaf153b6a47f99e84c96c92a17d722875d1c3046169b6c | @login_required(login_url='login')
def profile(request: object):
'Profile function processes 1 types of request.\n\n 1. GET\n Returns the reset profile page.\n '
if (request.method == 'GET'):
return render(request, template_name='alfastaff-products/profile.html', context={'user': request.us... | Profile function processes 1 types of request.
1. GET
Returns the reset profile page. | alfastaff_products/views.py | profile | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def profile(request: object):
'Profile function processes 1 types of request.\n\n 1. GET\n Returns the reset profile page.\n '
if (request.method == 'GET'):
return render(request, template_name='alfastaff-products/profile.html', context={'user': request.us... | @login_required(login_url='login')
def profile(request: object):
'Profile function processes 1 types of request.\n\n 1. GET\n Returns the reset profile page.\n '
if (request.method == 'GET'):
return render(request, template_name='alfastaff-products/profile.html', context={'user': request.us... |
23d69a37fff2f00741c13d7027e56b653b06c89506a748680cde301225a355a9 | @login_required(login_url='login')
def edit(request: object):
'Edit function processes 1 types of request.\n\n 1. GET\n Returns the edit page.\n '
if (request.method == 'GET'):
return render(request, template_name='alfastaff-products/edit.html', context={'user': request.user, 'avatar': requ... | Edit function processes 1 types of request.
1. GET
Returns the edit page. | alfastaff_products/views.py | edit | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def edit(request: object):
'Edit function processes 1 types of request.\n\n 1. GET\n Returns the edit page.\n '
if (request.method == 'GET'):
return render(request, template_name='alfastaff-products/edit.html', context={'user': request.user, 'avatar': requ... | @login_required(login_url='login')
def edit(request: object):
'Edit function processes 1 types of request.\n\n 1. GET\n Returns the edit page.\n '
if (request.method == 'GET'):
return render(request, template_name='alfastaff-products/edit.html', context={'user': request.user, 'avatar': requ... |
02246f70ead566342b1b9ce85fad8e403b304af73797c62bf2510a21ae18e002 | @login_required(login_url='login')
def edit_password(request: object):
'edit_password function processes 2 types of request post and get.\n\n 1. GET\n Redirect to the edit page;\n 2. POST\n Checks the validity of the data,\n checks whether the user verifies the passwords for equality;\n ... | edit_password function processes 2 types of request post and get.
1. GET
Redirect to the edit page;
2. POST
Checks the validity of the data,
checks whether the user verifies the passwords for equality;
if everything is good, then he changes the password and redirects to the page,
if the error retur... | alfastaff_products/views.py | edit_password | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def edit_password(request: object):
'edit_password function processes 2 types of request post and get.\n\n 1. GET\n Redirect to the edit page;\n 2. POST\n Checks the validity of the data,\n checks whether the user verifies the passwords for equality;\n ... | @login_required(login_url='login')
def edit_password(request: object):
'edit_password function processes 2 types of request post and get.\n\n 1. GET\n Redirect to the edit page;\n 2. POST\n Checks the validity of the data,\n checks whether the user verifies the passwords for equality;\n ... |
aa5e345671ac35196ff49ff32f563c96fc4142d386949f0a0dfe0c9bdcb0d209 | @login_required(login_url='login')
def edit_profile(request: object):
'edit_profile function processes 2 types of request post and get.\n\n 1. GET\n Redirect to the edit page;\n 2. POST\n Checks the validity of the data,\n changes the user’s object fields and checks for the presence of a ... | edit_profile function processes 2 types of request post and get.
1. GET
Redirect to the edit page;
2. POST
Checks the validity of the data,
changes the user’s object fields and checks for the presence of a standard photo,
saves the user and authorizes him again and then redirects to editing. | alfastaff_products/views.py | edit_profile | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def edit_profile(request: object):
'edit_profile function processes 2 types of request post and get.\n\n 1. GET\n Redirect to the edit page;\n 2. POST\n Checks the validity of the data,\n changes the user’s object fields and checks for the presence of a ... | @login_required(login_url='login')
def edit_profile(request: object):
'edit_profile function processes 2 types of request post and get.\n\n 1. GET\n Redirect to the edit page;\n 2. POST\n Checks the validity of the data,\n changes the user’s object fields and checks for the presence of a ... |
2304f1884d992935a24b254b5a723218ff9f6c75cfeb9a5366f423905751cff8 | @login_required(login_url='login')
def logout_user(request: object):
'logout_user function processes 1 types of request.\n\n 1. GET\n Returns the login page and logout user.\n '
if (request.method == 'GET'):
logout(request)
return render(request, template_name='alfastaff-account/log... | logout_user function processes 1 types of request.
1. GET
Returns the login page and logout user. | alfastaff_products/views.py | logout_user | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def logout_user(request: object):
'logout_user function processes 1 types of request.\n\n 1. GET\n Returns the login page and logout user.\n '
if (request.method == 'GET'):
logout(request)
return render(request, template_name='alfastaff-account/log... | @login_required(login_url='login')
def logout_user(request: object):
'logout_user function processes 1 types of request.\n\n 1. GET\n Returns the login page and logout user.\n '
if (request.method == 'GET'):
logout(request)
return render(request, template_name='alfastaff-account/log... |
511ea99bfb567325de6cdd299195772004fb6e199c5b88d442504d8d4e99b542 | @login_required(login_url='login')
def purchases(request: object):
'Purchases function processes 1 types of request.\n\n 1. GET\n return number of page on purchases.html\n '
if (request.method == 'GET'):
count_page = count_page_purchases(request)
return render(request, template_name... | Purchases function processes 1 types of request.
1. GET
return number of page on purchases.html | alfastaff_products/views.py | purchases | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def purchases(request: object):
'Purchases function processes 1 types of request.\n\n 1. GET\n return number of page on purchases.html\n '
if (request.method == 'GET'):
count_page = count_page_purchases(request)
return render(request, template_name... | @login_required(login_url='login')
def purchases(request: object):
'Purchases function processes 1 types of request.\n\n 1. GET\n return number of page on purchases.html\n '
if (request.method == 'GET'):
count_page = count_page_purchases(request)
return render(request, template_name... |
36622a86e4611c7a4c41817669ad8e86b209899d94b047f67313a584137ee260 | @login_required(login_url='login')
def purchases_page(request: object, page: int, sort: str):
'purchases_page function processes 1 types of request.\n\n 1. GET\n It takes several arguments from the query string such as the page number and sort name,\n takes out the elements according to the page an... | purchases_page function processes 1 types of request.
1. GET
It takes several arguments from the query string such as the page number and sort name,
takes out the elements according to the page and sorts them according to the sort name
and returns to the page. | alfastaff_products/views.py | purchases_page | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def purchases_page(request: object, page: int, sort: str):
'purchases_page function processes 1 types of request.\n\n 1. GET\n It takes several arguments from the query string such as the page number and sort name,\n takes out the elements according to the page an... | @login_required(login_url='login')
def purchases_page(request: object, page: int, sort: str):
'purchases_page function processes 1 types of request.\n\n 1. GET\n It takes several arguments from the query string such as the page number and sort name,\n takes out the elements according to the page an... |
30d2312331438e6f8cb6bbe48e29caf92a7750411cae98fa5e9955378df57c6c | @login_required(login_url='login')
def products(request: object):
'Product function processes 1 types of request.\n\n 1. GET\n return number of page on catalog.html\n '
if (request.method == 'GET'):
count_page = count_page_products()
return render(request, template_name='alfastaff-p... | Product function processes 1 types of request.
1. GET
return number of page on catalog.html | alfastaff_products/views.py | products | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def products(request: object):
'Product function processes 1 types of request.\n\n 1. GET\n return number of page on catalog.html\n '
if (request.method == 'GET'):
count_page = count_page_products()
return render(request, template_name='alfastaff-p... | @login_required(login_url='login')
def products(request: object):
'Product function processes 1 types of request.\n\n 1. GET\n return number of page on catalog.html\n '
if (request.method == 'GET'):
count_page = count_page_products()
return render(request, template_name='alfastaff-p... |
24394623048df6774b6521ffa057d7c96304ea173a62ca0188a4b594df736582 | @login_required(login_url='login')
def products_page(request: object, page: int, sort: str):
'products_page function processes 1 types of request.\n\n 1. GET\n It takes several arguments from the query string such as the page number and sort name,\n takes out the elements according to the page and ... | products_page function processes 1 types of request.
1. GET
It takes several arguments from the query string such as the page number and sort name,
takes out the elements according to the page and sorts them according to the sort name
and returns to the page. | alfastaff_products/views.py | products_page | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def products_page(request: object, page: int, sort: str):
'products_page function processes 1 types of request.\n\n 1. GET\n It takes several arguments from the query string such as the page number and sort name,\n takes out the elements according to the page and ... | @login_required(login_url='login')
def products_page(request: object, page: int, sort: str):
'products_page function processes 1 types of request.\n\n 1. GET\n It takes several arguments from the query string such as the page number and sort name,\n takes out the elements according to the page and ... |
2f92e38435debbbb8def0918c5db15f92f79d756ed356558272fd52fe45974d1 | @login_required(login_url='login')
def buy(request: object, id: int):
'buy function processes 1 types of request.\n\n 1. GET\n We get the goods from the user’s database,\n check whether the purchase is possible and create a new purchase object,\n then save it, after which we send the message... | buy function processes 1 types of request.
1. GET
We get the goods from the user’s database,
check whether the purchase is possible and create a new purchase object,
then save it, after which we send the message about the purchase to the administrator,
otherwise we return an error in JSON format | alfastaff_products/views.py | buy | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def buy(request: object, id: int):
'buy function processes 1 types of request.\n\n 1. GET\n We get the goods from the user’s database,\n check whether the purchase is possible and create a new purchase object,\n then save it, after which we send the message... | @login_required(login_url='login')
def buy(request: object, id: int):
'buy function processes 1 types of request.\n\n 1. GET\n We get the goods from the user’s database,\n check whether the purchase is possible and create a new purchase object,\n then save it, after which we send the message... |
dbbb6748e6d5c28507e8a2212e029c75f8bbb4241e33adebdadf849fc0a0be62 | @login_required(login_url='login')
def top_up_account(request: object):
'top up an account function processes 1 types of request.\n\n 1. POST\n '
if (request.method == 'POST'):
return top_up_account_processing(request) | top up an account function processes 1 types of request.
1. POST | alfastaff_products/views.py | top_up_account | spanickroon/Alfa-Staff | 1 | python | @login_required(login_url='login')
def top_up_account(request: object):
'top up an account function processes 1 types of request.\n\n 1. POST\n '
if (request.method == 'POST'):
return top_up_account_processing(request) | @login_required(login_url='login')
def top_up_account(request: object):
'top up an account function processes 1 types of request.\n\n 1. POST\n '
if (request.method == 'POST'):
return top_up_account_processing(request)<|docstring|>top up an account function processes 1 types of request.
1. POST<|... |
3f22a56aadb020be1fc28cc267f6d6c137f57bedb0f83d661bf6365fa1749217 | def parse_loc(location_in: List[float], filecache=True):
'Takes location parameter and returns a list of coordinates.\n\n This function cleans the location parameter to a list of coordinates. If\n the location_in is a list it returns the list, else it uses the geopy\n interface to generatea list of coordin... | Takes location parameter and returns a list of coordinates.
This function cleans the location parameter to a list of coordinates. If
the location_in is a list it returns the list, else it uses the geopy
interface to generatea list of coordinates from the descriptor.
Args:
location_in :List[float,float], str): List... | BuildingEnergySimulation/construction.py | parse_loc | cbaretzky/BuiidingEnergySimulation | 3 | python | def parse_loc(location_in: List[float], filecache=True):
'Takes location parameter and returns a list of coordinates.\n\n This function cleans the location parameter to a list of coordinates. If\n the location_in is a list it returns the list, else it uses the geopy\n interface to generatea list of coordin... | def parse_loc(location_in: List[float], filecache=True):
'Takes location parameter and returns a list of coordinates.\n\n This function cleans the location parameter to a list of coordinates. If\n the location_in is a list it returns the list, else it uses the geopy\n interface to generatea list of coordin... |
f63c56c00bf311c27028ae32a40a6142525d7de423309be64057420e5789d90e | def get_component(self, searchterm: str) -> list:
'Return all components of a specifc type.\n\n Args:\n searchterm (str): Name of component/type\n\n Returns:\n found (List): List of objects with specific name/type.\n\n '
found = []
for (name, component) in self.com... | Return all components of a specifc type.
Args:
searchterm (str): Name of component/type
Returns:
found (List): List of objects with specific name/type. | BuildingEnergySimulation/construction.py | get_component | cbaretzky/BuiidingEnergySimulation | 3 | python | def get_component(self, searchterm: str) -> list:
'Return all components of a specifc type.\n\n Args:\n searchterm (str): Name of component/type\n\n Returns:\n found (List): List of objects with specific name/type.\n\n '
found = []
for (name, component) in self.com... | def get_component(self, searchterm: str) -> list:
'Return all components of a specifc type.\n\n Args:\n searchterm (str): Name of component/type\n\n Returns:\n found (List): List of objects with specific name/type.\n\n '
found = []
for (name, component) in self.com... |
82f5aa039e4a8cec272d3780121be8d2b0546c2b50e1bca448e41a5de5805dc2 | def reg(self, component, *args, **kwargs):
'Wrapper to register from within the building instance.\n\n instead of::\n $ bes.Component.reg(*args, **kwargs)\n\n it can be::\n $ building.reg(bes.Wall, *args, **kwargs)\n\n '
component.reg(self, *args, **kwargs) | Wrapper to register from within the building instance.
instead of::
$ bes.Component.reg(*args, **kwargs)
it can be::
$ building.reg(bes.Wall, *args, **kwargs) | BuildingEnergySimulation/construction.py | reg | cbaretzky/BuiidingEnergySimulation | 3 | python | def reg(self, component, *args, **kwargs):
'Wrapper to register from within the building instance.\n\n instead of::\n $ bes.Component.reg(*args, **kwargs)\n\n it can be::\n $ building.reg(bes.Wall, *args, **kwargs)\n\n '
component.reg(self, *args, **kwargs) | def reg(self, component, *args, **kwargs):
'Wrapper to register from within the building instance.\n\n instead of::\n $ bes.Component.reg(*args, **kwargs)\n\n it can be::\n $ building.reg(bes.Wall, *args, **kwargs)\n\n '
component.reg(self, *args, **kwargs)<|docstring|... |
18676f5afc1a47856415ecd26505154eae44a62041df3f6eb7e72b73a5284d53 | def simulate(self, timeframe_start: datetime.datetime, timeframe_stop: datetime.datetime) -> pd.DataFrame:
'Run the simulation from timeframe_start to timeframe_stop with the\n defined timestep\n\n Args:\n timeframe_start (datetime.datetime): First date of timeframe.\n timeframe_... | Run the simulation from timeframe_start to timeframe_stop with the
defined timestep
Args:
timeframe_start (datetime.datetime): First date of timeframe.
timeframe_stop (datetime.datetime): Last date of timeframe. | BuildingEnergySimulation/construction.py | simulate | cbaretzky/BuiidingEnergySimulation | 3 | python | def simulate(self, timeframe_start: datetime.datetime, timeframe_stop: datetime.datetime) -> pd.DataFrame:
'Run the simulation from timeframe_start to timeframe_stop with the\n defined timestep\n\n Args:\n timeframe_start (datetime.datetime): First date of timeframe.\n timeframe_... | def simulate(self, timeframe_start: datetime.datetime, timeframe_stop: datetime.datetime) -> pd.DataFrame:
'Run the simulation from timeframe_start to timeframe_stop with the\n defined timestep\n\n Args:\n timeframe_start (datetime.datetime): First date of timeframe.\n timeframe_... |
31d164e7a3f0e844e4b9fa06fe668212f2978940c8abe4099d356cd4f43d15af | def reg(self, name, head):
'\n Let Classes register new losses\n '
pass | Let Classes register new losses | BuildingEnergySimulation/construction.py | reg | cbaretzky/BuiidingEnergySimulation | 3 | python | def reg(self, name, head):
'\n \n '
pass | def reg(self, name, head):
'\n \n '
pass<|docstring|>Let Classes register new losses<|endoftext|> |
6e1050a3e6f9ba171286894e0e525aecf154cd870c2fd6581ff32654ae0918a4 | def update(self, name, vals):
'\n Shift Timestamp forward\n Do Calculations\n '
pass | Shift Timestamp forward
Do Calculations | BuildingEnergySimulation/construction.py | update | cbaretzky/BuiidingEnergySimulation | 3 | python | def update(self, name, vals):
'\n Shift Timestamp forward\n Do Calculations\n '
pass | def update(self, name, vals):
'\n Shift Timestamp forward\n Do Calculations\n '
pass<|docstring|>Shift Timestamp forward
Do Calculations<|endoftext|> |
984dc1603a88837ed59d6b8a23928a9d5be080c41b3fb014bad1befa9000288f | def build_BNN(data, output_condition, cd=98, mss=1, md=30, relevant_neuron_dictionary={}, with_data=1, discretization=0, cluster_means=None):
'\n\tStarting from the target condition and until the conditions with respect \n\tto the first hidden layer, it extracts a DNF that explains each condition\n\tusing condition... | Starting from the target condition and until the conditions with respect
to the first hidden layer, it extracts a DNF that explains each condition
using conditions of the next shallower layer
param data: instance of DataSet
param output_condition: condition of interest
param cd: class dominance
param mss: minimum dat... | lens/models/ext_models/deep_red/decision_tree_induction.py | build_BNN | pietrobarbiero/logic_explained_networks | 18 | python | def build_BNN(data, output_condition, cd=98, mss=1, md=30, relevant_neuron_dictionary={}, with_data=1, discretization=0, cluster_means=None):
'\n\tStarting from the target condition and until the conditions with respect \n\tto the first hidden layer, it extracts a DNF that explains each condition\n\tusing condition... | def build_BNN(data, output_condition, cd=98, mss=1, md=30, relevant_neuron_dictionary={}, with_data=1, discretization=0, cluster_means=None):
'\n\tStarting from the target condition and until the conditions with respect \n\tto the first hidden layer, it extracts a DNF that explains each condition\n\tusing condition... |
f628079eb8cc10a08e5ec6354cb9b3db9a175615b978d61bab8b1fec0c015d4b | def temp_data(data, shallow, tc, deep=None):
'\n\t param data: the dataset\n\t type data: DataSet\n\t param shallow: shallow layer index\n\t type shallow: int\n\t param target_class: list of split points\n\t type target_class: list of (int, int, float) tuples\n\t return: a dataset that includes all instances from t... | param data: the dataset
type data: DataSet
param shallow: shallow layer index
type shallow: int
param target_class: list of split points
type target_class: list of (int, int, float) tuples
return: a dataset that includes all instances from the train and
valdation sets made of the attributes of the shallow layer a... | lens/models/ext_models/deep_red/decision_tree_induction.py | temp_data | pietrobarbiero/logic_explained_networks | 18 | python | def temp_data(data, shallow, tc, deep=None):
'\n\t param data: the dataset\n\t type data: DataSet\n\t param shallow: shallow layer index\n\t type shallow: int\n\t param target_class: list of split points\n\t type target_class: list of (int, int, float) tuples\n\t return: a dataset that includes all instances from t... | def temp_data(data, shallow, tc, deep=None):
'\n\t param data: the dataset\n\t type data: DataSet\n\t param shallow: shallow layer index\n\t type shallow: int\n\t param target_class: list of split points\n\t type target_class: list of (int, int, float) tuples\n\t return: a dataset that includes all instances from t... |
cdd5b47a1bdd227c764cb8ea4326c91685bd04df344670308c5bca873bf88992 | def server_error_401(request, template_name='401.html'):
'A simple 401 handler so we get media.'
response = render(request, template_name)
response.status_code = 401
return response | A simple 401 handler so we get media. | readthedocs/docsitalia/views/core_views.py | server_error_401 | italia/readthedocs.org | 19 | python | def server_error_401(request, template_name='401.html'):
response = render(request, template_name)
response.status_code = 401
return response | def server_error_401(request, template_name='401.html'):
response = render(request, template_name)
response.status_code = 401
return response<|docstring|>A simple 401 handler so we get media.<|endoftext|> |
b3721ac6a314deb54f56677b0d7ef01bff41bac4220da39acc775878456e0d34 | def search_by_tag(request, tag):
'Wrapper around readthedocs.search.views.elastic_search to search by tag.'
get_data = request.GET.copy()
if (get_data.get('tags') or get_data.get('q') or get_data.get('type')):
real_search = ('%s?%s' % (reverse('search'), request.GET.urlencode()))
return Http... | Wrapper around readthedocs.search.views.elastic_search to search by tag. | readthedocs/docsitalia/views/core_views.py | search_by_tag | italia/readthedocs.org | 19 | python | def search_by_tag(request, tag):
get_data = request.GET.copy()
if (get_data.get('tags') or get_data.get('q') or get_data.get('type')):
real_search = ('%s?%s' % (reverse('search'), request.GET.urlencode()))
return HttpResponseRedirect(real_search)
if (not get_data.get('q')):
get_... | def search_by_tag(request, tag):
get_data = request.GET.copy()
if (get_data.get('tags') or get_data.get('q') or get_data.get('type')):
real_search = ('%s?%s' % (reverse('search'), request.GET.urlencode()))
return HttpResponseRedirect(real_search)
if (not get_data.get('q')):
get_... |
f6bae6e311ed47222faa8e271d0bd39a40da8c004bb7a331313f6a4efe2d6845 | def get_queryset(self):
'\n Filter projects to show in homepage.\n\n We show in homepage projects that matches the following requirements:\n - Publisher is active\n - PublisherProject is active\n - document (Project) has a public build\n - Build is success and finished\n\n ... | Filter projects to show in homepage.
We show in homepage projects that matches the following requirements:
- Publisher is active
- PublisherProject is active
- document (Project) has a public build
- Build is success and finished
Ordering by:
- ProjectOrder model values
- modified_date descending
- pub_date descendin... | readthedocs/docsitalia/views/core_views.py | get_queryset | italia/readthedocs.org | 19 | python | def get_queryset(self):
'\n Filter projects to show in homepage.\n\n We show in homepage projects that matches the following requirements:\n - Publisher is active\n - PublisherProject is active\n - document (Project) has a public build\n - Build is success and finished\n\n ... | def get_queryset(self):
'\n Filter projects to show in homepage.\n\n We show in homepage projects that matches the following requirements:\n - Publisher is active\n - PublisherProject is active\n - document (Project) has a public build\n - Build is success and finished\n\n ... |
b8e66b40eb2337579c1be9f13d131b6045fc56306af1b024587dcf60335856da | def get_queryset(self):
'\n Filter publisher to be listed.\n\n We show publishers that matches the following requirements:\n - are active\n - have documents with successful public build\n '
active_pub_projects = PublisherProject.objects.filter(active=True, publisher__active=Tr... | Filter publisher to be listed.
We show publishers that matches the following requirements:
- are active
- have documents with successful public build | readthedocs/docsitalia/views/core_views.py | get_queryset | italia/readthedocs.org | 19 | python | def get_queryset(self):
'\n Filter publisher to be listed.\n\n We show publishers that matches the following requirements:\n - are active\n - have documents with successful public build\n '
active_pub_projects = PublisherProject.objects.filter(active=True, publisher__active=Tr... | def get_queryset(self):
'\n Filter publisher to be listed.\n\n We show publishers that matches the following requirements:\n - are active\n - have documents with successful public build\n '
active_pub_projects = PublisherProject.objects.filter(active=True, publisher__active=Tr... |
7e3e0c71c1583458179e010ab98d9d2e638113250f897491fb96ab254ab47ebc | def get_queryset(self):
'Filter for active Publisher.'
return Publisher.objects.filter(active=True) | Filter for active Publisher. | readthedocs/docsitalia/views/core_views.py | get_queryset | italia/readthedocs.org | 19 | python | def get_queryset(self):
return Publisher.objects.filter(active=True) | def get_queryset(self):
return Publisher.objects.filter(active=True)<|docstring|>Filter for active Publisher.<|endoftext|> |
1f2d72f0c43e1a2f020174a9fc217bc5fd765b7ed3d140adc131b16264003916 | def get_queryset(self):
'Filter for active PublisherProject.'
return PublisherProject.objects.filter(active=True, publisher__active=True) | Filter for active PublisherProject. | readthedocs/docsitalia/views/core_views.py | get_queryset | italia/readthedocs.org | 19 | python | def get_queryset(self):
return PublisherProject.objects.filter(active=True, publisher__active=True) | def get_queryset(self):
return PublisherProject.objects.filter(active=True, publisher__active=True)<|docstring|>Filter for active PublisherProject.<|endoftext|> |
30a63a0d8d8bbc1b6a5498fb6b6f46921344b8227de2431753d1c34370a712d1 | def get_queryset(self):
'Filter projects based on user permissions.'
return Project.objects.protected(self.request.user) | Filter projects based on user permissions. | readthedocs/docsitalia/views/core_views.py | get_queryset | italia/readthedocs.org | 19 | python | def get_queryset(self):
return Project.objects.protected(self.request.user) | def get_queryset(self):
return Project.objects.protected(self.request.user)<|docstring|>Filter projects based on user permissions.<|endoftext|> |
13b5c61b3b9ffc58dd999c989d3a62ab27f5a3ee16ba31feb8f4489276f5fc10 | def get(self, request, *args, **kwargs):
'Redirect to the canonical URL of the document.'
try:
document = self.get_queryset().get(slug=self.kwargs['slug'])
return HttpResponseRedirect('{}index.html'.format(document.get_docs_url(lang_slug=self.kwargs.get('lang'), version_slug=self.kwargs.get('ver... | Redirect to the canonical URL of the document. | readthedocs/docsitalia/views/core_views.py | get | italia/readthedocs.org | 19 | python | def get(self, request, *args, **kwargs):
try:
document = self.get_queryset().get(slug=self.kwargs['slug'])
return HttpResponseRedirect('{}index.html'.format(document.get_docs_url(lang_slug=self.kwargs.get('lang'), version_slug=self.kwargs.get('version'))))
except Project.DoesNotExist:
... | def get(self, request, *args, **kwargs):
try:
document = self.get_queryset().get(slug=self.kwargs['slug'])
return HttpResponseRedirect('{}index.html'.format(document.get_docs_url(lang_slug=self.kwargs.get('lang'), version_slug=self.kwargs.get('version'))))
except Project.DoesNotExist:
... |
0ade71f884f4bbb8d622ed61c97aeeb9806a2079e987c1177f9bb27fd2804726 | def post(self, request, *args, **kwargs):
"\n Handler for Project import.\n\n We import the Project only after validating the mandatory metadata.\n We then connect a Project to its PublisherProject.\n Finally we need to update the Project model with the data we have in the\n docum... | Handler for Project import.
We import the Project only after validating the mandatory metadata.
We then connect a Project to its PublisherProject.
Finally we need to update the Project model with the data we have in the
document_settings.yml. We don't care much about what it's in the model
and we consider the config f... | readthedocs/docsitalia/views/core_views.py | post | italia/readthedocs.org | 19 | python | def post(self, request, *args, **kwargs):
"\n Handler for Project import.\n\n We import the Project only after validating the mandatory metadata.\n We then connect a Project to its PublisherProject.\n Finally we need to update the Project model with the data we have in the\n docum... | def post(self, request, *args, **kwargs):
"\n Handler for Project import.\n\n We import the Project only after validating the mandatory metadata.\n We then connect a Project to its PublisherProject.\n Finally we need to update the Project model with the data we have in the\n docum... |
40946f53c03e4eaf11988f8faa92c9b1c490776b84c362690ee7a45f03daf0a9 | @click.command(short_help='Run PhISCS (CSP version).')
@click.argument('genotype_file', required=True, type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True))
@click.argument('alpha', required=True, type=float)
@click.argument('beta', required=True, type=float)
def phiscsb(genoty... | PhISCS-B.
A combinatorial approach for subperfect
tumor phylogeny reconstructionvia integrative use of
single-cell and bulk sequencing data :cite:`PhISCS`.
trisicell phiscsb input.SC 0.0001 0.1 | trisicell/commands/_phiscs.py | phiscsb | faridrashidi/trisicell | 2 | python | @click.command(short_help='Run PhISCS (CSP version).')
@click.argument('genotype_file', required=True, type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True))
@click.argument('alpha', required=True, type=float)
@click.argument('beta', required=True, type=float)
def phiscsb(genoty... | @click.command(short_help='Run PhISCS (CSP version).')
@click.argument('genotype_file', required=True, type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True))
@click.argument('alpha', required=True, type=float)
@click.argument('beta', required=True, type=float)
def phiscsb(genoty... |
bb45dbaad79c43298f446c2ff2feda7b2312c646c9650e97efcf7fab1972fa13 | @click.command(short_help='Run PhISCS (ILP version).')
@click.argument('genotype_file', required=True, type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True))
@click.argument('alpha', required=True, type=float)
@click.argument('beta', required=True, type=float)
@click.option('--t... | PhISCS-I.
A combinatorial approach for subperfect
tumor phylogeny reconstructionvia integrative use of
single-cell and bulk sequencing data :cite:`PhISCS`.
trisicell phiscsi input.SC 0.0001 0.1 -t 3600 -p 8 | trisicell/commands/_phiscs.py | phiscsi | faridrashidi/trisicell | 2 | python | @click.command(short_help='Run PhISCS (ILP version).')
@click.argument('genotype_file', required=True, type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True))
@click.argument('alpha', required=True, type=float)
@click.argument('beta', required=True, type=float)
@click.option('--t... | @click.command(short_help='Run PhISCS (ILP version).')
@click.argument('genotype_file', required=True, type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True))
@click.argument('alpha', required=True, type=float)
@click.argument('beta', required=True, type=float)
@click.option('--t... |
bbe1192c8fa47142f901e2a4e8589bb3c312b5b65960e18af35a9b0fde0b2b37 | def drop_out_matrices(layers_dims, m, keep_prob):
'\n Initializes the dropout matrices that will be used in both forward prop\n and back-prop on each layer. We\'ll use random numbers from uniform\n distribution.\n\n Arguments\n ---------\n layers_dims : list\n input size and size of each la... | Initializes the dropout matrices that will be used in both forward prop
and back-prop on each layer. We'll use random numbers from uniform
distribution.
Arguments
---------
layers_dims : list
input size and size of each layer, length: number of layers + 1.
m : int
number of training examples.
keep_prob : list
... | scripts/dropout.py | drop_out_matrices | johntiger1/blog-posts | 0 | python | def drop_out_matrices(layers_dims, m, keep_prob):
'\n Initializes the dropout matrices that will be used in both forward prop\n and back-prop on each layer. We\'ll use random numbers from uniform\n distribution.\n\n Arguments\n ---------\n layers_dims : list\n input size and size of each la... | def drop_out_matrices(layers_dims, m, keep_prob):
'\n Initializes the dropout matrices that will be used in both forward prop\n and back-prop on each layer. We\'ll use random numbers from uniform\n distribution.\n\n Arguments\n ---------\n layers_dims : list\n input size and size of each la... |
29c108619aace1516dbb6bf6113166c96bdc76ef304c87cd1130e4862c4aa24b | def L_model_forward(X, parameters, D, keep_prob, hidden_layers_activation_fn='relu'):
'\n Computes the output layer through looping over all units in topological\n order.\n\n X : 2d-array\n input matrix of shape input_size x training_examples.\n parameters : dict\n contains all the weight ... | Computes the output layer through looping over all units in topological
order.
X : 2d-array
input matrix of shape input_size x training_examples.
parameters : dict
contains all the weight matrices and bias vectors for all layers.
D : dict
dropout matrices for each layer l.
keep_prob : list
probabilitie... | scripts/dropout.py | L_model_forward | johntiger1/blog-posts | 0 | python | def L_model_forward(X, parameters, D, keep_prob, hidden_layers_activation_fn='relu'):
'\n Computes the output layer through looping over all units in topological\n order.\n\n X : 2d-array\n input matrix of shape input_size x training_examples.\n parameters : dict\n contains all the weight ... | def L_model_forward(X, parameters, D, keep_prob, hidden_layers_activation_fn='relu'):
'\n Computes the output layer through looping over all units in topological\n order.\n\n X : 2d-array\n input matrix of shape input_size x training_examples.\n parameters : dict\n contains all the weight ... |
c2ad044c9f0357651b0d06ce00870ca19938de126ff095ba9d6b0286f7ec7994 | def L_model_backward(AL, Y, caches, D, keep_prob, hidden_layers_activation_fn='relu'):
'\n Computes the gradient of output layer w.r.t weights, biases, etc. starting\n on the output layer in reverse topological order.\n\n Arguments\n ---------\n AL : 2d-array\n probability vector, output of th... | Computes the gradient of output layer w.r.t weights, biases, etc. starting
on the output layer in reverse topological order.
Arguments
---------
AL : 2d-array
probability vector, output of the forward propagation
(L_model_forward()).
y : 2d-array
true "label" vector (containing 0 if non-cat, 1 if cat).
cac... | scripts/dropout.py | L_model_backward | johntiger1/blog-posts | 0 | python | def L_model_backward(AL, Y, caches, D, keep_prob, hidden_layers_activation_fn='relu'):
'\n Computes the gradient of output layer w.r.t weights, biases, etc. starting\n on the output layer in reverse topological order.\n\n Arguments\n ---------\n AL : 2d-array\n probability vector, output of th... | def L_model_backward(AL, Y, caches, D, keep_prob, hidden_layers_activation_fn='relu'):
'\n Computes the gradient of output layer w.r.t weights, biases, etc. starting\n on the output layer in reverse topological order.\n\n Arguments\n ---------\n AL : 2d-array\n probability vector, output of th... |
5d4c2c422d518dd4fb4db68ade7926bd3b468ba36d64375ef121533085cb363f | def model_with_dropout(X, Y, layers_dims, keep_prob, learning_rate=0.01, num_iterations=3000, print_cost=True, hidden_layers_activation_fn='relu'):
'\n Implements multilayer neural network with dropout using gradient descent as the\n learning algorithm.\n\n Arguments\n ---------\n X : 2d-array\n ... | Implements multilayer neural network with dropout using gradient descent as the
learning algorithm.
Arguments
---------
X : 2d-array
data, shape: number of examples x num_px * num_px * 3.
y : 2d-array
true "label" vector, shape: 1 x number of examples.
layers_dims : list
input size and size of each layer, ... | scripts/dropout.py | model_with_dropout | johntiger1/blog-posts | 0 | python | def model_with_dropout(X, Y, layers_dims, keep_prob, learning_rate=0.01, num_iterations=3000, print_cost=True, hidden_layers_activation_fn='relu'):
'\n Implements multilayer neural network with dropout using gradient descent as the\n learning algorithm.\n\n Arguments\n ---------\n X : 2d-array\n ... | def model_with_dropout(X, Y, layers_dims, keep_prob, learning_rate=0.01, num_iterations=3000, print_cost=True, hidden_layers_activation_fn='relu'):
'\n Implements multilayer neural network with dropout using gradient descent as the\n learning algorithm.\n\n Arguments\n ---------\n X : 2d-array\n ... |
1b80b6191a9a41a609549603935669b23ee243daf877999ee924191f577a4c4f | def getType(self):
' Returns the type of an entity '
return self.type | Returns the type of an entity | tasksupervisor/entities/entity.py | getType | ramp-eu/Task_Supervisor | 0 | python | def getType(self):
' '
return self.type | def getType(self):
' '
return self.type<|docstring|>Returns the type of an entity<|endoftext|> |
c3e6b30fa4772b2bb409b6e1b4cb3d0329160f2a91954e53a20bfc537ddd4bad | def getId(self):
' Returns the unique ID of an entity '
return self.id | Returns the unique ID of an entity | tasksupervisor/entities/entity.py | getId | ramp-eu/Task_Supervisor | 0 | python | def getId(self):
' '
return self.id | def getId(self):
' '
return self.id<|docstring|>Returns the unique ID of an entity<|endoftext|> |
cdc9acc7509be446a50c0803f2008d93867a5ac8291564221a22f2cd7bb693ee | @abstractmethod
def forward(self, x_e: torch.FloatTensor, graph_ids: torch.LongTensor, entity_ids: Optional[torch.LongTensor]) -> FloatTensor:
'\n Obtain graph representations by aggregating node representations.\n\n :param x_e: shape: (num_nodes, dim)\n The node representations.\n :... | Obtain graph representations by aggregating node representations.
:param x_e: shape: (num_nodes, dim)
The node representations.
:param graph_ids: shape: (num_nodes,)
The graph ID for each node.
:param entity_ids: shape: (num_nodes,)
The global entity ID for each node.
:return: shape: (num_graphs, dim)
... | src/mphrqe/layer/pooling.py | forward | DimitrisAlivas/StarQE | 11 | python | @abstractmethod
def forward(self, x_e: torch.FloatTensor, graph_ids: torch.LongTensor, entity_ids: Optional[torch.LongTensor]) -> FloatTensor:
'\n Obtain graph representations by aggregating node representations.\n\n :param x_e: shape: (num_nodes, dim)\n The node representations.\n :... | @abstractmethod
def forward(self, x_e: torch.FloatTensor, graph_ids: torch.LongTensor, entity_ids: Optional[torch.LongTensor]) -> FloatTensor:
'\n Obtain graph representations by aggregating node representations.\n\n :param x_e: shape: (num_nodes, dim)\n The node representations.\n :... |
63f8416d28eab338a50873b85983828d2f3f84fb712cf82eb951b49cdbe8e173 | def forward(self, x_e: torch.FloatTensor, graph_ids: torch.LongTensor, entity_ids: Optional[torch.LongTensor]=None) -> FloatTensor:
'\n graph_ids: binary mask\n '
assert (entity_ids is not None)
mask = (entity_ids == (get_entity_mapper().highest_entity_index + 1))
assert (mask.sum() == gra... | graph_ids: binary mask | src/mphrqe/layer/pooling.py | forward | DimitrisAlivas/StarQE | 11 | python | def forward(self, x_e: torch.FloatTensor, graph_ids: torch.LongTensor, entity_ids: Optional[torch.LongTensor]=None) -> FloatTensor:
'\n \n '
assert (entity_ids is not None)
mask = (entity_ids == (get_entity_mapper().highest_entity_index + 1))
assert (mask.sum() == graph_ids.unique().shape[... | def forward(self, x_e: torch.FloatTensor, graph_ids: torch.LongTensor, entity_ids: Optional[torch.LongTensor]=None) -> FloatTensor:
'\n \n '
assert (entity_ids is not None)
mask = (entity_ids == (get_entity_mapper().highest_entity_index + 1))
assert (mask.sum() == graph_ids.unique().shape[... |
b944b2e6b172a132d61b061861cafbb95226c80c63f2d69f28e5a200ce61f9e4 | def init_application():
'Main entry point for initializing the Deckhand API service.\n\n Create routes for the v1.0 API and sets up logging.\n '
config_files = _get_config_files()
paste_file = config_files[(- 1)]
CONF([], project='deckhand', default_config_files=config_files)
setup_logging(CON... | Main entry point for initializing the Deckhand API service.
Create routes for the v1.0 API and sets up logging. | deckhand/control/api.py | init_application | att-comdev/test-submit | 0 | python | def init_application():
'Main entry point for initializing the Deckhand API service.\n\n Create routes for the v1.0 API and sets up logging.\n '
config_files = _get_config_files()
paste_file = config_files[(- 1)]
CONF([], project='deckhand', default_config_files=config_files)
setup_logging(CON... | def init_application():
'Main entry point for initializing the Deckhand API service.\n\n Create routes for the v1.0 API and sets up logging.\n '
config_files = _get_config_files()
paste_file = config_files[(- 1)]
CONF([], project='deckhand', default_config_files=config_files)
setup_logging(CON... |
3f774de91682eb63d50f7ff9ae1fa53d7c7927c9bebf8528789d8ca00756a2d3 | def add_logging_level(levelName: str, levelNum: int, methodName: Optional[str]=None) -> None:
'Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.\n\n `levelName` becomes an attribute of the `logging` module with the value\n `levelNum`. `methodName` bec... | Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.
`levelName` becomes an attribute of the `logging` module with the value
`levelNum`. `methodName` becomes a convenience method for both `logging`
itself and the class returned by `logging.getLoggerClass()` (usua... | unifi_protect_backup/unifi_protect_backup.py | add_logging_level | roastlechon/unifi-protect-backup | 0 | python | def add_logging_level(levelName: str, levelNum: int, methodName: Optional[str]=None) -> None:
'Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.\n\n `levelName` becomes an attribute of the `logging` module with the value\n `levelNum`. `methodName` bec... | def add_logging_level(levelName: str, levelNum: int, methodName: Optional[str]=None) -> None:
'Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.\n\n `levelName` becomes an attribute of the `logging` module with the value\n `levelNum`. `methodName` bec... |
2d439cfce5c6cf51114181c556fbab6efdbf9308c9b74fca150a7abad1088363 | def setup_logging(verbosity: int) -> None:
'Configures loggers to provided the desired level of verbosity.\n\n Verbosity 0: Only log info messages created by `unifi-protect-backup`, and all warnings\n verbosity 1: Only log info & debug messages created by `unifi-protect-backup`, and all warnings\n verbosit... | Configures loggers to provided the desired level of verbosity.
Verbosity 0: Only log info messages created by `unifi-protect-backup`, and all warnings
verbosity 1: Only log info & debug messages created by `unifi-protect-backup`, and all warnings
verbosity 2: Log info & debug messages created by `unifi-protect-backup`... | unifi_protect_backup/unifi_protect_backup.py | setup_logging | roastlechon/unifi-protect-backup | 0 | python | def setup_logging(verbosity: int) -> None:
'Configures loggers to provided the desired level of verbosity.\n\n Verbosity 0: Only log info messages created by `unifi-protect-backup`, and all warnings\n verbosity 1: Only log info & debug messages created by `unifi-protect-backup`, and all warnings\n verbosit... | def setup_logging(verbosity: int) -> None:
'Configures loggers to provided the desired level of verbosity.\n\n Verbosity 0: Only log info messages created by `unifi-protect-backup`, and all warnings\n verbosity 1: Only log info & debug messages created by `unifi-protect-backup`, and all warnings\n verbosit... |
0d2d9eb04ff12b37c07ffdf2e3937a0f4e74dc312f5ccfc64d002d7d85b070d6 | def human_readable_size(num):
'Turns a number into a human readable number with ISO/IEC 80000 binary prefixes.\n\n Based on: https://stackoverflow.com/a/1094933\n\n Args:\n num (int): The number to be converted into human readable format\n '
for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', '... | Turns a number into a human readable number with ISO/IEC 80000 binary prefixes.
Based on: https://stackoverflow.com/a/1094933
Args:
num (int): The number to be converted into human readable format | unifi_protect_backup/unifi_protect_backup.py | human_readable_size | roastlechon/unifi-protect-backup | 0 | python | def human_readable_size(num):
'Turns a number into a human readable number with ISO/IEC 80000 binary prefixes.\n\n Based on: https://stackoverflow.com/a/1094933\n\n Args:\n num (int): The number to be converted into human readable format\n '
for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', '... | def human_readable_size(num):
'Turns a number into a human readable number with ISO/IEC 80000 binary prefixes.\n\n Based on: https://stackoverflow.com/a/1094933\n\n Args:\n num (int): The number to be converted into human readable format\n '
for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', '... |
d044ea67851c969777f0b36cf23547890c4af69895cd01ab5603c9a1882f8cfb | def __init__(self, stdout, stderr, returncode):
'Exception class for when rclone does not exit with `0`.\n\n Args:\n stdout (str): What rclone output to stdout\n stderr (str): What rclone output to stderr\n returncode (str): The return code of the rclone process\n '
supe... | Exception class for when rclone does not exit with `0`.
Args:
stdout (str): What rclone output to stdout
stderr (str): What rclone output to stderr
returncode (str): The return code of the rclone process | unifi_protect_backup/unifi_protect_backup.py | __init__ | roastlechon/unifi-protect-backup | 0 | python | def __init__(self, stdout, stderr, returncode):
'Exception class for when rclone does not exit with `0`.\n\n Args:\n stdout (str): What rclone output to stdout\n stderr (str): What rclone output to stderr\n returncode (str): The return code of the rclone process\n '
supe... | def __init__(self, stdout, stderr, returncode):
'Exception class for when rclone does not exit with `0`.\n\n Args:\n stdout (str): What rclone output to stdout\n stderr (str): What rclone output to stderr\n returncode (str): The return code of the rclone process\n '
supe... |
8cc882511f3630b3ba4b04177f02c5d6ec9f19b1047efb757db92ebb8088329b | def __str__(self):
'Turns excpetion into a human readable form.'
return f'''Return Code: {self.returncode}
Stdout:
{self.stdout}
Stderr:
{self.stderr}''' | Turns excpetion into a human readable form. | unifi_protect_backup/unifi_protect_backup.py | __str__ | roastlechon/unifi-protect-backup | 0 | python | def __str__(self):
return f'Return Code: {self.returncode}
Stdout:
{self.stdout}
Stderr:
{self.stderr}' | def __str__(self):
return f'Return Code: {self.returncode}
Stdout:
{self.stdout}
Stderr:
{self.stderr}'<|docstring|>Turns excpetion into a human readable form.<|endoftext|> |
78c1d81c4fd8de4f0556ae6dd96ecc7e44bf0b1afc5149b737f15750a93746c6 | def __init__(self, address: str, username: str, password: str, verify_ssl: bool, rclone_destination: str, retention: str, rclone_args: str, ignore_cameras: List[str], verbose: int, port: int=443):
'Will configure logging settings and the Unifi Protect API (but not actually connect).\n\n Args:\n ad... | Will configure logging settings and the Unifi Protect API (but not actually connect).
Args:
address (str): Base address of the Unifi Protect instance
port (int): Post of the Unifi Protect instance, usually 443
username (str): Username to log into Unifi Protect instance
password (str): Password for Unif... | unifi_protect_backup/unifi_protect_backup.py | __init__ | roastlechon/unifi-protect-backup | 0 | python | def __init__(self, address: str, username: str, password: str, verify_ssl: bool, rclone_destination: str, retention: str, rclone_args: str, ignore_cameras: List[str], verbose: int, port: int=443):
'Will configure logging settings and the Unifi Protect API (but not actually connect).\n\n Args:\n ad... | def __init__(self, address: str, username: str, password: str, verify_ssl: bool, rclone_destination: str, retention: str, rclone_args: str, ignore_cameras: List[str], verbose: int, port: int=443):
'Will configure logging settings and the Unifi Protect API (but not actually connect).\n\n Args:\n ad... |
2dfc50cb2f99104f5746b7ef1848d8db46593968fa467e9d753919655eb5ae44 | async def start(self):
'Bootstrap the backup process and kick off the main loop.\n\n You should run this to start the realtime backup of Unifi Protect clips as they are created\n\n '
logger.info('Starting...')
logger.info('Checking rclone configuration...')
(await self._check_rclone())
... | Bootstrap the backup process and kick off the main loop.
You should run this to start the realtime backup of Unifi Protect clips as they are created | unifi_protect_backup/unifi_protect_backup.py | start | roastlechon/unifi-protect-backup | 0 | python | async def start(self):
'Bootstrap the backup process and kick off the main loop.\n\n You should run this to start the realtime backup of Unifi Protect clips as they are created\n\n '
logger.info('Starting...')
logger.info('Checking rclone configuration...')
(await self._check_rclone())
... | async def start(self):
'Bootstrap the backup process and kick off the main loop.\n\n You should run this to start the realtime backup of Unifi Protect clips as they are created\n\n '
logger.info('Starting...')
logger.info('Checking rclone configuration...')
(await self._check_rclone())
... |
4e581efdf88b0e357b2b4d0732c6e5ebfb742416975ab2a5da6bb436e9c12b47 | async def _check_rclone(self) -> None:
'Check if rclone is installed and the specified remote is configured.\n\n Raises:\n SubprocessException: If rclone is not installed or it failed to list remotes\n ValueError: The given rclone destination is for a remote that is not configured\n\n ... | Check if rclone is installed and the specified remote is configured.
Raises:
SubprocessException: If rclone is not installed or it failed to list remotes
ValueError: The given rclone destination is for a remote that is not configured | unifi_protect_backup/unifi_protect_backup.py | _check_rclone | roastlechon/unifi-protect-backup | 0 | python | async def _check_rclone(self) -> None:
'Check if rclone is installed and the specified remote is configured.\n\n Raises:\n SubprocessException: If rclone is not installed or it failed to list remotes\n ValueError: The given rclone destination is for a remote that is not configured\n\n ... | async def _check_rclone(self) -> None:
'Check if rclone is installed and the specified remote is configured.\n\n Raises:\n SubprocessException: If rclone is not installed or it failed to list remotes\n ValueError: The given rclone destination is for a remote that is not configured\n\n ... |
885ae6a498b94fcd3bc87f9c43d3fb38192da9610cde71587d7b57392949601f | def _websocket_callback(self, msg: WSSubscriptionMessage) -> None:
'Callback for "EVENT" websocket messages.\n\n Filters the incoming events, and puts completed events onto the download queue\n\n Args:\n msg (Event): Incoming event data\n '
logger.websocket_data(msg)
assert i... | Callback for "EVENT" websocket messages.
Filters the incoming events, and puts completed events onto the download queue
Args:
msg (Event): Incoming event data | unifi_protect_backup/unifi_protect_backup.py | _websocket_callback | roastlechon/unifi-protect-backup | 0 | python | def _websocket_callback(self, msg: WSSubscriptionMessage) -> None:
'Callback for "EVENT" websocket messages.\n\n Filters the incoming events, and puts completed events onto the download queue\n\n Args:\n msg (Event): Incoming event data\n '
logger.websocket_data(msg)
assert i... | def _websocket_callback(self, msg: WSSubscriptionMessage) -> None:
'Callback for "EVENT" websocket messages.\n\n Filters the incoming events, and puts completed events onto the download queue\n\n Args:\n msg (Event): Incoming event data\n '
logger.websocket_data(msg)
assert i... |
52775b06d7a72d1d75df7ab4ff2ed962a13271ffe12cb4703d08fac3615093d4 | async def _backup_events(self) -> None:
'Main loop for backing up events.\n\n Waits for an event in the queue, then downloads the corresponding clip and uploads it using rclone.\n If errors occur it will simply log the errors and wait for the next event. In a future release,\n retries will be a... | Main loop for backing up events.
Waits for an event in the queue, then downloads the corresponding clip and uploads it using rclone.
If errors occur it will simply log the errors and wait for the next event. In a future release,
retries will be added. | unifi_protect_backup/unifi_protect_backup.py | _backup_events | roastlechon/unifi-protect-backup | 0 | python | async def _backup_events(self) -> None:
'Main loop for backing up events.\n\n Waits for an event in the queue, then downloads the corresponding clip and uploads it using rclone.\n If errors occur it will simply log the errors and wait for the next event. In a future release,\n retries will be a... | async def _backup_events(self) -> None:
'Main loop for backing up events.\n\n Waits for an event in the queue, then downloads the corresponding clip and uploads it using rclone.\n If errors occur it will simply log the errors and wait for the next event. In a future release,\n retries will be a... |
2eeb84df8b4dfbf502034ac9440aaba5ef5896c30000b0f6fa347eecba6fb807 | async def _upload_video(self, video: bytes, destination: pathlib.Path, rclone_args: str):
'Upload video using rclone.\n\n In order to avoid writing to disk, the video file data is piped directly\n to the rclone process and uploaded using the `rcat` function of rclone.\n\n Args:\n vid... | Upload video using rclone.
In order to avoid writing to disk, the video file data is piped directly
to the rclone process and uploaded using the `rcat` function of rclone.
Args:
video (bytes): The data to be written to the file
destination (pathlib.Path): Where rclone should write the file
rclone_args (st... | unifi_protect_backup/unifi_protect_backup.py | _upload_video | roastlechon/unifi-protect-backup | 0 | python | async def _upload_video(self, video: bytes, destination: pathlib.Path, rclone_args: str):
'Upload video using rclone.\n\n In order to avoid writing to disk, the video file data is piped directly\n to the rclone process and uploaded using the `rcat` function of rclone.\n\n Args:\n vid... | async def _upload_video(self, video: bytes, destination: pathlib.Path, rclone_args: str):
'Upload video using rclone.\n\n In order to avoid writing to disk, the video file data is piped directly\n to the rclone process and uploaded using the `rcat` function of rclone.\n\n Args:\n vid... |
fe280a857498bb6055d85d772d26084049a4fbf0210cce3f9f83053034dbec46 | async def generate_file_path(self, event: Event) -> pathlib.Path:
'Generates the rclone destination path for the provided event.\n\n Generates paths in the following structure:\n ::\n rclone_destination\n |- Camera Name\n |- {Date}\n |- {start timestamp} {... | Generates the rclone destination path for the provided event.
Generates paths in the following structure:
::
rclone_destination
|- Camera Name
|- {Date}
|- {start timestamp} {event type} ({detections}).mp4
Args:
event: The event for which to create an output path
Returns:
pathlib.Path: The ... | unifi_protect_backup/unifi_protect_backup.py | generate_file_path | roastlechon/unifi-protect-backup | 0 | python | async def generate_file_path(self, event: Event) -> pathlib.Path:
'Generates the rclone destination path for the provided event.\n\n Generates paths in the following structure:\n ::\n rclone_destination\n |- Camera Name\n |- {Date}\n |- {start timestamp} {... | async def generate_file_path(self, event: Event) -> pathlib.Path:
'Generates the rclone destination path for the provided event.\n\n Generates paths in the following structure:\n ::\n rclone_destination\n |- Camera Name\n |- {Date}\n |- {start timestamp} {... |
08d134c5817bbf67da4b6d18c4bacb5b6262741adf2679b064f4327d40a0de49 | def setup_filepaths():
'Setup full file paths for functional net and BIOGRID'
if (organism == 'cerevisiae'):
biogridpath = os.path.join('..', 'data', 'BIOGRID-3.4.130-yeast-post2006.txt')
fnetpath = os.path.join('..', 'data', 'YeastNetDataFrame.pkl')
elif (organism == 'sapiens'):
bio... | Setup full file paths for functional net and BIOGRID | src/explorenet.py | setup_filepaths | jon-young/genetic_interact | 0 | python | def setup_filepaths():
if (organism == 'cerevisiae'):
biogridpath = os.path.join('..', 'data', 'BIOGRID-3.4.130-yeast-post2006.txt')
fnetpath = os.path.join('..', 'data', 'YeastNetDataFrame.pkl')
elif (organism == 'sapiens'):
biogridpath = os.path.join('..', '..', 'DataDownload', 'B... | def setup_filepaths():
if (organism == 'cerevisiae'):
biogridpath = os.path.join('..', 'data', 'BIOGRID-3.4.130-yeast-post2006.txt')
fnetpath = os.path.join('..', 'data', 'YeastNetDataFrame.pkl')
elif (organism == 'sapiens'):
biogridpath = os.path.join('..', '..', 'DataDownload', 'B... |
a9a6bd6ab1445866bb77781be3a52d9d8f19b9fd59b6a153e5ca2605bc894923 | def determine_col():
'Determine which gene column in the BIOGRID file to read'
entrezRegEx = re.compile('\\d+')
if (organism == 'cerevisiae'):
sysNameRegEx = re.compile('Y[A-Z][A-Z]\\d+')
ofcSymRegEx = re.compile('[A-Z]+')
elif (organism == 'sapiens'):
sysNameRegEx = re.compile('... | Determine which gene column in the BIOGRID file to read | src/explorenet.py | determine_col | jon-young/genetic_interact | 0 | python | def determine_col():
entrezRegEx = re.compile('\\d+')
if (organism == 'cerevisiae'):
sysNameRegEx = re.compile('Y[A-Z][A-Z]\\d+')
ofcSymRegEx = re.compile('[A-Z]+')
elif (organism == 'sapiens'):
sysNameRegEx = re.compile('\\w+')
ofcSymRegEx = re.compile('[A-Za-z]+.')
... | def determine_col():
entrezRegEx = re.compile('\\d+')
if (organism == 'cerevisiae'):
sysNameRegEx = re.compile('Y[A-Z][A-Z]\\d+')
ofcSymRegEx = re.compile('[A-Z]+')
elif (organism == 'sapiens'):
sysNameRegEx = re.compile('\\w+')
ofcSymRegEx = re.compile('[A-Za-z]+.')
... |
83a617657c8e37796e99b46861221c4294aa4577b5008479ddec6dafef8b9a36 | def get_path(self, path, *, relative_to, package=None):
"Return *path* relative to *relative_to* location.\n\n :param pathlike path:\n A path relative to bundle source root.\n\n :param str relative_to:\n Location name. Can be one of:\n - ``'sourceroot'``: bundle sou... | Return *path* relative to *relative_to* location.
:param pathlike path:
A path relative to bundle source root.
:param str relative_to:
Location name. Can be one of:
- ``'sourceroot'``: bundle source root
- ``'pkgsource'``: package source directory
- ``'pkgbuild'``: package build directory
... | metapkg/targets/generic/build.py | get_path | fantix/metapkg | 0 | python | def get_path(self, path, *, relative_to, package=None):
"Return *path* relative to *relative_to* location.\n\n :param pathlike path:\n A path relative to bundle source root.\n\n :param str relative_to:\n Location name. Can be one of:\n - ``'sourceroot'``: bundle sou... | def get_path(self, path, *, relative_to, package=None):
"Return *path* relative to *relative_to* location.\n\n :param pathlike path:\n A path relative to bundle source root.\n\n :param str relative_to:\n Location name. Can be one of:\n - ``'sourceroot'``: bundle sou... |
7f2bff1f697e8cd9eda30a2c0b79b0238ced2c97f30ba8a0b75c3874aca70529 | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['POST'])
def accept_ride(request):
'\n Creating trip object and setting passenger is_searching to false\n :param request:\n :return:\n '
data = request.data
driver_obj = request.user.driver
passenger... | Creating trip object and setting passenger is_searching to false
:param request:
:return: | bookingapp/views.py | accept_ride | bhargava-kush/dj_uber | 0 | python | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['POST'])
def accept_ride(request):
'\n Creating trip object and setting passenger is_searching to false\n :param request:\n :return:\n '
data = request.data
driver_obj = request.user.driver
passenger... | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['POST'])
def accept_ride(request):
'\n Creating trip object and setting passenger is_searching to false\n :param request:\n :return:\n '
data = request.data
driver_obj = request.user.driver
passenger... |
f49a9cc62b5dc983b3343d7314710c37dc8feae5516ee7c90a32b6f037e7f674 | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def request_ride(request):
'\n Passenger requesting for ride by setting is_searching to true\n :param request:\n :return:\n '
passenger_obj = request.user.passenger
last_trip = Trip.objects.filte... | Passenger requesting for ride by setting is_searching to true
:param request:
:return: | bookingapp/views.py | request_ride | bhargava-kush/dj_uber | 0 | python | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def request_ride(request):
'\n Passenger requesting for ride by setting is_searching to true\n :param request:\n :return:\n '
passenger_obj = request.user.passenger
last_trip = Trip.objects.filte... | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def request_ride(request):
'\n Passenger requesting for ride by setting is_searching to true\n :param request:\n :return:\n '
passenger_obj = request.user.passenger
last_trip = Trip.objects.filte... |
32d4d3d42dd734188384359f522ba09c1b21adc6f78bec1bbd5f4eedd38cd60d | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def is_ride_accepted(request):
'\n Checking if ride is accepted or not\n :param request:\n :return:\n '
passenger_obj = request.user.passenger
last_trip = Trip.objects.filter(passenger=passenger_... | Checking if ride is accepted or not
:param request:
:return: | bookingapp/views.py | is_ride_accepted | bhargava-kush/dj_uber | 0 | python | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def is_ride_accepted(request):
'\n Checking if ride is accepted or not\n :param request:\n :return:\n '
passenger_obj = request.user.passenger
last_trip = Trip.objects.filter(passenger=passenger_... | @authentication_classes([IsAuthenticated])
@permission_classes([IsAuthenticated])
@api_view(['GET'])
def is_ride_accepted(request):
'\n Checking if ride is accepted or not\n :param request:\n :return:\n '
passenger_obj = request.user.passenger
last_trip = Trip.objects.filter(passenger=passenger_... |
220aa3d6ab6e3762bd40d59a41ae1566b2bbeb70ce8eda34513c7aded125d4d2 | def __call__(self, input, target, mask=None):
' Args:\n input [batch_num, class_num]:\n The direct prediction of classification fc layer.\n target [batch_num, class_num]:\n Binary target (0 or 1) for each sample each class. The value is -1\n when the sample is ignored.... | Args:
input [batch_num, class_num]:
The direct prediction of classification fc layer.
target [batch_num, class_num]:
Binary target (0 or 1) for each sample each class. The value is -1
when the sample is ignored.
return: a scalar loss | MRC/Hybrid/loss.py | __call__ | xiaolinpeter/Question_Answering_Models | 159 | python | def __call__(self, input, target, mask=None):
' Args:\n input [batch_num, class_num]:\n The direct prediction of classification fc layer.\n target [batch_num, class_num]:\n Binary target (0 or 1) for each sample each class. The value is -1\n when the sample is ignored.... | def __call__(self, input, target, mask=None):
' Args:\n input [batch_num, class_num]:\n The direct prediction of classification fc layer.\n target [batch_num, class_num]:\n Binary target (0 or 1) for each sample each class. The value is -1\n when the sample is ignored.... |
116f5faba01852c220843391b9157356b6598e720b5d562fe9541e052804bf99 | def __call__(self, input, target, mask=None):
' Args:\n input [batch_num, 4 (* class_num)]:\n The prediction of box regression layer. Channel number can be 4 or\n (4 * class_num) depending on whether it is class-agnostic.\n target [batch_num, 4 (* class_num)]:\n The ta... | Args:
input [batch_num, 4 (* class_num)]:
The prediction of box regression layer. Channel number can be 4 or
(4 * class_num) depending on whether it is class-agnostic.
target [batch_num, 4 (* class_num)]:
The target regression values with the same size of input. | MRC/Hybrid/loss.py | __call__ | xiaolinpeter/Question_Answering_Models | 159 | python | def __call__(self, input, target, mask=None):
' Args:\n input [batch_num, 4 (* class_num)]:\n The prediction of box regression layer. Channel number can be 4 or\n (4 * class_num) depending on whether it is class-agnostic.\n target [batch_num, 4 (* class_num)]:\n The ta... | def __call__(self, input, target, mask=None):
' Args:\n input [batch_num, 4 (* class_num)]:\n The prediction of box regression layer. Channel number can be 4 or\n (4 * class_num) depending on whether it is class-agnostic.\n target [batch_num, 4 (* class_num)]:\n The ta... |
83cd3759b40012c15b8ebfd0cb96558682af4a20845909280821d8ef4f1bc035 | def calc(self, input, target, mask=None, is_mask=False):
' Args:\n input [batch_num, class_num]:\n The direct prediction of classification fc layer.\n target [batch_num, class_num]:\n Binary target (0 or 1) for each sample each class. The value is -1\n when the sample ... | Args:
input [batch_num, class_num]:
The direct prediction of classification fc layer.
target [batch_num, class_num]:
Binary target (0 or 1) for each sample each class. The value is -1
when the sample is ignored.
mask [batch_num, class_num] | MRC/Hybrid/loss.py | calc | xiaolinpeter/Question_Answering_Models | 159 | python | def calc(self, input, target, mask=None, is_mask=False):
' Args:\n input [batch_num, class_num]:\n The direct prediction of classification fc layer.\n target [batch_num, class_num]:\n Binary target (0 or 1) for each sample each class. The value is -1\n when the sample ... | def calc(self, input, target, mask=None, is_mask=False):
' Args:\n input [batch_num, class_num]:\n The direct prediction of classification fc layer.\n target [batch_num, class_num]:\n Binary target (0 or 1) for each sample each class. The value is -1\n when the sample ... |
a51b8e20db10555647b2be8b6d937e6b2ef65d29e4bc274b465d07cffa391127 | def enlist(lines_iter):
'\n arrange lines in a recursive list of tuples (item, [sub-items-touples])\n '
result = list()
list_stack = [result, None]
indent = 0
for line in lines_iter:
l = []
t = (line, l)
line_indent = _get_indent(line)
if (line_indent > indent):... | arrange lines in a recursive list of tuples (item, [sub-items-touples]) | nu.py | enlist | fbtd/notes_utilities | 0 | python | def enlist(lines_iter):
'\n \n '
result = list()
list_stack = [result, None]
indent = 0
for line in lines_iter:
l = []
t = (line, l)
line_indent = _get_indent(line)
if (line_indent > indent):
list_stack.append(l)
list_stack[(- 2)].append(... | def enlist(lines_iter):
'\n \n '
result = list()
list_stack = [result, None]
indent = 0
for line in lines_iter:
l = []
t = (line, l)
line_indent = _get_indent(line)
if (line_indent > indent):
list_stack.append(l)
list_stack[(- 2)].append(... |
8a8988db754bd79a19b6153200e0ab4a0b1c20cc1aa9b1bbed6d606bcc711ede | def deepsort(l):
'\n Recursively sort in place each list\n '
l.sort(key=(lambda e: e[0]))
for elem in l:
deepsort(elem[1]) | Recursively sort in place each list | nu.py | deepsort | fbtd/notes_utilities | 0 | python | def deepsort(l):
'\n \n '
l.sort(key=(lambda e: e[0]))
for elem in l:
deepsort(elem[1]) | def deepsort(l):
'\n \n '
l.sort(key=(lambda e: e[0]))
for elem in l:
deepsort(elem[1])<|docstring|>Recursively sort in place each list<|endoftext|> |
cc60d63408191a67d80a1d4ff7022f13f8b2791bae368e492b6b59e183c080ca | def delist(l, result=None):
'\n returns touple of lines from the recursive list of tuples (item, [sub-items-touples])\n '
if (not result):
result = []
for (line, sub) in l:
result.append(line)
delist(sub, result=result)
return tuple(result) | returns touple of lines from the recursive list of tuples (item, [sub-items-touples]) | nu.py | delist | fbtd/notes_utilities | 0 | python | def delist(l, result=None):
'\n \n '
if (not result):
result = []
for (line, sub) in l:
result.append(line)
delist(sub, result=result)
return tuple(result) | def delist(l, result=None):
'\n \n '
if (not result):
result = []
for (line, sub) in l:
result.append(line)
delist(sub, result=result)
return tuple(result)<|docstring|>returns touple of lines from the recursive list of tuples (item, [sub-items-touples])<|endoftext|> |
43312aece65aa86954aeab0ee6cb0145773e689edb47b7f5e6535f134e0d3f7f | @pytest.fixture(name='mock_setup')
def mock_setups():
'Prevent setup.'
with patch('homeassistant.components.flipr.async_setup_entry', return_value=True):
(yield) | Prevent setup. | tests/components/flipr/test_config_flow.py | mock_setups | GrandMoff100/homeassistant-core | 30,023 | python | @pytest.fixture(name='mock_setup')
def mock_setups():
with patch('homeassistant.components.flipr.async_setup_entry', return_value=True):
(yield) | @pytest.fixture(name='mock_setup')
def mock_setups():
with patch('homeassistant.components.flipr.async_setup_entry', return_value=True):
(yield)<|docstring|>Prevent setup.<|endoftext|> |
288fd7ac4e5fffda6a0b6c557be14405fb3f11a46d0198b0ad049820f9cf53bb | async def test_show_form(hass):
'Test we get the form.'
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}))
assert (result['type'] == data_entry_flow.RESULT_TYPE_FORM)
assert (result['step_id'] == config_entries.SOURCE_USER) | Test we get the form. | tests/components/flipr/test_config_flow.py | test_show_form | GrandMoff100/homeassistant-core | 30,023 | python | async def test_show_form(hass):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}))
assert (result['type'] == data_entry_flow.RESULT_TYPE_FORM)
assert (result['step_id'] == config_entries.SOURCE_USER) | async def test_show_form(hass):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}))
assert (result['type'] == data_entry_flow.RESULT_TYPE_FORM)
assert (result['step_id'] == config_entries.SOURCE_USER)<|docstring|>Test we get the form.<|endoftext|... |
6f892a17508ebdfd0efa9a5f1c75c7c93d727d91d84c18b290e9641d136a45a6 | async def test_invalid_credential(hass, mock_setup):
'Test invalid credential.'
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', side_effect=HTTPError()):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'bad_login',... | Test invalid credential. | tests/components/flipr/test_config_flow.py | test_invalid_credential | GrandMoff100/homeassistant-core | 30,023 | python | async def test_invalid_credential(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', side_effect=HTTPError()):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'bad_login', CONF_PASSWORD: 'bad_pass'... | async def test_invalid_credential(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', side_effect=HTTPError()):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'bad_login', CONF_PASSWORD: 'bad_pass'... |
866b94646de93b1d751f07744149836622fa8f94ccb9d32d5d8870b5ed309726 | async def test_nominal_case(hass, mock_setup):
'Test valid login form.'
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=['flipid']) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL:... | Test valid login form. | tests/components/flipr/test_config_flow.py | test_nominal_case | GrandMoff100/homeassistant-core | 30,023 | python | async def test_nominal_case(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=['flipid']) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'dummylogin', CONF_PASS... | async def test_nominal_case(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=['flipid']) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'dummylogin', CONF_PASS... |
d727571876a2f8a3c0a3b6dbfea0b1a992a5fc897501d2564aef07c5d590ca7c | async def test_multiple_flip_id(hass, mock_setup):
'Test multiple flipr id adding a config step.'
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=['FLIP1', 'FLIP2']) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entri... | Test multiple flipr id adding a config step. | tests/components/flipr/test_config_flow.py | test_multiple_flip_id | GrandMoff100/homeassistant-core | 30,023 | python | async def test_multiple_flip_id(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=['FLIP1', 'FLIP2']) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'dummylogin... | async def test_multiple_flip_id(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=['FLIP1', 'FLIP2']) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'dummylogin... |
2453b085f2e72dc499263b92b3dae24b69debf89fdde92a559caa85841acbcb0 | async def test_no_flip_id(hass, mock_setup):
'Test no flipr id found.'
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=[]) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'dummylo... | Test no flipr id found. | tests/components/flipr/test_config_flow.py | test_no_flip_id | GrandMoff100/homeassistant-core | 30,023 | python | async def test_no_flip_id(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=[]) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'dummylogin', CONF_PASSWORD: 'dum... | async def test_no_flip_id(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', return_value=[]) as mock_flipr_client:
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'dummylogin', CONF_PASSWORD: 'dum... |
3d33c2ef43e36701d154ba88f8baa04969032a927b34451b2c6b69fa0ad75a2a | async def test_http_errors(hass, mock_setup):
'Test HTTP Errors.'
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', side_effect=Timeout()):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'nada', CONF_PASSWORD: 'nada... | Test HTTP Errors. | tests/components/flipr/test_config_flow.py | test_http_errors | GrandMoff100/homeassistant-core | 30,023 | python | async def test_http_errors(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', side_effect=Timeout()):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'nada', CONF_PASSWORD: 'nada', CONF_FLIPR_ID: }... | async def test_http_errors(hass, mock_setup):
with patch('flipr_api.FliprAPIRestClient.search_flipr_ids', side_effect=Timeout()):
result = (await hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_USER}, data={CONF_EMAIL: 'nada', CONF_PASSWORD: 'nada', CONF_FLIPR_ID: }... |
0bdb7e271177f64661475fd600a922e29cbbe3a57b36505f8bd37be6d4af965a | def __init__(self, hidden_size, kernels=[2, 3, 4]):
'1DCNN layer with max pooling\n\n Args:\n hidden_size (int): embedding dimension\n kernels (list, optional): kernel sizes for convolution. Defaults to [2, 3, 4].\n '
super().__init__()
self.pool = nn.AdaptiveMaxPool1d(1)... | 1DCNN layer with max pooling
Args:
hidden_size (int): embedding dimension
kernels (list, optional): kernel sizes for convolution. Defaults to [2, 3, 4]. | src/byte_search/cnn.py | __init__ | urchade/urchade-byte_search | 0 | python | def __init__(self, hidden_size, kernels=[2, 3, 4]):
'1DCNN layer with max pooling\n\n Args:\n hidden_size (int): embedding dimension\n kernels (list, optional): kernel sizes for convolution. Defaults to [2, 3, 4].\n '
super().__init__()
self.pool = nn.AdaptiveMaxPool1d(1)... | def __init__(self, hidden_size, kernels=[2, 3, 4]):
'1DCNN layer with max pooling\n\n Args:\n hidden_size (int): embedding dimension\n kernels (list, optional): kernel sizes for convolution. Defaults to [2, 3, 4].\n '
super().__init__()
self.pool = nn.AdaptiveMaxPool1d(1)... |
4b5a0a89375849020c3a6517b06a4db435a40ea1909fa79909c875776e9ae853 | def forward(self, x):
'Forward function\n\n Args:\n x (torch.Tensor): [batch_size, length, hidden_size]\n\n Returns:\n torch.Tensor: [batch_size, hidden_size]\n '
x = x.transpose(1, 2)
convs = []
for conv in self.convs:
convolved = conv(x)
convo... | Forward function
Args:
x (torch.Tensor): [batch_size, length, hidden_size]
Returns:
torch.Tensor: [batch_size, hidden_size] | src/byte_search/cnn.py | forward | urchade/urchade-byte_search | 0 | python | def forward(self, x):
'Forward function\n\n Args:\n x (torch.Tensor): [batch_size, length, hidden_size]\n\n Returns:\n torch.Tensor: [batch_size, hidden_size]\n '
x = x.transpose(1, 2)
convs = []
for conv in self.convs:
convolved = conv(x)
convo... | def forward(self, x):
'Forward function\n\n Args:\n x (torch.Tensor): [batch_size, length, hidden_size]\n\n Returns:\n torch.Tensor: [batch_size, hidden_size]\n '
x = x.transpose(1, 2)
convs = []
for conv in self.convs:
convolved = conv(x)
convo... |
4f55876b4f7564d12385e3a79098cfcefce2229473cf9f35c42fdc9b89059635 | def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=(- 0.6347), weights=None, bconstr=True, volume_corr=False):
'\n FE mesh smoothing.\n\n Based on:\n\n [1] Steven K. Boyd, Ralph Muller, Smooth surface meshing for automated\n finite element model generation from 3D image data, Journal of\n Biomechanics, V... | FE mesh smoothing.
Based on:
[1] Steven K. Boyd, Ralph Muller, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/... | dicom2fem/seg2fem.py | smooth_mesh | vlukes/dicom2fem | 8 | python | def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=(- 0.6347), weights=None, bconstr=True, volume_corr=False):
'\n FE mesh smoothing.\n\n Based on:\n\n [1] Steven K. Boyd, Ralph Muller, Smooth surface meshing for automated\n finite element model generation from 3D image data, Journal of\n Biomechanics, V... | def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=(- 0.6347), weights=None, bconstr=True, volume_corr=False):
'\n FE mesh smoothing.\n\n Based on:\n\n [1] Steven K. Boyd, Ralph Muller, Smooth surface meshing for automated\n finite element model generation from 3D image data, Journal of\n Biomechanics, V... |
85cf4cc76a7ff9422dd966614015be52f4f77967019eb36650cbaa74ca82c9f0 | def gen_mesh_from_voxels(voxels, dims, etype='q', mtype='v'):
"\n Generate FE mesh from voxels (volumetric data).\n\n Parameters\n ----------\n voxels : array\n Voxel matrix, 1=material.\n dims : array\n Size of one voxel.\n etype : integer, optional\n 'q' - quadrilateral or h... | Generate FE mesh from voxels (volumetric data).
Parameters
----------
voxels : array
Voxel matrix, 1=material.
dims : array
Size of one voxel.
etype : integer, optional
'q' - quadrilateral or hexahedral elements
't' - triangular or tetrahedral elements
mtype : integer, optional
'v' - volumetric mes... | dicom2fem/seg2fem.py | gen_mesh_from_voxels | vlukes/dicom2fem | 8 | python | def gen_mesh_from_voxels(voxels, dims, etype='q', mtype='v'):
"\n Generate FE mesh from voxels (volumetric data).\n\n Parameters\n ----------\n voxels : array\n Voxel matrix, 1=material.\n dims : array\n Size of one voxel.\n etype : integer, optional\n 'q' - quadrilateral or h... | def gen_mesh_from_voxels(voxels, dims, etype='q', mtype='v'):
"\n Generate FE mesh from voxels (volumetric data).\n\n Parameters\n ----------\n voxels : array\n Voxel matrix, 1=material.\n dims : array\n Size of one voxel.\n etype : integer, optional\n 'q' - quadrilateral or h... |
31d171a2e3f029f94d4393114e258afe049dc087f6a093104276010362ed45cc | def find_patches_from_slide(slide_path, base_truth_dir=BASE_TRUTH_DIR, filter_non_tissue=True):
'Returns a dataframe of all patches in slide\n input: slide_path: path to WSI file\n output: samples: dataframe with the following columns:\n slide_path: path of slide\n is_tissue: sample contains tis... | Returns a dataframe of all patches in slide
input: slide_path: path to WSI file
output: samples: dataframe with the following columns:
slide_path: path of slide
is_tissue: sample contains tissue
is_tumor: truth status of sample
tile_loc: coordinates of samples in slide
option: base_truth_dir: dire... | 4 - Prediction and Evaluation/Prediction_fcn_unet.py | find_patches_from_slide | raktim-mondol/DeepLearningCamelyon | 70 | python | def find_patches_from_slide(slide_path, base_truth_dir=BASE_TRUTH_DIR, filter_non_tissue=True):
'Returns a dataframe of all patches in slide\n input: slide_path: path to WSI file\n output: samples: dataframe with the following columns:\n slide_path: path of slide\n is_tissue: sample contains tis... | def find_patches_from_slide(slide_path, base_truth_dir=BASE_TRUTH_DIR, filter_non_tissue=True):
'Returns a dataframe of all patches in slide\n input: slide_path: path to WSI file\n output: samples: dataframe with the following columns:\n slide_path: path of slide\n is_tissue: sample contains tis... |
b3d3120d68de8289f6357c527c783e3ef779791c6a0585c07c23a943bbd120ec | def gen_imgs(samples, batch_size, base_truth_dir=BASE_TRUTH_DIR, shuffle=False):
'This function returns a generator that \n yields tuples of (\n X: tensor, float - [batch_size, 256, 256, 3]\n y: tensor, int32 - [batch_size, 256, 256, NUM_CLASSES]\n )\n \n \n input: samples: samples data... | This function returns a generator that
yields tuples of (
X: tensor, float - [batch_size, 256, 256, 3]
y: tensor, int32 - [batch_size, 256, 256, NUM_CLASSES]
)
input: samples: samples dataframe
input: batch_size: The number of images to return for each pull
output: yield (X_train, y_train): generator of X, y... | 4 - Prediction and Evaluation/Prediction_fcn_unet.py | gen_imgs | raktim-mondol/DeepLearningCamelyon | 70 | python | def gen_imgs(samples, batch_size, base_truth_dir=BASE_TRUTH_DIR, shuffle=False):
'This function returns a generator that \n yields tuples of (\n X: tensor, float - [batch_size, 256, 256, 3]\n y: tensor, int32 - [batch_size, 256, 256, NUM_CLASSES]\n )\n \n \n input: samples: samples data... | def gen_imgs(samples, batch_size, base_truth_dir=BASE_TRUTH_DIR, shuffle=False):
'This function returns a generator that \n yields tuples of (\n X: tensor, float - [batch_size, 256, 256, 3]\n y: tensor, int32 - [batch_size, 256, 256, NUM_CLASSES]\n )\n \n \n input: samples: samples data... |
50bf78de16f994efe389efd8e37c87126eaf6a400cea7b62a2d9a36c39df6206 | @property
def end(self):
"\n Sets the end value for the y axis bins. The last bin may not\n end exactly at this value, we increment the bin edge by `size`\n from `start` until we reach or exceed `end`. Defaults to the\n maximum data value. Like `start`, for dates use a date string,\n ... | Sets the end value for the y axis bins. The last bin may not
end exactly at this value, we increment the bin edge by `size`
from `start` until we reach or exceed `end`. Defaults to the
maximum data value. Like `start`, for dates use a date string,
and for category data `end` is based on the category serial
numbers.
Th... | WatchDogs_Visualisation/oldApps/tweet-map/venv2/lib/python3.7/site-packages/plotly/graph_objs/histogram/__init__.py | end | tnreddy09/WatchDogs_StockMarketAnalysis | 6 | python | @property
def end(self):
"\n Sets the end value for the y axis bins. The last bin may not\n end exactly at this value, we increment the bin edge by `size`\n from `start` until we reach or exceed `end`. Defaults to the\n maximum data value. Like `start`, for dates use a date string,\n ... | @property
def end(self):
"\n Sets the end value for the y axis bins. The last bin may not\n end exactly at this value, we increment the bin edge by `size`\n from `start` until we reach or exceed `end`. Defaults to the\n maximum data value. Like `start`, for dates use a date string,\n ... |
0e691e6e2369226b7116d9ec17cc203cca570656d6f1f9b6be188c52c91a32db | @property
def size(self):
'\n Sets the size of each y axis bin. Default behavior: If `nbinsy`\n is 0 or omitted, we choose a nice round bin size such that the\n number of bins is about the same as the typical number of\n samples in each bin. If `nbinsy` is provided, we choose a nice\n ... | Sets the size of each y axis bin. Default behavior: If `nbinsy`
is 0 or omitted, we choose a nice round bin size such that the
number of bins is about the same as the typical number of
samples in each bin. If `nbinsy` is provided, we choose a nice
round bin size giving no more than that many bins. For date
data, use mi... | WatchDogs_Visualisation/oldApps/tweet-map/venv2/lib/python3.7/site-packages/plotly/graph_objs/histogram/__init__.py | size | tnreddy09/WatchDogs_StockMarketAnalysis | 6 | python | @property
def size(self):
'\n Sets the size of each y axis bin. Default behavior: If `nbinsy`\n is 0 or omitted, we choose a nice round bin size such that the\n number of bins is about the same as the typical number of\n samples in each bin. If `nbinsy` is provided, we choose a nice\n ... | @property
def size(self):
'\n Sets the size of each y axis bin. Default behavior: If `nbinsy`\n is 0 or omitted, we choose a nice round bin size such that the\n number of bins is about the same as the typical number of\n samples in each bin. If `nbinsy` is provided, we choose a nice\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.