function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def setUp(self):
self.ts = Series(np.random.randn(1000),
index=date_range('1/1/2000', periods=1000)) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def test_count(self):
self.ts[::3] = np.nan
grouper = TimeGrouper('A', label='right', closed='right')
result = self.ts.resample('A', how='count')
expected = self.ts.groupby(lambda x: x.year).count()
expected.index = result.index
assert_series_equal(result, expected) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def test_apply_iteration(self):
# #2300
N = 1000
ind = pd.date_range(start="2000-01-01", freq="D", periods=N)
df = DataFrame({'open': 1, 'close': 2}, index=ind)
tg = TimeGrouper('M')
_, grouper, _ = tg._get_grouper(df)
# Errors
grouped = df.groupby(grouper, group_keys=False)
f = lambda df: df['close'] / df['open']
# it works!
result = grouped.apply(f)
self.assertTrue(result.index.equals(df.index)) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def f(x):
assert(isinstance(x, Panel))
return x.mean(1) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def test_fails_on_no_datetime_index(self):
index_names = ('Int64Index', 'PeriodIndex', 'Index', 'Float64Index',
'MultiIndex')
index_funcs = (tm.makeIntIndex, tm.makePeriodIndex,
tm.makeUnicodeIndex, tm.makeFloatIndex,
lambda m: tm.makeCustomIndex(m, 2))
n = 2
for name, func in zip(index_names, index_funcs):
index = func(n)
df = DataFrame({'a': np.random.randn(n)}, index=index)
with tm.assertRaisesRegexp(TypeError,
"axis must be a DatetimeIndex, "
"but got an instance of %r" % name):
df.groupby(TimeGrouper('D')) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def test_aggregate_with_nat(self):
# check TimeGrouper's aggregation is identical as normal groupby
n = 20
data = np.random.randn(n, 4).astype('int64')
normal_df = DataFrame(data, columns=['A', 'B', 'C', 'D'])
normal_df['key'] = [1, 2, np.nan, 4, 5] * 4
dt_df = DataFrame(data, columns=['A', 'B', 'C', 'D'])
dt_df['key'] = [datetime(2013, 1, 1), datetime(2013, 1, 2), pd.NaT,
datetime(2013, 1, 4), datetime(2013, 1, 5)] * 4
normal_grouped = normal_df.groupby('key')
dt_grouped = dt_df.groupby(TimeGrouper(key='key', freq='D'))
for func in ['min', 'max', 'sum', 'prod']:
normal_result = getattr(normal_grouped, func)()
dt_result = getattr(dt_grouped, func)()
pad = DataFrame([[np.nan, np.nan, np.nan, np.nan]],
index=[3], columns=['A', 'B', 'C', 'D'])
expected = normal_result.append(pad)
expected = expected.sort_index()
expected.index = date_range(start='2013-01-01', freq='D', periods=5, name='key')
assert_frame_equal(expected, dt_result)
for func in ['count']:
normal_result = getattr(normal_grouped, func)()
pad = DataFrame([[0, 0, 0, 0]], index=[3], columns=['A', 'B', 'C', 'D'])
expected = normal_result.append(pad)
expected = expected.sort_index()
expected.index = date_range(start='2013-01-01', freq='D', periods=5, name='key')
dt_result = getattr(dt_grouped, func)()
assert_frame_equal(expected, dt_result)
for func in ['size']:
normal_result = getattr(normal_grouped, func)()
pad = Series([0], index=[3])
expected = normal_result.append(pad)
expected = expected.sort_index()
expected.index = date_range(start='2013-01-01', freq='D', periods=5, name='key')
dt_result = getattr(dt_grouped, func)()
assert_series_equal(expected, dt_result)
# GH 9925
self.assertEqual(dt_result.index.name, 'key')
# if NaT is included, 'var', 'std', 'mean', 'first','last' and 'nth' doesn't work yet | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def __init__(self, mode, was, now):
self.mode = mode
self.was = was
self.now = now | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def IsCopyright(change):
if len(change.now) != 1 or len(change.was) != 1: return False
if 'Copyright (c)' not in change.now[0]: return False
if 'Copyright (c)' not in change.was[0]: return False
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def IsBlankComment(change):
if change.now: return False
if len(change.was) != 1: return False
if change.was[0].strip() != '*': return False
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def IsBlank(change):
for line in change.now:
if line: return False
for line in change.was:
if line: return False
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def IsToCppComment(change):
if not len(change.now) or len(change.now) != len(change.was):
return False
for index in range(len(change.now)):
was = change.was[index].strip()
if was[:2] != '//':
return False
was = was[2:].strip()
now = change.now[index].strip()
if now[:2] != '/*':
return False
now = now[2:-2].strip()
if now != was:
return False
return True
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def IsSpacing(change):
if len(change.now) != len(change.was): return False
for i in range(len(change.now)):
# Also ignore right side comments
line = change.was[i]
offs = line.find('//')
if offs == -1:
offs = line.find('/*')
if offs >-1:
line = line[:offs-1]
words1 = change.now[i].split()
words2 = line.split()
if words1 != words2: return False
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def IsInclude(change):
for line in change.was:
if line.strip().find('struct'): return False
for line in change.now:
if line and '#include' not in line: return False
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def IsCppComment(change):
if len(change.now): return False
for line in change.was:
line = line.strip()
if line[:2] != '//': return False
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def ValidChange(change):
if IsToCppComment(change): return False
if IsCopyright(change): return False
if IsBlankComment(change): return False
if IsMergeComment(change): return False
if IsBlank(change): return False
if IsSpacing(change): return False
if IsInclude(change): return False
if IsCppComment(change): return False
return True | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def Swapped(last, next):
if not last.now and not next.was and len(last.was) == len(next.now):
cnt = len(last.was)
for i in range(cnt):
match = True
for j in range(cnt):
if last.was[j] != next.now[(i + j) % cnt]:
match = False
break;
if match: return True
if not last.was and not next.now and len(last.now) == len(next.was):
cnt = len(last.now)
for i in range(cnt):
match = True
for j in range(cnt):
if last.now[i] != next.was[(i + j) % cnt]:
match = False
break;
if match: return True
return False | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def GetChanges(output):
# Split on lines, adding an END marker to simply add logic
lines = output.split('\n')
lines = FilterLinesIn(lines)
lines.append('END')
changes = []
was = []
now = []
mode = ''
last = None
for line in lines:
#print("LINE=%s" % line)
if not line: continue
elif line[0] == '<':
if line[2:].strip() == '': continue
# Ignore prototypes
if len(line) > 10:
words = line[2:].split()
if len(words) == 2 and words[1][-1] == ';':
if words[0] == 'struct' or words[0] == 'union':
continue
was.append(line[2:])
elif line[0] == '>':
if line[2:].strip() == '': continue
if line[2:10] == '#include': continue
now.append(line[2:])
elif line[0] == '-':
continue
else:
change = Change(line, was, now)
was = []
now = []
if ValidChange(change):
changes.append(change)
if line == 'END':
break
return FilterChanges(changes) | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def Main(args):
filenames = ParseOptions(args)
if not filenames:
gendir = os.path.join(GetOption('gen'), '*.h')
filenames = sorted(glob.glob(gendir))
srcdir = os.path.join(GetOption('src'), '*.h')
srcs = sorted(glob.glob(srcdir))
for name in srcs:
name = os.path.split(name)[1]
name = os.path.join(GetOption('gen'), name)
if name not in filenames:
print('Missing: %s' % name)
for filename in filenames:
gen = filename
filename = filename[len(GetOption('gen')) + 1:]
src = os.path.join(GetOption('src'), filename)
diff = os.path.join(GetOption('diff'), filename)
p = subprocess.Popen(['diff', src, gen], stdout=subprocess.PIPE)
output, errors = p.communicate()
try:
input = open(diff, 'rt').read()
except:
input = ''
if input != output:
changes = GetChanges(output)
else:
changes = []
if changes:
print("\n\nDelta between:\n src=%s\n gen=%s\n" % (src, gen))
for change in changes:
change.Dump()
print('Done with %s\n\n' % src)
if GetOption('ok'):
open(diff, 'wt').write(output)
if GetOption('halt'):
return 1
else:
print("\nSAME:\n src=%s\n gen=%s" % (src, gen))
if input:
print(' ** Matched expected diff. **')
print('\n') | chromium/chromium | [
14247,
5365,
14247,
62,
1517864132
] |
def __init__(self,
opt,
staleness,
use_locking=False,
name="DropStaleGradient"):
"""Constructs a new DropStaleGradientOptimizer.
Args:
opt: The actual optimizer that will be used to compute and apply the
gradients. Must be one of the Optimizer classes.
staleness: The maximum staleness allowed for the optimizer.
use_locking: If `True` use locks for clip update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "DropStaleGradient".
"""
super(DropStaleGradientOptimizer, self).__init__(use_locking, name)
self._opt = opt
self._staleness = staleness | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def get_slot(self, *args, **kwargs):
return self._opt.get_slot(*args, **kwargs) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _GetGradSource(op_or_tensor):
"""Identify which call to tf.gradients created this gradient op or tensor.
TensorArray gradient calls use an accumulator TensorArray object. If
multiple gradients are calculated and run in the same session, the multiple
gradient nodes may accidentally flow throuth the same accumulator TensorArray.
This double counting breaks the TensorArray gradient flow.
The solution is to identify which gradient call this particular
TensorArray*Grad is being called in, by looking at the input gradient
tensor's name, and create or lookup an accumulator gradient TensorArray
associated with this specific call. This solves any confusion and ensures
different gradients from the same forward graph get their own accumulators.
This function creates the unique label associated with the tf.gradients call
that is used to create the gradient TensorArray.
Args:
op_or_tensor: `Tensor` or `Operation` which is an input to a
TensorArray*Grad call.
Returns:
A python string, the unique label associated with this particular
gradients calculation.
Raises:
ValueError: If not called within a gradients calculation.
"""
name_tokens = op_or_tensor.name.split("/")
grad_pos = [i for i, x in enumerate(name_tokens) if x.startswith("gradients")]
if not grad_pos:
raise ValueError(
"Expected op/tensor name to start with gradients (excluding scope)"
", got: %s" % op_or_tensor.name)
return "/".join(name_tokens[:grad_pos[-1] + 1]) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _TensorArrayReadGrad(op, grad):
"""Gradient for TensorArrayRead.
Args:
op: Forward TensorArrayRead op.
grad: Gradient `Tensor` to TensorArrayRead.
Returns:
A flow `Tensor`, which can be used in control dependencies to
force the write of `grad` to the gradient `TensorArray`.
"""
# Note: the forward flow dependency in the call to grad() is necessary for
# the case of dynamic sized TensorArrays. When creating the gradient
# TensorArray, the final size of the forward array must be known.
# For this we need to wait until it has been created by depending on
# the input flow of the original op.
handle = op.inputs[0]
index = op.inputs[1]
flow = op.inputs[2]
dtype = op.get_attr("dtype")
grad_source = _GetGradSource(grad)
g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow,
colocate_with_first_write_call=False)
.grad(source=grad_source, flow=flow))
w_g = g.write(index, grad)
return [None, None, w_g.flow] | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _TensorArrayWriteGrad(op, flow):
"""Gradient for TensorArrayWrite.
Args:
op: Forward TensorArrayWrite op.
flow: Gradient `Tensor` flow to TensorArrayWrite.
Returns:
A grad `Tensor`, the gradient created in an upstream ReadGrad or PackGrad.
"""
# handle is the output store_handle of TensorArrayReadGrad or
# the handle output of TensorArrayWriteGrad. we must use this one.
handle = op.inputs[0]
index = op.inputs[1]
dtype = op.get_attr("T")
grad_source = _GetGradSource(flow)
g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow,
colocate_with_first_write_call=False)
.grad(source=grad_source, flow=flow))
grad = g.read(index)
return [None, None, grad, flow] | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _TensorArrayGatherGrad(op, grad):
"""Gradient for TensorArrayGather.
Args:
op: Forward TensorArrayGather op.
grad: Gradient `Tensor` to TensorArrayGather.
Returns:
A flow `Tensor`, which can be used in control dependencies to
force the write of `grad` to the gradient `TensorArray`.
"""
# Note: the forward flow dependency in the call to grad() is necessary for
# the case of dynamic sized TensorArrays. When creating the gradient
# TensorArray, the final size of the forward array must be known.
# For this we need to wait until it has been created by depending on
# the input flow of the original op.
handle = op.inputs[0]
indices = op.inputs[1]
flow = op.inputs[2]
dtype = op.get_attr("dtype")
grad_source = _GetGradSource(grad)
g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow,
colocate_with_first_write_call=False)
.grad(source=grad_source, flow=flow))
u_g = g.scatter(indices, grad)
return [None, None, u_g.flow] | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _TensorArrayScatterGrad(op, flow):
"""Gradient for TensorArrayScatter.
Args:
op: Forward TensorArrayScatter op.
flow: Gradient `Tensor` flow to TensorArrayScatter.
Returns:
A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad.
"""
handle = op.inputs[0]
indices = op.inputs[1]
dtype = op.get_attr("T")
grad_source = _GetGradSource(flow)
g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow,
colocate_with_first_write_call=False)
.grad(source=grad_source, flow=flow))
grad = g.gather(indices)
return [None, None, grad, flow] | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _TensorArrayConcatGrad(op, grad, unused_lengths_grad):
"""Gradient for TensorArrayConcat.
Args:
op: Forward TensorArrayConcat op.
grad: Gradient `Tensor` to TensorArrayConcat.
Returns:
A flow `Tensor`, which can be used in control dependencies to
force the write of `grad` to the gradient `TensorArray`.
"""
# Note: the forward flow dependency in the call to grad() is necessary for
# the case of dynamic sized TensorArrays. When creating the gradient
# TensorArray, the final size of the forward array must be known.
# For this we need to wait until it has been created by depending on
# the input flow of the original op.
handle = op.inputs[0]
flow = op.inputs[1]
lengths = op.outputs[1]
dtype = op.get_attr("dtype")
grad_source = _GetGradSource(grad)
g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow,
colocate_with_first_write_call=False)
.grad(source=grad_source, flow=flow))
u_g = g.split(grad, lengths=lengths)
# handle, flow_in
return [None, u_g.flow] | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def setUp(self):
self._msg = array_ops.placeholder(dtype=dtypes.string)
self._encoded_f = string_ops.encode_base64(self._msg, pad=False)
self._decoded_f = string_ops.decode_base64(self._encoded_f)
self._encoded_t = string_ops.encode_base64(self._msg, pad=True)
self._decoded_t = string_ops.decode_base64(self._encoded_t) | npuichigo/ttsflow | [
16,
6,
16,
1,
1500635633
] |
def _RunTest(self, msg, pad):
with self.test_session() as sess:
if pad:
encoded, decoded = sess.run([self._encoded_t, self._decoded_t],
feed_dict={self._msg: msg})
else:
encoded, decoded = sess.run([self._encoded_f, self._decoded_f],
feed_dict={self._msg: msg})
if not isinstance(msg, (list, tuple)):
msg = [msg]
encoded = [encoded]
decoded = [decoded]
base64_msg = [base64.urlsafe_b64encode(m) for m in msg]
if not pad:
base64_msg = [self._RemovePad(m, b) for m, b in zip(msg, base64_msg)]
for i in range(len(msg)):
self.assertEqual(base64_msg[i], encoded[i])
self.assertEqual(msg[i], decoded[i]) | npuichigo/ttsflow | [
16,
6,
16,
1,
1500635633
] |
def testShape(self):
for pad in (False, True):
for _ in range(10):
msg = [np.random.bytes(np.random.randint(20))
for _ in range(np.random.randint(10))]
self._RunTest(msg, pad=pad)
# Zero-element, non-trivial shapes.
for _ in range(10):
k = np.random.randint(10)
msg = np.empty((0, k), dtype=bytes)
encoded = string_ops.encode_base64(msg, pad=pad)
decoded = string_ops.decode_base64(encoded)
with self.test_session() as sess:
encoded_value, decoded_value = sess.run([encoded, decoded])
self.assertEqual(encoded_value.shape, msg.shape)
self.assertEqual(decoded_value.shape, msg.shape) | npuichigo/ttsflow | [
16,
6,
16,
1,
1500635633
] |
def try_decode(enc):
self._decoded_f.eval(feed_dict={self._encoded_f: enc}) | npuichigo/ttsflow | [
16,
6,
16,
1,
1500635633
] |
def setUp(self):
self.params = tensor_forest.ForestHParams(
num_classes=2,
num_features=31,
layer_size=11,
num_layers=13,
num_trees=17,
connection_probability=0.1,
hybrid_tree_depth=4,
regularization_strength=0.01,
regularization="",
learning_rate=0.01,
weight_init_mean=0.0,
weight_init_std=0.1)
self.params.regression = False
self.params.num_nodes = 2**self.params.hybrid_tree_depth - 1
self.params.num_leaves = 2**(self.params.hybrid_tree_depth - 1)
# pylint: disable=W0612
self.input_data = constant_op.constant(
[[random.uniform(-1, 1) for i in range(self.params.num_features)]
for _ in range(100)]) | npuichigo/ttsflow | [
16,
6,
16,
1,
1500635633
] |
def __init__(self, pattern):
self.pattern = pattern | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def match(self):
return True | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def _getters(cls):
return {} | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def _getters(cls):
return {'aComputedField': (lambda s: 'thing')} | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def setUpClass(cls):
handle, cls.orig_libfile = mkstemp('orig_db')
os.close(handle)
# Set up a database with the two-field schema.
old_lib = DatabaseFixture2(cls.orig_libfile)
# Add an item to the old library.
old_lib._connection().execute(
'insert into test (field_one, field_two) values (4, 2)'
)
old_lib._connection().commit()
del old_lib | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def tearDownClass(cls):
os.remove(cls.orig_libfile) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def tearDown(self):
os.remove(self.libfile) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_open_with_new_field_adds_column(self):
new_lib = DatabaseFixture3(self.libfile)
c = new_lib._connection().cursor()
c.execute("select * from test")
row = c.fetchone()
self.assertEqual(len(row.keys()), len(ModelFixture3._fields)) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_open_with_multiple_new_fields(self):
new_lib = DatabaseFixture4(self.libfile)
c = new_lib._connection().cursor()
c.execute("select * from test")
row = c.fetchone()
self.assertEqual(len(row.keys()), len(ModelFixture4._fields)) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def setUp(self):
self.db = DatabaseFixture1(':memory:') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_mutate_increase_revision(self):
old_rev = self.db.revision
with self.db.transaction() as tx:
tx.mutate(
'INSERT INTO {} '
'(field_one) '
'VALUES (?);'.format(ModelFixture1._table),
(111,),
)
self.assertGreater(self.db.revision, old_rev) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def setUp(self):
self.db = DatabaseFixture1(':memory:') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_add_model(self):
model = ModelFixture1()
model.add(self.db)
rows = self.db._connection().execute('select * from test').fetchall()
self.assertEqual(len(rows), 1) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_revision(self):
old_rev = self.db.revision
model = ModelFixture1()
model.add(self.db)
model.store()
self.assertEqual(model._revision, self.db.revision)
self.assertGreater(self.db.revision, old_rev)
mid_rev = self.db.revision
model2 = ModelFixture1()
model2.add(self.db)
model2.store()
self.assertGreater(model2._revision, mid_rev)
self.assertGreater(self.db.revision, model._revision)
# revision changed, so the model should be re-loaded
model.load()
self.assertEqual(model._revision, self.db.revision)
# revision did not change, so no reload
mod2_old_rev = model2._revision
model2.load()
self.assertEqual(model2._revision, mod2_old_rev) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_store_and_retrieve_flexattr(self):
model = ModelFixture1()
model.add(self.db)
model.foo = 'bar'
model.store()
other_model = self.db._get(ModelFixture1, model.id)
self.assertEqual(other_model.foo, 'bar') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_delete_flexattr_via_dot(self):
model = ModelFixture1()
model['foo'] = 'bar'
self.assertTrue('foo' in model)
del model.foo
self.assertFalse('foo' in model) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_delete_non_existent_attribute(self):
model = ModelFixture1()
with self.assertRaises(KeyError):
del model['foo'] | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_null_value_normalization_by_type(self):
model = ModelFixture1()
model.field_one = None
self.assertEqual(model.field_one, 0) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_normalization_for_typed_flex_fields(self):
model = ModelFixture1()
model.some_float_field = None
self.assertEqual(model.some_float_field, 0.0) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_check_db_fails(self):
with self.assertRaisesRegex(ValueError, 'no database'):
dbcore.Model()._check_db()
with self.assertRaisesRegex(ValueError, 'no id'):
ModelFixture1(self.db)._check_db()
dbcore.Model(self.db)._check_db(need_id=False) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_computed_field(self):
model = ModelFixtureWithGetters()
self.assertEqual(model.aComputedField, 'thing')
with self.assertRaisesRegex(KeyError, 'computed field .+ deleted'):
del model.aComputedField | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_delete_internal_field(self):
model = dbcore.Model()
del model._db
with self.assertRaises(AttributeError):
model._db | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_format_fixed_field_integer(self):
model = ModelFixture1()
model.field_one = 155
value = model.formatted().get('field_one')
self.assertEqual(value, '155') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_format_fixed_field_string(self):
model = ModelFixture1()
model.field_two = 'caf\xe9'
value = model.formatted().get('field_two')
self.assertEqual(value, 'caf\xe9') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_format_flex_field_bytes(self):
model = ModelFixture1()
model.other_field = 'caf\xe9'.encode()
value = model.formatted().get('other_field')
self.assertTrue(isinstance(value, str))
self.assertEqual(value, 'caf\xe9') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_format_typed_flex_field(self):
model = ModelFixture1()
model.some_float_field = 3.14159265358979
value = model.formatted().get('some_float_field')
self.assertEqual(value, '3.1') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_keys_equal_model_keys(self):
model = ModelFixture1()
formatted = model.formatted()
self.assertEqual(set(model.keys(True)), set(formatted.keys())) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_get_method_with_default(self):
model = ModelFixture1()
formatted = model.formatted()
self.assertEqual(formatted.get('other_field'), '') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_parse_fixed_field(self):
value = ModelFixture1._parse('field_one', '2')
self.assertIsInstance(value, int)
self.assertEqual(value, 2) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_parse_untyped_field(self):
value = ModelFixture1._parse('field_nine', '2')
self.assertEqual(value, '2') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def pqp(self, part):
return dbcore.queryparse.parse_query_part(
part,
{'year': dbcore.query.NumericQuery},
{':': dbcore.query.RegexpQuery},
)[:-1] # remove the negate flag | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_one_keyed_term(self):
q = 'test:val'
r = ('test', 'val', dbcore.query.SubstringQuery)
self.assertEqual(self.pqp(q), r) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_one_basic_regexp(self):
q = r':regexp'
r = (None, 'regexp', dbcore.query.RegexpQuery)
self.assertEqual(self.pqp(q), r) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_escaped_colon(self):
q = r'test\:val'
r = (None, 'test:val', dbcore.query.SubstringQuery)
self.assertEqual(self.pqp(q), r) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_single_year(self):
q = 'year:1999'
r = ('year', '1999', dbcore.query.NumericQuery)
self.assertEqual(self.pqp(q), r) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_empty_query_part(self):
q = ''
r = (None, '', dbcore.query.SubstringQuery)
self.assertEqual(self.pqp(q), r) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def qfs(self, strings):
return dbcore.queryparse.query_from_strings(
dbcore.query.AndQuery,
ModelFixture1,
{':': dbcore.query.RegexpQuery},
strings,
) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_two_parts(self):
q = self.qfs(['foo', 'bar:baz'])
self.assertIsInstance(q, dbcore.query.AndQuery)
self.assertEqual(len(q.subqueries), 2)
self.assertIsInstance(q.subqueries[0], dbcore.query.AnyFieldQuery)
self.assertIsInstance(q.subqueries[1], dbcore.query.SubstringQuery) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_parse_flex_type_query(self):
q = self.qfs(['some_float_field:2..3'])
self.assertIsInstance(q.subqueries[0], dbcore.query.NumericQuery) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_parse_named_query(self):
q = self.qfs(['some_query:foo'])
self.assertIsInstance(q.subqueries[0], QueryFixture) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def sfs(self, strings):
return dbcore.queryparse.sort_from_strings(
ModelFixture1,
strings,
) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_one_parts(self):
s = self.sfs(['field+'])
self.assertIsInstance(s, dbcore.query.Sort) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_fixed_field_sort(self):
s = self.sfs(['field_one+'])
self.assertIsInstance(s, dbcore.query.FixedFieldSort)
self.assertEqual(s, dbcore.query.FixedFieldSort('field_one')) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_special_sort(self):
s = self.sfs(['some_sort+'])
self.assertIsInstance(s, SortFixture) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def psq(self, parts):
return dbcore.parse_sorted_query(
ModelFixture1,
parts.split(),
) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_or_query(self):
q, s = self.psq('foo , bar')
self.assertIsInstance(q, dbcore.query.OrQuery)
self.assertIsInstance(s, dbcore.query.NullSort)
self.assertEqual(len(q.subqueries), 2) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_no_spaces_or_query(self):
q, s = self.psq('foo,bar')
self.assertIsInstance(q, dbcore.query.AndQuery)
self.assertIsInstance(s, dbcore.query.NullSort)
self.assertEqual(len(q.subqueries), 1) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_leading_comma_or_query(self):
q, s = self.psq(', foo , bar')
self.assertIsInstance(q, dbcore.query.OrQuery)
self.assertIsInstance(s, dbcore.query.NullSort)
self.assertEqual(len(q.subqueries), 3) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def setUp(self):
self.db = DatabaseFixture1(':memory:')
model = ModelFixture1()
model['foo'] = 'baz'
model.add(self.db)
model = ModelFixture1()
model['foo'] = 'bar'
model.add(self.db) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_iterate_once(self):
objs = self.db._fetch(ModelFixture1)
self.assertEqual(len(list(objs)), 2) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_concurrent_iterators(self):
results = self.db._fetch(ModelFixture1)
it1 = iter(results)
it2 = iter(results)
next(it1)
list(it2)
self.assertEqual(len(list(it1)), 1) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_slow_query_negative(self):
q = dbcore.query.SubstringQuery('foo', 'qux', False)
objs = self.db._fetch(ModelFixture1, q)
self.assertEqual(len(list(objs)), 0) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_unsorted_subscript(self):
objs = self.db._fetch(ModelFixture1)
self.assertEqual(objs[0].foo, 'baz')
self.assertEqual(objs[1].foo, 'bar') | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_length(self):
objs = self.db._fetch(ModelFixture1)
self.assertEqual(len(objs), 2) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def test_no_results(self):
self.assertIsNone(self.db._fetch(
ModelFixture1, dbcore.query.FalseQuery()).get()) | beetbox/beets | [
11484,
1774,
11484,
509,
1281395840
] |
def fn():
try:
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(fd)
ch = sys.stdin.read(1)
except:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
raise Exception
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def __init__(self, header = 'LittleCoder', symbol = '>', inPip = None, inputMaintain = False):
self.strBuff = []
self.cmdBuff = []
self.historyCmd = -1
self.cursor = 0
self.inPip = [] if inPip == None else inPip
self.outPip = []
self.isLaunch = False
self.isPause = False
self.header = header
self.symbol = symbol
self.inputMaintain = inputMaintain | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def getch(self):
c = getch()
return c if c != '\r' else '\n' | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def output_command(self, s):
self.outPip.append(s if isinstance(s, unicode) else s.decode(sys.stdin.encoding))
if len(self.cmdBuff) >= CMD_HISTORY: self.cmdBuff = self.cmdBuff[::-1].pop()[::-1]
self.cmdBuff.append(s) | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def fast_input_test(self):
timer = threading.Timer(0.001, thread.interrupt_main)
c = None
try:
timer.start()
c = getch()
except:
pass
timer.cancel()
return c | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def process_char(self, c):
if ord(c) == 27: # Esc
if OS == 'Linux':
fitc1 = self.fast_input_test()
if ord(fitc1) == 91:
fitc2 = self.fast_input_test()
if 65 <= ord(fitc2) <= 68:
self.process_direction_char(fitc2)
return
sys.stdout.write('\r' + ' ' * 50 + '\r')
sys.stdout.flush()
self.reprint_input()
self.outPip.append(c)
time.sleep(0.02)
if 'fitc1' in dir():
self.process_char(fitc1)
self.cursor += 1
if 'fitc2' in dir():
self.process_char(fitc2)
self.cursor += 1
elif ord(c) == 3: # Ctrl+C
self.stop()
self.isPause = True
if raw_input('Exit?(y) ') == 'y':
sys.stdout.write('Command Line Exit')
else:
self.start()
self.isPause = False
elif ord(c) in (8, 127): # Backspace
if self.strBuff:
if ord(self.strBuff[-1]) < 128:
sys.stdout.write('\b \b')
else:
sys.stdout.write('\b\b \b')
if OS == 'Linux':
self.strBuff.pop()
self.strBuff.pop()
self.strBuff.pop()
self.cursor -= 1
elif c == '\n':
if self.strBuff:
if self.inputMaintain:
sys.stdout.write(c)
else:
sys.stdout.write('\r' + ' ' * 50 + '\r')
sys.stdout.flush()
self.reprint_input()
self.output_command(''.join(self.strBuff))
self.strBuff = []
self.historyCmd = -1
elif ord(c) == 224: # Windows direction
if OS == 'Windows':
direction = self.getch()
self.process_direction_char(direction)
else:
sys.stdout.write(c)
sys.stdout.flush()
self.strBuff.append(c)
self.cursor += 1 | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def start(self):
self.isLaunch = True
thread.start_new_thread(self.print_thread, ())
self.reprint_input()
thread.start_new_thread(self.command_thread, ()) | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def print_line(self, msg = None):
self.inPip.append(msg) | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def get_command_pip(self):
return self.outPip | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def loopinput(c):
while True:
c.print_line('LOOP INPUT......')
time.sleep(3) | littlecodersh/EasierLife | [
181,
138,
181,
1,
1453081737
] |
def __init__(
self, plotly_name="arrayminussrc", parent_name="bar.error_x", **kwargs | plotly/plotly.py | [
13052,
2308,
13052,
1319,
1385013188
] |
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"] | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
def color(self, val):
self["color"] = val | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for color . | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.