uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f624f087a5c53afa50d9a495 | train | class | class TimeFrame(object):
"""A TimeFrame is a single time span or period,
e.g. from "2013" to "2014".
Attributes
----------
_start : pd.Timestamp or None
if None and empty if False
then behave as if start is infinitely far into the past
_end : pd.Timestamp or None
if None... | class TimeFrame(object):
| """A TimeFrame is a single time span or period,
e.g. from "2013" to "2014".
Attributes
----------
_start : pd.Timestamp or None
if None and empty if False
then behave as if start is infinitely far into the past
_end : pd.Timestamp or None
if None and empty is False
... | from __future__ import print_function, division
import pandas as pd
from datetime import timedelta
from copy import deepcopy
class TimeFrame(object):
| 30 | 256 | 1,243 | 5 | 24 | pilillo/nilmtk | nilmtk/timeframe.py | Python | TimeFrame | TimeFrame | 6 | 203 | 6 | 6 | 79b7e01137ac7c75683fa660d39b9a19cb4e21ac | bigcode/the-stack | train |
3651a621b41ed5feaf16d4fa | train | function | def timeframes_from_periodindex(periods):
"""
Parameters
----------
periods : pd.PeriodIndex
Returns
-------
list of TimeFrames
"""
assert isinstance(periods, pd.tseries.period.PeriodIndex)
timeframes = []
for period in periods:
timeframe = TimeFrame(period.start_tim... | def timeframes_from_periodindex(periods):
| """
Parameters
----------
periods : pd.PeriodIndex
Returns
-------
list of TimeFrames
"""
assert isinstance(periods, pd.tseries.period.PeriodIndex)
timeframes = []
for period in periods:
timeframe = TimeFrame(period.start_time, period.end_time)
timeframes.app... | for timeframe in timeframes]
def timeframe_from_dict(d):
return TimeFrame(start=d['start'], end=d['end'])
def list_of_timeframes_from_list_of_dicts(dicts):
return [timeframe_from_dict(d) for d in dicts]
def timeframes_from_periodindex(periods):
| 64 | 64 | 87 | 9 | 55 | pilillo/nilmtk | nilmtk/timeframe.py | Python | timeframes_from_periodindex | timeframes_from_periodindex | 256 | 271 | 256 | 256 | 7121781398740e05cbd9357c2981eb4543faccf2 | bigcode/the-stack | train |
c39fd47c286206815a1f1284 | train | function | def list_of_timeframes_from_list_of_dicts(dicts):
return [timeframe_from_dict(d) for d in dicts]
| def list_of_timeframes_from_list_of_dicts(dicts):
| return [timeframe_from_dict(d) for d in dicts]
| Frame objects
Returns
-------
list of dicts
"""
return [timeframe.to_dict() for timeframe in timeframes]
def timeframe_from_dict(d):
return TimeFrame(start=d['start'], end=d['end'])
def list_of_timeframes_from_list_of_dicts(dicts):
| 63 | 64 | 28 | 13 | 50 | pilillo/nilmtk | nilmtk/timeframe.py | Python | list_of_timeframes_from_list_of_dicts | list_of_timeframes_from_list_of_dicts | 252 | 253 | 252 | 252 | 3501a093355646c6153d30de9be1bda3a839b4c8 | bigcode/the-stack | train |
69e750d29578ecf50e021cba | train | function | def merge_timeframes(timeframes, gap=0):
"""
Parameters
----------
timeframes : list of TimeFrame objects (must be sorted)
Returns
-------
merged : list of TimeFrame objects
Where adjacent timeframes have been merged.
"""
assert isinstance(timeframes, list)
assert all([... | def merge_timeframes(timeframes, gap=0):
| """
Parameters
----------
timeframes : list of TimeFrame objects (must be sorted)
Returns
-------
merged : list of TimeFrame objects
Where adjacent timeframes have been merged.
"""
assert isinstance(timeframes, list)
assert all([isinstance(timeframe, TimeFrame) for time... | other.start == self.start) and
(other.end == self.end) and
(other.empty == self.empty))
def to_dict(self):
return {'start': self.start.isoformat(),
'end': self.end.isoformat()}
def merge_timeframes(timeframes, gap=0):
| 63 | 64 | 176 | 11 | 52 | pilillo/nilmtk | nilmtk/timeframe.py | Python | merge_timeframes | merge_timeframes | 206 | 232 | 206 | 206 | a3a6b7f0bd5d0dddf7ab9a73cf3499c7164c80c1 | bigcode/the-stack | train |
a0702e2d51842f04f20e33ab | train | function | def list_of_timeframe_dicts(timeframes):
"""
Parameters
----------
timeframes : list of TimeFrame objects
Returns
-------
list of dicts
"""
return [timeframe.to_dict() for timeframe in timeframes]
| def list_of_timeframe_dicts(timeframes):
| """
Parameters
----------
timeframes : list of TimeFrame objects
Returns
-------
list of dicts
"""
return [timeframe.to_dict() for timeframe in timeframes]
| timeframes[0]]
for timeframe in timeframes[1:]:
if timeframe.adjacent(merged[-1], gap):
merged[-1] = timeframe.union(merged[-1])
else:
merged.append(timeframe)
return merged
def list_of_timeframe_dicts(timeframes):
| 64 | 64 | 54 | 10 | 53 | pilillo/nilmtk | nilmtk/timeframe.py | Python | list_of_timeframe_dicts | list_of_timeframe_dicts | 235 | 245 | 235 | 235 | ba6bf0ad106bbe1060893170db23f48f39325d05 | bigcode/the-stack | train |
99ee9c437795b8a4d322d742 | train | function | def timeframe_from_dict(d):
return TimeFrame(start=d['start'], end=d['end'])
| def timeframe_from_dict(d):
| return TimeFrame(start=d['start'], end=d['end'])
| return merged
def list_of_timeframe_dicts(timeframes):
"""
Parameters
----------
timeframes : list of TimeFrame objects
Returns
-------
list of dicts
"""
return [timeframe.to_dict() for timeframe in timeframes]
def timeframe_from_dict(d):
| 64 | 64 | 20 | 6 | 58 | pilillo/nilmtk | nilmtk/timeframe.py | Python | timeframe_from_dict | timeframe_from_dict | 248 | 249 | 248 | 248 | 276e4265dca522837ef2856fb8ce1656dcbbcdf8 | bigcode/the-stack | train |
d091ef599c7fb0aeb358a367 | train | function | def compile_resources():
gui_folder = Path(__file__).parent.absolute()
os.system(f'pyside6-rcc.exe "{gui_folder}/assets.qrc" -o "{gui_folder}/resources/assets_rc.py"')
os.system(f'pyside6-rcc.exe "{gui_folder}/components.qrc" -o "{gui_folder}/resources/components_rc.py"')
os.system(f'pyside6-rcc.exe "{g... | def compile_resources():
| gui_folder = Path(__file__).parent.absolute()
os.system(f'pyside6-rcc.exe "{gui_folder}/assets.qrc" -o "{gui_folder}/resources/assets_rc.py"')
os.system(f'pyside6-rcc.exe "{gui_folder}/components.qrc" -o "{gui_folder}/resources/components_rc.py"')
os.system(f'pyside6-rcc.exe "{gui_folder}/views.qrc" -o ... | _root():
qrc_root = Path(__file__).parent
return qrc_root.as_uri()
def get_view(name):
gui_folder = Path(__file__).parent
qml_file = gui_folder / 'views' / name
return QUrl(qml_file.as_uri())
def compile_resources():
| 64 | 64 | 105 | 4 | 60 | Saciotto/Sleeper-football-fantasy-analyzer | sleeper_gui/helpers.py | Python | compile_resources | compile_resources | 35 | 39 | 35 | 35 | b11090db0272b1a84438b104be68b2ac504c96bb | bigcode/the-stack | train |
9b51035bd6cbdae99a0d6316 | train | function | def enable_qml_logs():
qInstallMessageHandler(qt_message_handler)
| def enable_qml_logs():
| qInstallMessageHandler(qt_message_handler)
| mode = 'critical'
elif mode == QtFatalMsg:
mode = 'fatal'
else:
mode = 'Debug'
print("%s: %s (%s:%d, %s)" % (mode, message, context.file, context.line, context.file))
def enable_qml_logs():
| 64 | 64 | 16 | 6 | 58 | Saciotto/Sleeper-football-fantasy-analyzer | sleeper_gui/helpers.py | Python | enable_qml_logs | enable_qml_logs | 20 | 21 | 20 | 20 | 88379eda2c69d953dfc61f5cb79728707df68970 | bigcode/the-stack | train |
a33777ead4666ab85c92d99f | train | function | def get_qrc_root():
qrc_root = Path(__file__).parent
return qrc_root.as_uri()
| def get_qrc_root():
| qrc_root = Path(__file__).parent
return qrc_root.as_uri()
| 'fatal'
else:
mode = 'Debug'
print("%s: %s (%s:%d, %s)" % (mode, message, context.file, context.line, context.file))
def enable_qml_logs():
qInstallMessageHandler(qt_message_handler)
def get_qrc_root():
| 64 | 64 | 25 | 6 | 58 | Saciotto/Sleeper-football-fantasy-analyzer | sleeper_gui/helpers.py | Python | get_qrc_root | get_qrc_root | 24 | 26 | 24 | 24 | be51940df1ab737bdff4813a54c0bd1061d4ee95 | bigcode/the-stack | train |
feeeb065f7889bf50c19c28d | train | function | def qt_message_handler(mode, context, message):
if mode == QtInfoMsg:
mode = 'Info'
elif mode == QtWarningMsg:
mode = 'Warning'
elif mode == QtCriticalMsg:
mode = 'critical'
elif mode == QtFatalMsg:
mode = 'fatal'
else:
mode = 'Debug'
print("%s: %s (%s:%d,... | def qt_message_handler(mode, context, message):
| if mode == QtInfoMsg:
mode = 'Info'
elif mode == QtWarningMsg:
mode = 'Warning'
elif mode == QtCriticalMsg:
mode = 'critical'
elif mode == QtFatalMsg:
mode = 'fatal'
else:
mode = 'Debug'
print("%s: %s (%s:%d, %s)" % (mode, message, context.file, context.li... | import os
from pathlib import Path
from PySide6.QtCore import QUrl, QtInfoMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, qInstallMessageHandler
def qt_message_handler(mode, context, message):
| 49 | 64 | 105 | 10 | 38 | Saciotto/Sleeper-football-fantasy-analyzer | sleeper_gui/helpers.py | Python | qt_message_handler | qt_message_handler | 6 | 17 | 6 | 6 | f5fb55d107c73abcc8cf7b169086b31e2340d6ff | bigcode/the-stack | train |
262c57c408bc77daf10dc30a | train | function | def get_view(name):
gui_folder = Path(__file__).parent
qml_file = gui_folder / 'views' / name
return QUrl(qml_file.as_uri())
| def get_view(name):
| gui_folder = Path(__file__).parent
qml_file = gui_folder / 'views' / name
return QUrl(qml_file.as_uri())
| %s)" % (mode, message, context.file, context.line, context.file))
def enable_qml_logs():
qInstallMessageHandler(qt_message_handler)
def get_qrc_root():
qrc_root = Path(__file__).parent
return qrc_root.as_uri()
def get_view(name):
| 64 | 64 | 39 | 5 | 59 | Saciotto/Sleeper-football-fantasy-analyzer | sleeper_gui/helpers.py | Python | get_view | get_view | 29 | 32 | 29 | 29 | 837ce3a3bde04942053dc5abe9190bd2cea19f5f | bigcode/the-stack | train |
3f6de8c37f782c2adbbf7188 | train | function | def _mean_encoder_fn(value):
"""Function for building encoded mean.
This method decides, based on the tensor size, whether to use lossy
compression or keep it as is (use identity encoder). The motivation for this
pattern is due to the fact that compression of small model weights can provide
only negligible b... | def _mean_encoder_fn(value):
| """Function for building encoded mean.
This method decides, based on the tensor size, whether to use lossy
compression or keep it as is (use identity encoder). The motivation for this
pattern is due to the fact that compression of small model weights can provide
only negligible benefit, while at the same tim... | # currently support Variables.
spec = tf.TensorSpec(value.shape, value.dtype)
if value.shape.num_elements() > 10000:
return te.encoders.as_simple_encoder(
te.encoders.uniform_quantization(FLAGS.broadcast_quantization_bits),
spec)
else:
return te.encoders.as_simple_encoder(te.encoders.iden... | 80 | 80 | 268 | 7 | 73 | RosieLiu/federated | tensorflow_federated/python/research/compression/run_experiment.py | Python | _mean_encoder_fn | _mean_encoder_fn | 121 | 149 | 121 | 121 | ca49d9e138dbe70c56d6f63885f1b4d3c8cb5dc1 | bigcode/the-stack | train |
c8182c52f603f48aedc7050e | train | function | def model_builder():
"""Create a keras model based on the original FedAvg CNN."""
return emnist_models.create_original_fedavg_cnn_model(
only_digits=FLAGS.only_digits)
| def model_builder():
| """Create a keras model based on the original FedAvg CNN."""
return emnist_models.create_original_fedavg_cnn_model(
only_digits=FLAGS.only_digits)
| server '
'compression.')
flags.DEFINE_boolean('use_sparsity_in_aggregation', True,
'Whether to add sparsity to the aggregation. This will '
'only be used for client to server compression.')
# End of hyperparameter flags.
FLAGS = flags.FLAGS
def model_builder():
| 64 | 64 | 40 | 4 | 59 | RosieLiu/federated | tensorflow_federated/python/research/compression/run_experiment.py | Python | model_builder | model_builder | 81 | 84 | 81 | 81 | fcfab06d73ef3a6db5c29395fc41d1425d53685f | bigcode/the-stack | train |
e9bf3d6b6fb6eb8967b9178f | train | function | def run_experiment():
"""Data preprocessing and experiment execution."""
emnist_train, emnist_test = emnist_dataset.get_emnist_datasets(
FLAGS.client_batch_size,
FLAGS.client_epochs_per_round,
only_digits=FLAGS.only_digits)
example_dataset = emnist_train.create_tf_dataset_for_client(
emni... | def run_experiment():
| """Data preprocessing and experiment execution."""
emnist_train, emnist_test = emnist_dataset.get_emnist_datasets(
FLAGS.client_batch_size,
FLAGS.client_epochs_per_round,
only_digits=FLAGS.only_digits)
example_dataset = emnist_train.create_tf_dataset_for_client(
emnist_train.client_ids[0]... | :
A `te.core.GatherEncoder`.
"""
# TODO(b/131681951): We cannot use .from_tensor(...) because it does not
# currently support Variables.
spec = tf.TensorSpec(value.shape, value.dtype)
if value.shape.num_elements() > 10000:
if FLAGS.use_sparsity_in_aggregation:
return te.encoders.as_gather_encode... | 158 | 158 | 529 | 5 | 153 | RosieLiu/federated | tensorflow_federated/python/research/compression/run_experiment.py | Python | run_experiment | run_experiment | 152 | 216 | 152 | 152 | 85f93df588c8b322fdbbec42c18c5ce1ca9b68c9 | bigcode/the-stack | train |
39fedf98f03bd4db7f0d7b28 | train | function | def metrics_builder():
return [tf.keras.metrics.SparseCategoricalAccuracy()]
| def metrics_builder():
| return [tf.keras.metrics.SparseCategoricalAccuracy()]
| .FLAGS
def model_builder():
"""Create a keras model based on the original FedAvg CNN."""
return emnist_models.create_original_fedavg_cnn_model(
only_digits=FLAGS.only_digits)
def loss_builder():
return tf.keras.losses.SparseCategoricalCrossentropy()
def metrics_builder():
| 64 | 64 | 16 | 4 | 60 | RosieLiu/federated | tensorflow_federated/python/research/compression/run_experiment.py | Python | metrics_builder | metrics_builder | 91 | 92 | 91 | 91 | a0b28afbf6d8a0530db8bbaf26232b2c5c41dc91 | bigcode/the-stack | train |
f89927d79223f5afff54400e | train | function | def _broadcast_encoder_fn(value):
"""Function for building encoded broadcast.
This method decides, based on the tensor size, whether to use lossy
compression or keep it as is (use identity encoder). The motivation for this
pattern is due to the fact that compression of small model weights can provide
only ne... | def _broadcast_encoder_fn(value):
| """Function for building encoded broadcast.
This method decides, based on the tensor size, whether to use lossy
compression or keep it as is (use identity encoder). The motivation for this
pattern is due to the fact that compression of small model weights can provide
only negligible benefit, while at the sam... | Avg CNN."""
return emnist_models.create_original_fedavg_cnn_model(
only_digits=FLAGS.only_digits)
def loss_builder():
return tf.keras.losses.SparseCategoricalCrossentropy()
def metrics_builder():
return [tf.keras.metrics.SparseCategoricalAccuracy()]
def _broadcast_encoder_fn(value):
| 65 | 66 | 221 | 7 | 58 | RosieLiu/federated | tensorflow_federated/python/research/compression/run_experiment.py | Python | _broadcast_encoder_fn | _broadcast_encoder_fn | 95 | 118 | 95 | 95 | 3fefe387c77661c76400e48249a41ffd1013ccab | bigcode/the-stack | train |
c22d2036d37da36d4db57a29 | train | function | def main(argv):
if len(argv) > 1:
raise app.UsageError('Expected no command-line arguments, '
'got: {}'.format(argv))
tff.framework.set_default_executor(
tff.framework.local_executor_factory(max_fanout=25))
run_experiment()
| def main(argv):
| if len(argv) > 1:
raise app.UsageError('Expected no command-line arguments, '
'got: {}'.format(argv))
tff.framework.set_default_executor(
tff.framework.local_executor_factory(max_fanout=25))
run_experiment()
| encoded_mean_process,
broadcast_process=encoded_broadcast_process)
iterative_process = compression_process_adapter.CompressionProcessAdapter(
iterative_process)
training_loop.run(
iterative_process=iterative_process,
client_datasets_fn=client_datasets_fn,
validation_fn=evaluate_fn)
de... | 64 | 64 | 62 | 4 | 60 | RosieLiu/federated | tensorflow_federated/python/research/compression/run_experiment.py | Python | main | main | 219 | 227 | 219 | 219 | 4f90292600b38eca534eb8d04d227e446e9acc34 | bigcode/the-stack | train |
e116b2338a29d899b244139c | train | function | def loss_builder():
return tf.keras.losses.SparseCategoricalCrossentropy()
| def loss_builder():
| return tf.keras.losses.SparseCategoricalCrossentropy()
| used for client to server compression.')
# End of hyperparameter flags.
FLAGS = flags.FLAGS
def model_builder():
"""Create a keras model based on the original FedAvg CNN."""
return emnist_models.create_original_fedavg_cnn_model(
only_digits=FLAGS.only_digits)
def loss_builder():
| 64 | 64 | 17 | 4 | 60 | RosieLiu/federated | tensorflow_federated/python/research/compression/run_experiment.py | Python | loss_builder | loss_builder | 87 | 88 | 87 | 87 | 72e68b2dc9f829bda664bbd0472ad718e2735225 | bigcode/the-stack | train |
3d103809a6ec1a000b615cf7 | train | function | def _lombscargle(x, y, freqs, pgram, y_dot):
if pgram.dtype == "float32":
numba_type = float32
elif pgram.dtype == "float64":
numba_type = float64
device_id = cp.cuda.Device()
numSM = device_id.attributes["MultiProcessorCount"]
threadsperblock = (128,)
blockspergrid = (numSM * ... | def _lombscargle(x, y, freqs, pgram, y_dot):
| if pgram.dtype == "float32":
numba_type = float32
elif pgram.dtype == "float64":
numba_type = float64
device_id = cp.cuda.Device()
numSM = device_id.attributes["MultiProcessorCount"]
threadsperblock = (128,)
blockspergrid = (numSM * 20,)
_numba_lombscargle[blockspergrid, th... | c_tau * xs - s_tau * xc) ** 2
/ (c_tau2 * ss - cs_tau * cs + s_tau2 * cc)
)
)
) * yD
def _lombscargle(x, y, freqs, pgram, y_dot):
| 64 | 64 | 137 | 20 | 43 | awthomp/cusignal-icassp-tutorial | notebooks/numba_cuda/icassp_numba_v1.py | Python | _lombscargle | _lombscargle | 85 | 101 | 85 | 86 | 82999c5e7a6bd3f986c0c54948ed286a98f2bdbe | bigcode/the-stack | train |
9ba8e1af7f2258a4cfe2553d | train | function | @cuda.jit
def _numba_lombscargle(x, y, freqs, pgram, y_dot):
F = cuda.grid(1)
strideF = cuda.gridsize(1)
if not y_dot[0]:
yD = 1.0
else:
yD = 2.0 / y_dot[0]
for i in range(F, freqs.shape[0], strideF):
# Copy data to registers
freq = freqs[i]
xc = 0.0
... | @cuda.jit
def _numba_lombscargle(x, y, freqs, pgram, y_dot):
| F = cuda.grid(1)
strideF = cuda.gridsize(1)
if not y_dot[0]:
yD = 1.0
else:
yD = 2.0 / y_dot[0]
for i in range(F, freqs.shape[0], strideF):
# Copy data to registers
freq = freqs[i]
xc = 0.0
xs = 0.0
cc = 0.0
ss = 0.0
cs = 0.... | /awthomp/cusignal-icassp-tutorial/blob/main/notebooks/numba_cuda/icassp_numba_v1.py
import cupy as cp
import numpy as np
import sys
from cupy import prof
from math import sin, cos, atan2
from numba import cuda, float32, float64
from scipy import signal
# Numba: Version 1
# Naive implementation of Numba
@cuda.jit
de... | 120 | 120 | 402 | 27 | 92 | awthomp/cusignal-icassp-tutorial | notebooks/numba_cuda/icassp_numba_v1.py | Python | _numba_lombscargle | _numba_lombscargle | 30 | 82 | 30 | 32 | b3c53115655671a3f2ff3fba10e0a2f77b16af47 | bigcode/the-stack | train |
501a000a108aca6ee3354366 | train | function | def lombscargle(x, y, freqs, precenter=False, normalize=False):
pgram = cuda.device_array_like(freqs)
assert x.ndim == 1
assert y.ndim == 1
assert freqs.ndim == 1
# Check input sizes
if x.shape[0] != y.shape[0]:
raise ValueError("Input arrays do not have the same size.")
y_dot = ... | def lombscargle(x, y, freqs, precenter=False, normalize=False):
| pgram = cuda.device_array_like(freqs)
assert x.ndim == 1
assert y.ndim == 1
assert freqs.ndim == 1
# Check input sizes
if x.shape[0] != y.shape[0]:
raise ValueError("Input arrays do not have the same size.")
y_dot = cuda.device_array(shape=(1,), dtype=y.dtype)
if normalize:
... | * 20,)
_numba_lombscargle[blockspergrid, threadsperblock](
x, y, freqs, pgram, y_dot
)
cuda.synchronize()
def lombscargle(x, y, freqs, precenter=False, normalize=False):
| 64 | 64 | 170 | 19 | 45 | awthomp/cusignal-icassp-tutorial | notebooks/numba_cuda/icassp_numba_v1.py | Python | lombscargle | lombscargle | 104 | 127 | 104 | 105 | 515dbc5dcf7edd2722e4d3b57fc22c7c3d72a05a | bigcode/the-stack | train |
4007dcffad26ed15fbab9505 | train | class | class BlogHandler(webapp2.RequestHandler):
"""
Handles common functions needed for the blog's handlers
"""
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
params['user'] = self.user
return render_str(template, **params)
... | class BlogHandler(webapp2.RequestHandler):
| """
Handles common functions needed for the blog's handlers
"""
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
params['user'] = self.user
return render_str(template, **params)
def render(self, template, **kw):
... | ('Comment', int(comment_id),
parent=blog_key())
comment = db.get(key)
if comment.user_id == self.user.key().id():
return function(self, entry_id, comment_id)
else:
self.redirect("/" + entry_id +
"?error=You can't ed... | 82 | 82 | 274 | 9 | 72 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | BlogHandler | BlogHandler | 95 | 128 | 95 | 95 | 1df3a11f610ae0671e76510c0667f4c8e2121fab | bigcode/the-stack | train |
e8150988097c7f7c8a501b4a | train | function | def user_owns_comment(function):
@wraps(function)
def wrapper(self, entry_id, comment_id):
key = db.Key.from_path('Comment', int(comment_id),
parent=blog_key())
comment = db.get(key)
if comment.user_id == self.user.key().id():
return function(se... | def user_owns_comment(function):
@wraps(function)
| def wrapper(self, entry_id, comment_id):
key = db.Key.from_path('Comment', int(comment_id),
parent=blog_key())
comment = db.get(key)
if comment.user_id == self.user.key().id():
return function(self, entry_id, comment_id)
else:
se... | )
if entry.user_id == self.user.key().id():
return function(self, entry_id)
else:
self.redirect("/" + entry_id +
"?error=You can't edit someone else's entry")
return
return wrapper
def user_owns_comment(function):
@wraps(function)
| 64 | 64 | 104 | 13 | 50 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | user_owns_comment | user_owns_comment | 81 | 93 | 81 | 82 | e704d74f33d8f6ae6e945e0124068bd33d151c99 | bigcode/the-stack | train |
b89d646e1def1191d5d0be54 | train | function | def entry_exists(function):
@wraps(function)
def wrapper(self, entry_id):
key = db.Key.from_path('Entry', int(entry_id), parent=blog_key())
entry = db.get(key)
if entry:
return function(self, entry_id)
else:
self.error(404)
return
return wr... | def entry_exists(function):
@wraps(function)
| def wrapper(self, entry_id):
key = db.Key.from_path('Entry', int(entry_id), parent=blog_key())
entry = db.get(key)
if entry:
return function(self, entry_id)
else:
self.error(404)
return
return wrapper
| ):
@wraps(function)
def wrapper(self, *a):
if self.user:
return function(self, *a)
else:
self.redirect("/login?error=You must be logged in first")
return
return wrapper
def entry_exists(function):
@wraps(function)
| 64 | 64 | 73 | 11 | 52 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | entry_exists | entry_exists | 43 | 53 | 43 | 44 | 7f800fb7439ada834c2c5c9a7d1960237d0baadf | bigcode/the-stack | train |
2aee31367dac6b82852273ba | train | function | def blog_key(name='default'):
return db.Key.from_path('blogs', name)
| def blog_key(name='default'):
| return db.Key.from_path('blogs', name)
| secret = 'k8j4dsdf'
template_dir = os.path.abspath(os.path.join(os.path.dirname( __file__ ),
'..', 'templates'))
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
autoescape=True)
def blog_key(name='default'):
| 64 | 64 | 18 | 7 | 57 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | blog_key | blog_key | 17 | 18 | 17 | 17 | f822995a0ec3da96f7a0e2f90479eca0af834c35 | bigcode/the-stack | train |
c023c7a4829b945c1be7692f | train | function | def user_owns_entry(function):
@wraps(function)
def wrapper(self, entry_id):
key = db.Key.from_path('Entry', int(entry_id), parent=blog_key())
entry = db.get(key)
if entry.user_id == self.user.key().id():
return function(self, entry_id)
else:
self.redirect... | def user_owns_entry(function):
@wraps(function)
| def wrapper(self, entry_id):
key = db.Key.from_path('Entry', int(entry_id), parent=blog_key())
entry = db.get(key)
if entry.user_id == self.user.key().id():
return function(self, entry_id)
else:
self.redirect("/" + entry_id +
"?error=... | ('Comment', int(comment_id),
parent=blog_key())
comment = db.get(key)
if comment:
return function(self, entry_id, comment_id)
else:
self.error(404)
return
return wrapper
def user_owns_entry(function):
@wraps(function)
| 64 | 64 | 97 | 13 | 50 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | user_owns_entry | user_owns_entry | 68 | 79 | 68 | 69 | 1b8a1266540ab88b8adaf2c28c5cbc711e3bd833 | bigcode/the-stack | train |
3790641952f2984ea14f942d | train | function | def make_secure_val(val):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
| def make_secure_val(val):
| return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
| (template_dir),
autoescape=True)
def blog_key(name='default'):
return db.Key.from_path('blogs', name)
def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_val(val):
return val
def make_secure_val(val):
| 64 | 64 | 28 | 6 | 57 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | make_secure_val | make_secure_val | 25 | 26 | 25 | 25 | bdca4d39519eecd64aa1037bd1079319215a2e59 | bigcode/the-stack | train |
abbf7d0a5378df3e6f2aa5af | train | function | def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
| def render_str(template, **params):
| t = jinja_env.get_template(template)
return t.render(params)
| (secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_val(val):
return val
def make_secure_val(val):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
def render_str(template, **params):
| 64 | 64 | 24 | 8 | 56 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | render_str | render_str | 28 | 30 | 28 | 28 | 4a50bae968c34b60eece676b862830ac2d7fe5bf | bigcode/the-stack | train |
b8322556cb3d66d242c60e63 | train | function | def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_val(val):
return val
| def check_secure_val(secure_val):
| val = secure_val.split('|')[0]
if secure_val == make_secure_val(val):
return val
| (os.path.dirname( __file__ ),
'..', 'templates'))
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
autoescape=True)
def blog_key(name='default'):
return db.Key.from_path('blogs', name)
def check_secure_val(secure... | 64 | 64 | 32 | 8 | 56 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | check_secure_val | check_secure_val | 20 | 23 | 20 | 20 | a16ab09198859b293e97003371f87623f73cf7b3 | bigcode/the-stack | train |
ef103119ae2ba6b79e36afa6 | train | function | def comment_exists(function):
@wraps(function)
def wrapper(self, entry_id, comment_id):
key = db.Key.from_path('Comment', int(comment_id),
parent=blog_key())
comment = db.get(key)
if comment:
return function(self, entry_id, comment_id)
e... | def comment_exists(function):
@wraps(function)
| def wrapper(self, entry_id, comment_id):
key = db.Key.from_path('Comment', int(comment_id),
parent=blog_key())
comment = db.get(key)
if comment:
return function(self, entry_id, comment_id)
else:
self.error(404)
return... | key = db.Key.from_path('Entry', int(entry_id), parent=blog_key())
entry = db.get(key)
if entry:
return function(self, entry_id)
else:
self.error(404)
return
return wrapper
def comment_exists(function):
@wraps(function)
| 64 | 64 | 80 | 11 | 52 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | comment_exists | comment_exists | 55 | 66 | 55 | 56 | e4afd4379ba2db5dc4dbeab7a4582f458febfb1b | bigcode/the-stack | train |
c9e4874156edd50b93cf28c0 | train | function | def user_logged_in(function):
@wraps(function)
def wrapper(self, *a):
if self.user:
return function(self, *a)
else:
self.redirect("/login?error=You must be logged in first")
return
return wrapper
| def user_logged_in(function):
@wraps(function)
| def wrapper(self, *a):
if self.user:
return function(self, *a)
else:
self.redirect("/login?error=You must be logged in first")
return
return wrapper
| %s' % (val, hmac.new(secret, val).hexdigest())
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
# Decorators used to check validity of user actions
def user_logged_in(function):
@wraps(function)
| 63 | 64 | 58 | 12 | 50 | tobincorporated/TobincorpBlog | handlers/bloghandler.py | Python | user_logged_in | user_logged_in | 33 | 41 | 33 | 34 | 4043bcf9830ce5987fe5544f2920acba49fb772e | bigcode/the-stack | train |
c6db2c2ccecbcc0c6c843a42 | train | class | class DBRow:
TABLENAME: ClassVar[str] = ""
# automatically created/appended by Column and AssociatedColumnBase classes
PRIMARY_KEY_COLUMNS: ClassVar[List[str]]
# cant assign [] here otherwise col names of all subclasses will be appended to same list
COLUMNS: ClassVar[List[str]]
ASSOCIATED_COLU... | class DBRow:
| TABLENAME: ClassVar[str] = ""
# automatically created/appended by Column and AssociatedColumnBase classes
PRIMARY_KEY_COLUMNS: ClassVar[List[str]]
# cant assign [] here otherwise col names of all subclasses will be appended to same list
COLUMNS: ClassVar[List[str]]
ASSOCIATED_COLUMNS: ClassVar[... | from typing import List, Dict, Any, Tuple, Mapping, ClassVar, TYPE_CHECKING, Union, Type
if TYPE_CHECKING:
from ..manga_db import MangaDB
class DBRow:
| 43 | 202 | 676 | 4 | 38 | nilfoer/mangadb | manga_db/db/row.py | Python | DBRow | DBRow | 7 | 83 | 7 | 8 | 26c79fed9d4fe1ad57c1d55e12f0c3c5acaecebb | bigcode/the-stack | train |
bef478ce4d315ec2a4fa6ea1 | train | function | def Find(pat,text):
match = re.search(pat,text)
if match == None:
return ''
#print(match.group(1))
return match.group(1)
| def Find(pat,text):
| match = re.search(pat,text)
if match == None:
return ''
#print(match.group(1))
return match.group(1)
| ://music.163.com/",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
def Find(pat,text):
| 64 | 64 | 35 | 6 | 58 | lingjiameng/wyypy | crawler/song-crawler2.py | Python | Find | Find | 15 | 20 | 15 | 15 | e2052bb23d7b04738dc3f31720e10ab5a8c25c4a | bigcode/the-stack | train |
ee4c46b28e4c7d9c865342f6 | train | function | def getSong2(idSong = "246316"):
global fileSong,lock,threads,hashSongvisited,success,fail
urlSong = 'http://music.163.com/song?id='
try:
r = requests.get(urlSong + idSong,headers = headers,timeout = 2)
text = r.text
patTitle = r'(?:data-res-name=")(.+?)(?:")'
title = Find(patTitle,text)
#飞
patAuth... | def getSong2(idSong = "246316"):
| global fileSong,lock,threads,hashSongvisited,success,fail
urlSong = 'http://music.163.com/song?id='
try:
r = requests.get(urlSong + idSong,headers = headers,timeout = 2)
text = r.text
patTitle = r'(?:data-res-name=")(.+?)(?:")'
title = Find(patTitle,text)
#飞
patAuthor = r'(?:data-res-author=")(.+?)... | import pickle
headers = {
"Host":"music.163.com",
"Referer":"http://music.163.com/",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
def Find(pat,text):
match = re.search(pat,text)
if match == None:
return ''
#print(match.group(1)... | 123 | 123 | 410 | 11 | 112 | lingjiameng/wyypy | crawler/song-crawler2.py | Python | getSong2 | getSong2 | 22 | 63 | 22 | 22 | 442bb396833abc49285ecd4f82c71415ba45ef73 | bigcode/the-stack | train |
fbf537bb482fd33ac60ce6b7 | train | class | class HelperFunctionsTests(unittest.TestCase):
"""Tests for helper functions.
The setting of the encoding (set using sys.setdefaultencoding) used by
the Unicode implementation is not tested.
"""
def setUp(self):
"""Save a copy of sys.path"""
self.sys_path = sys.path[:]
sel... | class HelperFunctionsTests(unittest.TestCase):
| """Tests for helper functions.
The setting of the encoding (set using sys.setdefaultencoding) used by
the Unicode implementation is not tested.
"""
def setUp(self):
"""Save a copy of sys.path"""
self.sys_path = sys.path[:]
self.old_base = site.USER_BASE
self.old_si... | """Tests for 'site'.
Tests assume the initial paths in sys.path once the interpreter has begun
executing have not been removed.
"""
import unittest
from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
from test.test_support import captured_output
import __builtin__
import os
import sys
import re
im... | 242 | 256 | 2,165 | 8 | 234 | m4sterchain/mesapy | lib-python/2.7/test/test_site.py | Python | HelperFunctionsTests | HelperFunctionsTests | 37 | 253 | 37 | 37 | e39f898dc16414256199b06fbb9f37e7d1a44f1d | bigcode/the-stack | train |
4c505b33755fdb49ab9e5109 | train | function | def test_main():
run_unittest(HelperFunctionsTests, ImportSideEffectTests)
| def test_main():
| run_unittest(HelperFunctionsTests, ImportSideEffectTests)
| (self):
# If sitecustomize is available, it should have been imported.
if "sitecustomize" not in sys.modules:
try:
import sitecustomize
except ImportError:
pass
else:
self.fail("sitecustomize not imported automatically")... | 64 | 64 | 18 | 4 | 60 | m4sterchain/mesapy | lib-python/2.7/test/test_site.py | Python | test_main | test_main | 389 | 390 | 389 | 389 | 473e4bd6d85bda81a8e7cac322e65bbf432f06ea | bigcode/the-stack | train |
dc254378c1c83d765b6cf907 | train | class | class ImportSideEffectTests(unittest.TestCase):
"""Test side-effects from importing 'site'."""
def setUp(self):
"""Make a copy of sys.path"""
self.sys_path = sys.path[:]
def tearDown(self):
"""Restore sys.path"""
sys.path[:] = self.sys_path
def test_abs__file__(self):
... | class ImportSideEffectTests(unittest.TestCase):
| """Test side-effects from importing 'site'."""
def setUp(self):
"""Make a copy of sys.path"""
self.sys_path = sys.path[:]
def tearDown(self):
"""Restore sys.path"""
sys.path[:] = self.sys_path
def test_abs__file__(self):
# Make sure all imported modules have th... | finally:
FILE.close()
os.mkdir(self.good_dir_path)
def cleanup(self, prep=False):
"""Make sure that the .pth file is deleted, self.imported is not in
sys.modules, and that both self.good_dirname and self.bad_dirname are
not existing directories."""
if os.path.ex... | 182 | 182 | 609 | 9 | 173 | m4sterchain/mesapy | lib-python/2.7/test/test_site.py | Python | ImportSideEffectTests | ImportSideEffectTests | 310 | 387 | 310 | 310 | fca5ebaf9c9672a748a7ecf07934929eba21623b | bigcode/the-stack | train |
2999c7300c6b50fd48ee2b79 | train | class | class PthFile(object):
"""Helper class for handling testing of .pth files"""
def __init__(self, filename_base=TESTFN, imported="time",
good_dirname="__testdir__", bad_dirname="__bad"):
"""Initialize instance variables"""
self.filename = filename_base + ".pth"
self.ba... | class PthFile(object):
| """Helper class for handling testing of .pth files"""
def __init__(self, filename_base=TESTFN, imported="time",
good_dirname="__testdir__", bad_dirname="__bad"):
"""Initialize instance variables"""
self.filename = filename_base + ".pth"
self.base_dir = os.path.abspat... |
self.assertEqual(len(dirs), 2)
wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
'site-packages')
self.assertEqual(dirs[0], wanted)
wanted = os.path.join('xoxo', 'lib', 'site-python')
self.assertEqual(dirs[1], ... | 146 | 146 | 489 | 6 | 140 | m4sterchain/mesapy | lib-python/2.7/test/test_site.py | Python | PthFile | PthFile | 255 | 308 | 255 | 255 | b2d4fedb2c79b8e59537d044f39dde81759d453a | bigcode/the-stack | train |
67c8207f0afe70c57852051f | train | class | @pulumi.input_type
class _SecurityMonitoringDefaultRuleState:
def __init__(__self__, *,
cases: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleCaseArgs']]]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
filters: Optional[pulumi.Inp... | @pulumi.input_type
class _SecurityMonitoringDefaultRuleState:
| def __init__(__self__, *,
cases: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleCaseArgs']]]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
filters: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleFilterA... | pulumi.get(self, "enabled")
@enabled.setter
def enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enabled", value)
@property
@pulumi.getter
def filters(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleFilterArgs']]]]:
"""
... | 162 | 162 | 542 | 14 | 148 | pulumi/pulumi-datadog | sdk/python/pulumi_datadog/security_monitoring_default_rule.py | Python | _SecurityMonitoringDefaultRuleState | _SecurityMonitoringDefaultRuleState | 71 | 124 | 71 | 72 | 13b75145622b5e7f802aa337f965ce63e44ba7d4 | bigcode/the-stack | train |
6d79c5b91e37ab9059172295 | train | class | @pulumi.input_type
class SecurityMonitoringDefaultRuleArgs:
def __init__(__self__, *,
cases: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleCaseArgs']]]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
filters: Optional[pulumi.Input... | @pulumi.input_type
class SecurityMonitoringDefaultRuleArgs:
| def __init__(__self__, *,
cases: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleCaseArgs']]]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
filters: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleFilterA... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | 120 | 162 | 540 | 13 | 107 | pulumi/pulumi-datadog | sdk/python/pulumi_datadog/security_monitoring_default_rule.py | Python | SecurityMonitoringDefaultRuleArgs | SecurityMonitoringDefaultRuleArgs | 15 | 68 | 15 | 16 | 9c957c2c2f1d3e583abd9b70ea521cfcfb17d8a2 | bigcode/the-stack | train |
2f2c66f839fb69743c62a137 | train | class | class SecurityMonitoringDefaultRule(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cases: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityMonitoringDefaultRuleCas... | class SecurityMonitoringDefaultRule(pulumi.CustomResource):
@overload
| def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cases: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SecurityMonitoringDefaultRuleCaseArgs']]]]] = None,
enabled: Optional[pulumi.Input[bool]]... | """
return pulumi.get(self, "cases")
@cases.setter
def cases(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMonitoringDefaultRuleCaseArgs']]]]):
pulumi.set(self, "cases", value)
@property
@pulumi.getter
def enabled(self) -> Optional[pulumi.Input[bool]]:
... | 256 | 256 | 1,668 | 16 | 240 | pulumi/pulumi-datadog | sdk/python/pulumi_datadog/security_monitoring_default_rule.py | Python | SecurityMonitoringDefaultRule | SecurityMonitoringDefaultRule | 127 | 286 | 127 | 128 | 2b018c8e46427943ba6a52462fbac9a7f0089b9c | bigcode/the-stack | train |
3b25b6ce1e5d2e26fb7e0513 | train | function | def generate_input_sparse_tensor(file_name, voxel_size=0.05, batch_size=1):
# Create a batch, this process is done in a data loader during training in parallel.
batch = [
load_file(file_name, voxel_size),
] * batch_size
coordinates_, featrues_, pcds = list(zip(*batch))
coordinates, features ... | def generate_input_sparse_tensor(file_name, voxel_size=0.05, batch_size=1):
# Create a batch, this process is done in a data loader during training in parallel.
| batch = [
load_file(file_name, voxel_size),
] * batch_size
coordinates_, featrues_, pcds = list(zip(*batch))
coordinates, features = ME.utils.sparse_collate(coordinates_, featrues_)
# Normalize features and create a sparse tensor
return features, coordinates
| ize(quantized_coords, return_index=True)
return quantized_coords[inds], feats[inds], pcd
def generate_input_sparse_tensor(file_name, voxel_size=0.05, batch_size=1):
# Create a batch, this process is done in a data loader during training in parallel.
| 64 | 64 | 109 | 39 | 24 | jingyibo123/MinkowskiEngine | tests/global.py | Python | generate_input_sparse_tensor | generate_input_sparse_tensor | 60 | 69 | 60 | 61 | 7924065c6968e9c4149dfe1e82a65332fb647c21 | bigcode/the-stack | train |
7d1de4e36753f28072097a26 | train | function | def load_file(file_name, voxel_size):
pcd = o3d.io.read_point_cloud(file_name)
coords = np.array(pcd.points)
feats = np.array(pcd.colors)
quantized_coords = np.floor(coords / voxel_size)
inds = ME.utils.sparse_quantize(quantized_coords, return_index=True)
return quantized_coords[inds], feats[i... | def load_file(file_name, voxel_size):
| pcd = o3d.io.read_point_cloud(file_name)
coords = np.array(pcd.points)
feats = np.array(pcd.colors)
quantized_coords = np.floor(coords / voxel_size)
inds = ME.utils.sparse_quantize(quantized_coords, return_index=True)
return quantized_coords[inds], feats[inds], pcd
| type=str, default='1.ply')
parser.add_argument('--voxel_size', type=float, default=0.02)
parser.add_argument('--batch_size', type=int, default=1)
parser.add_argument('--max_kernel_size', type=int, default=7)
def load_file(file_name, voxel_size):
| 64 | 64 | 86 | 9 | 55 | jingyibo123/MinkowskiEngine | tests/global.py | Python | load_file | load_file | 49 | 57 | 49 | 49 | 0d68715741bb6af7e1b49de85a00bb6448150054 | bigcode/the-stack | train |
3f4b56f19d8dbbcf1b976e56 | train | function | def decrypt(key, passphrase, encrypted_file_path):
"""
Decrypts the specified file using a RSA key and its bound passphrase
:param key: an RSA key
:param passphrase: str
:param encrypted_file_path: str path of the file to be decrypted
:return: bytes decrypted data
"""
print('Decrypting f... | def decrypt(key, passphrase, encrypted_file_path):
| """
Decrypts the specified file using a RSA key and its bound passphrase
:param key: an RSA key
:param passphrase: str
:param encrypted_file_path: str path of the file to be decrypted
:return: bytes decrypted data
"""
print('Decrypting file {} ...'.format(encrypted_file_path))
rsa_ke... | # -*- coding: utf-8 -*-
# !/usr/bin/env python3
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP
def decrypt(key, passphrase, encrypted_file_path):
| 49 | 75 | 251 | 11 | 37 | hgohel/Python-for-Everyday-Life | section_4/5_encryption/decrypt.py | Python | decrypt | decrypt | 8 | 31 | 8 | 8 | 7970a5f3c3494efa9a61b9fead48b07389a2c337 | bigcode/the-stack | train |
c264ac30254f9ac1dc2972ad | train | class | class BallDistanceStat(BaseStat):
def calculate_player_stat(self, player_stat_map: Dict[str, PlayerStats], game: Game, proto_game: game_pb2.Game,
player_map: Dict[str, Player], data_frame: pd.DataFrame):
if len(player_map) == 0:
return
player_distances_da... | class BallDistanceStat(BaseStat):
| def calculate_player_stat(self, player_stat_map: Dict[str, PlayerStats], game: Game, proto_game: game_pb2.Game,
player_map: Dict[str, Player], data_frame: pd.DataFrame):
if len(player_map) == 0:
return
player_distances_data_frame, player_distance_times, pl... | from typing import Dict
import pandas as pd
from hiddenfigures.analysis.constants.basic_math import get_player_ball_displacements, get_distance_from_displacements, \
get_position_displacements
from ....analysis.stats.utils.pandas_utils import sum_deltas_by_player_name
from ....analysis.stats.stats import BaseStat... | 110 | 174 | 581 | 7 | 102 | millcityrunner/carball | hiddenfigures/analysis/stats/possession/ball_distances.py | Python | BallDistanceStat | BallDistanceStat | 15 | 71 | 15 | 16 | f7ae7edba73c0b6c621ccaab59494648803ee3af | bigcode/the-stack | train |
feb6d930631760455a1e8196 | train | class | class iMADSModel(object):
'''
classdocs
'''
def __init__(self, model_path, core, width, kmers):
'''
Constructor
'''
filename = os.path.basename(model_path)
print("Loading imads model: %s" % filename)
self.modeldict = self.load_model(model_pa... | class iMADSModel(object):
| '''
classdocs
'''
def __init__(self, model_path, core, width, kmers):
'''
Constructor
'''
filename = os.path.basename(model_path)
print("Loading imads model: %s" % filename)
self.modeldict = self.load_model(model_path)
self.... | '''
Created on Jul 16, 2019
@author:
This file is a modified version of https://github.com/Duke-GCB/Predict-TF-Binding
'''
import sys
sys.path.append('../libsvm-3.23/python')
import svmutil
import os
class iMADSModel(object):
| 67 | 187 | 624 | 7 | 59 | tiffanydho/chip2probe | src/probefilter/sitesfinder/imadsmodel.py | Python | iMADSModel | iMADSModel | 13 | 75 | 13 | 13 | 79f266b59b48b525a99514258516c85322d62d1c | bigcode/the-stack | train |
bae7bc56fc5e5efd73bb6ef6 | train | function | def pytest_collection_modifyitems(items):
"""
Mark test - unit, integration or other. Idea from https://github.com/pypa/pip/blob/master/tests/conftest.py
:param items:
:return:
"""
for item in items:
if not hasattr(item, "module"): # e.g.: DoctestTextfile
continue
mo... | def pytest_collection_modifyitems(items):
| """
Mark test - unit, integration or other. Idea from https://github.com/pypa/pip/blob/master/tests/conftest.py
:param items:
:return:
"""
for item in items:
if not hasattr(item, "module"): # e.g.: DoctestTextfile
continue
module_path = os.path.relpath(
i... | < 3:
import ConfigParser as configparser
else:
import configparser
def pytest_configure(config):
config.addinivalue_line("markers", "unit: unit tests")
config.addinivalue_line("markers", "integration: integration tests")
def pytest_collection_modifyitems(items):
| 64 | 64 | 179 | 7 | 57 | beliaev-maksim/artifactory | tests/conftest.py | Python | pytest_collection_modifyitems | pytest_collection_modifyitems | 24 | 42 | 24 | 24 | 1c1e623cdd43b8d0e4969ec7d90cd8ffbeb8bed8 | bigcode/the-stack | train |
eb3c34e3f50fc46f58d1d3fa | train | function | @pytest.fixture(scope="session")
def artifactory_auth_token():
config_path = os.path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
token = config.get("artifactory", "token")
yield token
| @pytest.fixture(scope="session")
def artifactory_auth_token():
| config_path = os.path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
token = config.get("artifactory", "token")
yield token
| config = configparser.ConfigParser()
config.read(config_path)
username = config.get("artifactory", "username")
password = config.get("artifactory", "password")
auth = (username, password)
yield auth
@pytest.fixture(scope="session")
def artifactory_auth_token():
| 64 | 64 | 61 | 13 | 50 | beliaev-maksim/artifactory | tests/conftest.py | Python | artifactory_auth_token | artifactory_auth_token | 67 | 75 | 67 | 68 | 31bd230ebaed6ce0b15f7044b7af135cc5d96b80 | bigcode/the-stack | train |
8ff9186ed911a7991deb87e3 | train | function | @pytest.fixture(scope="session")
def artifactory(artifactory_server, artifactory_auth):
artifactory_ = ArtifactoryPath(artifactory_server, auth=artifactory_auth)
yield artifactory_
| @pytest.fixture(scope="session")
def artifactory(artifactory_server, artifactory_auth):
| artifactory_ = ArtifactoryPath(artifactory_server, auth=artifactory_auth)
yield artifactory_
| .path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
token = config.get("artifactory", "token")
yield token
@pytest.fixture(scope="session")
def artifactory(artifactory_server, artifactory_auth):
| 64 | 64 | 50 | 21 | 42 | beliaev-maksim/artifactory | tests/conftest.py | Python | artifactory | artifactory | 78 | 81 | 78 | 79 | 019d5a72186992fd12e23a5f2717c8571de56b4b | bigcode/the-stack | train |
9a97fc55992020969d3eb243 | train | function | @pytest.fixture()
def user2(artifactory):
name = "user2"
user = artifactory.find_user(name)
if user is not None:
user.delete()
user = User(
artifactory=artifactory,
name=name,
email=f"{name}@example.com",
password="Pa55w@rd",
)
user.create()
yield user... | @pytest.fixture()
def user2(artifactory):
| name = "user2"
user = artifactory.find_user(name)
if user is not None:
user.delete()
user = User(
artifactory=artifactory,
name=name,
email=f"{name}@example.com",
password="Pa55w@rd",
)
user.create()
yield user
user.delete()
| user.delete()
user = User(
artifactory=artifactory,
name=name,
email=f"{name}@example.com",
password="Pa55w@rd",
)
user.create()
yield user
user.delete()
@pytest.fixture()
def user2(artifactory):
| 64 | 64 | 89 | 11 | 53 | beliaev-maksim/artifactory | tests/conftest.py | Python | user2 | user2 | 166 | 180 | 166 | 167 | 0c7afa083dedccc64869d15b13aa2e69ac341284 | bigcode/the-stack | train |
1275bef3a2edc6f198bcbe2e | train | function | def pytest_configure(config):
config.addinivalue_line("markers", "unit: unit tests")
config.addinivalue_line("markers", "integration: integration tests")
| def pytest_configure(config):
| config.addinivalue_line("markers", "unit: unit tests")
config.addinivalue_line("markers", "integration: integration tests")
| import Group
from dohq_artifactory import PermissionTarget
from dohq_artifactory import RepositoryLocal
from dohq_artifactory import User
if sys.version_info[0] < 3:
import ConfigParser as configparser
else:
import configparser
def pytest_configure(config):
| 64 | 64 | 38 | 6 | 57 | beliaev-maksim/artifactory | tests/conftest.py | Python | pytest_configure | pytest_configure | 19 | 21 | 19 | 19 | 4e98f16d77e2151a36c620d31b36b2f7447487d1 | bigcode/the-stack | train |
e62df78e3b12809d968209fe | train | function | @pytest.fixture(scope="session")
def artifactory_auth():
config_path = os.path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
username = config.get("artifactory", "username")
password = config.get("artifactory", "password")
auth = (user... | @pytest.fixture(scope="session")
def artifactory_auth():
| config_path = os.path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
username = config.get("artifactory", "username")
password = config.get("artifactory", "password")
auth = (username, password)
yield auth
| ifactory_server():
config_path = os.path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
uri = config.get("artifactory", "uri")
yield uri
@pytest.fixture(scope="session")
def artifactory_auth():
| 64 | 64 | 81 | 12 | 51 | beliaev-maksim/artifactory | tests/conftest.py | Python | artifactory_auth | artifactory_auth | 55 | 64 | 55 | 56 | 0920e1baa79e38424dce7a66178ad2306c4016b2 | bigcode/the-stack | train |
636361e2f0d3eadd743d2538 | train | function | @pytest.fixture()
def repo1(artifactory):
name = "repo1"
repo_ = artifactory.find_repository_local(name)
if repo_ is not None:
repo_.delete()
repo_ = RepositoryLocal(artifactory=artifactory, name=name)
repo_.create()
yield repo_
repo_.delete()
| @pytest.fixture()
def repo1(artifactory):
| name = "repo1"
repo_ = artifactory.find_repository_local(name)
if repo_ is not None:
repo_.delete()
repo_ = RepositoryLocal(artifactory=artifactory, name=name)
repo_.create()
yield repo_
repo_.delete()
| .fixture(scope="session")
def artifactory_token(artifactory_server, artifactory_auth_token):
artifactory_ = ArtifactoryPath(artifactory_server, token=artifactory_auth_token)
yield artifactory_
@pytest.fixture()
def repo1(artifactory):
| 63 | 64 | 75 | 11 | 52 | beliaev-maksim/artifactory | tests/conftest.py | Python | repo1 | repo1 | 90 | 99 | 90 | 91 | 0c1f0a4cc8611f34dcbc3f7b2a15c723150fd092 | bigcode/the-stack | train |
54753dc2a52eadf370341ddc | train | function | @pytest.fixture(scope="session")
def artifactory_token(artifactory_server, artifactory_auth_token):
artifactory_ = ArtifactoryPath(artifactory_server, token=artifactory_auth_token)
yield artifactory_
| @pytest.fixture(scope="session")
def artifactory_token(artifactory_server, artifactory_auth_token):
| artifactory_ = ArtifactoryPath(artifactory_server, token=artifactory_auth_token)
yield artifactory_
| (artifactory_server, artifactory_auth):
artifactory_ = ArtifactoryPath(artifactory_server, auth=artifactory_auth)
yield artifactory_
@pytest.fixture(scope="session")
def artifactory_token(artifactory_server, artifactory_auth_token):
| 63 | 64 | 53 | 23 | 40 | beliaev-maksim/artifactory | tests/conftest.py | Python | artifactory_token | artifactory_token | 84 | 87 | 84 | 85 | 2aa626810cc8ba566867bc9952c358f542465dbc | bigcode/the-stack | train |
45407f67235c8314d858360e | train | function | @pytest.fixture()
def integration_artifactory_path_repo(artifactory):
"""
Create repo if not exist and remove all files from this repo
:param artifactory:
:return:
"""
# Create repo if not exist
name = "integration-artifactory-path-repo"
repo_ = artifactory.find_repository_local(name)
... | @pytest.fixture()
def integration_artifactory_path_repo(artifactory):
| """
Create repo if not exist and remove all files from this repo
:param artifactory:
:return:
"""
# Create repo if not exist
name = "integration-artifactory-path-repo"
repo_ = artifactory.find_repository_local(name)
if repo_ is None:
repo_ = RepositoryLocal(artifactory=artifa... | _repository_local(name)
if repo_ is not None:
repo_.delete()
repo_ = RepositoryLocal(artifactory=artifactory, name=name)
repo_.create()
yield repo_
repo_.delete()
@pytest.fixture()
def integration_artifactory_path_repo(artifactory):
| 64 | 64 | 159 | 15 | 49 | beliaev-maksim/artifactory | tests/conftest.py | Python | integration_artifactory_path_repo | integration_artifactory_path_repo | 114 | 132 | 114 | 115 | f42352d4ab5fae4f8b54ecbffdefe667089c6f2a | bigcode/the-stack | train |
c5f7ae6b58be9e2e391556d3 | train | function | @pytest.fixture()
def permission(artifactory):
name = "fixture_permission"
# Remove if exist
permission_ = artifactory.find_permission_target(name)
if permission_ is not None:
permission_.delete()
permission_ = PermissionTarget(artifactory=artifactory, name=name)
permission_.create()
... | @pytest.fixture()
def permission(artifactory):
| name = "fixture_permission"
# Remove if exist
permission_ = artifactory.find_permission_target(name)
if permission_ is not None:
permission_.delete()
permission_ = PermissionTarget(artifactory=artifactory, name=name)
permission_.create()
yield permission_
permission_.delete()
| # Remove all file from repo
repo_path = ArtifactoryPath(str(artifactory) + "/" + name, auth=artifactory.auth)
for path_ in repo_path.glob("*"):
path_.unlink()
yield repo_
@pytest.fixture()
def permission(artifactory):
| 63 | 64 | 80 | 10 | 53 | beliaev-maksim/artifactory | tests/conftest.py | Python | permission | permission | 135 | 146 | 135 | 136 | 3fc9b624f8846bf5cfcbd6771d252cccecb62c40 | bigcode/the-stack | train |
d25b81387a7f2d4f990f7c36 | train | function | @pytest.fixture(scope="session")
def artifactory_server():
config_path = os.path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
uri = config.get("artifactory", "uri")
yield uri
| @pytest.fixture(scope="session")
def artifactory_server():
| config_path = os.path.join(os.path.dirname(__file__), "test.cfg")
config = configparser.ConfigParser()
config.read(config_path)
uri = config.get("artifactory", "uri")
yield uri
| _dir.startswith("integration"):
item.add_marker(pytest.mark.integration)
elif module_root_dir.startswith("unit"):
item.add_marker(pytest.mark.unit)
else:
raise RuntimeError("Unknown test type (filename = {})".format(module_path))
@pytest.fixture(scope="session")
def a... | 64 | 64 | 60 | 12 | 52 | beliaev-maksim/artifactory | tests/conftest.py | Python | artifactory_server | artifactory_server | 45 | 52 | 45 | 46 | f61edfca6b63fea003bcbfb28449fce0513b3b32 | bigcode/the-stack | train |
b3cdf105da926d2a4b736d31 | train | function | @pytest.fixture()
def group1(artifactory):
name = "group1"
group = artifactory.find_group(name)
if group is not None:
group.delete()
group = Group(artifactory=artifactory, name=name)
group.create()
yield group
group.delete()
| @pytest.fixture()
def group1(artifactory):
| name = "group1"
group = artifactory.find_group(name)
if group is not None:
group.delete()
group = Group(artifactory=artifactory, name=name)
group.create()
yield group
group.delete()
| user.delete()
user = User(
artifactory=artifactory,
name=name,
email=f"{name}@example.com",
password="Pa55w@rd",
)
user.create()
yield user
user.delete()
@pytest.fixture()
def group1(artifactory):
| 64 | 64 | 67 | 11 | 53 | beliaev-maksim/artifactory | tests/conftest.py | Python | group1 | group1 | 183 | 192 | 183 | 184 | 39809b2d708373e6c88cf99c6ac0df8e76035f48 | bigcode/the-stack | train |
9c7e4c0abeb223cbc0e1c736 | train | function | @pytest.fixture()
def user1(artifactory):
name = "user1"
user = artifactory.find_user(name)
if user is not None:
user.delete()
user = User(
artifactory=artifactory,
name=name,
email=f"{name}@example.com",
password="Pa55w@rd",
)
user.create()
yield user... | @pytest.fixture()
def user1(artifactory):
| name = "user1"
user = artifactory.find_user(name)
if user is not None:
user.delete()
user = User(
artifactory=artifactory,
name=name,
email=f"{name}@example.com",
password="Pa55w@rd",
)
user.create()
yield user
user.delete()
| artifactory.find_permission_target(name)
if permission_ is not None:
permission_.delete()
permission_ = PermissionTarget(artifactory=artifactory, name=name)
permission_.create()
yield permission_
permission_.delete()
@pytest.fixture()
def user1(artifactory):
| 64 | 64 | 89 | 11 | 53 | beliaev-maksim/artifactory | tests/conftest.py | Python | user1 | user1 | 149 | 163 | 149 | 150 | ee0244ad9a6efc7744ca0df7fa0a1a2837cc4502 | bigcode/the-stack | train |
7f7a6146cf62ab3623248737 | train | function | @pytest.fixture()
def repo2(artifactory):
name = "repo2"
repo_ = artifactory.find_repository_local(name)
if repo_ is not None:
repo_.delete()
repo_ = RepositoryLocal(artifactory=artifactory, name=name)
repo_.create()
yield repo_
repo_.delete()
| @pytest.fixture()
def repo2(artifactory):
| name = "repo2"
repo_ = artifactory.find_repository_local(name)
if repo_ is not None:
repo_.delete()
repo_ = RepositoryLocal(artifactory=artifactory, name=name)
repo_.create()
yield repo_
repo_.delete()
| artifactory.find_repository_local(name)
if repo_ is not None:
repo_.delete()
repo_ = RepositoryLocal(artifactory=artifactory, name=name)
repo_.create()
yield repo_
repo_.delete()
@pytest.fixture()
def repo2(artifactory):
| 64 | 64 | 75 | 11 | 53 | beliaev-maksim/artifactory | tests/conftest.py | Python | repo2 | repo2 | 102 | 111 | 102 | 103 | 9bcbb1ed85e185fb178c813ea3d252c050e4114c | bigcode/the-stack | train |
4d9f06a7b5042f8e7efeb45b | train | function | def test_local_file(run_test):
""" Test copying in local file """
local_fp = tempfile.NamedTemporaryFile()
local_fp.write(b'an external local file')
local_fp.flush()
with api.Bundle(TEST_CONTEXT, name=TEST_BUNDLE) as b:
b.add_data(local_fp.name)
b.add_tags({'info':'added a local fi... | def test_local_file(run_test):
| """ Test copying in local file """
local_fp = tempfile.NamedTemporaryFile()
local_fp.write(b'an external local file')
local_fp.flush()
with api.Bundle(TEST_CONTEXT, name=TEST_BUNDLE) as b:
b.add_data(local_fp.name)
b.add_tags({'info':'added a local file'})
saved_uuid = b.uuid
... | def md5_file(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def test_local_file(run_test):
| 64 | 64 | 128 | 7 | 57 | sayantansatpati/disdat | tests/bundles/test_file_bundle_api.py | Python | test_local_file | test_local_file | 48 | 64 | 48 | 48 | b8e4b13ca741c6fee7db2b4db7ee2d8f8d1acc79 | bigcode/the-stack | train |
cc39b6942bb3c318bc7b48bf | train | function | @moto.mock_s3
def test_copy_in_s3_file(run_test):
""" Test copying in s3 file
The file should be copied into the local context
"""
s3_resource = boto3.resource('s3')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
# Copy a local file to moto s3 bucket
saved_md5 = md5_file(__file__)
aws_s... | @moto.mock_s3
def test_copy_in_s3_file(run_test):
| """ Test copying in s3 file
The file should be copied into the local context
"""
s3_resource = boto3.resource('s3')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
# Copy a local file to moto s3 bucket
saved_md5 = md5_file(__file__)
aws_s3.put_s3_file(__file__, TEST_BUCKET_URL)
s3_f... | b = api.get(TEST_CONTEXT, None, uuid=saved_uuid)
assert md5_file(b.data[0]) == saved_f1_md5
assert md5_file(b.data[1]) == saved_f2_md5
@moto.mock_s3
def test_copy_in_s3_file(run_test):
| 64 | 64 | 209 | 16 | 47 | sayantansatpati/disdat | tests/bundles/test_file_bundle_api.py | Python | test_copy_in_s3_file | test_copy_in_s3_file | 89 | 113 | 89 | 90 | 4d9abe0df17cc0fac03746cdf4a6d4a5adcacaeb | bigcode/the-stack | train |
c30953aed4cbd60fa2aaee0e | train | function | def test_zero_copy_local_file(run_test):
""" Test managed path of a local file """
with api.Bundle(TEST_CONTEXT, name=TEST_BUNDLE) as b:
f1 = b.get_file("file_1.txt")
f2 = b.get_file("file_2.txt")
with open(f1, mode='w') as f:
f.write("This is our first file!")
with ... | def test_zero_copy_local_file(run_test):
| """ Test managed path of a local file """
with api.Bundle(TEST_CONTEXT, name=TEST_BUNDLE) as b:
f1 = b.get_file("file_1.txt")
f2 = b.get_file("file_2.txt")
with open(f1, mode='w') as f:
f.write("This is our first file!")
with open(f2, mode='w') as f:
f.wr... | file'})
saved_uuid = b.uuid
saved_md5 = md5_file(local_fp.name)
local_fp.close()
b = api.get(TEST_CONTEXT, None, uuid=saved_uuid)
assert md5_file(b.data) == saved_md5
def test_zero_copy_local_file(run_test):
| 64 | 64 | 209 | 9 | 54 | sayantansatpati/disdat | tests/bundles/test_file_bundle_api.py | Python | test_zero_copy_local_file | test_zero_copy_local_file | 67 | 86 | 67 | 67 | 987a17e068cc900fea25df848e3622cc9a26847c | bigcode/the-stack | train |
df2999faeb0ac821c7c652a3 | train | function | def md5_file(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
| def md5_file(fname):
| hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
| ucket'
TEST_BUCKET_URL = "s3://{}".format(TEST_BUCKET)
# Setup moto s3 resources
# Make sure bucket is empty
#objects = s3_client.list_objects(Bucket=TEST_BUCKET)
#assert 'Contents' not in objects, 'Bucket should be empty'
def md5_file(fname):
| 64 | 64 | 57 | 6 | 58 | sayantansatpati/disdat | tests/bundles/test_file_bundle_api.py | Python | md5_file | md5_file | 40 | 45 | 40 | 40 | 1b298367e715a9a9f3a53d69dab11db29e2d8819 | bigcode/the-stack | train |
48064e83340fc81819a88535 | train | function | @moto.mock_s3
def test_copy_in_s3_file_with_remote(run_test):
""" Test copying in s3 file
The file should be copied into the remote context
"""
s3_resource = boto3.resource('s3')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
api.remote(TEST_CONTEXT, TEST_REMOTE, TEST_BUCKET_URL)
# Copy a ... | @moto.mock_s3
def test_copy_in_s3_file_with_remote(run_test):
| """ Test copying in s3 file
The file should be copied into the remote context
"""
s3_resource = boto3.resource('s3')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
api.remote(TEST_CONTEXT, TEST_REMOTE, TEST_BUCKET_URL)
# Copy a local file to moto s3 bucket
saved_md5 = md5_file(__file__... |
b = api.get(TEST_CONTEXT, None, uuid=saved_uuid)
md5 = md5_file(b.data)
print(md5)
print(saved_md5)
assert md5 == saved_md5
@moto.mock_s3
def test_copy_in_s3_file_with_remote(run_test):
| 64 | 64 | 204 | 18 | 45 | sayantansatpati/disdat | tests/bundles/test_file_bundle_api.py | Python | test_copy_in_s3_file_with_remote | test_copy_in_s3_file_with_remote | 116 | 139 | 116 | 117 | 7640ceafb3503340ad970b1f437f946cf9540732 | bigcode/the-stack | train |
b4429fe70a1542b4e7ced3a4 | train | function | @moto.mock_s3
def test_zero_copy_s3_file(run_test):
""" Test managed path in local file """
s3_resource = boto3.resource('s3')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
api.remote(TEST_CONTEXT, TEST_REMOTE, TEST_BUCKET_URL)
saved_md5 = md5_file(__file__)
with api.Bundle(TEST_CONTEXT, name... | @moto.mock_s3
def test_zero_copy_s3_file(run_test):
| """ Test managed path in local file """
s3_resource = boto3.resource('s3')
s3_resource.create_bucket(Bucket=TEST_BUCKET)
api.remote(TEST_CONTEXT, TEST_REMOTE, TEST_BUCKET_URL)
saved_md5 = md5_file(__file__)
with api.Bundle(TEST_CONTEXT, name=TEST_BUNDLE) as b:
s3_path = b.get_remote_f... | _file)
b.add_tags({'info': 'added an s3 file'})
saved_uuid = b.uuid
b = api.get(TEST_CONTEXT, None, uuid=saved_uuid)
assert b.data.startswith("s3://")
@moto.mock_s3
def test_zero_copy_s3_file(run_test):
| 64 | 64 | 203 | 16 | 48 | sayantansatpati/disdat | tests/bundles/test_file_bundle_api.py | Python | test_zero_copy_s3_file | test_zero_copy_s3_file | 142 | 164 | 142 | 143 | 13244c034c978f7f4709269e45a5780c59ac2c2c | bigcode/the-stack | train |
2d7cd36514f050e1ed816cf0 | train | function | def render(obj, lexer):
out = ""
if isinstance(obj, basestring):
out += pygment_html_render(obj, lexer)
elif isinstance(obj, (tuple, list)):
for i, s in enumerate(obj):
out += "<div>List item #{}</div>".format(i)
out += "<div>" + pygment_html_render(s, lexer) + "</div... | def render(obj, lexer):
| out = ""
if isinstance(obj, basestring):
out += pygment_html_render(obj, lexer)
elif isinstance(obj, (tuple, list)):
for i, s in enumerate(obj):
out += "<div>List item #{}</div>".format(i)
out += "<div>" + pygment_html_render(s, lexer) + "</div>"
elif isinstance(o... | m.pool
return Markup("<a href='{url}'>{m.pool}</a>".format(**locals()))
def pygment_html_render(s, lexer=lexers.TextLexer):
return highlight(
s,
lexer(),
HtmlFormatter(linenos=True),
)
def render(obj, lexer):
| 64 | 64 | 136 | 6 | 58 | change/incubator-airflow | airflow/www/views.py | Python | render | render | 194 | 206 | 194 | 194 | e52a71d5f258d158b79cb07ae6bbb9bba481e2d9 | bigcode/the-stack | train |
952a7081ab1aa6b456a05888 | train | class | class ConfigurationView(wwwutils.SuperUserMixin, BaseView):
@expose('/')
def conf(self):
raw = request.args.get('raw') == "true"
title = "Airflow Configuration"
subtitle = conf.AIRFLOW_CONFIG
if conf.getboolean("webserver", "expose_config"):
with open(conf.AIRFLOW_CON... | class ConfigurationView(wwwutils.SuperUserMixin, BaseView):
@expose('/')
| def conf(self):
raw = request.args.get('raw') == "true"
title = "Airflow Configuration"
subtitle = conf.AIRFLOW_CONFIG
if conf.getboolean("webserver", "expose_config"):
with open(conf.AIRFLOW_CONFIG, 'r') as f:
config = f.read()
table = [(secti... | as f:
git_version = f.readline()
except Exception as e:
self.logger.error(e)
# Render information
title = "Version Info"
return self.render('airflow/version.html',
title=title,
airflow_version=airflow_ver... | 81 | 81 | 272 | 17 | 64 | change/incubator-airflow | airflow/www/views.py | Python | ConfigurationView | ConfigurationView | 2,553 | 2,586 | 2,553 | 2,554 | e38bb1f193cd049b152da6057a7b6b0d1b7b836a | bigcode/the-stack | train |
3a11290142ce50c9ef1f429a | train | function | def fqueued_slots(v, c, m, p):
url = (
'/admin/taskinstance/' +
'?flt1_pool_equals=' + m.pool +
'&flt2_state_equals=queued&sort=10&desc=1')
return Markup("<a href='{0}'>{1}</a>".format(url, m.queued_slots()))
| def fqueued_slots(v, c, m, p):
| url = (
'/admin/taskinstance/' +
'?flt1_pool_equals=' + m.pool +
'&flt2_state_equals=queued&sort=10&desc=1')
return Markup("<a href='{0}'>{1}</a>".format(url, m.queued_slots()))
| = (
'/admin/taskinstance/' +
'?flt1_pool_equals=' + m.pool +
'&flt2_state_equals=running')
return Markup("<a href='{0}'>{1}</a>".format(url, m.used_slots()))
def fqueued_slots(v, c, m, p):
| 63 | 64 | 74 | 12 | 51 | change/incubator-airflow | airflow/www/views.py | Python | fqueued_slots | fqueued_slots | 252 | 257 | 252 | 252 | e27a5ddd887a64a54abcbe8999ea3772da5e3046 | bigcode/the-stack | train |
7656e59f671cade865be21d0 | train | class | class VariableView(wwwutils.DataProfilingMixin, AirflowModelView):
verbose_name = "Variable"
verbose_name_plural = "Variables"
list_template = 'airflow/variable_list.html'
def hidden_field_formatter(view, context, model, name):
if should_hide_value_for_key(model.key):
return Markup(... | class VariableView(wwwutils.DataProfilingMixin, AirflowModelView):
| verbose_name = "Variable"
verbose_name_plural = "Variables"
list_template = 'airflow/variable_list.html'
def hidden_field_formatter(view, context, model, name):
if should_hide_value_for_key(model.key):
return Markup('*' * 8)
return getattr(model, name)
form_columns = (
... | View):
pass
# NOTE: For debugging / troubleshooting
# mv = KnowEventTypeView(
# models.KnownEventType,
# Session, name="Known Event Types", category="Manage")
# admin.add_view(mv)
# class DagPickleView(SuperUserMixin, ModelView):
# pass
# mv = DagPickleView(
# models.DagPickle,
# Session, name... | 119 | 119 | 398 | 15 | 104 | change/incubator-airflow | airflow/www/views.py | Python | VariableView | VariableView | 2,132 | 2,188 | 2,132 | 2,132 | b8984f8de8d7226bc62e75fcb10fe0cfc78315e7 | bigcode/the-stack | train |
cf0b84914e8c6f07b9f7d770 | train | class | class KnowEventView(wwwutils.DataProfilingMixin, AirflowModelView):
verbose_name = "known event"
verbose_name_plural = "known events"
form_columns = (
'label',
'event_type',
'start_date',
'end_date',
'reported_by',
'description')
column_list = (
'l... | class KnowEventView(wwwutils.DataProfilingMixin, AirflowModelView):
| verbose_name = "known event"
verbose_name_plural = "known events"
form_columns = (
'label',
'event_type',
'start_date',
'end_date',
'reported_by',
'description')
column_list = (
'label', 'event_type', 'start_date', 'end_date', 'reported_by')
co... | ('area', 'stackedAreaChart'),
('stacked_area', 'stackedAreaChart'),
('percent_area', 'stackedAreaChart'),
('datatable', 'datatable'),
)
chart_mapping = dict(chart_mapping)
class KnowEventView(wwwutils.DataProfilingMixin, AirflowModelView):
| 64 | 64 | 102 | 16 | 48 | change/incubator-airflow | airflow/www/views.py | Python | KnowEventView | KnowEventView | 2,100 | 2,112 | 2,100 | 2,100 | 23ac63c92b8fee263f6fc033a65cd142edf3457a | bigcode/the-stack | train |
c9e2a432e9174ed41e012818 | train | function | def wrapped_markdown(s):
return '<div class="rich_doc">' + markdown.markdown(s) + "</div>"
| def wrapped_markdown(s):
| return '<div class="rich_doc">' + markdown.markdown(s) + "</div>"
| + "</div>"
elif isinstance(obj, dict):
for k, v in obj.items():
out += '<div>Dict item "{}"</div>'.format(k)
out += "<div>" + pygment_html_render(v, lexer) + "</div>"
return out
def wrapped_markdown(s):
| 64 | 64 | 25 | 6 | 57 | change/incubator-airflow | airflow/www/views.py | Python | wrapped_markdown | wrapped_markdown | 209 | 210 | 209 | 209 | 4e68d1eebb350527fe570a6a08377f68c4b8349a | bigcode/the-stack | train |
69a362f0d936ac59dd862fa3 | train | function | def should_hide_value_for_key(key_name):
return any(s in key_name for s in DEFAULT_SENSITIVE_VARIABLE_FIELDS) \
and conf.getboolean('admin', 'hide_sensitive_variable_fields')
| def should_hide_value_for_key(key_name):
| return any(s in key_name for s in DEFAULT_SENSITIVE_VARIABLE_FIELDS) \
and conf.getboolean('admin', 'hide_sensitive_variable_fields')
| _to_dag[subtask.task_id] = tasks.subdag
recurse_tasks(subtasks, task_ids, dag_ids, task_id_to_dag)
if isinstance(tasks, BaseOperator):
task_id_to_dag[tasks.task_id] = tasks.dag
def should_hide_value_for_key(key_name):
| 64 | 64 | 40 | 9 | 54 | change/incubator-airflow | airflow/www/views.py | Python | should_hide_value_for_key | should_hide_value_for_key | 277 | 279 | 277 | 277 | 737b8bdd2822a9a663486d6176617c91b9f7d236 | bigcode/the-stack | train |
1639375f5b4c6534ffb8d2a7 | train | function | def nobr_f(v, c, m, p):
return Markup("<nobr>{}</nobr>".format(getattr(m, p)))
| def nobr_f(v, c, m, p):
| return Markup("<nobr>{}</nobr>".format(getattr(m, p)))
| format() if attr else ''
if datetime.now().isoformat()[:4] == dttm[:4]:
dttm = dttm[5:]
return Markup("<nobr>{}</nobr>".format(dttm))
def nobr_f(v, c, m, p):
| 64 | 64 | 31 | 12 | 52 | change/incubator-airflow | airflow/www/views.py | Python | nobr_f | nobr_f | 166 | 167 | 166 | 166 | 67790f2983546be4d986e4eec9a65004a4d1ce22 | bigcode/the-stack | train |
dc0764104e3e43fea393f631 | train | function | def fused_slots(v, c, m, p):
url = (
'/admin/taskinstance/' +
'?flt1_pool_equals=' + m.pool +
'&flt2_state_equals=running')
return Markup("<a href='{0}'>{1}</a>".format(url, m.used_slots()))
| def fused_slots(v, c, m, p):
| url = (
'/admin/taskinstance/' +
'?flt1_pool_equals=' + m.pool +
'&flt2_state_equals=running')
return Markup("<a href='{0}'>{1}</a>".format(url, m.used_slots()))
| .is_anonymous() and current_user.data_profiling())
):
return f(*args, **kwargs)
else:
flash("This page requires data profiling privileges", "error")
return redirect(url_for('admin.index'))
return decorated_function
def fused_slots(v, c, m, p):
| 64 | 64 | 64 | 11 | 52 | change/incubator-airflow | airflow/www/views.py | Python | fused_slots | fused_slots | 244 | 249 | 244 | 244 | 9c53bf5fab99c262b051e4b3f347ec596cf33527 | bigcode/the-stack | train |
0ffb93ba5e448ec806a41ebe | train | class | class XComView(wwwutils.SuperUserMixin, AirflowModelView):
verbose_name = "XCom"
verbose_name_plural = "XComs"
page_size = 20
form_columns = (
'key',
'value',
'execution_date',
'task_id',
'dag_id',
)
form_extra_fields = {
'value': StringField('Va... | class XComView(wwwutils.SuperUserMixin, AirflowModelView):
| verbose_name = "XCom"
verbose_name_plural = "XComs"
page_size = 20
form_columns = (
'key',
'value',
'execution_date',
'task_id',
'dag_id',
)
form_extra_fields = {
'value': StringField('Value'),
}
column_filters = ('key', 'timestamp', 'ex... | Content-Disposition"] = "attachment; filename=variables.json"
return response
def on_form_prefill(self, form, id):
if should_hide_value_for_key(form.key.data):
form.val.data = '*' * 8
class XComView(wwwutils.SuperUserMixin, AirflowModelView):
| 64 | 64 | 133 | 15 | 48 | change/incubator-airflow | airflow/www/views.py | Python | XComView | XComView | 2,191 | 2,209 | 2,191 | 2,191 | 0a96bfa9e41d8bbd82862e41371dffd68b1635ca | bigcode/the-stack | train |
b8553899b1df8c03a0372756 | train | function | def task_instance_link(v, c, m, p):
url = url_for(
'airflow.task',
dag_id=m.dag_id,
task_id=m.task_id,
execution_date=m.execution_date.isoformat())
url_root = url_for(
'airflow.graph',
dag_id=m.dag_id,
root=m.task_id,
execution_date=m.execution_dat... | def task_instance_link(v, c, m, p):
| url = url_for(
'airflow.task',
dag_id=m.dag_id,
task_id=m.task_id,
execution_date=m.execution_date.isoformat())
url_root = url_for(
'airflow.graph',
dag_id=m.dag_id,
root=m.task_id,
execution_date=m.execution_date.isoformat())
return Markup(
... | log_url_formatter(v, c, m, p):
return Markup(
'<a href="{m.log_url}">'
' <span class="glyphicon glyphicon-book" aria-hidden="true">'
'</span></a>').format(**locals())
def task_instance_link(v, c, m, p):
| 64 | 64 | 173 | 12 | 52 | change/incubator-airflow | airflow/www/views.py | Python | task_instance_link | task_instance_link | 119 | 139 | 119 | 119 | 720c0fe6092695253f55e0ee1a81156e036aca57 | bigcode/the-stack | train |
78b9ed4f194975a629fcf8f3 | train | class | class PoolModelView(wwwutils.SuperUserMixin, AirflowModelView):
column_list = ('pool', 'slots', 'used_slots', 'queued_slots')
column_formatters = dict(
pool=pool_link, used_slots=fused_slots, queued_slots=fqueued_slots)
named_filter_urls = True
| class PoolModelView(wwwutils.SuperUserMixin, AirflowModelView):
| column_list = ('pool', 'slots', 'used_slots', 'queued_slots')
column_formatters = dict(
pool=pool_link, used_slots=fused_slots, queued_slots=fqueued_slots)
named_filter_urls = True
| Modifying the base ModelView class for non edit, browse only operations
"""
named_filter_urls = True
can_create = False
can_edit = False
can_delete = False
column_display_pk = True
class PoolModelView(wwwutils.SuperUserMixin, AirflowModelView):
| 64 | 64 | 65 | 15 | 48 | change/incubator-airflow | airflow/www/views.py | Python | PoolModelView | PoolModelView | 1,964 | 1,968 | 1,964 | 1,964 | 3f866ed5a5628ae369f2a138a3439f5faa2fb5e4 | bigcode/the-stack | train |
d5b25bd0c95609dd1e413041 | train | class | class LogModelView(ModelViewOnly):
verbose_name_plural = "logs"
verbose_name = "log"
column_default_sort = ('dttm', True)
column_filters = ('dag_id', 'task_id', 'execution_date')
column_formatters = dict(
dttm=datetime_f, execution_date=datetime_f, dag_id=dag_link)
| class LogModelView(ModelViewOnly):
| verbose_name_plural = "logs"
verbose_name = "log"
column_default_sort = ('dttm', True)
column_filters = ('dag_id', 'task_id', 'execution_date')
column_formatters = dict(
dttm=datetime_f, execution_date=datetime_f, dag_id=dag_link)
| =session)
flash(
"{count} dag runs were set to '{target_state}'".format(**locals()))
except Exception as ex:
if not self.handle_view_exception(ex):
raise Exception("Ooops")
flash('Failed to set state', 'error')
class LogModelView(ModelViewOnly)... | 64 | 64 | 76 | 8 | 56 | change/incubator-airflow | airflow/www/views.py | Python | LogModelView | LogModelView | 2,307 | 2,313 | 2,307 | 2,307 | 7439668c6ca2baa3d46412b55ab3d6d9913dbd23 | bigcode/the-stack | train |
70493bca4163df3d89f44f72 | train | class | class HomeView(AdminIndexView):
@expose("/")
@login_required
def index(self):
session = Session()
DM = models.DagModel
qry = None
# restrict the dags shown if filter_by_owner and current user is not superuser
do_filter = FILTER_BY_OWNER and (not current_user.is_super... | class HomeView(AdminIndexView):
@expose("/")
@login_required
| def index(self):
session = Session()
DM = models.DagModel
qry = None
# restrict the dags shown if filter_by_owner and current user is not superuser
do_filter = FILTER_BY_OWNER and (not current_user.is_superuser())
owner_mode = conf.get('webserver', 'OWNER_MODE').stri... | (self, form):
try:
if request.method == 'POST':
data = request.json
if data:
session = settings.Session()
var = models.Variable(key=form, val=json.dumps(data))
session.add(var)
session.com... | 240 | 240 | 802 | 17 | 223 | change/incubator-airflow | airflow/www/views.py | Python | HomeView | HomeView | 1,780 | 1,876 | 1,780 | 1,782 | 6e00764d6003e4717ffb2257c813ce356b0aa09c | bigcode/the-stack | train |
34f0e2cb84957040a6ead587 | train | class | class UserModelView(wwwutils.SuperUserMixin, AirflowModelView):
verbose_name = "User"
verbose_name_plural = "Users"
column_default_sort = 'username'
| class UserModelView(wwwutils.SuperUserMixin, AirflowModelView):
| verbose_name = "User"
verbose_name_plural = "Users"
column_default_sort = 'username'
| extra', '{}'))
except Exception:
d = {}
for field in list(self.form_extra_fields.keys()):
value = d.get(field, '')
if value:
field = getattr(form, field)
field.data = value
class UserModelView(wwwutils.SuperUserMixin, AirflowModelView)... | 64 | 64 | 38 | 15 | 48 | change/incubator-airflow | airflow/www/views.py | Python | UserModelView | UserModelView | 2,521 | 2,524 | 2,521 | 2,521 | e1b9c28b4a6bc8dd9c2007bdde9b892389cd287a | bigcode/the-stack | train |
57ebb5649f11ddd82d7596cb | train | class | class ChartModelView(wwwutils.DataProfilingMixin, AirflowModelView):
verbose_name = "chart"
verbose_name_plural = "charts"
form_columns = (
'label',
'owner',
'conn_id',
'chart_type',
'show_datatable',
'x_is_date',
'y_log_scale',
'show_sql',
... | class ChartModelView(wwwutils.DataProfilingMixin, AirflowModelView):
| verbose_name = "chart"
verbose_name_plural = "charts"
form_columns = (
'label',
'owner',
'conn_id',
'chart_type',
'show_datatable',
'x_is_date',
'y_log_scale',
'show_sql',
'height',
'sql_layout',
'sql',
'default_... |
column_display_pk = True
class PoolModelView(wwwutils.SuperUserMixin, AirflowModelView):
column_list = ('pool', 'slots', 'used_slots', 'queued_slots')
column_formatters = dict(
pool=pool_link, used_slots=fused_slots, queued_slots=fqueued_slots)
named_filter_urls = True
class SlaMissModelVie... | 256 | 256 | 857 | 16 | 240 | change/incubator-airflow | airflow/www/views.py | Python | ChartModelView | ChartModelView | 1,991 | 2,085 | 1,991 | 1,991 | 7bd943c681da9644f6a243ffa0a4e4c686c8a029 | bigcode/the-stack | train |
098a6f4fee6dcb694d472e78 | train | class | class ModelViewOnly(wwwutils.LoginMixin, AirflowModelView):
"""
Modifying the base ModelView class for non edit, browse only operations
"""
named_filter_urls = True
can_create = False
can_edit = False
can_delete = False
column_display_pk = True
| class ModelViewOnly(wwwutils.LoginMixin, AirflowModelView):
| """
Modifying the base ModelView class for non edit, browse only operations
"""
named_filter_urls = True
can_create = False
can_edit = False
can_delete = False
column_display_pk = True
| (ModelView):
list_template = 'airflow/model_list.html'
edit_template = 'airflow/model_edit.html'
create_template = 'airflow/model_create.html'
column_display_actions = True
page_size = 500
class ModelViewOnly(wwwutils.LoginMixin, AirflowModelView):
| 64 | 64 | 66 | 14 | 49 | change/incubator-airflow | airflow/www/views.py | Python | ModelViewOnly | ModelViewOnly | 1,953 | 1,961 | 1,953 | 1,953 | 94c5c8fd766f60fa1f3d57bbbe3ee88c5011c47b | bigcode/the-stack | train |
f8f58064a4f2df7840779afb | train | class | class Airflow(BaseView):
def is_visible(self):
return False
@expose('/')
@login_required
def index(self):
return self.render('airflow/dags.html')
@expose('/chart_data')
@data_profiling_required
@wwwutils.gzipped
# @cache.cached(timeout=3600, key_prefix=wwwutils.make_ca... | class Airflow(BaseView):
| def is_visible(self):
return False
@expose('/')
@login_required
def index(self):
return self.render('airflow/dags.html')
@expose('/chart_data')
@data_profiling_required
@wwwutils.gzipped
# @cache.cached(timeout=3600, key_prefix=wwwutils.make_cache_key)
def chart_dat... | + m.pool +
'&flt2_state_equals=queued&sort=10&desc=1')
return Markup("<a href='{0}'>{1}</a>".format(url, m.queued_slots()))
def recurse_tasks(tasks, task_ids, dag_ids, task_id_to_dag):
if isinstance(tasks, list):
for task in tasks:
recurse_tasks(task, task_ids, dag_ids, task_id_to... | 256 | 256 | 11,962 | 6 | 250 | change/incubator-airflow | airflow/www/views.py | Python | Airflow | Airflow | 282 | 1,777 | 282 | 283 | c9c68e37810a69919a850d60873bf89380aef850 | bigcode/the-stack | train |
27a660249b3bda808a1de1a8 | train | function | def datetime_f(v, c, m, p):
attr = getattr(m, p)
dttm = attr.isoformat() if attr else ''
if datetime.now().isoformat()[:4] == dttm[:4]:
dttm = dttm[5:]
return Markup("<nobr>{}</nobr>".format(dttm))
| def datetime_f(v, c, m, p):
| attr = getattr(m, p)
dttm = attr.isoformat() if attr else ''
if datetime.now().isoformat()[:4] == dttm[:4]:
dttm = dttm[5:]
return Markup("<nobr>{}</nobr>".format(dttm))
| }</span>'.format(**locals()))
def state_f(v, c, m, p):
return state_token(m.state)
def duration_f(v, c, m, p):
if m.end_date and m.duration:
return timedelta(seconds=m.duration)
def datetime_f(v, c, m, p):
| 64 | 64 | 78 | 11 | 53 | change/incubator-airflow | airflow/www/views.py | Python | datetime_f | datetime_f | 158 | 163 | 158 | 158 | 8883ef7fcee64a6fd272a3e094c442b3fc64ef19 | bigcode/the-stack | train |
108569b6924c1797c4241b30 | train | class | class QueryView(wwwutils.DataProfilingMixin, BaseView):
@expose('/', methods=['POST', 'GET'])
@wwwutils.gzipped
def query(self):
session = settings.Session()
dbs = session.query(models.Connection).order_by(
models.Connection.conn_id).all()
session.expunge_all()
db... | class QueryView(wwwutils.DataProfilingMixin, BaseView):
@expose('/', methods=['POST', 'GET'])
@wwwutils.gzipped
| def query(self):
session = settings.Session()
dbs = session.query(models.Connection).order_by(
models.Connection.conn_id).all()
session.expunge_all()
db_choices = list(
((db.conn_id, db.conn_id) for db in dbs if db.get_hook()))
conn_id_str = request.fo... | == current_user.user.username
}
else:
webserver_dags = {
dag.dag_id: dag
for dag in unfiltered_webserver_dags
}
all_dag_ids = sorted(set(orm_dags.keys()) | set(webserver_dags.keys()))
return self.render(
'airflow/d... | 146 | 146 | 489 | 32 | 114 | change/incubator-airflow | airflow/www/views.py | Python | QueryView | QueryView | 1,879 | 1,942 | 1,879 | 1,881 | 265fbb8f3f9c25647385b6192d466d4e59c9ef9e | bigcode/the-stack | train |
4f9a66bb2d2020173c7ca96f | train | function | def label_link(v, c, m, p):
try:
default_params = ast.literal_eval(m.default_params)
except:
default_params = {}
url = url_for(
'airflow.chart', chart_id=m.id, iteration_no=m.iteration_no,
**default_params)
return Markup("<a href='{url}'>{m.label}</a>".format(**locals()))... | def label_link(v, c, m, p):
| try:
default_params = ast.literal_eval(m.default_params)
except:
default_params = {}
url = url_for(
'airflow.chart', chart_id=m.id, iteration_no=m.iteration_no,
**default_params)
return Markup("<a href='{url}'>{m.label}</a>".format(**locals()))
| m[5:]
return Markup("<nobr>{}</nobr>".format(dttm))
def nobr_f(v, c, m, p):
return Markup("<nobr>{}</nobr>".format(getattr(m, p)))
def label_link(v, c, m, p):
| 63 | 64 | 82 | 11 | 52 | change/incubator-airflow | airflow/www/views.py | Python | label_link | label_link | 170 | 178 | 170 | 170 | e6eb64b54460ab77818015cb06491946b717aba6 | bigcode/the-stack | train |
a315408c29b9a9ad11d2d581 | train | class | class SlaMissModelView(wwwutils.SuperUserMixin, ModelViewOnly):
verbose_name_plural = "SLA misses"
verbose_name = "SLA miss"
column_list = (
'dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp')
column_formatters = dict(
task_id=task_instance_link,
execution_date=date... | class SlaMissModelView(wwwutils.SuperUserMixin, ModelViewOnly):
| verbose_name_plural = "SLA misses"
verbose_name = "SLA miss"
column_list = (
'dag_id', 'task_id', 'execution_date', 'email_sent', 'timestamp')
column_formatters = dict(
task_id=task_instance_link,
execution_date=datetime_f,
timestamp=datetime_f,
dag_id=dag_link)
... | _list = ('pool', 'slots', 'used_slots', 'queued_slots')
column_formatters = dict(
pool=pool_link, used_slots=fused_slots, queued_slots=fqueued_slots)
named_filter_urls = True
class SlaMissModelView(wwwutils.SuperUserMixin, ModelViewOnly):
| 64 | 64 | 167 | 16 | 47 | change/incubator-airflow | airflow/www/views.py | Python | SlaMissModelView | SlaMissModelView | 1,971 | 1,988 | 1,971 | 1,971 | f39adc6a60a149eebfa53152f74fa86834a06ca9 | bigcode/the-stack | train |
8c232e3da89888b5868a61fa | train | class | class AirflowModelView(ModelView):
list_template = 'airflow/model_list.html'
edit_template = 'airflow/model_edit.html'
create_template = 'airflow/model_create.html'
column_display_actions = True
page_size = 500
| class AirflowModelView(ModelView):
| list_template = 'airflow/model_list.html'
edit_template = 'airflow/model_edit.html'
create_template = 'airflow/model_create.html'
column_display_actions = True
page_size = 500
| /text")
form = QueryForm(request.form, data=data)
session.commit()
session.close()
return self.render(
'airflow/query.html', form=form,
title="Ad Hoc Query",
results=results or '',
has_data=has_data)
class AirflowModelView(ModelView):
| 64 | 64 | 55 | 8 | 56 | change/incubator-airflow | airflow/www/views.py | Python | AirflowModelView | AirflowModelView | 1,945 | 1,950 | 1,945 | 1,945 | 86c146cb92d89e50c3913660b3e8c350d4db1f0f | bigcode/the-stack | train |
b78fc67ea4aab6deb9dcd26b | train | function | def log_url_formatter(v, c, m, p):
return Markup(
'<a href="{m.log_url}">'
' <span class="glyphicon glyphicon-book" aria-hidden="true">'
'</span></a>').format(**locals())
| def log_url_formatter(v, c, m, p):
| return Markup(
'<a href="{m.log_url}">'
' <span class="glyphicon glyphicon-book" aria-hidden="true">'
'</span></a>').format(**locals())
| , c, m, p):
url = url_for(
'airflow.graph',
dag_id=m.dag_id)
return Markup(
'<a href="{url}">{m.dag_id}</a>'.format(**locals()))
def log_url_formatter(v, c, m, p):
| 63 | 64 | 53 | 12 | 51 | change/incubator-airflow | airflow/www/views.py | Python | log_url_formatter | log_url_formatter | 112 | 116 | 112 | 112 | 6956e81b948a4bc1632e90b0d305c9f254266b50 | bigcode/the-stack | train |
9481e51c82a22881335b374c | train | function | def pool_link(v, c, m, p):
url = '/admin/taskinstance/?flt1_pool_equals=' + m.pool
return Markup("<a href='{url}'>{m.pool}</a>".format(**locals()))
| def pool_link(v, c, m, p):
| url = '/admin/taskinstance/?flt1_pool_equals=' + m.pool
return Markup("<a href='{url}'>{m.pool}</a>".format(**locals()))
| _params = {}
url = url_for(
'airflow.chart', chart_id=m.id, iteration_no=m.iteration_no,
**default_params)
return Markup("<a href='{url}'>{m.label}</a>".format(**locals()))
def pool_link(v, c, m, p):
| 63 | 64 | 48 | 11 | 52 | change/incubator-airflow | airflow/www/views.py | Python | pool_link | pool_link | 181 | 183 | 181 | 181 | bcf1ba8b4d1482c070ce9ee9e0ae56aced874355 | bigcode/the-stack | train |
c713da47d985f27279b3ae20 | train | class | class JobModelView(ModelViewOnly):
verbose_name_plural = "jobs"
verbose_name = "job"
column_default_sort = ('start_date', True)
column_filters = (
'job_type', 'dag_id', 'state',
'unixname', 'hostname', 'start_date', 'end_date', 'latest_heartbeat')
column_formatters = dict(
st... | class JobModelView(ModelViewOnly):
| verbose_name_plural = "jobs"
verbose_name = "job"
column_default_sort = ('start_date', True)
column_filters = (
'job_type', 'dag_id', 'state',
'unixname', 'hostname', 'start_date', 'end_date', 'latest_heartbeat')
column_formatters = dict(
start_date=datetime_f,
end_da... | 'value': StringField('Value'),
}
column_filters = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id')
column_searchable_list = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id')
class JobModelView(ModelViewOnly):
| 64 | 64 | 110 | 8 | 56 | change/incubator-airflow | airflow/www/views.py | Python | JobModelView | JobModelView | 2,212 | 2,224 | 2,212 | 2,212 | 75b5ff3b34c3d5b3b84656b2b4e9af4c62e18040 | bigcode/the-stack | train |
08e11245df9b0b27925d7988 | train | class | class TaskInstanceModelView(ModelViewOnly):
verbose_name_plural = "task instances"
verbose_name = "task instance"
column_filters = (
'state', 'dag_id', 'task_id', 'execution_date', 'hostname',
'queue', 'pool', 'operator', 'start_date', 'end_date')
named_filter_urls = True
column_form... | class TaskInstanceModelView(ModelViewOnly):
| verbose_name_plural = "task instances"
verbose_name = "task instance"
column_filters = (
'state', 'dag_id', 'task_id', 'execution_date', 'hostname',
'queue', 'pool', 'operator', 'start_date', 'end_date')
named_filter_urls = True
column_formatters = dict(
log_url=log_url_forma... | ids, target_state, session=None):
try:
DR = models.DagRun
count = 0
dirty_ids = []
for dr in session.query(DR).filter(DR.id.in_(ids)).all():
dirty_ids.append(dr.dag_id)
count += 1
dr.state = target_state
... | 256 | 256 | 1,046 | 9 | 247 | change/incubator-airflow | airflow/www/views.py | Python | TaskInstanceModelView | TaskInstanceModelView | 2,316 | 2,428 | 2,316 | 2,316 | 9d99be68112c53fef7cea25c5dc8c02289570395 | bigcode/the-stack | train |
d6c7e3ddcc1ef94a27646853 | train | function | def state_f(v, c, m, p):
return state_token(m.state)
| def state_f(v, c, m, p):
| return state_token(m.state)
| span>
""".format(**locals()))
def state_token(state):
color = State.color(state)
return Markup(
'<span class="label" style="background-color:{color};">'
'{state}</span>'.format(**locals()))
def state_f(v, c, m, p):
| 63 | 64 | 18 | 11 | 52 | change/incubator-airflow | airflow/www/views.py | Python | state_f | state_f | 149 | 150 | 149 | 149 | 25df35ff07f8786e1292aa62c979b3c2f7b60518 | bigcode/the-stack | train |
62a7090b2bb9a3fd8db329e1 | train | function | def recurse_tasks(tasks, task_ids, dag_ids, task_id_to_dag):
if isinstance(tasks, list):
for task in tasks:
recurse_tasks(task, task_ids, dag_ids, task_id_to_dag)
return
if isinstance(tasks, SubDagOperator):
subtasks = tasks.subdag.tasks
dag_ids.append(tasks.subdag.da... | def recurse_tasks(tasks, task_ids, dag_ids, task_id_to_dag):
| if isinstance(tasks, list):
for task in tasks:
recurse_tasks(task, task_ids, dag_ids, task_id_to_dag)
return
if isinstance(tasks, SubDagOperator):
subtasks = tasks.subdag.tasks
dag_ids.append(tasks.subdag.dag_id)
for subtask in subtasks:
if subtask... | _equals=' + m.pool +
'&flt2_state_equals=queued&sort=10&desc=1')
return Markup("<a href='{0}'>{1}</a>".format(url, m.queued_slots()))
def recurse_tasks(tasks, task_ids, dag_ids, task_id_to_dag):
| 63 | 64 | 165 | 17 | 46 | change/incubator-airflow | airflow/www/views.py | Python | recurse_tasks | recurse_tasks | 260 | 274 | 260 | 260 | 362c78045541dd0ba98d71dc13f8291051cf77c1 | bigcode/the-stack | train |
c2e7b44016bf1233080f0408 | train | class | class DagModelView(wwwutils.SuperUserMixin, ModelView):
column_list = ('dag_id', 'owners')
column_editable_list = ('is_paused',)
form_excluded_columns = ('is_subdag', 'is_active')
column_searchable_list = ('dag_id',)
column_filters = (
'dag_id', 'owners', 'is_paused', 'is_active', 'is_subdag... | class DagModelView(wwwutils.SuperUserMixin, ModelView):
| column_list = ('dag_id', 'owners')
column_editable_list = ('is_paused',)
form_excluded_columns = ('is_subdag', 'is_active')
column_searchable_list = ('dag_id',)
column_filters = (
'dag_id', 'owners', 'is_paused', 'is_active', 'is_subdag',
'last_scheduler_run', 'last_expired')
for... | Response(
response=config,
status=200,
mimetype="application/text")
else:
code_html = Markup(highlight(
config,
lexers.IniLexer(), # Lexer call
HtmlFormatter(noclasses=True))
)
r... | 117 | 117 | 391 | 13 | 104 | change/incubator-airflow | airflow/www/views.py | Python | DagModelView | DagModelView | 2,589 | 2,638 | 2,589 | 2,589 | 856d0dbd282d79d9a0f4fe113819623ee21d550e | bigcode/the-stack | train |
54bf41d40b7979a0fbb9fc2c | train | function | def data_profiling_required(f):
'''
Decorator for views requiring data profiling access
'''
@wraps(f)
def decorated_function(*args, **kwargs):
if (
current_app.config['LOGIN_DISABLED'] or
(not current_user.is_anonymous() and current_user.data_profiling... | def data_profiling_required(f):
| '''
Decorator for views requiring data profiling access
'''
@wraps(f)
def decorated_function(*args, **kwargs):
if (
current_app.config['LOGIN_DISABLED'] or
(not current_user.is_anonymous() and current_user.data_profiling())
):
retur... | , lexers.RstLexer),
'doc_yaml': lambda x: render(x, lexers.YamlLexer),
'doc_md': wrapped_markdown,
'python_callable': lambda x: render(
inspect.getsource(x), lexers.PythonLexer),
}
def data_profiling_required(f):
| 64 | 64 | 109 | 8 | 56 | change/incubator-airflow | airflow/www/views.py | Python | data_profiling_required | data_profiling_required | 227 | 241 | 227 | 227 | a50023a6b2cbfae644f0389c1a5b5a5f6475771c | bigcode/the-stack | train |
47b8ca73f62802beea4fcbe0 | train | function | def duration_f(v, c, m, p):
if m.end_date and m.duration:
return timedelta(seconds=m.duration)
| def duration_f(v, c, m, p):
| if m.end_date and m.duration:
return timedelta(seconds=m.duration)
| State.color(state)
return Markup(
'<span class="label" style="background-color:{color};">'
'{state}</span>'.format(**locals()))
def state_f(v, c, m, p):
return state_token(m.state)
def duration_f(v, c, m, p):
| 64 | 64 | 27 | 11 | 53 | change/incubator-airflow | airflow/www/views.py | Python | duration_f | duration_f | 153 | 155 | 153 | 153 | ed0c3a4b06ff1ce3637bdc8b5e1cd56ad8b6f19b | bigcode/the-stack | train |
9b521af5e680e1f4f6f5c795 | train | function | def state_token(state):
color = State.color(state)
return Markup(
'<span class="label" style="background-color:{color};">'
'{state}</span>'.format(**locals()))
| def state_token(state):
| color = State.color(state)
return Markup(
'<span class="label" style="background-color:{color};">'
'{state}</span>'.format(**locals()))
| <a href="{url_root}" title="Filter on this task and upstream">
<span class="glyphicon glyphicon-filter" style="margin-left: 0px;"
aria-hidden="true"></span>
</a>
</span>
""".format(**locals()))
def state_token(state):
| 63 | 64 | 42 | 5 | 58 | change/incubator-airflow | airflow/www/views.py | Python | state_token | state_token | 142 | 146 | 142 | 142 | bdd8751685ab92c6ed1e5b3ffebb7dce19ec3031 | bigcode/the-stack | train |
85d4ac96d28c6da1b25dc812 | train | class | class DagRunModelView(ModelViewOnly):
verbose_name_plural = "DAG Runs"
can_edit = True
can_create = True
column_editable_list = ('state',)
verbose_name = "dag run"
column_default_sort = ('execution_date', True)
form_choices = {
'state': [
('success', 'success'),
... | class DagRunModelView(ModelViewOnly):
| verbose_name_plural = "DAG Runs"
can_edit = True
can_create = True
column_editable_list = ('state',)
verbose_name = "dag run"
column_default_sort = ('execution_date', True)
form_choices = {
'state': [
('success', 'success'),
('running', 'running'),
... | 'task_id',
'dag_id',
)
form_extra_fields = {
'value': StringField('Value'),
}
column_filters = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id')
column_searchable_list = ('key', 'timestamp', 'execution_date', 'task_id', 'dag_id')
class JobModelView(ModelViewOnly):
... | 193 | 193 | 644 | 9 | 184 | change/incubator-airflow | airflow/www/views.py | Python | DagRunModelView | DagRunModelView | 2,227 | 2,304 | 2,227 | 2,227 | f37eb29d78d74482a6087b5b13926db5c964b645 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.