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
7eb74fd6873f1d664a784e6f
train
function
def capture_init(init): @functools.wraps(init) def __init__(self, *args, **kwargs): self._init_args_kwargs = (args, kwargs) init(self, *args, **kwargs) return __init__
def capture_init(init): @functools.wraps(init)
def __init__(self, *args, **kwargs): self._init_args_kwargs = (args, kwargs) init(self, *args, **kwargs) return __init__
().items()} save_to = path if str(path).endswith(".gz"): save_to = gzip.open(path, "wb", compresslevel=5) th.save((klass, args, kwargs, state), save_to) def capture_init(init): @functools.wraps(init)
64
64
54
14
50
roger-tseng/demucs
demucs/utils.py
Python
capture_init
capture_init
181
187
181
182
65685e51b32f6256f9171c52075a22a03b3b6382
bigcode/the-stack
train
71bafb548f041cb9bc460236
train
function
def sizeof_fmt(num, suffix='B'): """ Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 ...
def sizeof_fmt(num, suffix='B'):
""" Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi...
.socket() while True: port = random.randint(low, high) try: sock.bind((host, port)) except OSError as error: if error.errno == errno.EADDRINUSE: continue raise return port def sizeof_fmt(num, suffix='B'):
64
64
120
9
54
roger-tseng/demucs
demucs/utils.py
Python
sizeof_fmt
sizeof_fmt
67
76
67
67
78bc59baed57a72ab6c1e59c0066df6c2dd5033c
bigcode/the-stack
train
fd0c43831408594a456cebbf
train
function
def average_metric(metric, count=1.): """ Average `metric` which should be a float across all hosts. `count` should be the weight for this particular host (i.e. number of examples). """ metric = th.tensor([count, count * metric], dtype=th.float32, device='cuda') distributed.all_reduce(metric, op...
def average_metric(metric, count=1.):
""" Average `metric` which should be a float across all hosts. `count` should be the weight for this particular host (i.e. number of examples). """ metric = th.tensor([count, count * metric], dtype=th.float32, device='cuda') distributed.all_reduce(metric, op=distributed.ReduceOp.SUM) return ...
if delta < 0: raise ValueError("tensor must be larger than reference. " f"Delta is {delta}.") if delta: tensor = tensor[..., delta // 2:-(delta - delta // 2)] return tensor def average_metric(metric, count=1.):
64
64
101
10
53
roger-tseng/demucs
demucs/utils.py
Python
average_metric
average_metric
39
46
39
39
d2e7403df41de7f0b6ae7c38baf9a9dd0de9c41c
bigcode/the-stack
train
4c230fe5d72cb02bf4b19f7f
train
function
def center_trim(tensor, reference): """ Center trim `tensor` with respect to `reference`, along the last dimension. `reference` can also be a number, representing the length to trim to. If the size difference != 0 mod 2, the extra sample is removed on the right side. """ if hasattr(reference, "s...
def center_trim(tensor, reference):
""" Center trim `tensor` with respect to `reference`, along the last dimension. `reference` can also be a number, representing the length to trim to. If the size difference != 0 mod 2, the extra sample is removed on the right side. """ if hasattr(reference, "size"): reference = reference...
this source tree. import errno import functools import gzip import os import random import socket import tempfile import warnings from contextlib import contextmanager import torch as th import tqdm from torch import distributed from torch.nn import functional as F def center_trim(tensor, reference):
64
64
149
8
55
roger-tseng/demucs
demucs/utils.py
Python
center_trim
center_trim
23
36
23
23
a4d3be57e4417ec3491ff9b47d9637497726f4a4
bigcode/the-stack
train
cc81ca6c8c7d7d2a2b170552
train
function
def apply_model(model, emb, mix, shifts=None, split=False, progress=False): """ Apply model to a given mixture. Args: shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec and apply the oppositve shift to the output. This is repeated `shifts` time and ...
def apply_model(model, emb, mix, shifts=None, split=False, progress=False):
""" Apply model to a given mixture. Args: shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec and apply the oppositve shift to the output. This is repeated `shifts` time and all predictions are averaged. This effectively makes the model ti...
) def human_seconds(seconds, display='.2f'): """ Given `seconds` seconds, return human readable duration. """ value = seconds * 1e6 ratios = [1e3, 1e3, 60, 60, 24] names = ['us', 'ms', 's', 'min', 'hrs', 'days'] last = names.pop(0) for name, ratio in zip(names, ratios): if valu...
153
154
515
18
135
roger-tseng/demucs
demucs/utils.py
Python
apply_model
apply_model
95
143
95
95
51e6e3de57de1c0fefd8f36acd96faaae360fd35
bigcode/the-stack
train
1a5d8b37197d454fb82e0c5e
train
function
def load_model(path): with warnings.catch_warnings(): warnings.simplefilter("ignore") load_from = path if str(path).endswith(".gz"): load_from = gzip.open(path, "rb") klass, args, kwargs, state = th.load(load_from, 'cpu') model = klass(*args, **kwargs) model.load_...
def load_model(path):
with warnings.catch_warnings(): warnings.simplefilter("ignore") load_from = path if str(path).endswith(".gz"): load_from = gzip.open(path, "rb") klass, args, kwargs, state = th.load(load_from, 'cpu') model = klass(*args, **kwargs) model.load_state_dict(state) ...
_filenames(count, delete=True, **kwargs): names = [] try: for _ in range(count): names.append(tempfile.NamedTemporaryFile(delete=False).name) yield names finally: if delete: for name in names: os.unlink(name) def load_model(path):
64
64
84
5
59
roger-tseng/demucs
demucs/utils.py
Python
load_model
load_model
159
168
159
159
26a1edc78e0c32b0b28b95d7720f41581d2d7a27
bigcode/the-stack
train
c61231facaa47c97c1397afe
train
function
def save_model(model, path): args, kwargs = model._init_args_kwargs klass = model.__class__ state = {k: p.data.to('cpu') for k, p in model.state_dict().items()} save_to = path if str(path).endswith(".gz"): save_to = gzip.open(path, "wb", compresslevel=5) th.save((klass, args, kwargs, sta...
def save_model(model, path):
args, kwargs = model._init_args_kwargs klass = model.__class__ state = {k: p.data.to('cpu') for k, p in model.state_dict().items()} save_to = path if str(path).endswith(".gz"): save_to = gzip.open(path, "wb", compresslevel=5) th.save((klass, args, kwargs, state), save_to)
str(path).endswith(".gz"): load_from = gzip.open(path, "rb") klass, args, kwargs, state = th.load(load_from, 'cpu') model = klass(*args, **kwargs) model.load_state_dict(state) return model def save_model(model, path):
64
64
95
7
56
roger-tseng/demucs
demucs/utils.py
Python
save_model
save_model
171
178
171
171
34e5728f727daf480085d21f1554049286c03b64
bigcode/the-stack
train
dee9afefb4cbd156d2247cbe
train
function
@contextmanager def temp_filenames(count, delete=True, **kwargs): names = [] try: for _ in range(count): names.append(tempfile.NamedTemporaryFile(delete=False).name) yield names finally: if delete: for name in names: os.unlink(name)
@contextmanager def temp_filenames(count, delete=True, **kwargs):
names = [] try: for _ in range(count): names.append(tempfile.NamedTemporaryFile(delete=False).name) yield names finally: if delete: for name in names: os.unlink(name)
2)) with th.no_grad(): #print("model input size:", padded.unsqueeze(0).size(), emb.size()) out = model(padded.unsqueeze(0), emb)[0] return center_trim(out, mix) @contextmanager def temp_filenames(count, delete=True, **kwargs):
64
64
65
16
48
roger-tseng/demucs
demucs/utils.py
Python
temp_filenames
temp_filenames
146
156
146
147
3421735b4667988db140a970f60bab0d09738636
bigcode/the-stack
train
292b05b7c9e64a4dff069eaf
train
function
def human_seconds(seconds, display='.2f'): """ Given `seconds` seconds, return human readable duration. """ value = seconds * 1e6 ratios = [1e3, 1e3, 60, 60, 24] names = ['us', 'ms', 's', 'min', 'hrs', 'days'] last = names.pop(0) for name, ratio in zip(names, ratios): if value / ...
def human_seconds(seconds, display='.2f'):
""" Given `seconds` seconds, return human readable duration. """ value = seconds * 1e6 ratios = [1e3, 1e3, 60, 60, 24] names = ['us', 'ms', 's', 'min', 'hrs', 'days'] last = names.pop(0) for name, ratio in zip(names, ratios): if value / ratio < 0.3: break valu...
abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) def human_seconds(seconds, display='.2f'):
64
64
134
10
54
roger-tseng/demucs
demucs/utils.py
Python
human_seconds
human_seconds
79
92
79
79
40580178a07a4a740af52fcee4b617d932814b1a
bigcode/the-stack
train
1b46050b1552ba18ed95e6be
train
function
def free_port(host='', low=20000, high=40000): """ Return a port number that is most likely free. This could suffer from a race condition although it should be quite rare. """ sock = socket.socket() while True: port = random.randint(low, high) try: sock.bind((host...
def free_port(host='', low=20000, high=40000):
""" Return a port number that is most likely free. This could suffer from a race condition although it should be quite rare. """ sock = socket.socket() while True: port = random.randint(low, high) try: sock.bind((host, port)) except OSError as error: ...
th.tensor([count, count * metric], dtype=th.float32, device='cuda') distributed.all_reduce(metric, op=distributed.ReduceOp.SUM) return metric[1].item() / metric[0].item() def free_port(host='', low=20000, high=40000):
64
64
106
15
49
roger-tseng/demucs
demucs/utils.py
Python
free_port
free_port
49
64
49
49
b078453857d6798b49bc7c144986b0eb8cebbd4e
bigcode/the-stack
train
ad85a5b4f0f2be80c930ceb6
train
function
def _choose_step(step): if step is None: return training_util.get_global_step() if not isinstance(step, ops.Tensor): return ops.convert_to_tensor(step, dtypes.int64) return step
def _choose_step(step):
if step is None: return training_util.get_global_step() if not isinstance(step, ops.Tensor): return ops.convert_to_tensor(step, dtypes.int64) return step
, "eval" if not name else "eval_" + name) def _serialize_graph(arbitrary_graph): if isinstance(arbitrary_graph, ops.Graph): return arbitrary_graph.as_graph_def(add_shapes=True).SerializeToString() else: return arbitrary_graph.SerializeToString() def _choose_step(step):
64
64
46
6
58
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
_choose_step
_choose_step
552
557
552
552
7a24fd1a181395129f0a85643a116d67d940c142
bigcode/the-stack
train
a8a77284ad3c8aa7ca356574
train
function
def create_summary_db_writer(db_uri, experiment_name=None, run_name=None, user_name=None, name=None): """Creates a summary database writer in the current context. This can be used to write tensors fr...
def create_summary_db_writer(db_uri, experiment_name=None, run_name=None, user_name=None, name=None):
"""Creates a summary database writer in the current context. This can be used to write tensors from the execution graph directly to a database. Only SQLite is supported right now. This function will create the schema if it doesn't exist. Entries in the Users, Experiments, and Runs tables will be created auto...
with ops.device("cpu:0"): if max_queue is None: max_queue = constant_op.constant(10) if flush_millis is None: flush_millis = constant_op.constant(2 * 60 * 1000) if filename_suffix is None: filename_suffix = constant_op.constant("") return _make_summary_writer( name, g...
142
142
475
27
115
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
create_summary_db_writer
create_summary_db_writer
213
261
213
217
9c876abceb5f182f1dbfae9b1684b939c9a4a86b
bigcode/the-stack
train
891be56bdad4bc7d64579505
train
function
def import_event(tensor, name=None): """Writes a @{tf.Event} binary proto. When using create_summary_db_writer(), this can be used alongside @{tf.TFRecordReader} to load event logs into the database. Please note that this is lower level than the other summary functions and will ignore any conditions set by m...
def import_event(tensor, name=None):
"""Writes a @{tf.Event} binary proto. When using create_summary_db_writer(), this can be used alongside @{tf.TFRecordReader} to load event logs into the database. Please note that this is lower level than the other summary functions and will ignore any conditions set by methods like @{tf.contrib.summary.sh...
_tensor(_serialize_graph(param), dtypes.string) else: tensor = array_ops.identity(param) return gen_summary_ops.write_graph_summary( writer, _choose_step(step), tensor, name=name) _graph = graph # for functions with a graph parameter def import_event(tensor, name=None):
64
64
159
9
54
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
import_event
import_event
498
516
498
498
0777f983e79d32bdfea48c518489f02557080cab
bigcode/the-stack
train
0866478458c7c72976bb17b1
train
function
def audio(name, tensor, sample_rate, max_outputs, family=None, step=None): """Writes an audio summary if possible.""" def function(tag, scope): # Note the identity to move the tensor to the CPU. return gen_summary_ops.write_audio_summary( context.context().summary_writer_resource, _choose_s...
def audio(name, tensor, sample_rate, max_outputs, family=None, step=None):
"""Writes an audio summary if possible.""" def function(tag, scope): # Note the identity to move the tensor to the CPU. return gen_summary_ops.write_audio_summary( context.context().summary_writer_resource, _choose_step(step), tag, array_ops.identity(tensor), sample_...
_resource, _choose_step(step), tag, array_ops.identity(tensor), bad_color_, max_images, name=scope) return summary_writer_function(name, tensor, function, family=family) def audio(name, tensor, sample_rate, max_outputs, family=None, step=None):
64
64
113
18
46
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
audio
audio
433
447
433
433
9f2d9dbb481e2509c821000eda4cc1713410de5e
bigcode/the-stack
train
6ecf5f5efdfb5d3a3776ee35
train
function
def generic(name, tensor, metadata=None, family=None, step=None): """Writes a tensor summary if possible.""" def function(tag, scope): if metadata is None: serialized_metadata = constant_op.constant("") elif hasattr(metadata, "SerializeToString"): serialized_metadata = constant_op.constant(meta...
def generic(name, tensor, metadata=None, family=None, step=None):
"""Writes a tensor summary if possible.""" def function(tag, scope): if metadata is None: serialized_metadata = constant_op.constant("") elif hasattr(metadata, "SerializeToString"): serialized_metadata = constant_op.constant(metadata.SerializeToString()) else: serialized_metadata = me...
op = utils.smart_cond( should_record_summaries(), record, _nothing, name="") ops.add_to_collection(ops.GraphKeys._SUMMARY_COLLECTION, op) # pylint: disable=protected-access return op def generic(name, tensor, metadata=None, family=None, step=None):
64
64
145
15
48
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
generic
generic
346
364
346
346
e36c2741725d404c75b10fbae47298ce5830e743
bigcode/the-stack
train
1db0687453b671b0449495d1
train
class
class SummaryWriter(object): """Encapsulates a stateful summary writer resource. See also: - @{tf.contrib.summary.create_summary_file_writer} - @{tf.contrib.summary.create_summary_db_writer} """ def __init__(self, resource): self._resource = resource if context.in_eager_mode(): self._resour...
class SummaryWriter(object):
"""Encapsulates a stateful summary writer resource. See also: - @{tf.contrib.summary.create_summary_file_writer} - @{tf.contrib.summary.create_summary_db_writer} """ def __init__(self, resource): self._resource = resource if context.in_eager_mode(): self._resource_deleter = resource_variabl...
old @tf_contextlib.contextmanager def never_record_summaries(): """Sets the should_record_summaries Tensor to always false.""" collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] collection_ref[:] = [False] yield collection_ref[:] = old class SummaryWriter(objec...
78
78
261
5
72
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
SummaryWriter
SummaryWriter
101
132
101
101
2db379195ca66c8b0b4dacea2906e24d180da1b5
bigcode/the-stack
train
69724cf3291f324c79e61979
train
function
@tf_contextlib.contextmanager def record_summaries_every_n_global_steps(n, global_step=None): """Sets the should_record_summaries Tensor to true if global_step % n == 0.""" if global_step is None: global_step = training_util.get_global_step() collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NA...
@tf_contextlib.contextmanager def record_summaries_every_n_global_steps(n, global_step=None):
"""Sets the should_record_summaries Tensor to true if global_step % n == 0.""" if global_step is None: global_step = training_util.get_global_step() collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] with ops.device("cpu:0"): collection_ref[:] = [math_ops.eq...
tensor specified for whether summaries " "should be recorded: %s" % should_record_collection) return should_record_collection[0] # TODO(apassos) consider how to handle local step here. @tf_contextlib.contextmanager def record_summaries_every_n_global_steps(n, global_step=None):
64
64
121
22
42
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
record_summaries_every_n_global_steps
record_summaries_every_n_global_steps
68
78
68
69
98bad81f619b139dbeed696594a75177f716b325
bigcode/the-stack
train
c1466a7e414d626e88e6a350
train
function
def histogram(name, tensor, family=None, step=None): """Writes a histogram summary if possible.""" def function(tag, scope): # Note the identity to move the tensor to the CPU. return gen_summary_ops.write_histogram_summary( context.context().summary_writer_resource, _choose_step(step), ...
def histogram(name, tensor, family=None, step=None):
"""Writes a histogram summary if possible.""" def function(tag, scope): # Note the identity to move the tensor to the CPU. return gen_summary_ops.write_histogram_summary( context.context().summary_writer_resource, _choose_step(step), tag, array_ops.identity(tensor), ...
return gen_summary_ops.write_scalar_summary( context.context().summary_writer_resource, _choose_step(step), tag, array_ops.identity(tensor), name=scope) return summary_writer_function(name, tensor, function, family=family) def histogram(name, tensor, family=None, step=None):
64
64
95
12
52
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
histogram
histogram
399
411
399
399
7e14b5537f9fada8daa4803dd438646e19e188e1
bigcode/the-stack
train
aea0cc368bc952cb2540e073
train
function
def initialize( graph=None, # pylint: disable=redefined-outer-name session=None): """Initializes summary writing for graph execution mode. This helper method provides a higher-level alternative to using @{tf.contrib.summary.summary_writer_initializer_op} and @{tf.contrib.summary.graph}. Most users ...
def initialize( graph=None, # pylint: disable=redefined-outer-name session=None):
"""Initializes summary writing for graph execution mode. This helper method provides a higher-level alternative to using @{tf.contrib.summary.summary_writer_initializer_op} and @{tf.contrib.summary.graph}. Most users will also want to call @{tf.train.create_global_step} which can happen before or after th...
.context().summary_writer_resource = self._resource yield self # Flushes the summary writer in eager mode or in graph functions, but not # in legacy graph mode (you're on your own there). with ops.device("cpu:0"): gen_summary_ops.flush_summary_writer(self._resource) context.context...
97
97
325
22
74
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
initialize
initialize
135
169
135
137
ec22bc2c2eb212dfbb6513c585d54950ce75783a
bigcode/the-stack
train
8ad1ddc4bd3f6273be466bc5
train
function
def scalar(name, tensor, family=None, step=None): """Writes a scalar summary if possible. Unlike @{tf.contrib.summary.generic} this op may change the dtype depending on the writer, for both practical and efficiency concerns. Args: name: An arbitrary name for this summary. tensor: A @{tf.Tensor} Must b...
def scalar(name, tensor, family=None, step=None):
"""Writes a scalar summary if possible. Unlike @{tf.contrib.summary.generic} this op may change the dtype depending on the writer, for both practical and efficiency concerns. Args: name: An arbitrary name for this summary. tensor: A @{tf.Tensor} Must be one of the following types: `float32`, `fl...
Note the identity to move the tensor to the CPU. return gen_summary_ops.write_summary( context.context().summary_writer_resource, _choose_step(step), array_ops.identity(tensor), tag, serialized_metadata, name=scope) return summary_writer_function(name, tensor, func...
79
79
264
12
67
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
scalar
scalar
367
396
367
367
15c98256435c9e667b79767d950e2697d4380ee4
bigcode/the-stack
train
ea92d35bd30b54075df71db2
train
function
def should_record_summaries(): """Returns boolean Tensor which is true if summaries should be recorded.""" should_record_collection = ops.get_collection(_SHOULD_RECORD_SUMMARIES_NAME) if not should_record_collection: return False if len(should_record_collection) != 1: raise ValueError( "More tha...
def should_record_summaries():
"""Returns boolean Tensor which is true if summaries should be recorded.""" should_record_collection = ops.get_collection(_SHOULD_RECORD_SUMMARIES_NAME) if not should_record_collection: return False if len(should_record_collection) != 1: raise ValueError( "More than one tensor specified for whet...
NS = re.compile(r"^[^\x00-\x1F<>]{0,512}$") _USER_NAME_PATTERNS = re.compile(r"^[a-z]([-a-z0-9]{0,29}[a-z0-9])?$", re.I) def should_record_summaries():
64
64
100
7
57
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
should_record_summaries
should_record_summaries
55
64
55
55
a2926c7289d12d5c39ead9c93cdff4f9450aab79
bigcode/the-stack
train
9d24eceeb824a4c7c3c4217f
train
function
@tf_contextlib.contextmanager def always_record_summaries(): """Sets the should_record_summaries Tensor to always true.""" collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] collection_ref[:] = [True] yield collection_ref[:] = old
@tf_contextlib.contextmanager def always_record_summaries():
"""Sets the should_record_summaries Tensor to always true.""" collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] collection_ref[:] = [True] yield collection_ref[:] = old
ULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] with ops.device("cpu:0"): collection_ref[:] = [math_ops.equal(global_step % n, 0)] yield collection_ref[:] = old @tf_contextlib.contextmanager def always_record_summaries():
64
64
71
14
49
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
always_record_summaries
always_record_summaries
81
88
81
82
cb39788df1ddd5bec4442c0138a6b8dcdb51ccba
bigcode/the-stack
train
c2fb76d892a6b3a5dffc0860
train
function
def _cleanse_string(name, pattern, value): if isinstance(value, six.string_types) and pattern.search(value) is None: raise ValueError("%s (%s) must match %s" % (name, value, pattern.pattern)) return ops.convert_to_tensor(value, dtypes.string)
def _cleanse_string(name, pattern, value):
if isinstance(value, six.string_types) and pattern.search(value) is None: raise ValueError("%s (%s) must match %s" % (name, value, pattern.pattern)) return ops.convert_to_tensor(value, dtypes.string)
factory(resource, **kwargs) # if not context.in_eager_mode(): # ops.get_default_session().run(node) ops.add_to_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME, factory(resource, **kwargs)) return SummaryWriter(resource) def _cleanse_string(name, pattern, value):
64
64
63
11
53
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
_cleanse_string
_cleanse_string
275
278
275
275
6baa5c6cfd146bb2824ffa47b01a9f31ec9c4b71
bigcode/the-stack
train
d3c3c6c69c9de8ba6c59b6f5
train
function
def eval_dir(model_dir, name=None): """Construct a logdir for an eval summary writer.""" return os.path.join(model_dir, "eval" if not name else "eval_" + name)
def eval_dir(model_dir, name=None):
"""Construct a logdir for an eval summary writer.""" return os.path.join(model_dir, "eval" if not name else "eval_" + name)
Returns: The created @{tf.Operation}. """ if writer is None: writer = context.context().summary_writer_resource if writer is None: return control_flow_ops.no_op() return gen_summary_ops.flush_summary_writer(writer, name=name) def eval_dir(model_dir, name=None):
64
64
42
9
55
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
eval_dir
eval_dir
540
542
540
540
967b3f813884b09d16113aab2ce614dad384dfc6
bigcode/the-stack
train
e9fb5a3bb0d4a0dc74ba2442
train
function
@tf_contextlib.contextmanager def never_record_summaries(): """Sets the should_record_summaries Tensor to always false.""" collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] collection_ref[:] = [False] yield collection_ref[:] = old
@tf_contextlib.contextmanager def never_record_summaries():
"""Sets the should_record_summaries Tensor to always false.""" collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] collection_ref[:] = [False] yield collection_ref[:] = old
ummaries Tensor to always true.""" collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME) old = collection_ref[:] collection_ref[:] = [True] yield collection_ref[:] = old @tf_contextlib.contextmanager def never_record_summaries():
64
64
71
14
49
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
never_record_summaries
never_record_summaries
91
98
91
92
583cfbc8bf41f55e8bb354f1bdaa352ce788b26b
bigcode/the-stack
train
316bb27b7eea8816120fc902
train
function
def all_summary_ops(): """Graph-mode only. Returns all summary ops. Please note this excludes @{tf.contrib.summary.graph} ops. Returns: The summary ops. Raises: RuntimeError: If in Eager mode. """ if context.in_eager_mode(): raise RuntimeError( "tf.contrib.summary.all_summary_ops is o...
def all_summary_ops():
"""Graph-mode only. Returns all summary ops. Please note this excludes @{tf.contrib.summary.graph} ops. Returns: The summary ops. Raises: RuntimeError: If in Eager mode. """ if context.in_eager_mode(): raise RuntimeError( "tf.contrib.summary.all_summary_ops is only supported in graph ...
raise ValueError("%s (%s) must match %s" % (name, value, pattern.pattern)) return ops.convert_to_tensor(value, dtypes.string) def _nothing(): """Convenient else branch for when summaries do not record.""" return constant_op.constant(False) def all_summary_ops():
64
64
102
5
59
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
all_summary_ops
all_summary_ops
286
300
286
286
8fd312593661015afb86a7515069d772f90219ae
bigcode/the-stack
train
43a18325a94a41532a2cd777
train
function
def _make_summary_writer(name, factory, **kwargs): resource = gen_summary_ops.summary_writer(shared_name=name) # TODO(apassos): Consider doing this instead. # node = factory(resource, **kwargs) # if not context.in_eager_mode(): # ops.get_default_session().run(node) ops.add_to_collection(_SUMMARY_WRITER_IN...
def _make_summary_writer(name, factory, **kwargs):
resource = gen_summary_ops.summary_writer(shared_name=name) # TODO(apassos): Consider doing this instead. # node = factory(resource, **kwargs) # if not context.in_eager_mode(): # ops.get_default_session().run(node) ops.add_to_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME, factory...
_PATTERNS, user_name) return _make_summary_writer( name, gen_summary_ops.create_summary_db_writer, db_uri=db_uri, experiment_name=experiment_name, run_name=run_name, user_name=user_name) def _make_summary_writer(name, factory, **kwargs):
64
64
93
12
52
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
_make_summary_writer
_make_summary_writer
264
272
264
264
21dbf3bcd0dccedb1552c790b9cf037b094994e7
bigcode/the-stack
train
ff678d81789a3cce83032dde
train
function
def graph(param, step=None, name=None): """Writes a TensorFlow graph to the summary interface. The graph summary is, strictly speaking, not a summary. Conditions like @{tf.contrib.summary.never_record_summaries} do not apply. Only a single graph can be associated with a particular run. If multiple graphs are...
def graph(param, step=None, name=None):
"""Writes a TensorFlow graph to the summary interface. The graph summary is, strictly speaking, not a summary. Conditions like @{tf.contrib.summary.never_record_summaries} do not apply. Only a single graph can be associated with a particular run. If multiple graphs are written, then only the last one will be...
(name, tensor, function, family=family) def audio(name, tensor, sample_rate, max_outputs, family=None, step=None): """Writes an audio summary if possible.""" def function(tag, scope): # Note the identity to move the tensor to the CPU. return gen_summary_ops.write_audio_summary( context.context()....
133
133
445
10
123
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
graph
graph
450
492
450
450
a53646794432a4621d02e2a3533b03b4583ff226
bigcode/the-stack
train
05f7848328279a70aac79759
train
function
def summary_writer_initializer_op(): """Graph-mode only. Returns the list of ops to create all summary writers. Returns: The initializer ops. Raises: RuntimeError: If in Eager mode. """ if context.in_eager_mode(): raise RuntimeError( "tf.contrib.summary.summary_writer_initializer_op is o...
def summary_writer_initializer_op():
"""Graph-mode only. Returns the list of ops to create all summary writers. Returns: The initializer ops. Raises: RuntimeError: If in Eager mode. """ if context.in_eager_mode(): raise RuntimeError( "tf.contrib.summary.summary_writer_initializer_op is only " "supported in graph mod...
If in Eager mode. """ if context.in_eager_mode(): raise RuntimeError( "tf.contrib.summary.all_summary_ops is only supported in graph mode.") return ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access def summary_writer_initializer_op():
64
64
91
6
57
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
summary_writer_initializer_op
summary_writer_initializer_op
303
316
303
303
95f83c805a2b754ad6dd9d69dd42574c40e8277c
bigcode/the-stack
train
8d53261c4f51d631381410b4
train
function
def _serialize_graph(arbitrary_graph): if isinstance(arbitrary_graph, ops.Graph): return arbitrary_graph.as_graph_def(add_shapes=True).SerializeToString() else: return arbitrary_graph.SerializeToString()
def _serialize_graph(arbitrary_graph):
if isinstance(arbitrary_graph, ops.Graph): return arbitrary_graph.as_graph_def(add_shapes=True).SerializeToString() else: return arbitrary_graph.SerializeToString()
() return gen_summary_ops.flush_summary_writer(writer, name=name) def eval_dir(model_dir, name=None): """Construct a logdir for an eval summary writer.""" return os.path.join(model_dir, "eval" if not name else "eval_" + name) def _serialize_graph(arbitrary_graph):
64
64
44
8
56
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
_serialize_graph
_serialize_graph
545
549
545
545
509efa47897c0e2b223c12afdac01c88735284a5
bigcode/the-stack
train
b6d5578f32c90e2a9c7c28a4
train
function
def flush(writer=None, name=None): """Forces summary writer to send any buffered data to storage. This operation blocks until that finishes. Args: writer: The @{tf.contrib.summary.SummaryWriter} resource to flush. The thread default will be used if this parameter is None. Otherwise a @{tf.no_op}...
def flush(writer=None, name=None):
"""Forces summary writer to send any buffered data to storage. This operation blocks until that finishes. Args: writer: The @{tf.contrib.summary.SummaryWriter} resource to flush. The thread default will be used if this parameter is None. Otherwise a @{tf.no_op} is returned. name: A name for ...
` containing a serialized @{tf.Event} proto. name: A name for the operation (optional). Returns: The created @{tf.Operation}. """ return gen_summary_ops.import_event( context.context().summary_writer_resource, tensor, name=name) def flush(writer=None, name=None):
64
64
139
8
56
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
flush
flush
519
537
519
519
166e78789b311c702db0ffcc5aa1c5d17a7e0cbc
bigcode/the-stack
train
ca6b57517b5fed06858fe1bb
train
function
def _nothing(): """Convenient else branch for when summaries do not record.""" return constant_op.constant(False)
def _nothing():
"""Convenient else branch for when summaries do not record.""" return constant_op.constant(False)
se_string(name, pattern, value): if isinstance(value, six.string_types) and pattern.search(value) is None: raise ValueError("%s (%s) must match %s" % (name, value, pattern.pattern)) return ops.convert_to_tensor(value, dtypes.string) def _nothing():
64
64
24
4
60
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
_nothing
_nothing
281
283
281
281
5da6f424cf6b7b5494fb08007fbb85e56fdddc63
bigcode/the-stack
train
8604d2df5b486d7f8dc2c1f7
train
function
def summary_writer_function(name, tensor, function, family=None): """Helper function to write summaries. Args: name: name of the summary tensor: main tensor to form the summary function: function taking a tag and a scope which writes the summary family: optional, the summary's family Returns: ...
def summary_writer_function(name, tensor, function, family=None):
"""Helper function to write summaries. Args: name: name of the summary tensor: main tensor to form the summary function: function taking a tag and a scope which writes the summary family: optional, the summary's family Returns: The result of writing the summary. """ def record(): wit...
Eager mode. """ if context.in_eager_mode(): raise RuntimeError( "tf.contrib.summary.summary_writer_initializer_op is only " "supported in graph mode.") return ops.get_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME) def summary_writer_function(name, tensor, function, family=None):
64
64
203
13
51
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
summary_writer_function
summary_writer_function
319
343
319
319
b316bec34427998084cde3e0fa1a77a5e2cb40d0
bigcode/the-stack
train
5fd575ea4020817f478d0fe9
train
function
def image(name, tensor, bad_color=None, max_images=3, family=None, step=None): """Writes an image summary if possible.""" def function(tag, scope): bad_color_ = (constant_op.constant([255, 0, 0, 255], dtype=dtypes.uint8) if bad_color is None else bad_color) # Note the identity to move the...
def image(name, tensor, bad_color=None, max_images=3, family=None, step=None):
"""Writes an image summary if possible.""" def function(tag, scope): bad_color_ = (constant_op.constant([255, 0, 0, 255], dtype=dtypes.uint8) if bad_color is None else bad_color) # Note the identity to move the tensor to the CPU. return gen_summary_ops.write_image_summary( con...
context.context().summary_writer_resource, _choose_step(step), tag, array_ops.identity(tensor), name=scope) return summary_writer_function(name, tensor, function, family=family) def image(name, tensor, bad_color=None, max_images=3, family=None, step=None):
64
64
148
21
43
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
image
image
414
430
414
414
5bdcb86fdd0d2bafe5b9003d75b6f79a409bb675
bigcode/the-stack
train
332657133e37551a26f5b692
train
function
def create_summary_file_writer(logdir, max_queue=None, flush_millis=None, filename_suffix=None, name=None): """Creates a summary file writer in the current context. Args: logdir: a string...
def create_summary_file_writer(logdir, max_queue=None, flush_millis=None, filename_suffix=None, name=None):
"""Creates a summary file writer in the current context. Args: logdir: a string, or None. If a string, creates a summary file writer which writes to the directory named by the string. If None, returns a mock object which acts like a summary writer but does nothing, useful to use as a context man...
is None: raise ValueError("session must be passed if no default session exists") session.run(summary_writer_initializer_op()) if graph is not None: data = _serialize_graph(graph) x = array_ops.placeholder(dtypes.string) session.run(_graph(x, 0), feed_dict={x: data}) def create_summary_file_writer...
96
96
323
28
68
JanX2/tensorflow
tensorflow/contrib/summary/summary_ops.py
Python
create_summary_file_writer
create_summary_file_writer
172
210
172
176
0fa8f3d7d99da972394977adc80465cfb30b23df
bigcode/the-stack
train
10843d0ad6364d9da49b2018
train
class
class LineBreak(IntFlag): NonBreak = 0 BreakBefore = 1 # B BreakAfter = 2 # A BreakAny = 3 # B/A
class LineBreak(IntFlag):
NonBreak = 0 BreakBefore = 1 # B BreakAfter = 2 # A BreakAny = 3 # B/A
odedata from enum import IntFlag from FileGenerator import Regenerate from GenerateCharacterCategory import CharacterClass, CategoryClassifyMap from MultiStageTable import * from UnicodeData import * # Unicode Line Breaking Algorithm # https://www.unicode.org/reports/tr14/ class LineBreak(IntFlag):
64
64
44
6
58
Novodes/notepad2
scintilla/scripts/GenerateLineBreak.py
Python
LineBreak
LineBreak
16
20
16
16
696045a143d9971f86e04d6b4ab3b8b91cd3ade1
bigcode/the-stack
train
fd8388e569b3bb7786320fde
train
function
def updateUnicodeLineBreak(filename): lineBreakTable = ['XX'] * UnicodeCharacterCount # @missing # https://www.unicode.org/Public/UCD/latest/ucd/LineBreak.txt version, propertyList = readUnicodePropertyFile('LineBreak.txt') flattenUnicodePropertyTable(lineBreakTable, propertyList) lineBreakTable[ord('<')] = 'OP' ...
def updateUnicodeLineBreak(filename):
lineBreakTable = ['XX'] * UnicodeCharacterCount # @missing # https://www.unicode.org/Public/UCD/latest/ucd/LineBreak.txt version, propertyList = readUnicodePropertyFile('LineBreak.txt') flattenUnicodePropertyTable(lineBreakTable, propertyList) lineBreakTable[ord('<')] = 'OP' # open punctuation lineBreakTable[ord...
XB) 'PO', # Postfix Numeric (XB) ], LineBreak.BreakAny: [ 'AI', # Ambiguous (Alphabetic or Ideograph) 'CB', # Contingent Break Opportunity (B/A) 'CJ', # Conditional Japanese Starter, treat as ID: CSS normal breaking 'H2', # Hangul LV Syllable (B/A) 'H3', # Hangul LVT Syllable (B/A) 'JT', # Hangul T Jamo...
195
195
652
7
187
Novodes/notepad2
scintilla/scripts/GenerateLineBreak.py
Python
updateUnicodeLineBreak
updateUnicodeLineBreak
84
153
84
84
19cfe11d5a25954dc48a1c359a907c86a97dda39
bigcode/the-stack
train
1a8a5d0ccba6540a4f553455
train
class
class P2PConnection(asyncio.Protocol): """A low-level connection object to a node's P2P interface. This class is responsible for: - opening and closing the TCP connection to the node - reading bytes from and writing bytes to the socket - deserializing and serializing the P2P message header - l...
class P2PConnection(asyncio.Protocol):
"""A low-level connection object to a node's P2P interface. This class is responsible for: - opening and closing the TCP connection to the node - reading bytes from and writing bytes to the socket - deserializing and serializing the P2P message header - logging messages as they are sent and re...
b"feefilter": msg_feefilter, b"getaddr": msg_getaddr, b"getblocks": msg_getblocks, b"getblocktxn": msg_getblocktxn, b"getdata": msg_getdata, b"getheaders": msg_getheaders, b"headers": msg_headers, b"inv": msg_inv, b"mempool": msg_mempool, b"notfound": msg_notfound, b"ping": msg_...
256
256
1,467
9
247
lurchinms/Auroracoin
test/functional/test_framework/mininode.py
Python
P2PConnection
P2PConnection
92
251
92
92
665c7b135cbae7d3d2fcbf90c35511e9c7937d9c
bigcode/the-stack
train
5148680fb4e8debfb8667353
train
class
class P2PDataStore(P2PInterface): """A P2P data store class. Keeps a block and transaction store and responds correctly to getdata and getheaders requests.""" def __init__(self): super().__init__() # store of blocks. key is block hash, value is a CBlock object self.block_store = {}...
class P2PDataStore(P2PInterface):
"""A P2P data store class. Keeps a block and transaction store and responds correctly to getdata and getheaders requests.""" def __init__(self): super().__init__() # store of blocks. key is block hash, value is a CBlock object self.block_store = {} self.last_block_hash = ''...
izing all data access between the network event loop (see # NetworkThread below) and the thread running the test logic. For simplicity, # P2PConnection acquires this lock whenever delivering a message to a P2PInterface. # This lock should be acquired in the thread running the test logic to synchronize # access to any ...
256
256
1,208
11
245
lurchinms/Auroracoin
test/functional/test_framework/mininode.py
Python
P2PDataStore
P2PDataStore
462
588
462
462
8cdeaf79c85cc8650b1a4a6b39f4678fafb0d12d
bigcode/the-stack
train
6b2a4616d19983467cb1feeb
train
class
class NetworkThread(threading.Thread): network_event_loop = None def __init__(self): super().__init__(name="NetworkThread") # There is only one event loop and no more than one thread must be created assert not self.network_event_loop NetworkThread.network_event_loop = asyncio.n...
class NetworkThread(threading.Thread):
network_event_loop = None def __init__(self): super().__init__(name="NetworkThread") # There is only one event loop and no more than one thread must be created assert not self.network_event_loop NetworkThread.network_event_loop = asyncio.new_event_loop() def run(self): ...
acquires this lock whenever delivering a message to a P2PInterface. # This lock should be acquired in the thread running the test logic to synchronize # access to any data shared with the P2PInterface or P2PConnection. mininode_lock = threading.RLock() class NetworkThread(threading.Thread):
64
64
154
7
57
lurchinms/Auroracoin
test/functional/test_framework/mininode.py
Python
NetworkThread
NetworkThread
440
459
440
440
78689bc96d239f4791dfa263c791fd4457ef3fe6
bigcode/the-stack
train
c0f7b018b36a8a17d6977b00
train
class
class P2PInterface(P2PConnection): """A high-level P2P interface class for communicating with a DigiByte node. This class provides high-level callbacks for processing P2P message payloads, as well as convenience methods for interacting with the node over P2P. Individual testcases should subclass t...
class P2PInterface(P2PConnection):
"""A high-level P2P interface class for communicating with a DigiByte node. This class provides high-level callbacks for processing P2P message payloads, as well as convenience methods for interacting with the node over P2P. Individual testcases should subclass this and override the on_* methods ...
return self._transport.write(tmsg) NetworkThread.network_event_loop.call_soon_threadsafe(maybe_write) # Class utility methods def build_message(self, message): """Build a serialized P2P message""" command = message.command data = message.serialize() ...
256
256
1,584
10
246
lurchinms/Auroracoin
test/functional/test_framework/mininode.py
Python
P2PInterface
P2PInterface
254
429
254
254
e7a7d14fed8a26f8220dcf138a2a7504b8f3f2d2
bigcode/the-stack
train
d04824556a32aae7c5a7d467
train
class
class GetIncidentInput(komand.Input): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "incident_id": { "type": "integer", "title": "Incident ID", "description": "Incident ID", "order": 1 } }, "required": [ "incident_id" ] } """...
class GetIncidentInput(komand.Input):
schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "incident_id": { "type": "integer", "title": "Incident ID", "description": "Incident ID", "order": 1 } }, "required": [ "incident_id" ] } """) def __init__(self): sup...
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: INCIDENT_ID = "incident_id" class Output: INCIDENT = "incident" class GetIncidentInput(komand.Input):
47
64
112
9
38
xhennessy-r7/insightconnect-plugins
samanage/komand_samanage/actions/get_incident/schema.py
Python
GetIncidentInput
GetIncidentInput
14
34
14
14
aeeb77ea9f464a82267fadb7decd9d7c86d3a450
bigcode/the-stack
train
02abc66226754bd1f63555fd
train
class
class GetIncidentOutput(komand.Output): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "incident": { "$ref": "#/definitions/incident", "title": "Incident", "description": "Details of an incident with the given ID", "order": 1 } }, "requ...
class GetIncidentOutput(komand.Output):
schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "incident": { "$ref": "#/definitions/incident", "title": "Incident", "description": "Details of an incident with the given ID", "order": 1 } }, "required": [ "incident" ], "definiti...
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: INCIDENT_ID = "incident_id" class Output: INCIDENT = "incident" class GetIncidentInput(komand.Input): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "incident_id": { ...
160
256
2,354
9
151
xhennessy-r7/insightconnect-plugins
samanage/komand_samanage/actions/get_incident/schema.py
Python
GetIncidentOutput
GetIncidentOutput
37
433
37
37
3683d11002d311d3476c046248895f55f5d1661b
bigcode/the-stack
train
43f03a977ac5f914df91fbe8
train
class
class Input: INCIDENT_ID = "incident_id"
class Input:
INCIDENT_ID = "incident_id"
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input:
20
64
11
3
16
xhennessy-r7/insightconnect-plugins
samanage/komand_samanage/actions/get_incident/schema.py
Python
Input
Input
6
7
6
6
d02202131fa949e3d47864c17350bcbe589a4769
bigcode/the-stack
train
b4b3c15ba3bf81bca950f625
train
class
class Output: INCIDENT = "incident"
class Output:
INCIDENT = "incident"
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: INCIDENT_ID = "incident_id" class Output:
31
64
9
3
28
xhennessy-r7/insightconnect-plugins
samanage/komand_samanage/actions/get_incident/schema.py
Python
Output
Output
10
11
10
10
f7ed5e8a6bc05e51a161eb4fc5d64ee914aa267d
bigcode/the-stack
train
e90f2a98a8a6a0361a503cef
train
class
class Configuration(dict): def __init__(self, doc=None,): dict.__init__( self, doc if doc != None else {} ) def load_yaml(self, f): return self.load(yaml.load(f)) def load_json(self, f): if hasattr(f, "read"): return self.load(json.load(f)) elif hasattr(f, "__len__"): return self.load(js...
class Configuration(dict):
def __init__(self, doc=None,): dict.__init__( self, doc if doc != None else {} ) def load_yaml(self, f): return self.load(yaml.load(f)) def load_json(self, f): if hasattr(f, "read"): return self.load(json.load(f)) elif hasattr(f, "__len__"): return self.load(json.loads(f)) def load(sel...
import yaml, json class Configuration(dict):
10
64
109
5
4
halfak/snuggle
snuggle/configuration.py
Python
Configuration
Configuration
3
21
3
4
10fed02f4252587622fdeb2d6766d75b343a3bc8
bigcode/the-stack
train
90dcdd9317b18eb59763b09a
train
function
@periodic_task(run_every=crontab(hour=0, minute=5)) def expire_account(): logger.info('Started') buyers_with_plans = Buyer.objects.select_related('buyerplan') for buyer in buyers_with_plans.filter( buyerplan__active=True, buyerplan__expire__lt=datetime.date.today() ).exclude( b...
@periodic_task(run_every=crontab(hour=0, minute=5)) def expire_account():
logger.info('Started') buyers_with_plans = Buyer.objects.select_related('buyerplan') for buyer in buyers_with_plans.filter( buyerplan__active=True, buyerplan__expire__lt=datetime.date.today() ).exclude( buyerplan__expire=None ): buyer.buyerplan.expire_account() ...
import logging from celery.schedules import crontab from celery.task.base import periodic_task from django.conf import settings from plans.models import Buyer logger = logging.getLogger('plans.tasks') @periodic_task(run_every=crontab(hour=0, minute=5)) def expire_account():
64
64
178
22
42
Nuurek/django-plans
plans/tasks.py
Python
expire_account
expire_account
12
34
12
14
a8941bbb99a422f445e7e4eac12f049b3197ddcd
bigcode/the-stack
train
fd1138a27cd6742c9f9e4e7c
train
class
class BaseMeasureTestCase(TestCase): def setUp(self): self.measure = Measure('myclient', ('localhost', 1984))
class BaseMeasureTestCase(TestCase):
def setUp(self): self.measure = Measure('myclient', ('localhost', 1984))
localhost', 1984)]) self.assertEqual( measure.socket.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE), socket.SOCK_DGRAM) # socket is non-blocking self.assertEqual(measure.socket.gettimeout(), 0.0) class BaseMeasureTestCase(TestCase):
64
64
30
8
56
EwertonBello/measures
tests/unit/test_measure.py
Python
BaseMeasureTestCase
BaseMeasureTestCase
24
27
24
25
55805d0df7c2c1af4e8babec534484ccd23be480
bigcode/the-stack
train
de9baa8af95fdbc22db97c2d
train
class
class MeasureTestCase(TestCase): def test_must_create_a_measure_object_with_correct_attributes(self): measure = Measure('myclient', ('localhost', 1984)) self.assertEqual(measure.client, 'myclient') self.assertEqual(measure.addresses, [('localhost', 1984)]) self.assertEqual( ...
class MeasureTestCase(TestCase):
def test_must_create_a_measure_object_with_correct_attributes(self): measure = Measure('myclient', ('localhost', 1984)) self.assertEqual(measure.client, 'myclient') self.assertEqual(measure.addresses, [('localhost', 1984)]) self.assertEqual( measure.socket.getsockopt(sock...
# -*- coding: utf-8 -*- from unittest import TestCase from measures import Measure from mock import patch import json import socket from nose_focus import focus class MeasureTestCase(TestCase):
43
64
114
7
35
EwertonBello/measures
tests/unit/test_measure.py
Python
MeasureTestCase
MeasureTestCase
11
21
11
12
737368cfeed19756608106ec1421caf7094c094c
bigcode/the-stack
train
5917ba627f478c56afbcb2d5
train
class
class MeasureSendTestCase(BaseMeasureTestCase): @patch('socket.socket.sendto') def test_must_send_a_packet_to_correct_address(self, mock_sendto): self.measure.send('mymetric', None) self.assertEqual(mock_sendto.call_count, 1) self.assertEqual(mock_sendto.call_args[0][1], ('localhost', ...
class MeasureSendTestCase(BaseMeasureTestCase): @patch('socket.socket.sendto')
def test_must_send_a_packet_to_correct_address(self, mock_sendto): self.measure.send('mymetric', None) self.assertEqual(mock_sendto.call_count, 1) self.assertEqual(mock_sendto.call_args[0][1], ('localhost', 1984)) @patch('socket.socket.sendto') def test_must_send_packet_with_dimens...
.assertEqual(message['error_type'], str(ValueError)) self.assertIn('error_value', message) self.assertEqual(message['error_value'], 'foo') @patch('socket.socket.sendto') def test_must_send_packet_with_dimensions_on_error(self, mock_sendto): with self.assertRaises(ValueError): ...
169
169
566
19
150
EwertonBello/measures
tests/unit/test_measure.py
Python
MeasureSendTestCase
MeasureSendTestCase
236
295
236
238
97b89093f399b6ca78e5456768f0078243d296e5
bigcode/the-stack
train
5943107582041e4b6018be98
train
class
class MeasureTimeTestCase(BaseMeasureTestCase): @patch('socket.socket.sendto') def test_must_send_a_packet_to_correct_address(self, mock_sendto): with self.measure.time('mymetric'): pass self.assertEqual(mock_sendto.call_count, 1) self.assertEqual(mock_sendto.call_args[0][1...
class MeasureTimeTestCase(BaseMeasureTestCase): @patch('socket.socket.sendto')
def test_must_send_a_packet_to_correct_address(self, mock_sendto): with self.measure.time('mymetric'): pass self.assertEqual(mock_sendto.call_count, 1) self.assertEqual(mock_sendto.call_args[0][1], ('localhost', 1984)) @patch('socket.socket.sendto') def test_must_send_p...
client': 'myclient', 'metric': 'mymetric', 'count': 1, } message = json.loads(mock_sendto.call_args[0][0].decode('utf-8')) self.assertDictEqual(message, expected_message) @patch('socket.socket.sendto') def test_must_not_change_dimensions_dict(self, mock_sendto): ...
255
256
1,276
19
237
EwertonBello/measures
tests/unit/test_measure.py
Python
MeasureTimeTestCase
MeasureTimeTestCase
105
233
105
107
aed75256e26426e135ac765276b6f6aa5fa7a69b
bigcode/the-stack
train
55f28390a81ecb80b06b03c0
train
class
class MeasureCountTestCase(BaseMeasureTestCase): @patch('socket.socket.sendto') def test_must_send_a_packet_to_correct_address(self, mock_sendto): self.measure.count('mymetric') self.assertEqual(mock_sendto.call_count, 1) self.assertEqual(mock_sendto.call_args[0][1], ('localhost', 1984)...
class MeasureCountTestCase(BaseMeasureTestCase): @patch('socket.socket.sendto')
def test_must_send_a_packet_to_correct_address(self, mock_sendto): self.measure.count('mymetric') self.assertEqual(mock_sendto.call_count, 1) self.assertEqual(mock_sendto.call_args[0][1], ('localhost', 1984)) @patch('socket.socket.sendto') def test_must_send_a_packet_with_counter_of...
# -*- coding: utf-8 -*- from unittest import TestCase from measures import Measure from mock import patch import json import socket from nose_focus import focus class MeasureTestCase(TestCase): def test_must_create_a_measure_object_with_correct_attributes(self): measure = Measure('myclient', ('localhost...
199
218
728
19
180
EwertonBello/measures
tests/unit/test_measure.py
Python
MeasureCountTestCase
MeasureCountTestCase
30
102
30
32
54dcc2f78e66959b9d312d1c75648513caba1e3a
bigcode/the-stack
train
18dd2adc3db1d6216d8544dc
train
function
def _child_matches(tag, selector): # The tag cannot match as a child if it does not have a parent. if not hasattr(tag, 'parent') or tag.parent is None: return False primary_match = _selector_matches(tag, selector.subselector) if not primary_match: return False return _selector_matche...
def _child_matches(tag, selector): # The tag cannot match as a child if it does not have a parent.
if not hasattr(tag, 'parent') or tag.parent is None: return False primary_match = _selector_matches(tag, selector.subselector) if not primary_match: return False return _selector_matches(tag.parent, selector.selector)
selector.subselector) if not primary_match: return False # Need to walk back up the tree checking the selector return _any_ancestor_matches(tag, selector.selector) def _child_matches(tag, selector): # The tag cannot match as a child if it does not have a parent.
64
64
78
25
39
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_child_matches
_child_matches
78
85
78
79
5b14b4cb00af69e5ed960bd0aa1e540a6a5a738c
bigcode/the-stack
train
135ca361bd43fdafaa1582e9
train
function
def _general_sibling_matches(tag, selector): # The tag must match the subselector, while some sibling before this tag in # the parent must match the selector. if not hasattr(tag, 'parent') or tag.parent is None: return False primary_match = _selector_matches(tag, selector.subselector) if no...
def _general_sibling_matches(tag, selector): # The tag must match the subselector, while some sibling before this tag in # the parent must match the selector.
if not hasattr(tag, 'parent') or tag.parent is None: return False primary_match = _selector_matches(tag, selector.subselector) if not primary_match: return False for sibling in tag.parent.tag_children(): if sibling is tag: return False if _selector_matches(s...
(tag, selector.subselector) if not primary_match: return False return _selector_matches(tag.parent, selector.selector) def _general_sibling_matches(tag, selector): # The tag must match the subselector, while some sibling before this tag in # the parent must match the selector.
64
64
117
37
27
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_general_sibling_matches
_general_sibling_matches
88
103
88
90
112531dee8844957b651a65c69f527fea01aa4a6
bigcode/the-stack
train
52ec61d37d86abe05fb449c3
train
function
def _attribute_matches(tag, selector): if not _selector_matches(tag, selector.selector): return False # This selector allows a namespace to be specified as well, but that is # not handled here. # There are also options related to how to compare the values case-wise # but that is apparently n...
def _attribute_matches(tag, selector):
if not _selector_matches(tag, selector.selector): return False # This selector allows a namespace to be specified as well, but that is # not handled here. # There are also options related to how to compare the values case-wise # but that is apparently not handled by cssselect. if selecto...
the parent then # it can't have a previous sibling. if tag_index == 0: return False sibling = tag_children[tag_index - 1] return _selector_matches(sibling, selector.selector) def _column_matches(tag, selector): # I don't know how to check this one. return False def _attribute_matches(...
78
78
263
8
69
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_attribute_matches
_attribute_matches
131
159
131
131
067a756b38d284904d93a065737781accb44d1d9
bigcode/the-stack
train
2de25d07eae5bc1001987340
train
function
def _column_matches(tag, selector): # I don't know how to check this one. return False
def _column_matches(tag, selector): # I don't know how to check this one.
return False
then # it can't have a previous sibling. if tag_index == 0: return False sibling = tag_children[tag_index - 1] return _selector_matches(sibling, selector.selector) def _column_matches(tag, selector): # I don't know how to check this one.
64
64
23
19
45
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_column_matches
_column_matches
126
128
126
127
932331017372db6c08a6b8ea6d0d57f310c4c080
bigcode/the-stack
train
7aee01cc47c2aaef7f28bb32
train
function
def _hash_matches(tag, hash): if not hasattr(tag, 'id') or tag.id is None: return False if hasattr(tag, 'data'): return False return tag.id == hash.id and ( hash.selector is None or _selector_matches(tag, hash.selector) )
def _hash_matches(tag, hash):
if not hasattr(tag, 'id') or tag.id is None: return False if hasattr(tag, 'data'): return False return tag.id == hash.id and ( hash.selector is None or _selector_matches(tag, hash.selector) )
# Probably not. if not hasattr(tag, 'tag'): return False if hasattr(tag, 'data'): return False # element.element will be None for the universal selector ('*') return tag.tag == element.element or element.element is None def _hash_matches(tag, hash):
64
64
66
8
55
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_hash_matches
_hash_matches
29
37
29
29
960a5ec21811d21ec709dcf4411371e4072c3742
bigcode/the-stack
train
0be208115270532b7aed49ec
train
function
def _pseudoclass_matches(tag, selector): # This is a pseudo-class that does not take arguments # Candidates to support: # :any-link # :empty # :first-child # :first-of-type # :last-child # :last-of-type # :only-child # :only-of-type # :root (equivalent of 'h...
def _pseudoclass_matches(tag, selector): # This is a pseudo-class that does not take arguments # Candidates to support: # :any-link # :empty # :first-child # :first-of-type # :last-child # :last-of-type # :only-child # :only-of-type # :root (equivalent of 'h...
if selector.ident in _pseudoclasses: return _pseudoclasses[selector.ident]( tag, selector ) return False
def _pseudoclass_matches(tag, selector): # This is a pseudo-class that does not take arguments # Candidates to support: # :any-link # :empty # :first-child # :first-of-type # :last-child # :last-of-type # :only-child # :only-of-type # :root (equivalent of 'h...
117
64
152
117
0
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_pseudoclass_matches
_pseudoclass_matches
236
254
236
248
ca962c8be237f35d8acadea8909d75c58c9fcc5d
bigcode/the-stack
train
c8818a376d40e81e2758db04
train
function
def _more_specific(specificity1, specificity2): """ Returns True if the first argument is more specific than the second, otherwise False. Specificity is a concept defined for CSS selectors: https://www.w3.org/TR/selectors/#specificity For our purposes, each specificity will be a tuple with thr...
def _more_specific(specificity1, specificity2):
""" Returns True if the first argument is more specific than the second, otherwise False. Specificity is a concept defined for CSS selectors: https://www.w3.org/TR/selectors/#specificity For our purposes, each specificity will be a tuple with three elements. """ return _compare_specifi...
_selector_matches(tag, s.parsed_tree) if is_match: if _more_specific(s.specificity(), best_specificity): matched = True best_specificity = s.specificity() return matched, best_specificity def _more_specific(specificity1, specificity2):
64
64
92
12
51
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_more_specific
_more_specific
337
347
337
337
4e38b71cac082d0f721abae38a8f0bf4630674bd
bigcode/the-stack
train
baa19e06054c2822a8db85c0
train
function
def _compare_specificity(specificity1, specificity2): """ Determines if one specificity are less than, equal to, or greater than another. Returns -1, 0 or 1 for those cases respectively. Specificity is a concept defined for CSS selectors: https://www.w3.org/TR/selectors/#specificity For our pu...
def _compare_specificity(specificity1, specificity2):
""" Determines if one specificity are less than, equal to, or greater than another. Returns -1, 0 or 1 for those cases respectively. Specificity is a concept defined for CSS selectors: https://www.w3.org/TR/selectors/#specificity For our purposes, each specificity will be a tuple with three el...
, specificity2) > 0 def _compare(a, b, c=None): if a == b: if c is None: return 0 else: return c else: return a - b def _compare_specificity(specificity1, specificity2):
64
64
205
13
50
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_compare_specificity
_compare_specificity
360
391
360
360
76c09c8007384bad0a4ff61dcc0ac7151bfd9011
bigcode/the-stack
train
b1c344751af2f45e95876dc7
train
function
def _combination_matches(tag, selector): if selector.combinator == ' ': return _descendant_matches(tag, selector) elif selector.combinator == '>': return _child_matches(tag, selector) elif selector.combinator == '~': return _general_sibling_matches(tag, selector) elif selector.co...
def _combination_matches(tag, selector):
if selector.combinator == ' ': return _descendant_matches(tag, selector) elif selector.combinator == '>': return _child_matches(tag, selector) elif selector.combinator == '~': return _general_sibling_matches(tag, selector) elif selector.combinator == '+': return _adjacent...
(selector.value)) if selector.operator == '^=': return attr_val.startswith(selector.value) if selector.operator == '$=': return attr_val.endswith(selector.value) if selector.operator == '*=': return selector.value in attr_val return False def _combination_...
64
64
111
9
54
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_combination_matches
_combination_matches
162
173
162
162
3cec9650f2a446accc438885194066b41e35ee13
bigcode/the-stack
train
fc72d614e565d0d3f5bd9e75
train
function
def _last_child_matches(tag, selector): if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False tag_children = tag.parent.tag_children() if len(tag_children) == 0: # wat return False return tag_children[-1] is tag and _s...
def _last_child_matches(tag, selector):
if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False tag_children = tag.parent.tag_children() if len(tag_children) == 0: # wat return False return tag_children[-1] is tag and _selector_matches(tag, selector.selector)
hasattr(tag, 'data'): return False tag_children = tag.parent.tag_children() if len(tag_children) == 0: # wat return False return tag_children[0] is tag and _selector_matches(tag, selector.selector) def _last_child_matches(tag, selector):
64
64
85
9
55
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_last_child_matches
_last_child_matches
218
227
218
218
68e165075b87203334e5de11cebad5e49e5226c1
bigcode/the-stack
train
d0d8092c984ec982d1d80789
train
function
def _nth_child_matches(tag, selector): if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False # A lot of ways this could fail! # TODO: Apparently this can take arguments like 'odd', 'even', '5n' (every 5th element) n = int(selector.arg...
def _nth_child_matches(tag, selector):
if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False # A lot of ways this could fail! # TODO: Apparently this can take arguments like 'odd', 'even', '5n' (every 5th element) n = int(selector.arguments[0].value) tag_children = tag...
ibling_matches(tag, selector) elif selector.combinator == '+': return _adjacent_sibling_matches(tag, selector) elif selector.combinator == '||': return _column_matches(tag, selector) return False # Pseudo Classes def _nth_child_matches(tag, selector):
64
64
129
9
54
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_nth_child_matches
_nth_child_matches
178
189
178
178
c996a32b161ee094f64f906bdb6dae034a619d02
bigcode/the-stack
train
24b1965673e432aa36ffc382
train
function
def _compare(a, b, c=None): if a == b: if c is None: return 0 else: return c else: return a - b
def _compare(a, b, c=None):
if a == b: if c is None: return 0 else: return c else: return a - b
defined for CSS selectors: https://www.w3.org/TR/selectors/#specificity For our purposes, each specificity will be a tuple with three elements. """ return _compare_specificity(specificity1, specificity2) > 0 def _compare(a, b, c=None):
64
64
43
10
53
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_compare
_compare
350
357
350
350
bb82a892e3dc6962a9a5f71f717be3a3ae2198cb
bigcode/the-stack
train
98cbbd69aabfb0b83eb00be5
train
function
def _any_ancestor_matches(tag, selector): if not hasattr(tag, 'parent') or tag.parent is None: return False if _selector_matches(tag.parent, selector): return True return _any_ancestor_matches(tag.parent, selector)
def _any_ancestor_matches(tag, selector):
if not hasattr(tag, 'parent') or tag.parent is None: return False if _selector_matches(tag.parent, selector): return True return _any_ancestor_matches(tag.parent, selector)
) # Combination match functions def _negation_matches(tag, selector): if hasattr(tag, 'data'): return False return ( _selector_matches(tag, selector.selector) and not _selector_matches(tag, selector.subselector) ) def _any_ancestor_matches(tag, selector):
64
64
55
10
54
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_any_ancestor_matches
_any_ancestor_matches
59
64
59
59
c0b0c9ed6cda180deb32ae16ee3c8c45da0aeec7
bigcode/the-stack
train
1aa68b974a8eef506991cc6c
train
function
def _class_matches(tag, klass): if not hasattr(tag, 'classes') or tag.classes is None: return False if hasattr(tag, 'data'): return False return klass.class_name in tag.classes and _selector_matches(tag, klass.selector)
def _class_matches(tag, klass):
if not hasattr(tag, 'classes') or tag.classes is None: return False if hasattr(tag, 'data'): return False return klass.class_name in tag.classes and _selector_matches(tag, klass.selector)
not hasattr(tag, 'id') or tag.id is None: return False if hasattr(tag, 'data'): return False return tag.id == hash.id and ( hash.selector is None or _selector_matches(tag, hash.selector) ) def _class_matches(tag, klass):
64
64
56
8
56
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_class_matches
_class_matches
40
45
40
40
d8809fffcb3bb36101be5481814610b9a32b612e
bigcode/the-stack
train
de4593f3863a097d03349699
train
function
def _first_child_matches(tag, selector): if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False tag_children = tag.parent.tag_children() if len(tag_children) == 0: # wat return False return tag_children[0] is tag and _s...
def _first_child_matches(tag, selector):
if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False tag_children = tag.parent.tag_children() if len(tag_children) == 0: # wat return False return tag_children[0] is tag and _selector_matches(tag, selector.selector)
5th element) n = int(selector.arguments[0].value) tag_children = tag.parent.tag_children() if n > len(tag_children): return False return tag_children[-n] is tag and _selector_matches(tag, selector.selector) def _first_child_matches(tag, selector):
64
64
85
9
55
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_first_child_matches
_first_child_matches
206
215
206
206
d2c859d4e9edee7ef10733e84bd415a82a990f14
bigcode/the-stack
train
e843c488a79de6ed87388073
train
function
def _pseudofunction_matches(tag, selector): # This is a pseudo-class that takes arguments # Candidates to support: # :dir() # :has() # :is() # :lang() # :nth-child() # :nth-col() # :nth-last-child() # :nth-last-col() # :nth-last-of-type() # :nth-of-typ...
def _pseudofunction_matches(tag, selector): # This is a pseudo-class that takes arguments # Candidates to support: # :dir() # :has() # :is() # :lang() # :nth-child() # :nth-col() # :nth-last-child() # :nth-last-col() # :nth-last-of-type() # :nth-of-typ...
if selector.name in _pseudofunctions: return _pseudofunctions[selector.name]( tag, selector ) return False
def _pseudofunction_matches(tag, selector): # This is a pseudo-class that takes arguments # Candidates to support: # :dir() # :has() # :is() # :lang() # :nth-child() # :nth-col() # :nth-last-child() # :nth-last-col() # :nth-last-of-type() # :nth-of-typ...
105
64
142
105
0
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_pseudofunction_matches
_pseudofunction_matches
263
282
263
276
9910da26bc551eba2e3819a2d376e3190ad05d4b
bigcode/the-stack
train
5f4be768a41347474dd5cfd4
train
function
def _adjacent_sibling_matches(tag, selector): # The tag must match the subselector, while the sibling immediately before # this tag in the parent must match the selector. if not hasattr(tag, 'parent') or tag.parent is None: return False primary_match = _selector_matches(tag, selector.subselecto...
def _adjacent_sibling_matches(tag, selector): # The tag must match the subselector, while the sibling immediately before # this tag in the parent must match the selector.
if not hasattr(tag, 'parent') or tag.parent is None: return False primary_match = _selector_matches(tag, selector.subselector) if not primary_match: return False tag_children = tag.parent.tag_children() tag_index = tag_children.index(tag) # If the tag is the first within the pa...
tag: return False if _selector_matches(sibling, selector.selector): return True return False def _adjacent_sibling_matches(tag, selector): # The tag must match the subselector, while the sibling immediately before # this tag in the parent must match the selector.
64
64
155
39
24
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_adjacent_sibling_matches
_adjacent_sibling_matches
106
123
106
108
f911f7fc8bc469b37748678b75e3335b730b7b3a
bigcode/the-stack
train
f6754347d6fc4323dc991f7e
train
function
def _element_matches(tag, element): # Unclear if the document root should match anything. # Probably not. if not hasattr(tag, 'tag'): return False if hasattr(tag, 'data'): return False # element.element will be None for the universal selector ('*') return tag.tag == element.eleme...
def _element_matches(tag, element): # Unclear if the document root should match anything. # Probably not.
if not hasattr(tag, 'tag'): return False if hasattr(tag, 'data'): return False # element.element will be None for the universal selector ('*') return tag.tag == element.element or element.element is None
Element, Class, FunctionalPseudoElement, Function, Pseudo, Negation, Attrib, Hash, CombinedSelector, ) # Basic match functions def _element_matches(tag, element): # Unclear if the document root should match anything. # Probably not.
64
64
77
25
38
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_element_matches
_element_matches
18
26
18
20
319d0543b4d65103bfc95c32bdf1415b974dd96f
bigcode/the-stack
train
3f2a7e626f5a33da162c5a67
train
function
def _pseudoelement_matches(tag, selector): # It is unclear if cssselect supports all peudo-elements or only ones that # take arguments, but we are not supporting any of them anyway. return False
def _pseudoelement_matches(tag, selector): # It is unclear if cssselect supports all peudo-elements or only ones that # take arguments, but we are not supporting any of them anyway.
return False
ofunctions[selector.name]( tag, selector ) return False def _pseudoelement_matches(tag, selector): # It is unclear if cssselect supports all peudo-elements or only ones that # take arguments, but we are not supporting any of them anyway.
64
64
48
44
19
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_pseudoelement_matches
_pseudoelement_matches
285
288
285
287
64f13fa08d3b39e930ef0f26f8cf32c6fa5568a9
bigcode/the-stack
train
666c569b4c8a53b2687b32ee
train
function
def _descendant_matches(tag, selector): # The tag must match the subselector, while some ancestor element must match # the main selector. primary_match = _selector_matches(tag, selector.subselector) if not primary_match: return False # Need to walk back up the tree checking the selector ...
def _descendant_matches(tag, selector): # The tag must match the subselector, while some ancestor element must match # the main selector.
primary_match = _selector_matches(tag, selector.subselector) if not primary_match: return False # Need to walk back up the tree checking the selector return _any_ancestor_matches(tag, selector.selector)
None: return False if _selector_matches(tag.parent, selector): return True return _any_ancestor_matches(tag.parent, selector) def _descendant_matches(tag, selector): # The tag must match the subselector, while some ancestor element must match # the main selector.
64
64
80
32
32
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_descendant_matches
_descendant_matches
67
75
67
69
dd4858b821151285ca1d759b4b27a30e2a1b0001
bigcode/the-stack
train
4eb9a8cdb288155846c0b5ee
train
class
class Specificity(object): """ Specificity wrapper to allow for comparisons during sorting. """ def __init__(self, specificity): self.specificity = specificity def __getitem__(self, key): return self.specificity[key] def __eq__(self, other): return _compare_specificity...
class Specificity(object):
""" Specificity wrapper to allow for comparisons during sorting. """ def __init__(self, specificity): self.specificity = specificity def __getitem__(self, key): return self.specificity[key] def __eq__(self, other): return _compare_specificity(self.specificity, other.sp...
[1], specificity2[1], _compare( specificity1[2], specificity2[2], ) ) ) if result > 0: return 1 elif result < 0: return -1 return result class Specificity(object):
64
64
199
5
58
khoulihan/gopher-render
gopher_render/_selectors.py
Python
Specificity
Specificity
394
418
394
394
4a63afd00113b26f38a97f987495420730bddf93
bigcode/the-stack
train
7f3380c99f55ba7566e3bc0f
train
function
def tag_matches(tag, selector): """ Determine if a given tag matches a given selector. Returns a boolean indicating a match or not, and a value indicating the specificity of the matched selector. """ # The selector will actually be a list, though perhaps one with only one # element. If mult...
def tag_matches(tag, selector):
""" Determine if a given tag matches a given selector. Returns a boolean indicating a match or not, and a value indicating the specificity of the matched selector. """ # The selector will actually be a list, though perhaps one with only one # element. If multiple elements match then we need...
pseudofunction_matches(tag, selector) elif isinstance(selector, FunctionalPseudoElement): return _pseudoelement_matches(tag, selector) elif isinstance(selector, CombinedSelector): return _combination_matches(tag, selector) # oh no return False def tag_matches(tag, selector):
64
64
157
7
56
khoulihan/gopher-render
gopher_render/_selectors.py
Python
tag_matches
tag_matches
315
334
315
315
d69e23def9c44fa74693eb359e22806214b04f3c
bigcode/the-stack
train
4ee62fc2af45ebeff4aa62e2
train
function
def _selector_matches(tag, selector): if isinstance(selector, Element): return _element_matches(tag, selector) elif isinstance(selector, Class): return _class_matches(tag, selector) elif isinstance(selector, Hash): return _hash_matches(tag, selector) elif isinstance(selector, Neg...
def _selector_matches(tag, selector):
if isinstance(selector, Element): return _element_matches(tag, selector) elif isinstance(selector, Class): return _class_matches(tag, selector) elif isinstance(selector, Hash): return _hash_matches(tag, selector) elif isinstance(selector, Negation): return _negation_match...
selector ) return False def _pseudoelement_matches(tag, selector): # It is unclear if cssselect supports all peudo-elements or only ones that # take arguments, but we are not supporting any of them anyway. return False def _selector_matches(tag, selector):
64
64
178
8
55
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_selector_matches
_selector_matches
291
312
291
291
0ece9689d026d5f92fc06bffc60da545cc1185eb
bigcode/the-stack
train
510fa40eca5cd7f7cd4b0e9a
train
function
def _nth_last_child_matches(tag, selector): if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False # A lot of ways this could fail! # TODO: Apparently this can take arguments like 'odd', 'even', '5n' (every 5th element) n = int(selecto...
def _nth_last_child_matches(tag, selector):
if not hasattr(tag, 'parent') or tag.parent is None: return False if hasattr(tag, 'data'): return False # A lot of ways this could fail! # TODO: Apparently this can take arguments like 'odd', 'even', '5n' (every 5th element) n = int(selector.arguments[0].value) tag_children = tag...
element) n = int(selector.arguments[0].value) tag_children = tag.parent.tag_children() if n > len(tag_children): return False return tag_children[n - 1] is tag and _selector_matches(tag, selector.selector) def _nth_last_child_matches(tag, selector):
64
64
128
10
54
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_nth_last_child_matches
_nth_last_child_matches
192
203
192
192
fc31895d3f4fe4babebeffe65efd4874ba31ffa0
bigcode/the-stack
train
e3f6adad930df1fc89e5bbfd
train
function
def _negation_matches(tag, selector): if hasattr(tag, 'data'): return False return ( _selector_matches(tag, selector.selector) and not _selector_matches(tag, selector.subselector) )
def _negation_matches(tag, selector):
if hasattr(tag, 'data'): return False return ( _selector_matches(tag, selector.selector) and not _selector_matches(tag, selector.subselector) )
klass): if not hasattr(tag, 'classes') or tag.classes is None: return False if hasattr(tag, 'data'): return False return klass.class_name in tag.classes and _selector_matches(tag, klass.selector) # Combination match functions def _negation_matches(tag, selector):
64
64
48
9
54
khoulihan/gopher-render
gopher_render/_selectors.py
Python
_negation_matches
_negation_matches
50
56
50
50
9ee33f6ea0ed01f9dd31263e4277fc8ac635989c
bigcode/the-stack
train
416d1bfe1e4fa68a26bf6cf5
train
class
class DescribeMonitoringAgentHostsRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Cms', '2019-01-01', 'DescribeMonitoringAgentHosts','cms') def get_HostName(self): return self.get_query_params().get('HostName') def set_HostName(self,HostName): self.add_query_param('HostName',HostNa...
class DescribeMonitoringAgentHostsRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Cms', '2019-01-01', 'DescribeMonitoringAgentHosts','cms') def get_HostName(self): return self.get_query_params().get('HostName') def set_HostName(self,HostName): self.add_query_param('HostName',HostName) def get_InstanceIds(self): return self.get_qu...
www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissi...
98
98
327
10
87
sdk-team/aliyun-openapi-python-sdk
aliyun-python-sdk-cms/aliyunsdkcms/request/v20190101/DescribeMonitoringAgentHostsRequest.py
Python
DescribeMonitoringAgentHostsRequest
DescribeMonitoringAgentHostsRequest
21
66
21
22
2d680c36de53a9d5c346f1e43741577d6976c0d4
bigcode/the-stack
train
1723e862840971f96ba0dd54
train
function
def select_dest(pp): global dest, outfile if pp != dest: if outfile is not None: outfile.close() dest = pp libname = "kicad_libs/%s.lib" % dest try: chk1 = open(libname, "r") chk1.close() # File already existed, so open as append, a...
def select_dest(pp):
global dest, outfile if pp != dest: if outfile is not None: outfile.close() dest = pp libname = "kicad_libs/%s.lib" % dest try: chk1 = open(libname, "r") chk1.close() # File already existed, so open as append, and don't put in heade...
] = map2[aa[1]] ll = " ".join(aa) + "\n" else: print("map2 lookup failed for " + aa[1]) fdo.write(ll) if not test_only: rename(ofile, filen) def select_dest(pp):
64
64
179
5
59
BerkeleyLab/Marble
design/scripts/dissect_lib3.py
Python
select_dest
select_dest
80
99
80
80
73a57f12cf74b558610312699a192387b5c9c44d
bigcode/the-stack
train
8de423cdb7a7fc19335591a2
train
function
def kill_ending(s, t): if s.endswith(t): return True, s[0:-len(t)] else: return False, s
def kill_ending(s, t):
if s.endswith(t): return True, s[0:-len(t)] else: return False, s
except IOError: print("Creating " + pp) outfile = open(libname, "w") outfile.write("EESchema-LIBRARY Version 2.4\n") outfile.write("#encoding utf-8\n") outfile.write("#\n") def kill_ending(s, t):
64
64
34
8
56
BerkeleyLab/Marble
design/scripts/dissect_lib3.py
Python
kill_ending
kill_ending
102
106
102
102
73bea794179599d8a2b617a4184defe9ecd2827f
bigcode/the-stack
train
c8d298f32fcc3813508a048a
train
function
def process_schem(filen): print("Processing " + filen) ofile = filen + "2" with open(filen, "r") as fdi: with open(ofile, "w") as fdo: for ll in fdi.readlines(): aa = ll.split() if len(aa) == 3 and aa[0] == "L": if aa[1] in map2: ...
def process_schem(filen):
print("Processing " + filen) ofile = filen + "2" with open(filen, "r") as fdi: with open(ofile, "w") as fdo: for ll in fdi.readlines(): aa = ll.split() if len(aa) == 3 and aa[0] == "L": if aa[1] in map2: aa[1] = ...
# Implicitly depends on the value of global map2 # Example modification: # -L FPGA_Xilinx_Kintex7:XC7K160T-FFG676 U? # +L marble_misc:XC7K160T-FFG676 U? def process_schem(filen):
64
64
157
7
57
BerkeleyLab/Marble
design/scripts/dissect_lib3.py
Python
process_schem
process_schem
62
77
62
62
c575af19be774560f9de11d3f002161b6af3b832
bigcode/the-stack
train
cb2f7b51b908033917a4b451
train
class
@declare(guid=guid("aa4c798d-d91b-4b07-a013-787f5803d6fc"), event_id=100, version=0) class Microsoft_Windows_StorageSpaces_ManagementAgent_100_0(Etw): pattern = Struct( "hc_stateid" / Int32ul )
@declare(guid=guid("aa4c798d-d91b-4b07-a013-787f5803d6fc"), event_id=100, version=0) class Microsoft_Windows_StorageSpaces_ManagementAgent_100_0(Etw):
pattern = Struct( "hc_stateid" / Int32ul )
Etw, declare, guid @declare(guid=guid("aa4c798d-d91b-4b07-a013-787f5803d6fc"), event_id=100, version=0) class Microsoft_Windows_StorageSpaces_ManagementAgent_100_0(Etw):
64
64
75
57
6
IMULMUL/etl-parser
etl/parsers/etw/Microsoft_Windows_StorageSpaces_ManagementAgent.py
Python
Microsoft_Windows_StorageSpaces_ManagementAgent_100_0
Microsoft_Windows_StorageSpaces_ManagementAgent_100_0
12
16
12
13
6a8fb66040f0e63f4cb24d6c2dab9883f498da48
bigcode/the-stack
train
503ec7d21cd57ed007e41826
train
function
def get_function(function_name: Optional[str] = None, job_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFunctionResult: """ A function object, containing all information associ...
def get_function(function_name: Optional[str] = None, job_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFunctionResult:
""" A function object, containing all information associated with the named function. All functions are contained under a streaming job. :param str function_name: The name of the function. :param str job_name: The name of the streaming job. :param str resource_group_name: The name of the resource ...
: yield self return GetFunctionResult( id=self.id, name=self.name, properties=self.properties, type=self.type) def get_function(function_name: Optional[str] = None, job_name: Optional[str] = None, resource_group_name: ...
84
84
282
53
31
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/streamanalytics/v20170401preview/get_function.py
Python
get_function
get_function
82
108
82
85
9bc4221fb6815d028663ea9d2ba5d04e08f1b60a
bigcode/the-stack
train
b82f74081619757c5bc79ec6
train
class
@pulumi.output_type class GetFunctionResult: """ A function object, containing all information associated with the named function. All functions are contained under a streaming job. """ def __init__(__self__, id=None, name=None, properties=None, type=None): if id and not isinstance(id, str): ...
@pulumi.output_type class GetFunctionResult:
""" A function object, containing all information associated with the named function. All functions are contained under a streaming job. """ def __init__(__self__, id=None, name=None, properties=None, type=None): if id and not isinstance(id, str): raise TypeError("Expected argument '...
WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 from ... import _utilities, _tables from . import outputs _...
108
108
361
11
97
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/streamanalytics/v20170401preview/get_function.py
Python
GetFunctionResult
GetFunctionResult
18
67
18
19
0fc3afdac1d11d4fecb86bffdf071c666f16966e
bigcode/the-stack
train
63c3c53516e717eca71793cb
train
class
class AwaitableGetFunctionResult(GetFunctionResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetFunctionResult( id=self.id, name=self.name, properties=self.properties, type=self.type)
class AwaitableGetFunctionResult(GetFunctionResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetFunctionResult( id=self.id, name=self.name, properties=self.properties, type=self.type)
.get(self, "properties") @property @pulumi.getter def type(self) -> str: """ Resource type """ return pulumi.get(self, "type") class AwaitableGetFunctionResult(GetFunctionResult): # pylint: disable=using-constant-test
64
64
62
21
43
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/streamanalytics/v20170401preview/get_function.py
Python
AwaitableGetFunctionResult
AwaitableGetFunctionResult
70
79
70
71
ec9399c1477c7d19d25a0b400171c13597d8f4e2
bigcode/the-stack
train
8f555f4232368c1ca4625b4a
train
function
def read_input_args(): parser = argparse.ArgumentParser() parser.add_argument( "--model_path", type=validate_existing_filepath, required=True, help="Path of model weights" ) parser.add_argument( "--model_info_path", type=validate_existing_filepath, required=True, ...
def read_input_args():
parser = argparse.ArgumentParser() parser.add_argument( "--model_path", type=validate_existing_filepath, required=True, help="Path of model weights" ) parser.add_argument( "--model_info_path", type=validate_existing_filepath, required=True, help="Path of model top...
_architect.utils.generic import pad_sentences from nlp_architect.utils.io import validate_existing_filepath from nlp_architect.utils.text import SpacyInstance nlp = SpacyInstance(disable=["tagger", "ner", "parser", "vectors", "textcat"]) def read_input_args():
63
64
85
5
58
ikuyamada/nlp-architect
examples/intent_extraction/interactive.py
Python
read_input_args
read_input_args
32
44
32
32
02da76a0987562ce0ce81314847c7cbbd4f56da7
bigcode/the-stack
train
ec22f47c3e2fb073570dc267
train
function
def process_text(text): input_text = " ".join(text.strip().split()) return nlp.tokenize(input_text)
def process_text(text):
input_text = " ".join(text.strip().split()) return nlp.tokenize(input_text)
input_args = parser.parse_args() return input_args def load_saved_model(): if model_type == "seq2seq": model = Seq2SeqIntentModel() else: model = MultiTaskIntentModel() model.load(args.model_path) return model def process_text(text):
64
64
26
5
58
ikuyamada/nlp-architect
examples/intent_extraction/interactive.py
Python
process_text
process_text
56
58
56
56
9ea3719899b4dbc40c496adf6dd97d9ec5dac490
bigcode/the-stack
train
d117cf7d15febe80a9ba0fd1
train
function
def vectorize(doc, vocab, char_vocab=None): words = np.asarray([vocab[w.lower()] if w.lower() in vocab else 1 for w in doc]).reshape(1, -1) if char_vocab is not None: sentence_chars = [] for w in doc: word_chars = [] for c in w: if c in char_vocab: ...
def vectorize(doc, vocab, char_vocab=None):
words = np.asarray([vocab[w.lower()] if w.lower() in vocab else 1 for w in doc]).reshape(1, -1) if char_vocab is not None: sentence_chars = [] for w in doc: word_chars = [] for c in w: if c in char_vocab: _cid = char_vocab[c] ...
2SeqIntentModel() else: model = MultiTaskIntentModel() model.load(args.model_path) return model def process_text(text): input_text = " ".join(text.strip().split()) return nlp.tokenize(input_text) def vectorize(doc, vocab, char_vocab=None):
64
64
149
11
53
ikuyamada/nlp-architect
examples/intent_extraction/interactive.py
Python
vectorize
vectorize
61
77
61
61
3348929374f4457650e63181dfed84d145e9e6e8
bigcode/the-stack
train
7cf361bf44f12871be48ef58
train
function
def load_saved_model(): if model_type == "seq2seq": model = Seq2SeqIntentModel() else: model = MultiTaskIntentModel() model.load(args.model_path) return model
def load_saved_model():
if model_type == "seq2seq": model = Seq2SeqIntentModel() else: model = MultiTaskIntentModel() model.load(args.model_path) return model
_filepath, required=True, help="Path of model weights" ) parser.add_argument( "--model_info_path", type=validate_existing_filepath, required=True, help="Path of model topology", ) input_args = parser.parse_args() return input_args def load_saved_model():
64
64
46
5
58
ikuyamada/nlp-architect
examples/intent_extraction/interactive.py
Python
load_saved_model
load_saved_model
47
53
47
47
b56ca9d77b5a28e8d6f04884160b3e3010804071
bigcode/the-stack
train
eb3b170edde4fb03ab75e213
train
function
def bezier_fit(x, y): dy = y[1:] - y[:-1] dx = x[1:] - x[:-1] dt = (dx ** 2 + dy ** 2)**0.5 t = dt/dt.sum() t = np.hstack(([0], t)) t = t.cumsum() data = np.column_stack((x, y)) Pseudoinverse = np.linalg.pinv(BezierCoeff(t)) # (9,4) -> (4,9) control_points = Pseudoinverse.dot(data)...
def bezier_fit(x, y):
dy = y[1:] - y[:-1] dx = x[1:] - x[:-1] dt = (dx ** 2 + dy ** 2)**0.5 t = dt/dt.sum() t = np.hstack(([0], t)) t = t.cumsum() data = np.column_stack((x, y)) Pseudoinverse = np.linalg.pinv(BezierCoeff(t)) # (9,4) -> (4,9) control_points = Pseudoinverse.dot(data) # (4,9)*(9,2) -> ...
) Mtk = lambda n, t, k: t**k * (1-t)**(n-k) * n_over_k(n,k) BezierCoeff = lambda ts: [[Mtk(3,t,k) for k in range(4)] for t in ts] def bezier_fit(x, y):
64
64
165
8
56
Pxtri2156/AdelaiDet_v2
datasets/custom_data/Bezier_generator2.py
Python
bezier_fit
bezier_fit
98
111
98
98
463b9fbfac01db9e611522135072ae3a6c93769e
bigcode/the-stack
train
0da1564dfae728a88ee95525
train
class
class Bezier(nn.Module): def __init__(self, ps, ctps): """ ps: numpy array of points """ super(Bezier, self).__init__() self.x1 = nn.Parameter(torch.as_tensor(ctps[0], dtype=torch.float64)) self.x2 = nn.Parameter(torch.as_tensor(ctps[2], dtype=torch.float64)) ...
class Bezier(nn.Module):
def __init__(self, ps, ctps): """ ps: numpy array of points """ super(Bezier, self).__init__() self.x1 = nn.Parameter(torch.as_tensor(ctps[0], dtype=torch.float64)) self.x2 = nn.Parameter(torch.as_tensor(ctps[2], dtype=torch.float64)) self.y1 = nn.Parameter(to...
.image as mpimg from scipy import interpolate from scipy.special import comb as n_over_k import glob, os import cv2 from skimage import data, color from skimage.transform import rescale, resize, downscale_local_mean import matplotlib.pyplot as plt import math import numpy as np import random # from scipy.optimize imp...
160
160
535
6
153
Pxtri2156/AdelaiDet_v2
datasets/custom_data/Bezier_generator2.py
Python
Bezier
Bezier
34
67
34
34
e2208debccc4a0078bf88ad5ac0e22afe05d67a4
bigcode/the-stack
train
e11f3439511ff35a96671deb
train
function
def draw(ps, control_points, t): x = ps[:, 0] y = ps[:, 1] x0, x1, x2, x3, y0, y1, y2, y3 = control_points fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x,y,color='m',linestyle='',marker='.') bezier_x = (1-t)*((1-t)*((1-t)*x0+t*x1)+t*((1-t)*x1+t*x2))+t*((1-t)*((1-t)*x1+t*x2)+t*((1-t)*...
def draw(ps, control_points, t):
x = ps[:, 0] y = ps[:, 1] x0, x1, x2, x3, y0, y1, y2, y3 = control_points fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x,y,color='m',linestyle='',marker='.') bezier_x = (1-t)*((1-t)*((1-t)*x0+t*x1)+t*((1-t)*x1+t*x2))+t*((1-t)*((1-t)*x1+t*x2)+t*((1-t)*x2+t*x3)) bezier_y = (1-t)*((...
.y2.item(), self.y3 def train(x, y, ctps, lr): x, y = np.array(x), np.array(y) ps = np.vstack((x, y)).transpose() bezier = Bezier(ps, ctps) return bezier.control_points_f() def draw(ps, control_points, t):
73
73
245
9
64
Pxtri2156/AdelaiDet_v2
datasets/custom_data/Bezier_generator2.py
Python
draw
draw
77
91
77
77
147a659bbed29640efd966bb987fae032fc62f80
bigcode/the-stack
train
0af307d6d6b8b2f03fe5295f
train
function
def is_close_to_line(xs, ys, thres): regression_model = LinearRegression() # Fit the data(train the model) regression_model.fit(xs.reshape(-1,1), ys.reshape(-1,1)) # Predict y_predicted = regression_model.predict(xs.reshape(-1,1)) # model evaluation rmse = mean_s...
def is_close_to_line(xs, ys, thres):
regression_model = LinearRegression() # Fit the data(train the model) regression_model.fit(xs.reshape(-1,1), ys.reshape(-1,1)) # Predict y_predicted = regression_model.predict(xs.reshape(-1,1)) # model evaluation rmse = mean_squared_error(ys.reshape(-1,1)**2, y_p...
* x[-1])/3.0 yc02 = (y[0] + 2* y[-1])/3.0 control_points = [xc01,yc01,xc02,yc02] return control_points def is_close_to_line(xs, ys, thres):
64
64
145
12
51
Pxtri2156/AdelaiDet_v2
datasets/custom_data/Bezier_generator2.py
Python
is_close_to_line
is_close_to_line
121
135
121
121
7f09eb4eb5de88b72e20638c08596c8330030476
bigcode/the-stack
train
19c6f7692823da7d69886bd7
train
function
def train(x, y, ctps, lr): x, y = np.array(x), np.array(y) ps = np.vstack((x, y)).transpose() bezier = Bezier(ps, ctps) return bezier.control_points_f()
def train(x, y, ctps, lr):
x, y = np.array(x), np.array(y) ps = np.vstack((x, y)).transpose() bezier = Bezier(ps, ctps) return bezier.control_points_f()
self.y2, self.y3 def control_points_f(self): return self.x0, self.x1.item(), self.x2.item(), self.x3, self.y0, self.y1.item(), self.y2.item(), self.y3 def train(x, y, ctps, lr):
64
64
56
11
52
Pxtri2156/AdelaiDet_v2
datasets/custom_data/Bezier_generator2.py
Python
train
train
70
75
70
70
a96e46ee9513fbbdb2abf5c0f808240cdf3596fc
bigcode/the-stack
train
0b3a243adc9f523e0ca420c7
train
function
def bezier_fitv2(x, y): xc01 = (2*x[0] + x[-1])/3.0 yc01 = (2*y[0] + y[-1])/3.0 xc02 = (x[0] + 2* x[-1])/3.0 yc02 = (y[0] + 2* y[-1])/3.0 control_points = [xc01,yc01,xc02,yc02] return control_points
def bezier_fitv2(x, y):
xc01 = (2*x[0] + x[-1])/3.0 yc01 = (2*y[0] + y[-1])/3.0 xc02 = (x[0] + 2* x[-1])/3.0 yc02 = (y[0] + 2* y[-1])/3.0 control_points = [xc01,yc01,xc02,yc02] return control_points
,9) control_points = Pseudoinverse.dot(data) # (4,9)*(9,2) -> (4,2) medi_ctp = control_points[1:-1,:].flatten().tolist() return medi_ctp def bezier_fitv2(x, y):
64
64
112
10
53
Pxtri2156/AdelaiDet_v2
datasets/custom_data/Bezier_generator2.py
Python
bezier_fitv2
bezier_fitv2
113
119
113
113
796f8052d90f5250821b0f9c9f1d1ceb0bfad883
bigcode/the-stack
train
89503507acf95c7aeb269d49
train
function
def is_close_to_linev2(xs, ys, size, thres = 0.05): pts = [] nor_pixel = int(size**0.5) for i in range(len(xs)): pts.append(Point([xs[i], ys[i]])) import itertools # iterate by pairs of points slopes = [(second.y-first.y)/(second.x-first.x) if not (second....
def is_close_to_linev2(xs, ys, size, thres = 0.05):
pts = [] nor_pixel = int(size**0.5) for i in range(len(xs)): pts.append(Point([xs[i], ys[i]])) import itertools # iterate by pairs of points slopes = [(second.y-first.y)/(second.x-first.x) if not (second.x-first.x) == 0.0 else math.inf*np.sign((second.y-fi...
se/(ys.reshape(-1,1)**2- y_predicted**2).max()**2 if rmse > thres: return 0.0 else: return 2.0 def is_close_to_linev2(xs, ys, size, thres = 0.05):
68
68
229
21
46
Pxtri2156/AdelaiDet_v2
datasets/custom_data/Bezier_generator2.py
Python
is_close_to_linev2
is_close_to_linev2
137
154
137
137
b874c5dd9c37d297665f7e4e84579f2e309e503b
bigcode/the-stack
train
e9d57fed7374ca12fdedcf98
train
function
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_replace(request): h5pl.replace(b'/opt/hdf5/vendor-plugin', 0) assert h5pl.size() == 1 assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin'
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_replace(request):
h5pl.replace(b'/opt/hdf5/vendor-plugin', 0) assert h5pl.size() == 1 assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin'
assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' assert h5pl.get(1) == b'h5py_plugin_test' @insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_replace(request):
64
64
77
28
36
Priyansh863/e-backend
Lib/site-packages/h5py/tests/test_h5pl.py
Python
test_replace
test_replace
59
64
59
61
e6c4e39ab54201b33c449d19a02aff4bcbe64f76
bigcode/the-stack
train
da3be413232c391ccaf7d328
train
function
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_prepend(request): h5pl.prepend(b'/opt/hdf5/vendor-plugin') assert h5pl.size() == 2 assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' assert h5pl.get(1) == b'h5py_plugin_test'
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_prepend(request):
h5pl.prepend(b'/opt/hdf5/vendor-plugin') assert h5pl.size() == 2 assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' assert h5pl.get(1) == b'h5py_plugin_test'
assert h5pl.get(0) == b'h5py_plugin_test' assert h5pl.get(1) == b'/opt/hdf5/vendor-plugin' @insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_prepend(request):
64
64
91
29
35
Priyansh863/e-backend
Lib/site-packages/h5py/tests/test_h5pl.py
Python
test_prepend
test_prepend
41
47
41
43
dd3ebb0871410a79fad623f53dcc860983424bd7
bigcode/the-stack
train
c5e543428a7cb1160df9c147
train
function
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_insert(request): h5pl.insert(b'/opt/hdf5/vendor-plugin', 0) assert h5pl.size() == 2 assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' assert h5pl.get(1) == b'h5py_plugin_test'
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_insert(request):
h5pl.insert(b'/opt/hdf5/vendor-plugin', 0) assert h5pl.size() == 2 assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' assert h5pl.get(1) == b'h5py_plugin_test'
assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' assert h5pl.get(1) == b'h5py_plugin_test' @insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_insert(request):
64
64
92
28
36
Priyansh863/e-backend
Lib/site-packages/h5py/tests/test_h5pl.py
Python
test_insert
test_insert
50
56
50
52
ff6b60c866c4706cba584acea9b682bb8cc9de39
bigcode/the-stack
train
d51f6da37d9093c0aa19ed75
train
function
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_default(request): assert h5pl.size() == 1 assert h5pl.get(0) == b'h5py_plugin_test'
@insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_default(request):
assert h5pl.size() == 1 assert h5pl.get(0) == b'h5py_plugin_test'
( h5py.version.hdf5_version_tuple < (1, 10, 1), reason='HDF5 1.10.1+ required' ) @insubprocess @subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) def test_default(request):
64
64
56
28
36
Priyansh863/e-backend
Lib/site-packages/h5py/tests/test_h5pl.py
Python
test_default
test_default
25
29
25
27
a62d00b7007ce8d8e984182a1ca3e34619066f97
bigcode/the-stack
train