Unnamed: 0
int64 0
2.44k
| repo
stringlengths 32
81
| hash
stringlengths 40
40
| diff
stringlengths 113
1.17k
| old_path
stringlengths 5
84
| rewrite
stringlengths 34
79
| initial_state
stringlengths 75
980
| final_state
stringlengths 76
980
|
---|---|---|---|---|---|---|---|
0 | https://:@github.com/emedvedev/attention-ocr.git | 291042e7cb623c8a908e9badd132c1fa2360288c | @@ -465,7 +465,7 @@ class Model(object):
mh = 32
mw = math.floor(1. * w / h * mh)
img = img.resize(
- (mw, h),
+ (mw, mh),
Image.ANTIALIAS)
img_data = np.asarray(img, dtype=np.uint8)
for idx in xrange(len(output)):
| aocr/model/model.py | ReplaceText(target='mh' @(468,25)->(468,26)) | class Model(object):
mh = 32
mw = math.floor(1. * w / h * mh)
img = img.resize(
(mw, h),
Image.ANTIALIAS)
img_data = np.asarray(img, dtype=np.uint8)
for idx in xrange(len(output)): | class Model(object):
mh = 32
mw = math.floor(1. * w / h * mh)
img = img.resize(
(mw, mh),
Image.ANTIALIAS)
img_data = np.asarray(img, dtype=np.uint8)
for idx in xrange(len(output)): |
1 | https://:@github.com/emedvedev/attention-ocr.git | 6e6593c27fe0e63118adadf11562b1c4699b14e3 | @@ -477,7 +477,7 @@ class Model(object):
attention_orig[i] = attention[int(i/4)-1]
attention_orig = np.convolve(attention_orig, [0.199547, 0.200226, 0.200454, 0.200226, 0.199547], mode='same')
attention_orig = np.maximum(attention_orig, 0.3)
- attention_out = np.zeros((h, mw))
+ attention_out = np.zeros((mh, mw))
for i in xrange(mw):
attention_out[:, i] = attention_orig[i]
if len(img_data.shape) == 3:
| aocr/model/model.py | ReplaceText(target='mh' @(480,42)->(480,43)) | class Model(object):
attention_orig[i] = attention[int(i/4)-1]
attention_orig = np.convolve(attention_orig, [0.199547, 0.200226, 0.200454, 0.200226, 0.199547], mode='same')
attention_orig = np.maximum(attention_orig, 0.3)
attention_out = np.zeros((h, mw))
for i in xrange(mw):
attention_out[:, i] = attention_orig[i]
if len(img_data.shape) == 3: | class Model(object):
attention_orig[i] = attention[int(i/4)-1]
attention_orig = np.convolve(attention_orig, [0.199547, 0.200226, 0.200454, 0.200226, 0.199547], mode='same')
attention_orig = np.maximum(attention_orig, 0.3)
attention_out = np.zeros((mh, mw))
for i in xrange(mw):
attention_out[:, i] = attention_orig[i]
if len(img_data.shape) == 3: |
2 | https://:@github.com/emedvedev/attention-ocr.git | e741baf7170e72a974754908d323cacc0bd55247 | @@ -133,7 +133,7 @@ class Model(object):
self.target_weights = []
for i in xrange(self.decoder_size + 1):
self.decoder_inputs.append(
- tf.tile([0], [num_images])
+ tf.tile([1], [num_images])
)
if i < self.decoder_size:
self.target_weights.append(tf.tile([1.], [num_images]))
| aocr/model/model.py | ReplaceText(target='1' @(136,29)->(136,30)) | class Model(object):
self.target_weights = []
for i in xrange(self.decoder_size + 1):
self.decoder_inputs.append(
tf.tile([0], [num_images])
)
if i < self.decoder_size:
self.target_weights.append(tf.tile([1.], [num_images])) | class Model(object):
self.target_weights = []
for i in xrange(self.decoder_size + 1):
self.decoder_inputs.append(
tf.tile([1], [num_images])
)
if i < self.decoder_size:
self.target_weights.append(tf.tile([1.], [num_images])) |
3 | https://:@github.com/matthewdowney/TogglPy.git | d5b630aec58d29b85ccffa527d24766eef6f61f9 | @@ -197,7 +197,7 @@ class Toggl():
day = datetime.now().day if not day else day
hour = datetime.now().hour if not hour else hour
- timestruct = datetime(year, month, day, hour - hourdiff).isoformat() + '.000Z'
+ timestruct = datetime(year, month, day, hour + hourdiff).isoformat() + '.000Z'
data['time_entry']['start'] = timestruct
data['time_entry']['duration'] = hourduration * 3600
data['time_entry']['pid'] = projectid
| toggl/TogglPy.py | ReplaceText(target='+' @(200,53)->(200,54)) | class Toggl():
day = datetime.now().day if not day else day
hour = datetime.now().hour if not hour else hour
timestruct = datetime(year, month, day, hour - hourdiff).isoformat() + '.000Z'
data['time_entry']['start'] = timestruct
data['time_entry']['duration'] = hourduration * 3600
data['time_entry']['pid'] = projectid | class Toggl():
day = datetime.now().day if not day else day
hour = datetime.now().hour if not hour else hour
timestruct = datetime(year, month, day, hour + hourdiff).isoformat() + '.000Z'
data['time_entry']['start'] = timestruct
data['time_entry']['duration'] = hourduration * 3600
data['time_entry']['pid'] = projectid |
4 | https://:@github.com/eEcoLiDAR/eEcoLiDAR.git | f0b2a0b7a5fdd41887ba40b7687c8161c0faba1e | @@ -28,6 +28,6 @@ class Test3FeatureExtractor(AbstractFeatureExtractor):
return ['test3_a']
def extract(self, sourcepc, neighborhood, targetpc, targetindex, volume):
- t2a, t2c = utils.get_features(targetpc, targetindex, self.requires())
+ t2a, t2c = utils.get_features(targetpc, self.requires(), targetindex)
x, y, z = utils.get_point(targetpc, targetindex)
return t2c - t2a - z # z
| laserchicken/test_feature_extractor/feature_test23.py | ArgSwap(idxs=1<->2 @(31,19)->(31,37)) | class Test3FeatureExtractor(AbstractFeatureExtractor):
return ['test3_a']
def extract(self, sourcepc, neighborhood, targetpc, targetindex, volume):
t2a, t2c = utils.get_features(targetpc, targetindex, self.requires())
x, y, z = utils.get_point(targetpc, targetindex)
return t2c - t2a - z # z | class Test3FeatureExtractor(AbstractFeatureExtractor):
return ['test3_a']
def extract(self, sourcepc, neighborhood, targetpc, targetindex, volume):
t2a, t2c = utils.get_features(targetpc, self.requires(), targetindex)
x, y, z = utils.get_point(targetpc, targetindex)
return t2c - t2a - z # z |
5 | https://:@github.com/eEcoLiDAR/eEcoLiDAR.git | f0b2a0b7a5fdd41887ba40b7687c8161c0faba1e | @@ -31,7 +31,7 @@ class TestUtils(unittest.TestCase):
pc[keys.point]["color"] = {"type": "double", "data": cols}
pc[keys.point]["flavor"] = {"type": "double", "data": flavs}
x, y, z = utils.get_point(pc, 2)
- c, f = utils.get_features(pc, 2, ("color", "flavor"))
+ c, f = utils.get_features(pc, ("color", "flavor"), 2)
self.assertEqual(c, 0.5 * (x + y))
self.assertEqual(f, 0.5 * (x - y))
| laserchicken/test_utils.py | ArgSwap(idxs=1<->2 @(34,15)->(34,33)) | class TestUtils(unittest.TestCase):
pc[keys.point]["color"] = {"type": "double", "data": cols}
pc[keys.point]["flavor"] = {"type": "double", "data": flavs}
x, y, z = utils.get_point(pc, 2)
c, f = utils.get_features(pc, 2, ("color", "flavor"))
self.assertEqual(c, 0.5 * (x + y))
self.assertEqual(f, 0.5 * (x - y))
| class TestUtils(unittest.TestCase):
pc[keys.point]["color"] = {"type": "double", "data": cols}
pc[keys.point]["flavor"] = {"type": "double", "data": flavs}
x, y, z = utils.get_point(pc, 2)
c, f = utils.get_features(pc, ("color", "flavor"), 2)
self.assertEqual(c, 0.5 * (x + y))
self.assertEqual(f, 0.5 * (x - y))
|
6 | https://:@github.com/eEcoLiDAR/eEcoLiDAR.git | 502a365efda1393b130281803702d01f7e2d1dcd | @@ -29,7 +29,7 @@ class TestExtractEigenValues(unittest.TestCase):
["eigenv_1", "eigenv_2", "eigenv_3"], InfiniteCylinder(5))
self.assertEqual("laserchicken.feature_extractor.eigenvals_feature_extractor",
- target_point_cloud[keys.provenance][0]["module"])
+ target_point_cloud[keys.provenance][1]["module"])
@staticmethod
def test_eigenvalues_of_too_few_points_results_in_0():
| laserchicken/feature_extractor/test_eigenvals_feature_extractor.py | ReplaceText(target='1' @(32,61)->(32,62)) | class TestExtractEigenValues(unittest.TestCase):
["eigenv_1", "eigenv_2", "eigenv_3"], InfiniteCylinder(5))
self.assertEqual("laserchicken.feature_extractor.eigenvals_feature_extractor",
target_point_cloud[keys.provenance][0]["module"])
@staticmethod
def test_eigenvalues_of_too_few_points_results_in_0(): | class TestExtractEigenValues(unittest.TestCase):
["eigenv_1", "eigenv_2", "eigenv_3"], InfiniteCylinder(5))
self.assertEqual("laserchicken.feature_extractor.eigenvals_feature_extractor",
target_point_cloud[keys.provenance][1]["module"])
@staticmethod
def test_eigenvalues_of_too_few_points_results_in_0(): |
7 | https://:@github.com/eEcoLiDAR/eEcoLiDAR.git | eb7b021147a60b57e5dec536bd6f118c213f0952 | @@ -29,7 +29,7 @@ class TestExtractEigenValues(unittest.TestCase):
["eigenv_1", "eigenv_2", "eigenv_3"], InfiniteCylinder(5))
self.assertEqual("laserchicken.feature_extractor.eigenvals_feature_extractor",
- target_point_cloud[keys.provenance][1]["module"])
+ target_point_cloud[keys.provenance][-1]["module"])
@staticmethod
def test_eigenvalues_of_too_few_points_results_in_0():
| laserchicken/feature_extractor/test_eigenvals_feature_extractor.py | ReplaceText(target='-1' @(32,61)->(32,62)) | class TestExtractEigenValues(unittest.TestCase):
["eigenv_1", "eigenv_2", "eigenv_3"], InfiniteCylinder(5))
self.assertEqual("laserchicken.feature_extractor.eigenvals_feature_extractor",
target_point_cloud[keys.provenance][1]["module"])
@staticmethod
def test_eigenvalues_of_too_few_points_results_in_0(): | class TestExtractEigenValues(unittest.TestCase):
["eigenv_1", "eigenv_2", "eigenv_3"], InfiniteCylinder(5))
self.assertEqual("laserchicken.feature_extractor.eigenvals_feature_extractor",
target_point_cloud[keys.provenance][-1]["module"])
@staticmethod
def test_eigenvalues_of_too_few_points_results_in_0(): |
8 | https://:@github.com/VinF/deer.git | 66ea41db02c3361f18874dea7fd97720b1b06590 | @@ -441,7 +441,7 @@ class CircularBuffer(object):
if end == sys.maxsize:
return self._data[self._lb+start:self._ub]
- elif self._lb + end >= self._ub:
+ elif self._lb + end > self._ub:
raise IndexError()
else:
return self._data[self._lb+start:self._lb+end]
| General_Deep_Q_RL/agent.py | ReplaceText(target='>' @(444,28)->(444,30)) | class CircularBuffer(object):
if end == sys.maxsize:
return self._data[self._lb+start:self._ub]
elif self._lb + end >= self._ub:
raise IndexError()
else:
return self._data[self._lb+start:self._lb+end] | class CircularBuffer(object):
if end == sys.maxsize:
return self._data[self._lb+start:self._ub]
elif self._lb + end > self._ub:
raise IndexError()
else:
return self._data[self._lb+start:self._lb+end] |
9 | https://:@github.com/VinF/deer.git | fd939e272d5441d48fd7d30bf24312c0f6bc8aaa | @@ -176,7 +176,7 @@ class MyEnv(Environment):
# Lack of energy
if (self._lastPonctualObservation[0]*self.battery_size>Energy_needed_from_battery):
# If enough energy in the battery, use it
- self._lastPonctualObservation[0]=self._lastPonctualObservation[0]-Energy_needed_from_battery/self.battery_size*self.battery_eta
+ self._lastPonctualObservation[0]=self._lastPonctualObservation[0]-Energy_needed_from_battery/self.battery_size/self.battery_eta
else:
# Otherwise: use what is left and then penalty
reward-=(Energy_needed_from_battery-self._lastPonctualObservation[0]*self.battery_size)*2 #2euro/kWh
| General_Deep_Q_RL/environments/MG_two_storages_env.py | ReplaceText(target='/' @(179,126)->(179,127)) | class MyEnv(Environment):
# Lack of energy
if (self._lastPonctualObservation[0]*self.battery_size>Energy_needed_from_battery):
# If enough energy in the battery, use it
self._lastPonctualObservation[0]=self._lastPonctualObservation[0]-Energy_needed_from_battery/self.battery_size*self.battery_eta
else:
# Otherwise: use what is left and then penalty
reward-=(Energy_needed_from_battery-self._lastPonctualObservation[0]*self.battery_size)*2 #2euro/kWh | class MyEnv(Environment):
# Lack of energy
if (self._lastPonctualObservation[0]*self.battery_size>Energy_needed_from_battery):
# If enough energy in the battery, use it
self._lastPonctualObservation[0]=self._lastPonctualObservation[0]-Energy_needed_from_battery/self.battery_size/self.battery_eta
else:
# Otherwise: use what is left and then penalty
reward-=(Energy_needed_from_battery-self._lastPonctualObservation[0]*self.battery_size)*2 #2euro/kWh |
10 | https://:@github.com/piccolbo/altair_recipes.git | 4992dd864a317eaad641d0408f003c429ed24af6 | @@ -6,7 +6,7 @@ from vega_datasets import data
@viz_reg_test
def test_boxplot_melted():
- return ar.boxplot(data.iris(), "species", "petalLength")
+ return ar.boxplot(data.iris(), "petalLength", "species")
@viz_reg_test
| tests/test_boxplot.py | ArgSwap(idxs=1<->2 @(9,11)->(9,21)) | from vega_datasets import data
@viz_reg_test
def test_boxplot_melted():
return ar.boxplot(data.iris(), "species", "petalLength")
@viz_reg_test | from vega_datasets import data
@viz_reg_test
def test_boxplot_melted():
return ar.boxplot(data.iris(), "petalLength", "species")
@viz_reg_test |
11 | https://:@github.com/tailhook/zorro.git | dcbc37d47fe2a8de029f5a2f3ae13adf52e7aace | @@ -121,7 +121,7 @@ class RequestChannel(channel.PipelinedReqChannel):
clen = int(headers.get('Content-Length', '0'))
if clen < 0:
raise EOFError("Wrong content length")
- while pos[0] + clen < len(buf):
+ while pos[0] + clen > len(buf):
readmore()
return status, headers, buf[pos[0]:pos[0]+clen]
| zorro/http.py | ReplaceText(target='>' @(124,32)->(124,33)) | class RequestChannel(channel.PipelinedReqChannel):
clen = int(headers.get('Content-Length', '0'))
if clen < 0:
raise EOFError("Wrong content length")
while pos[0] + clen < len(buf):
readmore()
return status, headers, buf[pos[0]:pos[0]+clen]
| class RequestChannel(channel.PipelinedReqChannel):
clen = int(headers.get('Content-Length', '0'))
if clen < 0:
raise EOFError("Wrong content length")
while pos[0] + clen > len(buf):
readmore()
return status, headers, buf[pos[0]:pos[0]+clen]
|
12 | https://:@gitlab.com/eavise/brambox.git | f1faeed0b52d6f1c9c9ba6da818c1656f841622c | @@ -73,7 +73,7 @@ def test_multiclass(parser, df_anno_simple):
parser = parser()
with pytest.raises(ValueError) as errinfo:
- bb.io.save(parser, df_anno_simple, 'path.txt')
+ bb.io.save(df_anno_simple, parser, 'path.txt')
assert 'single-class problems' in str(errinfo.value)
| test/io/parser/test_anno_cvc.py | ArgSwap(idxs=0<->1 @(76,8)->(76,18)) | def test_multiclass(parser, df_anno_simple):
parser = parser()
with pytest.raises(ValueError) as errinfo:
bb.io.save(parser, df_anno_simple, 'path.txt')
assert 'single-class problems' in str(errinfo.value)
| def test_multiclass(parser, df_anno_simple):
parser = parser()
with pytest.raises(ValueError) as errinfo:
bb.io.save(df_anno_simple, parser, 'path.txt')
assert 'single-class problems' in str(errinfo.value)
|
13 | https://:@github.com/uber/h3-py.git | 359924df907144c85ec323ae2804e2c0d173dfc5 | @@ -631,7 +631,7 @@ def hex_ranges(h3_address_list, ring_size):
(1 + math.sqrt(1 + 8 * math.ceil(j / 6.0))) / 2)) - 1
# hexRanges doesn't return distance array
hex_range_list[ring_index].add(
- h3_to_string(krings[i * num_hexagons + j]))
+ h3_to_string(krings[i * array_len + j]))
return out
| h3/h3.py | ReplaceText(target='array_len' @(634,40)->(634,52)) | def hex_ranges(h3_address_list, ring_size):
(1 + math.sqrt(1 + 8 * math.ceil(j / 6.0))) / 2)) - 1
# hexRanges doesn't return distance array
hex_range_list[ring_index].add(
h3_to_string(krings[i * num_hexagons + j]))
return out
| def hex_ranges(h3_address_list, ring_size):
(1 + math.sqrt(1 + 8 * math.ceil(j / 6.0))) / 2)) - 1
# hexRanges doesn't return distance array
hex_range_list[ring_index].add(
h3_to_string(krings[i * array_len + j]))
return out
|
14 | https://:@github.com/polysquare/polysquare-generic-file-linter.git | e9dbb28ea30955ab59d1339c04f0710b24ba53aa | @@ -388,7 +388,7 @@ def _maybe_log_technical_terms(global_options, tool_options):
terms = set(terms_file.read().splitlines()) # suppress(PYC70)
terms_file.seek(0) # suppress(PYC70)
terms_file.truncate(0) # suppress(PYC70)
- tech_terms = freduce(lambda x, y: x + y,
+ tech_terms = freduce(lambda x, y: x | y,
_drain(log_technical_terms_to_queue))
terms_file.write("\n".join(list(terms | # suppress(PYC70)
set(tech_terms))))
| polysquarelinter/linter.py | ReplaceText(target='|' @(391,48)->(391,49)) | def _maybe_log_technical_terms(global_options, tool_options):
terms = set(terms_file.read().splitlines()) # suppress(PYC70)
terms_file.seek(0) # suppress(PYC70)
terms_file.truncate(0) # suppress(PYC70)
tech_terms = freduce(lambda x, y: x + y,
_drain(log_technical_terms_to_queue))
terms_file.write("\n".join(list(terms | # suppress(PYC70)
set(tech_terms)))) | def _maybe_log_technical_terms(global_options, tool_options):
terms = set(terms_file.read().splitlines()) # suppress(PYC70)
terms_file.seek(0) # suppress(PYC70)
terms_file.truncate(0) # suppress(PYC70)
tech_terms = freduce(lambda x, y: x | y,
_drain(log_technical_terms_to_queue))
terms_file.write("\n".join(list(terms | # suppress(PYC70)
set(tech_terms)))) |
15 | https://:@github.com/johntruckenbrodt/spatialist.git | c9d552e64cd47b30156b288e035d17debea48b45 | @@ -300,7 +300,7 @@ def centerdist(obj1, obj2):
def intersect(obj1, obj2):
- if not (isinstance(obj1, Vector) or isinstance(obj2, Vector)):
+ if not (isinstance(obj1, Vector) and isinstance(obj2, Vector)):
raise IOError('object must be of type Vector')
obj1.reproject(obj2.srs)
| pyroSAR/spatial/vector.py | ReplaceText(target='and' @(303,37)->(303,39)) | def centerdist(obj1, obj2):
def intersect(obj1, obj2):
if not (isinstance(obj1, Vector) or isinstance(obj2, Vector)):
raise IOError('object must be of type Vector')
obj1.reproject(obj2.srs)
| def centerdist(obj1, obj2):
def intersect(obj1, obj2):
if not (isinstance(obj1, Vector) and isinstance(obj2, Vector)):
raise IOError('object must be of type Vector')
obj1.reproject(obj2.srs)
|
16 | https://:@github.com/Toblerity/Shapely.git | 9f1b78e6fd5f4286f210b54827bdd26661f0ee7a | @@ -40,7 +40,7 @@ if __name__ == '__main__':
]
if pattern:
- tests = [f for f in docfiles if f.find(pattern) >= 0]
+ tests = [f for f in docfiles if f.find(pattern) == 0]
else:
tests = docfiles
| tests/runalldoctests.py | ReplaceText(target='==' @(43,56)->(43,58)) | if __name__ == '__main__':
]
if pattern:
tests = [f for f in docfiles if f.find(pattern) >= 0]
else:
tests = docfiles
| if __name__ == '__main__':
]
if pattern:
tests = [f for f in docfiles if f.find(pattern) == 0]
else:
tests = docfiles
|
17 | https://:@github.com/Toblerity/Shapely.git | d6fc8cc0e0d50b23ba0d7ca6195bc530b2f8d1b9 | @@ -11,7 +11,7 @@ def halton(base):
i = index
while i > 0:
result += f * (i % base)
- i = i/base
+ i = i//base
f = f/base
return result
i = 1
| shapely/tests/test_unary_union.py | ReplaceText(target='//' @(14,17)->(14,18)) | def halton(base):
i = index
while i > 0:
result += f * (i % base)
i = i/base
f = f/base
return result
i = 1 | def halton(base):
i = index
while i > 0:
result += f * (i % base)
i = i//base
f = f/base
return result
i = 1 |
18 | https://:@github.com/Toblerity/Shapely.git | 5f0db7fdc052beeeef36aa1251f19175d0abeedb | @@ -36,7 +36,7 @@ if version is None:
# Handle UTF-8 encoding of certain text files.
open_kwds = {}
-if sys.version_info > (3,):
+if sys.version_info >= (3,):
open_kwds['encoding'] = 'utf-8'
with open('VERSION.txt', 'w', **open_kwds) as fp:
| setup.py | ReplaceText(target='>=' @(39,20)->(39,21)) | if version is None:
# Handle UTF-8 encoding of certain text files.
open_kwds = {}
if sys.version_info > (3,):
open_kwds['encoding'] = 'utf-8'
with open('VERSION.txt', 'w', **open_kwds) as fp: | if version is None:
# Handle UTF-8 encoding of certain text files.
open_kwds = {}
if sys.version_info >= (3,):
open_kwds['encoding'] = 'utf-8'
with open('VERSION.txt', 'w', **open_kwds) as fp: |
19 | https://:@github.com/svetlyak40wt/django-tagging-ng.git | 0293b78ee0274d123eb70c1f8c5c01a5b36e2b40 | @@ -163,7 +163,7 @@ class TaggedItemManager(models.Manager):
associated with a given Tag or list of Tags.
"""
tags = get_tag_list(tags)
- if len(tags) == 0:
+ if len(tags) == 1:
tag = tags[0] # Optimisation for single tag
else:
return self.get_intersection_by_model(Model, tags)
| models.py | ReplaceText(target='1' @(166,24)->(166,25)) | class TaggedItemManager(models.Manager):
associated with a given Tag or list of Tags.
"""
tags = get_tag_list(tags)
if len(tags) == 0:
tag = tags[0] # Optimisation for single tag
else:
return self.get_intersection_by_model(Model, tags) | class TaggedItemManager(models.Manager):
associated with a given Tag or list of Tags.
"""
tags = get_tag_list(tags)
if len(tags) == 1:
tag = tags[0] # Optimisation for single tag
else:
return self.get_intersection_by_model(Model, tags) |
20 | https://:@github.com/svetlyak40wt/django-tagging-ng.git | 3285d40e4c1de628886a7fa45a6d4cf6ed4cd7e7 | @@ -163,7 +163,7 @@ class TaggedItemManager(models.Manager):
associated with a given Tag or list of Tags.
"""
tags = get_tag_list(tags)
- if len(tags) == 0:
+ if len(tags) == 1:
tag = tags[0] # Optimisation for single tag
else:
return self.get_intersection_by_model(Model, tags)
| models.py | ReplaceText(target='1' @(166,24)->(166,25)) | class TaggedItemManager(models.Manager):
associated with a given Tag or list of Tags.
"""
tags = get_tag_list(tags)
if len(tags) == 0:
tag = tags[0] # Optimisation for single tag
else:
return self.get_intersection_by_model(Model, tags) | class TaggedItemManager(models.Manager):
associated with a given Tag or list of Tags.
"""
tags = get_tag_list(tags)
if len(tags) == 1:
tag = tags[0] # Optimisation for single tag
else:
return self.get_intersection_by_model(Model, tags) |
21 | https://:@github.com/zzzsochi/yadm.git | 03efd06fe95c7d84264455c4fac5c8cbb17eb4dd | @@ -316,7 +316,7 @@ class QuerySet(BaseQuerySet):
if data is None:
if exc is not None:
- raise exc(criteria)
+ raise exc(qs)
else:
return None
| yadm/queryset.py | ReplaceText(target='qs' @(319,26)->(319,34)) | class QuerySet(BaseQuerySet):
if data is None:
if exc is not None:
raise exc(criteria)
else:
return None
| class QuerySet(BaseQuerySet):
if data is None:
if exc is not None:
raise exc(qs)
else:
return None
|
22 | https://:@github.com/instacart/lore.git | 1c1e0efdac6b27dc111eaa93bb99317c59aaffaf | @@ -196,7 +196,7 @@ class Base(object):
def upload(self):
self.fitting = 0
self.save()
- lore.io.upload(self.remote_model_path(), self.model_path())
+ lore.io.upload(self.model_path(), self.remote_model_path())
@classmethod
def download(cls, fitting=0):
| lore/models/base.py | ArgSwap(idxs=0<->1 @(199,8)->(199,22)) | class Base(object):
def upload(self):
self.fitting = 0
self.save()
lore.io.upload(self.remote_model_path(), self.model_path())
@classmethod
def download(cls, fitting=0): | class Base(object):
def upload(self):
self.fitting = 0
self.save()
lore.io.upload(self.model_path(), self.remote_model_path())
@classmethod
def download(cls, fitting=0): |
23 | https://:@github.com/instacart/lore.git | 1c1e0efdac6b27dc111eaa93bb99317c59aaffaf | @@ -78,7 +78,7 @@ class Base(lore.models.base.Base):
def upload(self):
super(Base, self).upload()
- lore.io.upload(self.remote_weights_path(), self.weights_path())
+ lore.io.upload(self.weights_path(), self.remote_weights_path())
@classmethod
def download(cls, fitting=0):
| lore/models/keras.py | ArgSwap(idxs=0<->1 @(81,8)->(81,22)) | class Base(lore.models.base.Base):
def upload(self):
super(Base, self).upload()
lore.io.upload(self.remote_weights_path(), self.weights_path())
@classmethod
def download(cls, fitting=0): | class Base(lore.models.base.Base):
def upload(self):
super(Base, self).upload()
lore.io.upload(self.weights_path(), self.remote_weights_path())
@classmethod
def download(cls, fitting=0): |
24 | https://:@github.com/instacart/lore.git | f4ded2b3199d1c33ba6c9c79cd66b25d43c83c81 | @@ -464,7 +464,7 @@ class Base(BaseEstimator):
result = self.keras.predict(dataframe, batch_size=self.batch_size)
if self.towers > 1:
- result = numpy.mean(result, axis=0).squeeze(axis=0)
+ result = numpy.mean(result, axis=0).squeeze(axis=1)
return result
| lore/estimators/keras.py | ReplaceText(target='1' @(467,61)->(467,62)) | class Base(BaseEstimator):
result = self.keras.predict(dataframe, batch_size=self.batch_size)
if self.towers > 1:
result = numpy.mean(result, axis=0).squeeze(axis=0)
return result
| class Base(BaseEstimator):
result = self.keras.predict(dataframe, batch_size=self.batch_size)
if self.towers > 1:
result = numpy.mean(result, axis=0).squeeze(axis=1)
return result
|
25 | https://:@github.com/baliga-lab/cmonkey2.git | 3201a0e97688724450196da8fef96d283c855b3f | @@ -273,7 +273,7 @@ class ClusterMembership:
#logging.warn("cluster %s already associated with %s",
# str(cluster), str(column))
pass
- if columns not in columns:
+ if column not in columns:
columns.append(column)
def remove_cluster_from_column(self, column, cluster):
| cmonkey/membership.py | ReplaceText(target='column' @(276,11)->(276,18)) | class ClusterMembership:
#logging.warn("cluster %s already associated with %s",
# str(cluster), str(column))
pass
if columns not in columns:
columns.append(column)
def remove_cluster_from_column(self, column, cluster): | class ClusterMembership:
#logging.warn("cluster %s already associated with %s",
# str(cluster), str(column))
pass
if column not in columns:
columns.append(column)
def remove_cluster_from_column(self, column, cluster): |
26 | https://:@github.com/baliga-lab/cmonkey2.git | 48d14ac785b1013354a55a37239c66433fbf19eb | @@ -460,7 +460,7 @@ class ClusterMembership:
max_score = sys.float_info.min
for row in range(sm.num_rows()):
if sm_values[row][0] > max_score:
- max_score = sm[row][0]
+ max_score = sm_values[row][0]
max_row = row
return sm.row_names[max_row]
| cmonkey/membership.py | ReplaceText(target='sm_values' @(463,32)->(463,34)) | class ClusterMembership:
max_score = sys.float_info.min
for row in range(sm.num_rows()):
if sm_values[row][0] > max_score:
max_score = sm[row][0]
max_row = row
return sm.row_names[max_row]
| class ClusterMembership:
max_score = sys.float_info.min
for row in range(sm.num_rows()):
if sm_values[row][0] > max_score:
max_score = sm_values[row][0]
max_row = row
return sm.row_names[max_row]
|
27 | https://:@github.com/baliga-lab/cmonkey2.git | 311548905a9def1cbdf63d2e0fd8a17346564742 | @@ -17,7 +17,7 @@ class MicrobesOnlineTest(unittest.TestCase): # pylint: disable-msg=R0904
"""test fixture"""
if not os.path.exists('testcache'):
os.mkdir('testcache')
- self.service = mo.MicrobesOnline(mo.MICROBES_ONLINE_BASE_URL, 'testcache')
+ self.service = mo.MicrobesOnline('testcache', mo.MICROBES_ONLINE_BASE_URL)
def tearDown(self): # pylint: disable-msg=C0103
"""test cleanup"""
| test/microbes_online_test.py | ArgSwap(idxs=0<->1 @(20,23)->(20,40)) | class MicrobesOnlineTest(unittest.TestCase): # pylint: disable-msg=R0904
"""test fixture"""
if not os.path.exists('testcache'):
os.mkdir('testcache')
self.service = mo.MicrobesOnline(mo.MICROBES_ONLINE_BASE_URL, 'testcache')
def tearDown(self): # pylint: disable-msg=C0103
"""test cleanup""" | class MicrobesOnlineTest(unittest.TestCase): # pylint: disable-msg=R0904
"""test fixture"""
if not os.path.exists('testcache'):
os.mkdir('testcache')
self.service = mo.MicrobesOnline('testcache', mo.MICROBES_ONLINE_BASE_URL)
def tearDown(self): # pylint: disable-msg=C0103
"""test cleanup""" |
28 | https://:@github.com/muammar/ml4chem.git | dbb7de0379cb8881538d211899e4bec8794f16e3 | @@ -344,7 +344,7 @@ def train(inputs, targets, model=None, data=None, optimizer=None, lr=None,
logger.info('Training finished in {} hours {} minutes {:.2f} seconds.'
.format(h, m, s))
logger.info('outputs')
- logger.info(outputs)
+ logger.info(outputs_)
logger.info('targets')
logger.info(targets)
| mlchem/models/neuralnetwork.py | ReplaceText(target='outputs_' @(347,16)->(347,23)) | def train(inputs, targets, model=None, data=None, optimizer=None, lr=None,
logger.info('Training finished in {} hours {} minutes {:.2f} seconds.'
.format(h, m, s))
logger.info('outputs')
logger.info(outputs)
logger.info('targets')
logger.info(targets)
| def train(inputs, targets, model=None, data=None, optimizer=None, lr=None,
logger.info('Training finished in {} hours {} minutes {:.2f} seconds.'
.format(h, m, s))
logger.info('outputs')
logger.info(outputs_)
logger.info('targets')
logger.info(targets)
|
29 | https://:@github.com/chris7/pyquant.git | 3730fbdb9789a59a65d38f5a2ae21c645086096f | @@ -624,7 +624,7 @@ def findAllPeaks(xdata, ydata_original, min_dist=0, method=None, local_filter_si
best_fit = np.array(best_fit)
peak_func = bigauss_ndim if bigauss_fit else gauss_ndim
# Get rid of peaks with low r^2
- if micro and r2_cutoff is not None:
+ if not micro and r2_cutoff is not None:
final_fit = np.array([])
for peak_index in xrange(0, len(best_fit), step_size):
| pyquant/peaks.py | ReplaceText(target='not ' @(627,7)->(627,7)) | def findAllPeaks(xdata, ydata_original, min_dist=0, method=None, local_filter_si
best_fit = np.array(best_fit)
peak_func = bigauss_ndim if bigauss_fit else gauss_ndim
# Get rid of peaks with low r^2
if micro and r2_cutoff is not None:
final_fit = np.array([])
for peak_index in xrange(0, len(best_fit), step_size):
| def findAllPeaks(xdata, ydata_original, min_dist=0, method=None, local_filter_si
best_fit = np.array(best_fit)
peak_func = bigauss_ndim if bigauss_fit else gauss_ndim
# Get rid of peaks with low r^2
if not micro and r2_cutoff is not None:
final_fit = np.array([])
for peak_index in xrange(0, len(best_fit), step_size):
|
30 | https://:@github.com/chris7/pyquant.git | 4a0755563e0a36fecf1f4393554cfaf4c1615c2c | @@ -615,7 +615,7 @@ def find_peaks_derivative(xdata, ydata, ydata_peaks=None, min_slope=None, rel_pe
# By default, cross points returns the left side
for i in xrange(len(cross_points)):
index = cross_points[i]
- if index < len(cross_points):
+ if index < len(ydata):
if ydata[index] < ydata[index+1]:
cross_points[i] = index+1
| pyquant/utils.py | ReplaceText(target='ydata' @(618,23)->(618,35)) | def find_peaks_derivative(xdata, ydata, ydata_peaks=None, min_slope=None, rel_pe
# By default, cross points returns the left side
for i in xrange(len(cross_points)):
index = cross_points[i]
if index < len(cross_points):
if ydata[index] < ydata[index+1]:
cross_points[i] = index+1
| def find_peaks_derivative(xdata, ydata, ydata_peaks=None, min_slope=None, rel_pe
# By default, cross points returns the left side
for i in xrange(len(cross_points)):
index = cross_points[i]
if index < len(ydata):
if ydata[index] < ydata[index+1]:
cross_points[i] = index+1
|
31 | https://:@github.com/chris7/pyquant.git | cd61286935d8ca64eb539851e39a98a0655ff400 | @@ -611,7 +611,7 @@ def find_peaks_derivative(xdata, ydata, ydata_peaks=None, min_slope=None, rel_pe
ydata = np.abs(ydata_peaks)
if min_peak_width is None:
- max_peak_width = int(len(ydata) / 2)
+ min_peak_width = int(len(ydata) / 2)
if min_peak_width > 5:
min_peak_width = 5
| pyquant/utils.py | ReplaceText(target='min_peak_width' @(614,8)->(614,22)) | def find_peaks_derivative(xdata, ydata, ydata_peaks=None, min_slope=None, rel_pe
ydata = np.abs(ydata_peaks)
if min_peak_width is None:
max_peak_width = int(len(ydata) / 2)
if min_peak_width > 5:
min_peak_width = 5
| def find_peaks_derivative(xdata, ydata, ydata_peaks=None, min_slope=None, rel_pe
ydata = np.abs(ydata_peaks)
if min_peak_width is None:
min_peak_width = int(len(ydata) / 2)
if min_peak_width > 5:
min_peak_width = 5
|
32 | https://:@github.com/ssec/sift.git | 24ce052cd497c42c917de06f0c89a7c5be13ab50 | @@ -599,7 +599,7 @@ class ProbeGraphDisplay (object) :
x_point = self.workspace.get_content_point(x_uuid, point_xy)
format_str, unit_str, x_point = self.document.convert_units(x_uuid, x_point)
y_point = self.workspace.get_content_point(y_uuid, point_xy)
- format_str, unit_str, y_point = self.document.convert_units(x_uuid, y_point)
+ format_str, unit_str, y_point = self.document.convert_units(y_uuid, y_point)
else:
x_point = None
y_point = None
| py/cspov/view/ProbeGraphs.py | ReplaceText(target='y_uuid' @(602,76)->(602,82)) | class ProbeGraphDisplay (object) :
x_point = self.workspace.get_content_point(x_uuid, point_xy)
format_str, unit_str, x_point = self.document.convert_units(x_uuid, x_point)
y_point = self.workspace.get_content_point(y_uuid, point_xy)
format_str, unit_str, y_point = self.document.convert_units(x_uuid, y_point)
else:
x_point = None
y_point = None | class ProbeGraphDisplay (object) :
x_point = self.workspace.get_content_point(x_uuid, point_xy)
format_str, unit_str, x_point = self.document.convert_units(x_uuid, x_point)
y_point = self.workspace.get_content_point(y_uuid, point_xy)
format_str, unit_str, y_point = self.document.convert_units(y_uuid, y_point)
else:
x_point = None
y_point = None |
33 | https://:@github.com/threatwatch/twigs.git | 7ee5d95178a459a8c2e8ff7855e3156e620c395c | @@ -85,7 +85,7 @@ def parse_inventory(email,data,params):
asset_map = {}
asset_map['owner'] = email
asset_map['host'] = host
- asset_map['id'] = host
+ asset_map['id'] = vmuuid
asset_map['name'] = host
asset_map['tags'] = [ ]
asset_map['patch_tracker'] = { } # To help remove duplicate patches
| twigs/azure.py | ReplaceText(target='vmuuid' @(88,30)->(88,34)) | def parse_inventory(email,data,params):
asset_map = {}
asset_map['owner'] = email
asset_map['host'] = host
asset_map['id'] = host
asset_map['name'] = host
asset_map['tags'] = [ ]
asset_map['patch_tracker'] = { } # To help remove duplicate patches | def parse_inventory(email,data,params):
asset_map = {}
asset_map['owner'] = email
asset_map['host'] = host
asset_map['id'] = vmuuid
asset_map['name'] = host
asset_map['tags'] = [ ]
asset_map['patch_tracker'] = { } # To help remove duplicate patches |
34 | https://:@github.com/Keeper-Security/Commander.git | 9bd55c8dd48ab62759bbbb8dfcd38ab364cec2dc | @@ -1550,7 +1550,7 @@ def prepare_record(params, record):
else:
if params.debug: print('Generated record key')
unencrypted_key = os.urandom(32)
- record_object['record_key'] = encrypt_aes(params.data_key, unencrypted_key)
+ record_object['record_key'] = encrypt_aes(unencrypted_key, params.data_key)
record_object['revision'] = 0
data['title'] = record.title
| keepercommander/api.py | ArgSwap(idxs=0<->1 @(1553,38)->(1553,49)) | def prepare_record(params, record):
else:
if params.debug: print('Generated record key')
unencrypted_key = os.urandom(32)
record_object['record_key'] = encrypt_aes(params.data_key, unencrypted_key)
record_object['revision'] = 0
data['title'] = record.title | def prepare_record(params, record):
else:
if params.debug: print('Generated record key')
unencrypted_key = os.urandom(32)
record_object['record_key'] = encrypt_aes(unencrypted_key, params.data_key)
record_object['revision'] = 0
data['title'] = record.title |
35 | https://:@github.com/hpapaxen/rope.git | 27d5085b30e89095e88339c96d9940e338482106 | @@ -69,7 +69,7 @@ class JobSet(object):
def get_percent_done(self):
if self.count is not None and self.count > 0:
- percent = self.done * 100 / self.count
+ percent = self.done * 100 // self.count
return min(percent, 100)
def get_name(self):
| rope/base/taskhandle.py | ReplaceText(target='//' @(72,38)->(72,39)) | class JobSet(object):
def get_percent_done(self):
if self.count is not None and self.count > 0:
percent = self.done * 100 / self.count
return min(percent, 100)
def get_name(self): | class JobSet(object):
def get_percent_done(self):
if self.count is not None and self.count > 0:
percent = self.done * 100 // self.count
return min(percent, 100)
def get_name(self): |
36 | https://:@github.com/hpapaxen/rope.git | 27d5085b30e89095e88339c96d9940e338482106 | @@ -524,7 +524,7 @@ class ProgressBar(object):
self.text['text'] = text
def _draw_shape(self):
- width = int(self.canvas['width']) * self.percent / 100
+ width = int(self.canvas['width']) * self.percent // 100
self.canvas.create_rectangle(0, 0, width, self.canvas['height'],
fill=self.color)
total_width = self.canvas['width']
| rope/ui/uihelpers.py | ReplaceText(target='//' @(527,57)->(527,58)) | class ProgressBar(object):
self.text['text'] = text
def _draw_shape(self):
width = int(self.canvas['width']) * self.percent / 100
self.canvas.create_rectangle(0, 0, width, self.canvas['height'],
fill=self.color)
total_width = self.canvas['width'] | class ProgressBar(object):
self.text['text'] = text
def _draw_shape(self):
width = int(self.canvas['width']) * self.percent // 100
self.canvas.create_rectangle(0, 0, width, self.canvas['height'],
fill=self.color)
total_width = self.canvas['width'] |
37 | https://:@github.com/hpapaxen/rope.git | 2720419618aceab7fba51aaa4d66f7eae005b22d | @@ -129,7 +129,7 @@ class SimilarFinderTest(unittest.TestCase):
source = 'x.a = 1\n'
finder = similarfinder.SimilarFinder(source)
result = list(finder.get_matches('${a} = 1'))
- self.assertEquals(1, len(result))
+ self.assertEquals(0, len(result))
def test_functions_not_matching_when_only_first_parameters(self):
source = 'f(1, 2)\n'
| ropetest/refactor/similarfindertest.py | ReplaceText(target='0' @(132,26)->(132,27)) | class SimilarFinderTest(unittest.TestCase):
source = 'x.a = 1\n'
finder = similarfinder.SimilarFinder(source)
result = list(finder.get_matches('${a} = 1'))
self.assertEquals(1, len(result))
def test_functions_not_matching_when_only_first_parameters(self):
source = 'f(1, 2)\n' | class SimilarFinderTest(unittest.TestCase):
source = 'x.a = 1\n'
finder = similarfinder.SimilarFinder(source)
result = list(finder.get_matches('${a} = 1'))
self.assertEquals(0, len(result))
def test_functions_not_matching_when_only_first_parameters(self):
source = 'f(1, 2)\n' |
38 | https://:@github.com/hpapaxen/rope.git | 0eb3cb58493cdaea83a4e24d47b5bd4dbd19f963 | @@ -32,7 +32,7 @@ class BuiltinModule(pyobjects.AbstractModule):
result.update(self.initial)
for modname in self.submodules:
name = modname.split('.')[-1]
- result[name] = BuiltinModule(name, self.submodules)
+ result[name] = BuiltinModule(modname, self.submodules)
return result
@property
| rope/base/builtins.py | ReplaceText(target='modname' @(35,41)->(35,45)) | class BuiltinModule(pyobjects.AbstractModule):
result.update(self.initial)
for modname in self.submodules:
name = modname.split('.')[-1]
result[name] = BuiltinModule(name, self.submodules)
return result
@property | class BuiltinModule(pyobjects.AbstractModule):
result.update(self.initial)
for modname in self.submodules:
name = modname.split('.')[-1]
result[name] = BuiltinModule(modname, self.submodules)
return result
@property |
39 | https://:@github.com/hpapaxen/rope.git | 528744bb4bc1b8076680f7c2c1bfac508ddca4f9 | @@ -37,7 +37,7 @@ def relative(root, path):
if os.path.samefile(root, path):
return '/'.join(reversed(rel))
parent = os.path.dirname(path)
- if not path or parent == path:
+ if not parent or parent == path:
break
rel.append(os.path.basename(path))
path = parent
| rope/base/libutils.py | ReplaceText(target='parent' @(40,15)->(40,19)) | def relative(root, path):
if os.path.samefile(root, path):
return '/'.join(reversed(rel))
parent = os.path.dirname(path)
if not path or parent == path:
break
rel.append(os.path.basename(path))
path = parent | def relative(root, path):
if os.path.samefile(root, path):
return '/'.join(reversed(rel))
parent = os.path.dirname(path)
if not parent or parent == path:
break
rel.append(os.path.basename(path))
path = parent |
40 | https://:@github.com/benjamincrom/baseball.git | 6ef29729ad07458aebe709b4e42f56ecd3761ec4 | @@ -111,7 +111,7 @@ def write_game_svg_and_html(game_id, game, output_path):
html_filename = game_id + '.html'
svg_text = game.get_svg_str()
- html_text = HTML_WRAPPER.format(title=game_id, filename=html_filename)
+ html_text = HTML_WRAPPER.format(title=game_id, filename=svg_filename)
output_svg_path = join(output_path, svg_filename)
output_html_path = join(output_path, html_filename)
| fetch_game.py | ReplaceText(target='svg_filename' @(114,60)->(114,73)) | def write_game_svg_and_html(game_id, game, output_path):
html_filename = game_id + '.html'
svg_text = game.get_svg_str()
html_text = HTML_WRAPPER.format(title=game_id, filename=html_filename)
output_svg_path = join(output_path, svg_filename)
output_html_path = join(output_path, html_filename) | def write_game_svg_and_html(game_id, game, output_path):
html_filename = game_id + '.html'
svg_text = game.get_svg_str()
html_text = HTML_WRAPPER.format(title=game_id, filename=svg_filename)
output_svg_path = join(output_path, svg_filename)
output_html_path = join(output_path, html_filename) |
41 | https://:@github.com/sporestack/bitcash.git | dbc65e1b47426e0e4d286db5b27216ec36cb32cf | @@ -16,7 +16,7 @@ def test_set_fee_cache_time():
def test_get_fee():
- assert get_fee(fast=True) != get_fee(fast=False)
+ assert get_fee(fast=True) >= get_fee(fast=False)
class TestFeeCache:
| tests/network/test_fees.py | ReplaceText(target='>=' @(19,30)->(19,32)) | def test_set_fee_cache_time():
def test_get_fee():
assert get_fee(fast=True) != get_fee(fast=False)
class TestFeeCache: | def test_set_fee_cache_time():
def test_get_fee():
assert get_fee(fast=True) >= get_fee(fast=False)
class TestFeeCache: |
42 | https://:@github.com/galaxy-genome-annotation/python-apollo.git | 53e514b619844fa1f87179d738b9d29830027300 | @@ -29,7 +29,7 @@ class ApolloTestCase(unittest.TestCase):
"""
org_info = wa.organisms.show_organism(org_id)
- if 'directory' in org_info:
+ if 'directory' not in org_info:
time.sleep(1)
org_info = wa.organisms.show_organism(org_id)
| test/__init__.py | ReplaceText(target=' not in ' @(32,22)->(32,26)) | class ApolloTestCase(unittest.TestCase):
"""
org_info = wa.organisms.show_organism(org_id)
if 'directory' in org_info:
time.sleep(1)
org_info = wa.organisms.show_organism(org_id)
| class ApolloTestCase(unittest.TestCase):
"""
org_info = wa.organisms.show_organism(org_id)
if 'directory' not in org_info:
time.sleep(1)
org_info = wa.organisms.show_organism(org_id)
|
43 | https://:@github.com/jakubplichta/grafana-dashboard-builder.git | 3228e6950d65b9bd347cacb56a9e85ec410b14ce | @@ -35,7 +35,7 @@ class Context(object):
formatter = string.Formatter()
(result, to_expand) = (formatter.vformat(to_expand, (), self._context), to_expand)
while result != to_expand:
- (result, to_expand) = (formatter.vformat(to_expand, (), self._context), result)
+ (result, to_expand) = (formatter.vformat(result, (), self._context), result)
return result
elif isinstance(to_expand, list):
return [self.expand_placeholders(value) for value in to_expand]
| grafana_dashboards/context.py | ReplaceText(target='result' @(38,57)->(38,66)) | class Context(object):
formatter = string.Formatter()
(result, to_expand) = (formatter.vformat(to_expand, (), self._context), to_expand)
while result != to_expand:
(result, to_expand) = (formatter.vformat(to_expand, (), self._context), result)
return result
elif isinstance(to_expand, list):
return [self.expand_placeholders(value) for value in to_expand] | class Context(object):
formatter = string.Formatter()
(result, to_expand) = (formatter.vformat(to_expand, (), self._context), to_expand)
while result != to_expand:
(result, to_expand) = (formatter.vformat(result, (), self._context), result)
return result
elif isinstance(to_expand, list):
return [self.expand_placeholders(value) for value in to_expand] |
44 | https://:@github.com/Phylliade/ikpy.git | 815dbff3a521532a7b792c309902ffea82abac85 | @@ -13,7 +13,7 @@ class TestFK(unittest.TestCase):
one_move[5] = np.pi / 4
one_move[6] = -np.pi / 2
one_move[4] = -np.pi / 2
- self.test_pos = one_move
+ self.test_pos = all_zeros
def test_fk_creature(self):
| tests/test_fk.py | ReplaceText(target='all_zeros' @(16,24)->(16,32)) | class TestFK(unittest.TestCase):
one_move[5] = np.pi / 4
one_move[6] = -np.pi / 2
one_move[4] = -np.pi / 2
self.test_pos = one_move
def test_fk_creature(self):
| class TestFK(unittest.TestCase):
one_move[5] = np.pi / 4
one_move[6] = -np.pi / 2
one_move[4] = -np.pi / 2
self.test_pos = all_zeros
def test_fk_creature(self):
|
45 | https://:@github.com/tingbot/tingbot-python.git | 5374186675f6809faf9ce953fc35c81217348753 | @@ -72,7 +72,7 @@ class RunLoop(object):
while self.running:
if len(self.timers) > 0:
try:
- self._wait(self.timers[0].next_fire_time)
+ self._wait(self.timers[-1].next_fire_time)
except Exception as e:
self._error(e)
continue
| tingbot/run_loop.py | ReplaceText(target='-1' @(75,43)->(75,44)) | class RunLoop(object):
while self.running:
if len(self.timers) > 0:
try:
self._wait(self.timers[0].next_fire_time)
except Exception as e:
self._error(e)
continue | class RunLoop(object):
while self.running:
if len(self.timers) > 0:
try:
self._wait(self.timers[-1].next_fire_time)
except Exception as e:
self._error(e)
continue |
46 | https://:@github.com/nyoka-pmml/nyoka.git | 8d5c0d31d0bf1e251abe686f06b614a16e5ffcfb | @@ -74,7 +74,7 @@ class TestMethods(unittest.TestCase):
self.assertEqual(pmml_obj.NearestNeighborModel[0].ComparisonMeasure.kind, "distance")
##3
- self.assertEqual(pmml_obj.steps[-1][-1].n_neighbors, pmml_obj.NearestNeighborModel[0].numberOfNeighbors)
+ self.assertEqual(pipeline_obj.steps[-1][-1].n_neighbors, pmml_obj.NearestNeighborModel[0].numberOfNeighbors)
def test_sklearn_03(self):
| nyoka/tests/skl_to_pmml_UnitTest.py | ReplaceText(target='pipeline_obj' @(77,25)->(77,33)) | class TestMethods(unittest.TestCase):
self.assertEqual(pmml_obj.NearestNeighborModel[0].ComparisonMeasure.kind, "distance")
##3
self.assertEqual(pmml_obj.steps[-1][-1].n_neighbors, pmml_obj.NearestNeighborModel[0].numberOfNeighbors)
def test_sklearn_03(self): | class TestMethods(unittest.TestCase):
self.assertEqual(pmml_obj.NearestNeighborModel[0].ComparisonMeasure.kind, "distance")
##3
self.assertEqual(pipeline_obj.steps[-1][-1].n_neighbors, pmml_obj.NearestNeighborModel[0].numberOfNeighbors)
def test_sklearn_03(self): |
47 | https://:@github.com/iris-edu/pyweed.git | 77d919acd8d54d4879d1a34598e9e04f16fdf708 | @@ -97,7 +97,7 @@ class WaveformEntry(AttribDict):
self.error = None
- self.start_time = self.distances.arrival + self.config.offsets[0]
+ self.start_time = self.distances.arrival - self.config.offsets[0]
self.end_time = self.distances.arrival + self.config.offsets[1]
self.start_string = UTCDateTime(self.start_time).format_iris_web_service().replace(':', '_')
| pyweed/waveforms_handler.py | ReplaceText(target='-' @(100,49)->(100,50)) | class WaveformEntry(AttribDict):
self.error = None
self.start_time = self.distances.arrival + self.config.offsets[0]
self.end_time = self.distances.arrival + self.config.offsets[1]
self.start_string = UTCDateTime(self.start_time).format_iris_web_service().replace(':', '_') | class WaveformEntry(AttribDict):
self.error = None
self.start_time = self.distances.arrival - self.config.offsets[0]
self.end_time = self.distances.arrival + self.config.offsets[1]
self.start_string = UTCDateTime(self.start_time).format_iris_web_service().replace(':', '_') |
48 | https://:@github.com/anaxilaus/coindata.git | 2e5067311c4eed50eed41c45f43ad63e8973e579 | @@ -52,6 +52,6 @@ def dump_json(data, filepath):
try:
with open(filepath, 'w') as file:
- json.dump(data, filepath)
+ json.dump(data, file)
except TypeError as e:
print("Data isn't JSON compatible.\n", e)
| coindata/utils.py | ReplaceText(target='file' @(55,28)->(55,36)) | def dump_json(data, filepath):
try:
with open(filepath, 'w') as file:
json.dump(data, filepath)
except TypeError as e:
print("Data isn't JSON compatible.\n", e) | def dump_json(data, filepath):
try:
with open(filepath, 'w') as file:
json.dump(data, file)
except TypeError as e:
print("Data isn't JSON compatible.\n", e) |
49 | https://:@github.com/Pixelapse/pyglass.git | a31e95cbc259ce61f5851d6f0d769792aaa182fe | @@ -20,7 +20,7 @@ def preview(src_path):
preview_path = thumbnail_preview(src_path)
if preview_path:
- mimetype = magic.from_file(src_path, mime=True).lower()
+ mimetype = magic.from_file(preview_path, mime=True).lower()
if mimetype in [ExportMimeType.PNG, ExportMimeType.PDF]:
return preview_path
| pyglass/quicklook/api.py | ReplaceText(target='preview_path' @(23,31)->(23,39)) | def preview(src_path):
preview_path = thumbnail_preview(src_path)
if preview_path:
mimetype = magic.from_file(src_path, mime=True).lower()
if mimetype in [ExportMimeType.PNG, ExportMimeType.PDF]:
return preview_path
| def preview(src_path):
preview_path = thumbnail_preview(src_path)
if preview_path:
mimetype = magic.from_file(preview_path, mime=True).lower()
if mimetype in [ExportMimeType.PNG, ExportMimeType.PDF]:
return preview_path
|
50 | https://:@github.com/erezsh/plyplus.git | 8cc69bebfcb2cb0480ac66d07fe1f4b8637bba11 | @@ -784,7 +784,7 @@ class _Grammar(object):
subtree.extend(child.tail)
else:
subtree.append(child)
- p[0] = self.tree_class(rule_name, subtree, skip_adjustments=True) if len(subtree) > 1 else subtree[0]
+ p[0] = self.tree_class(rule_name, subtree, skip_adjustments=True) if len(subtree) != 1 else subtree[0]
else:
def p_rule(self, p):
p[0] = self.tree_class(rule_name, p[1:], skip_adjustments=True)
| plyplus/plyplus.py | ReplaceText(target='!=' @(787,98)->(787,99)) | class _Grammar(object):
subtree.extend(child.tail)
else:
subtree.append(child)
p[0] = self.tree_class(rule_name, subtree, skip_adjustments=True) if len(subtree) > 1 else subtree[0]
else:
def p_rule(self, p):
p[0] = self.tree_class(rule_name, p[1:], skip_adjustments=True) | class _Grammar(object):
subtree.extend(child.tail)
else:
subtree.append(child)
p[0] = self.tree_class(rule_name, subtree, skip_adjustments=True) if len(subtree) != 1 else subtree[0]
else:
def p_rule(self, p):
p[0] = self.tree_class(rule_name, p[1:], skip_adjustments=True) |
51 | https://:@github.com/olls/graphics.git | 877ef2670d4ad34c4fcf951dab0922419f081531 | @@ -22,7 +22,7 @@ def colorStr(text, color=WHITE):
return seq
sys.stdout.write(seq + '\n')
else:
- return seq
+ return text
sys.stdout.write(text + '\n')
if __name__ == '__main__':
| colors.py | ReplaceText(target='text' @(25,9)->(25,12)) | def colorStr(text, color=WHITE):
return seq
sys.stdout.write(seq + '\n')
else:
return seq
sys.stdout.write(text + '\n')
if __name__ == '__main__': | def colorStr(text, color=WHITE):
return seq
sys.stdout.write(seq + '\n')
else:
return text
sys.stdout.write(text + '\n')
if __name__ == '__main__': |
52 | https://:@github.com/hkwi/twink.git | 5ef359deb609fc55659596a8cb327abb9c7e4653 | @@ -319,7 +319,7 @@ def ofp_action_set_field(message, offset):
cursor = _cursor(offset)
offset = cursor.offset
- (type,len) = ofp_action_header(message, offset)
+ (type,len) = ofp_action_header(message, cursor)
field = message[cursor.offset:offset+len]
cursor.offset = offset+len
return namedtuple("ofp_action_set_field",
| twink/ofp4/parse.py | ReplaceText(target='cursor' @(322,41)->(322,47)) | def ofp_action_set_field(message, offset):
cursor = _cursor(offset)
offset = cursor.offset
(type,len) = ofp_action_header(message, offset)
field = message[cursor.offset:offset+len]
cursor.offset = offset+len
return namedtuple("ofp_action_set_field", | def ofp_action_set_field(message, offset):
cursor = _cursor(offset)
offset = cursor.offset
(type,len) = ofp_action_header(message, cursor)
field = message[cursor.offset:offset+len]
cursor.offset = offset+len
return namedtuple("ofp_action_set_field", |
53 | https://:@github.com/hkwi/twink.git | fc6f5ad63cb12f9caf5455e3179ecfd9cd9de060 | @@ -27,7 +27,7 @@ def _unpack(fmt, message, offset):
return struct.unpack_from(fmt, message, offset)
def _align(length):
- return (length+7)/8*8
+ return (length+7)//8*8
# 7.1
def ofp_header(version, type, length, xid):
| twink/ofp4/build.py | ReplaceText(target='//' @(30,18)->(30,19)) | def _unpack(fmt, message, offset):
return struct.unpack_from(fmt, message, offset)
def _align(length):
return (length+7)/8*8
# 7.1
def ofp_header(version, type, length, xid): | def _unpack(fmt, message, offset):
return struct.unpack_from(fmt, message, offset)
def _align(length):
return (length+7)//8*8
# 7.1
def ofp_header(version, type, length, xid): |
54 | https://:@github.com/biolab/orange3-datafusion.git | 54f941a66a9b369a73190dfe2007e5b6dae1803a | @@ -33,7 +33,7 @@ def _find_completion(fuser, relation):
for fuser_relation in fuser.fusion_graph.get_relations(relation.row_type,
relation.col_type):
if fuser_relation._id == relation._id:
- return fuser.complete(fuser_relation)
+ return fuser.complete(relation)
return None
| orangecontrib/datafusion/widgets/owcompletionscoring.py | ReplaceText(target='relation' @(36,34)->(36,48)) | def _find_completion(fuser, relation):
for fuser_relation in fuser.fusion_graph.get_relations(relation.row_type,
relation.col_type):
if fuser_relation._id == relation._id:
return fuser.complete(fuser_relation)
return None
| def _find_completion(fuser, relation):
for fuser_relation in fuser.fusion_graph.get_relations(relation.row_type,
relation.col_type):
if fuser_relation._id == relation._id:
return fuser.complete(relation)
return None
|
55 | https://:@github.com/aiqm/torchani.git | 5bb6691515e5e56fbe4994b140dd40b73043a33f | @@ -151,7 +151,7 @@ class PrepareInput(torch.nn.Module):
new_tensors = []
for t in tensors:
new_tensors.append(t.index_select(1, reverse))
- return (species, *tensors)
+ return (species, *new_tensors)
def forward(self, species_coordinates):
species, coordinates = species_coordinates
| torchani/aev.py | ReplaceText(target='new_tensors' @(154,26)->(154,33)) | class PrepareInput(torch.nn.Module):
new_tensors = []
for t in tensors:
new_tensors.append(t.index_select(1, reverse))
return (species, *tensors)
def forward(self, species_coordinates):
species, coordinates = species_coordinates | class PrepareInput(torch.nn.Module):
new_tensors = []
for t in tensors:
new_tensors.append(t.index_select(1, reverse))
return (species, *new_tensors)
def forward(self, species_coordinates):
species, coordinates = species_coordinates |
56 | https://:@github.com/aiqm/torchani.git | abc8f7f842ae4b273c6e867b392413dcadd9c921 | @@ -593,7 +593,7 @@ def collate_fn(data, chunk_threshold, properties_info):
if properties_info['padding_values'][i] is None:
prop = torch.stack(prop)
else:
- prop = torch.nn.utils.rnn.pad_sequence(batch_species,
+ prop = torch.nn.utils.rnn.pad_sequence(prop,
batch_first=True,
padding_value=properties_info['padding_values'][i])
# sort with number of atoms
| torchani/data/new.py | ReplaceText(target='prop' @(596,51)->(596,64)) | def collate_fn(data, chunk_threshold, properties_info):
if properties_info['padding_values'][i] is None:
prop = torch.stack(prop)
else:
prop = torch.nn.utils.rnn.pad_sequence(batch_species,
batch_first=True,
padding_value=properties_info['padding_values'][i])
# sort with number of atoms | def collate_fn(data, chunk_threshold, properties_info):
if properties_info['padding_values'][i] is None:
prop = torch.stack(prop)
else:
prop = torch.nn.utils.rnn.pad_sequence(prop,
batch_first=True,
padding_value=properties_info['padding_values'][i])
# sort with number of atoms |
57 | https://:@github.com/aiqm/torchani.git | c18f4a5ea1f9732cc07c8816caa401981e43dc48 | @@ -274,7 +274,7 @@ def compute_aev(species: Tensor, coordinates: Tensor, cell: Tensor,
num_atoms = species.shape[1]
num_species_pairs = angular_length // angular_sublength
# PBC calculation is bypassed if there are no shifts
- if shifts.numel() == 1:
+ if shifts.numel() == 0:
atom_index1, atom_index2, shifts = neighbor_pairs_nopbc(species == -1, coordinates, cell, shifts, Rcr)
else:
atom_index1, atom_index2, shifts = neighbor_pairs(species == -1, coordinates, cell, shifts, Rcr)
| torchani/aev.py | ReplaceText(target='0' @(277,25)->(277,26)) | def compute_aev(species: Tensor, coordinates: Tensor, cell: Tensor,
num_atoms = species.shape[1]
num_species_pairs = angular_length // angular_sublength
# PBC calculation is bypassed if there are no shifts
if shifts.numel() == 1:
atom_index1, atom_index2, shifts = neighbor_pairs_nopbc(species == -1, coordinates, cell, shifts, Rcr)
else:
atom_index1, atom_index2, shifts = neighbor_pairs(species == -1, coordinates, cell, shifts, Rcr) | def compute_aev(species: Tensor, coordinates: Tensor, cell: Tensor,
num_atoms = species.shape[1]
num_species_pairs = angular_length // angular_sublength
# PBC calculation is bypassed if there are no shifts
if shifts.numel() == 0:
atom_index1, atom_index2, shifts = neighbor_pairs_nopbc(species == -1, coordinates, cell, shifts, Rcr)
else:
atom_index1, atom_index2, shifts = neighbor_pairs(species == -1, coordinates, cell, shifts, Rcr) |
58 | https://:@github.com/cs207group4/cs207-FinalProject.git | e7f1cc613ace275a8d259de7455ee39ca063e029 | @@ -120,7 +120,7 @@ class ChemSolver:
r.set_initial_value(y0, 0)
self._t = [0]
self._y = [y0]
- while r.successful() and r.t <= t1:
+ while r.successful() and r.t < t1:
self._t.append(r.t + dt)
self._y.append(r.integrate(r.t + dt))
self._t = np.array(self._t)
| pychemkin/ChemSolver.py | ReplaceText(target='<' @(123,37)->(123,39)) | class ChemSolver:
r.set_initial_value(y0, 0)
self._t = [0]
self._y = [y0]
while r.successful() and r.t <= t1:
self._t.append(r.t + dt)
self._y.append(r.integrate(r.t + dt))
self._t = np.array(self._t) | class ChemSolver:
r.set_initial_value(y0, 0)
self._t = [0]
self._y = [y0]
while r.successful() and r.t < t1:
self._t.append(r.t + dt)
self._y.append(r.integrate(r.t + dt))
self._t = np.array(self._t) |
59 | https://:@github.com/MrLeeh/pyads.git | d14fd2a7bb2d4b784a4f6a47b6981ba2a86b699c | @@ -97,7 +97,7 @@ def set_local_address(ams_netid):
else:
ams_netid_st = ams_netid
- assert isinstance(ams_netid, SAmsNetId)
+ assert isinstance(ams_netid_st, SAmsNetId)
if linux:
return adsSetLocalAddress(ams_netid_st)
| pyads/ads.py | ReplaceText(target='ams_netid_st' @(100,22)->(100,31)) | def set_local_address(ams_netid):
else:
ams_netid_st = ams_netid
assert isinstance(ams_netid, SAmsNetId)
if linux:
return adsSetLocalAddress(ams_netid_st) | def set_local_address(ams_netid):
else:
ams_netid_st = ams_netid
assert isinstance(ams_netid_st, SAmsNetId)
if linux:
return adsSetLocalAddress(ams_netid_st) |
60 | https://:@github.com/pytorch/fairseq.git | 0a836276129ef71fa6c44975dd02ab70bccc496d | @@ -58,7 +58,7 @@ class FConvEncoder(FairseqEncoder):
self.projections = nn.ModuleList()
self.convolutions = nn.ModuleList()
for (out_channels, kernel_size) in convolutions:
- pad = (kernel_size - 1) // 2
+ pad = (kernel_size - 1) / 2
self.projections.append(Linear(in_channels, out_channels)
if in_channels != out_channels else None)
self.convolutions.append(
| fairseq/models/fconv.py | ReplaceText(target='/' @(61,36)->(61,38)) | class FConvEncoder(FairseqEncoder):
self.projections = nn.ModuleList()
self.convolutions = nn.ModuleList()
for (out_channels, kernel_size) in convolutions:
pad = (kernel_size - 1) // 2
self.projections.append(Linear(in_channels, out_channels)
if in_channels != out_channels else None)
self.convolutions.append( | class FConvEncoder(FairseqEncoder):
self.projections = nn.ModuleList()
self.convolutions = nn.ModuleList()
for (out_channels, kernel_size) in convolutions:
pad = (kernel_size - 1) / 2
self.projections.append(Linear(in_channels, out_channels)
if in_channels != out_channels else None)
self.convolutions.append( |
61 | https://:@github.com/pytorch/fairseq.git | f68a44359b6596997b931d2e662a899ffba9d407 | @@ -62,7 +62,7 @@ class SinusoidalPositionalEmbedding(nn.Module):
# recompute/expand embeddings if needed
bsz, seq_len = input.size()
max_pos = self.padding_idx + 1 + seq_len
- if seq_len > self.weights.size(0):
+ if max_pos > self.weights.size(0):
self.weights = SinusoidalPositionalEmbedding.get_embedding(
max_pos,
self.embedding_dim,
| fairseq/modules/sinusoidal_positional_embedding.py | ReplaceText(target='max_pos' @(65,11)->(65,18)) | class SinusoidalPositionalEmbedding(nn.Module):
# recompute/expand embeddings if needed
bsz, seq_len = input.size()
max_pos = self.padding_idx + 1 + seq_len
if seq_len > self.weights.size(0):
self.weights = SinusoidalPositionalEmbedding.get_embedding(
max_pos,
self.embedding_dim, | class SinusoidalPositionalEmbedding(nn.Module):
# recompute/expand embeddings if needed
bsz, seq_len = input.size()
max_pos = self.padding_idx + 1 + seq_len
if max_pos > self.weights.size(0):
self.weights = SinusoidalPositionalEmbedding.get_embedding(
max_pos,
self.embedding_dim, |
62 | https://:@github.com/pytorch/fairseq.git | 762956a559e65e1e48df8f8b4df515d23b66fddb | @@ -82,7 +82,7 @@ def main(args):
train_meter.start()
valid_losses = [None]
valid_subsets = args.valid_subset.split(',')
- while lr > args.min_lr and epoch_itr.epoch <= max_epoch and trainer.get_num_updates() < max_update:
+ while lr > args.min_lr and epoch_itr.epoch < max_epoch and trainer.get_num_updates() < max_update:
# train for one epoch
train(args, trainer, task, epoch_itr)
| train.py | ReplaceText(target='<' @(85,47)->(85,49)) | def main(args):
train_meter.start()
valid_losses = [None]
valid_subsets = args.valid_subset.split(',')
while lr > args.min_lr and epoch_itr.epoch <= max_epoch and trainer.get_num_updates() < max_update:
# train for one epoch
train(args, trainer, task, epoch_itr)
| def main(args):
train_meter.start()
valid_losses = [None]
valid_subsets = args.valid_subset.split(',')
while lr > args.min_lr and epoch_itr.epoch < max_epoch and trainer.get_num_updates() < max_update:
# train for one epoch
train(args, trainer, task, epoch_itr)
|
63 | https://:@github.com/pytorch/fairseq.git | e9967cd334783f5da50deadc17cf8a4fc3380171 | @@ -82,7 +82,7 @@ def main(args):
train_meter.start()
valid_losses = [None]
valid_subsets = args.valid_subset.split(',')
- while lr > args.min_lr and epoch_itr.epoch <= max_epoch and trainer.get_num_updates() < max_update:
+ while lr > args.min_lr and epoch_itr.epoch < max_epoch and trainer.get_num_updates() < max_update:
# train for one epoch
train(args, trainer, task, epoch_itr)
| train.py | ReplaceText(target='<' @(85,47)->(85,49)) | def main(args):
train_meter.start()
valid_losses = [None]
valid_subsets = args.valid_subset.split(',')
while lr > args.min_lr and epoch_itr.epoch <= max_epoch and trainer.get_num_updates() < max_update:
# train for one epoch
train(args, trainer, task, epoch_itr)
| def main(args):
train_meter.start()
valid_losses = [None]
valid_subsets = args.valid_subset.split(',')
while lr > args.min_lr and epoch_itr.epoch < max_epoch and trainer.get_num_updates() < max_update:
# train for one epoch
train(args, trainer, task, epoch_itr)
|
64 | https://:@github.com/pytorch/fairseq.git | 7bcb487aad8504043d13c9b869d555aa565a46c7 | @@ -49,7 +49,7 @@ class LabelSmoothedCrossEntropyCriterion(FairseqCriterion):
sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']
logging_output = {
'loss': utils.item(loss.data) if reduce else loss.data,
- 'nll_loss': utils.item(nll_loss.data) if reduce else loss.data,
+ 'nll_loss': utils.item(nll_loss.data) if reduce else nll_loss.data,
'ntokens': sample['ntokens'],
'sample_size': sample_size,
}
| fairseq/criterions/label_smoothed_cross_entropy.py | ReplaceText(target='nll_loss' @(52,65)->(52,69)) | class LabelSmoothedCrossEntropyCriterion(FairseqCriterion):
sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']
logging_output = {
'loss': utils.item(loss.data) if reduce else loss.data,
'nll_loss': utils.item(nll_loss.data) if reduce else loss.data,
'ntokens': sample['ntokens'],
'sample_size': sample_size,
} | class LabelSmoothedCrossEntropyCriterion(FairseqCriterion):
sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']
logging_output = {
'loss': utils.item(loss.data) if reduce else loss.data,
'nll_loss': utils.item(nll_loss.data) if reduce else nll_loss.data,
'ntokens': sample['ntokens'],
'sample_size': sample_size,
} |
65 | https://:@github.com/pytorch/fairseq.git | 74efc21403477d103bd426ae64c37b7a30d8f4bf | @@ -154,7 +154,7 @@ class TestIncrementalDecoder(FairseqIncrementalDecoder):
probs[:, i, self.dictionary.eos()] = 1.0
# random attention
- attn = torch.rand(bbsz, src_len, tgt_len)
+ attn = torch.rand(bbsz, tgt_len, src_len)
return Variable(probs), Variable(attn)
| tests/utils.py | ArgSwap(idxs=1<->2 @(157,15)->(157,25)) | class TestIncrementalDecoder(FairseqIncrementalDecoder):
probs[:, i, self.dictionary.eos()] = 1.0
# random attention
attn = torch.rand(bbsz, src_len, tgt_len)
return Variable(probs), Variable(attn)
| class TestIncrementalDecoder(FairseqIncrementalDecoder):
probs[:, i, self.dictionary.eos()] = 1.0
# random attention
attn = torch.rand(bbsz, tgt_len, src_len)
return Variable(probs), Variable(attn)
|
66 | https://:@github.com/pytorch/fairseq.git | dfd77717b91a6e233829735795ab49d6fd85c0b3 | @@ -93,7 +93,7 @@ class CosineSchedule(FairseqLRScheduler):
else:
i = math.floor(curr_updates / self.period)
t_i = self.period
- t_curr = num_updates - (self.period * i)
+ t_curr = curr_updates - (self.period * i)
lr_shrink = self.lr_shrink ** i
min_lr = self.min_lr * lr_shrink
| fairseq/optim/lr_scheduler/cosine_lr_scheduler.py | ReplaceText(target='curr_updates' @(96,25)->(96,36)) | class CosineSchedule(FairseqLRScheduler):
else:
i = math.floor(curr_updates / self.period)
t_i = self.period
t_curr = num_updates - (self.period * i)
lr_shrink = self.lr_shrink ** i
min_lr = self.min_lr * lr_shrink | class CosineSchedule(FairseqLRScheduler):
else:
i = math.floor(curr_updates / self.period)
t_i = self.period
t_curr = curr_updates - (self.period * i)
lr_shrink = self.lr_shrink ** i
min_lr = self.min_lr * lr_shrink |
67 | https://:@github.com/pytorch/fairseq.git | 0eea6923b9d7f408e667714709b070171ac7fe05 | @@ -312,7 +312,7 @@ def make_positions(tensor, padding_idx, left_pad, onnx_trace=False):
positions = range_buf.expand_as(tensor)
if left_pad:
positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1)
- return positions * mask.long() + positions * (1 - mask.long())
+ return positions * mask.long() + padding_idx * (1 - mask.long())
max_pos = padding_idx + 1 + tensor.size(1)
if not hasattr(make_positions, 'range_buf'):
| fairseq/utils.py | ReplaceText(target='padding_idx' @(315,41)->(315,50)) | def make_positions(tensor, padding_idx, left_pad, onnx_trace=False):
positions = range_buf.expand_as(tensor)
if left_pad:
positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1)
return positions * mask.long() + positions * (1 - mask.long())
max_pos = padding_idx + 1 + tensor.size(1)
if not hasattr(make_positions, 'range_buf'): | def make_positions(tensor, padding_idx, left_pad, onnx_trace=False):
positions = range_buf.expand_as(tensor)
if left_pad:
positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1)
return positions * mask.long() + padding_idx * (1 - mask.long())
max_pos = padding_idx + 1 + tensor.size(1)
if not hasattr(make_positions, 'range_buf'): |
68 | https://:@github.com/pytorch/fairseq.git | 4d3401b09f155995cd81fd394dfa50bf65ee8e5f | @@ -183,7 +183,7 @@ class Sampling(Search):
lprobs = lprobs[:, ::beam_size, :].contiguous()
# we exclude the first two vocab items, one of which is pad
- assert self.pad == 1, 'sampling assumes the first two symbols can be ignored'
+ assert self.pad <= 1, 'sampling assumes the first two symbols can be ignored'
lprobs_nopad = lprobs[:, :, 2:]
# only sample from top-k candidates
| fairseq/search.py | ReplaceText(target='<=' @(186,24)->(186,26)) | class Sampling(Search):
lprobs = lprobs[:, ::beam_size, :].contiguous()
# we exclude the first two vocab items, one of which is pad
assert self.pad == 1, 'sampling assumes the first two symbols can be ignored'
lprobs_nopad = lprobs[:, :, 2:]
# only sample from top-k candidates | class Sampling(Search):
lprobs = lprobs[:, ::beam_size, :].contiguous()
# we exclude the first two vocab items, one of which is pad
assert self.pad <= 1, 'sampling assumes the first two symbols can be ignored'
lprobs_nopad = lprobs[:, :, 2:]
# only sample from top-k candidates |
69 | https://:@github.com/pytorch/fairseq.git | 2340832fdd7acaaaf07626daa6a0cef6fda06cd1 | @@ -160,7 +160,7 @@ def main(args):
))
# update running id counter
- start_id += len(results)
+ start_id += len(inputs)
def cli_main():
| interactive.py | ReplaceText(target='inputs' @(163,24)->(163,31)) | def main(args):
))
# update running id counter
start_id += len(results)
def cli_main(): | def main(args):
))
# update running id counter
start_id += len(inputs)
def cli_main(): |
70 | https://:@github.com/pytorch/fairseq.git | 39a60b844aad67aa59267d873edeb4948f6f0af9 | @@ -351,7 +351,7 @@ class LSTMDecoder(FairseqIncrementalDecoder):
self.additional_fc = Linear(hidden_size, out_embed_dim)
if adaptive_softmax_cutoff is not None:
# setting adaptive_softmax dropout to dropout_out for now but can be redefined
- self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, embed_dim, adaptive_softmax_cutoff,
+ self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, hidden_size, adaptive_softmax_cutoff,
dropout=dropout_out)
elif not self.share_input_output_embed:
self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out)
| fairseq/models/lstm.py | ReplaceText(target='hidden_size' @(354,68)->(354,77)) | class LSTMDecoder(FairseqIncrementalDecoder):
self.additional_fc = Linear(hidden_size, out_embed_dim)
if adaptive_softmax_cutoff is not None:
# setting adaptive_softmax dropout to dropout_out for now but can be redefined
self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, embed_dim, adaptive_softmax_cutoff,
dropout=dropout_out)
elif not self.share_input_output_embed:
self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out) | class LSTMDecoder(FairseqIncrementalDecoder):
self.additional_fc = Linear(hidden_size, out_embed_dim)
if adaptive_softmax_cutoff is not None:
# setting adaptive_softmax dropout to dropout_out for now but can be redefined
self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, hidden_size, adaptive_softmax_cutoff,
dropout=dropout_out)
elif not self.share_input_output_embed:
self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out) |
71 | https://:@github.com/pytorch/fairseq.git | 49177c99c45f7d6e99a8f1500d16396e2d7b4519 | @@ -498,7 +498,7 @@ class TransformerDecoder(FairseqIncrementalDecoder):
del state_dict[k]
version_key = '{}.version'.format(name)
- if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2:
+ if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2:
# earlier checkpoints did not normalize after the stack of layers
self.layer_norm = None
self.normalize = False
| fairseq/models/transformer.py | ReplaceText(target='<=' @(501,73)->(501,74)) | class TransformerDecoder(FairseqIncrementalDecoder):
del state_dict[k]
version_key = '{}.version'.format(name)
if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2:
# earlier checkpoints did not normalize after the stack of layers
self.layer_norm = None
self.normalize = False | class TransformerDecoder(FairseqIncrementalDecoder):
del state_dict[k]
version_key = '{}.version'.format(name)
if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2:
# earlier checkpoints did not normalize after the stack of layers
self.layer_norm = None
self.normalize = False |
72 | https://:@github.com/pytorch/fairseq.git | 5d7a81099462e9f19715ce5fa37c03816a750e12 | @@ -412,7 +412,7 @@ class LevenshteinTransformerModel(FairseqNATModel):
max_lens = torch.zeros_like(output_tokens).fill_(255)
else:
if encoder_out.encoder_padding_mask is None:
- max_src_len = encoder_out.encoder_out.size(1)
+ max_src_len = encoder_out.encoder_out.size(0)
src_lens = encoder_out.encoder_out.new(bsz).fill_(max_src_len)
else:
src_lens = (~encoder_out.encoder_padding_mask).sum(1)
| fairseq/models/nat/levenshtein_transformer.py | ReplaceText(target='0' @(415,59)->(415,60)) | class LevenshteinTransformerModel(FairseqNATModel):
max_lens = torch.zeros_like(output_tokens).fill_(255)
else:
if encoder_out.encoder_padding_mask is None:
max_src_len = encoder_out.encoder_out.size(1)
src_lens = encoder_out.encoder_out.new(bsz).fill_(max_src_len)
else:
src_lens = (~encoder_out.encoder_padding_mask).sum(1) | class LevenshteinTransformerModel(FairseqNATModel):
max_lens = torch.zeros_like(output_tokens).fill_(255)
else:
if encoder_out.encoder_padding_mask is None:
max_src_len = encoder_out.encoder_out.size(0)
src_lens = encoder_out.encoder_out.new(bsz).fill_(max_src_len)
else:
src_lens = (~encoder_out.encoder_padding_mask).sum(1) |
73 | https://:@github.com/pytorch/fairseq.git | 431d604f696a15c06fceab56b4ace271bb85e74b | @@ -331,7 +331,7 @@ class SequenceGenerator(object):
avg_attn_scores = avg_attn_scores[0]
if avg_attn_scores is not None:
if attn is None:
- attn = scores.new(bsz * beam_size, src_tokens.size(1), max_len + 2)
+ attn = scores.new(bsz * beam_size, avg_attn_scores.size(1), max_len + 2)
attn_buf = attn.clone()
attn[:, :, step + 1].copy_(avg_attn_scores)
| fairseq/sequence_generator.py | ReplaceText(target='avg_attn_scores' @(334,55)->(334,65)) | class SequenceGenerator(object):
avg_attn_scores = avg_attn_scores[0]
if avg_attn_scores is not None:
if attn is None:
attn = scores.new(bsz * beam_size, src_tokens.size(1), max_len + 2)
attn_buf = attn.clone()
attn[:, :, step + 1].copy_(avg_attn_scores)
| class SequenceGenerator(object):
avg_attn_scores = avg_attn_scores[0]
if avg_attn_scores is not None:
if attn is None:
attn = scores.new(bsz * beam_size, avg_attn_scores.size(1), max_len + 2)
attn_buf = attn.clone()
attn[:, :, step + 1].copy_(avg_attn_scores)
|
74 | https://:@github.com/pytorch/fairseq.git | 4f8b0643c80d6a41039ae29e94fca6b44de8791a | @@ -138,7 +138,7 @@ def should_stop_early(args, valid_loss):
return False
else:
should_stop_early.num_runs += 1
- return should_stop_early.num_runs > args.patience
+ return should_stop_early.num_runs >= args.patience
@metrics.aggregate('train')
| fairseq_cli/train.py | ReplaceText(target='>=' @(141,42)->(141,43)) | def should_stop_early(args, valid_loss):
return False
else:
should_stop_early.num_runs += 1
return should_stop_early.num_runs > args.patience
@metrics.aggregate('train') | def should_stop_early(args, valid_loss):
return False
else:
should_stop_early.num_runs += 1
return should_stop_early.num_runs >= args.patience
@metrics.aggregate('train') |
75 | https://:@github.com/pytorch/fairseq.git | 9a718e29855713a51877237b2dcc25e39c234c82 | @@ -110,5 +110,5 @@ class TranslationFromPretrainedBARTTask(TranslationTask):
for s_t in src_tokens:
s_t = torch.cat([s_t, s_t.new(1).fill_(src_lang_id)])
source_tokens.append(s_t)
- dataset = LanguagePairDataset(src_tokens, src_lengths, self.source_dictionary)
+ dataset = LanguagePairDataset(source_tokens, src_lengths, self.source_dictionary)
return dataset
| fairseq/tasks/translation_from_pretrained_bart.py | ReplaceText(target='source_tokens' @(113,38)->(113,48)) | class TranslationFromPretrainedBARTTask(TranslationTask):
for s_t in src_tokens:
s_t = torch.cat([s_t, s_t.new(1).fill_(src_lang_id)])
source_tokens.append(s_t)
dataset = LanguagePairDataset(src_tokens, src_lengths, self.source_dictionary)
return dataset | class TranslationFromPretrainedBARTTask(TranslationTask):
for s_t in src_tokens:
s_t = torch.cat([s_t, s_t.new(1).fill_(src_lang_id)])
source_tokens.append(s_t)
dataset = LanguagePairDataset(source_tokens, src_lengths, self.source_dictionary)
return dataset |
76 | https://:@github.com/pytorch/fairseq.git | b689b6ff3ab7b806217b8aa41821bb8fc85f7cd8 | @@ -264,7 +264,7 @@ class LanguagePairDataset(FairseqDataset):
tgt_item = torch.cat([torch.LongTensor([bos]), self.tgt[index]])
bos = self.src_dict.bos()
- if self.src[index][-1] != bos:
+ if self.src[index][0] != bos:
src_item = torch.cat([torch.LongTensor([bos]), self.src[index]])
if self.remove_eos_from_source:
| fairseq/data/language_pair_dataset.py | ReplaceText(target='0' @(267,31)->(267,33)) | class LanguagePairDataset(FairseqDataset):
tgt_item = torch.cat([torch.LongTensor([bos]), self.tgt[index]])
bos = self.src_dict.bos()
if self.src[index][-1] != bos:
src_item = torch.cat([torch.LongTensor([bos]), self.src[index]])
if self.remove_eos_from_source: | class LanguagePairDataset(FairseqDataset):
tgt_item = torch.cat([torch.LongTensor([bos]), self.tgt[index]])
bos = self.src_dict.bos()
if self.src[index][0] != bos:
src_item = torch.cat([torch.LongTensor([bos]), self.src[index]])
if self.remove_eos_from_source: |
77 | https://:@github.com/prprprus/PyMySQLPool.git | 66b07cdf844554245cf209a72de89bd17133269c | @@ -169,7 +169,7 @@ class Pool(object):
if self.ping_check:
now = int(time())
timeout = now
- if isinstance(int, self.ping_check):
+ if isinstance(self.ping_check, int):
timeout = timeout - self.ping_check
if not hasattr(c, '__ping_check_timestamp'):
c.__ping_check_timestamp = now
| pymysqlpool/pool.py | ArgSwap(idxs=0<->1 @(172,15)->(172,25)) | class Pool(object):
if self.ping_check:
now = int(time())
timeout = now
if isinstance(int, self.ping_check):
timeout = timeout - self.ping_check
if not hasattr(c, '__ping_check_timestamp'):
c.__ping_check_timestamp = now | class Pool(object):
if self.ping_check:
now = int(time())
timeout = now
if isinstance(self.ping_check, int):
timeout = timeout - self.ping_check
if not hasattr(c, '__ping_check_timestamp'):
c.__ping_check_timestamp = now |
78 | https://:@github.com/dailymuse/oz.git | a15adf73c721d07b9dac886fcc27145e2449563c | @@ -173,7 +173,7 @@ class S3File(CDNFile):
def copy(self, new_path, replace=False):
"""Uses boto to copy the file to the new path instead of uploading another file to the new key"""
- if replace or get_file(new_path).exists():
+ if replace or not get_file(new_path).exists():
self.key.copy(self.key.bucket, new_path)
return True
return False
| oz/aws_cdn/__init__.py | ReplaceText(target='not ' @(176,22)->(176,22)) | class S3File(CDNFile):
def copy(self, new_path, replace=False):
"""Uses boto to copy the file to the new path instead of uploading another file to the new key"""
if replace or get_file(new_path).exists():
self.key.copy(self.key.bucket, new_path)
return True
return False | class S3File(CDNFile):
def copy(self, new_path, replace=False):
"""Uses boto to copy the file to the new path instead of uploading another file to the new key"""
if replace or not get_file(new_path).exists():
self.key.copy(self.key.bucket, new_path)
return True
return False |
79 | https://:@github.com/juju/amulet.git | 016bfab60aca89cbcb58e80f4103e371a77b06ba | @@ -77,7 +77,7 @@ class Deployment(object):
pass # Copy the current parent directory to temp and deploy that
elif self.charm_name:
if charm_name == self.charm_name:
- charm = os.getcwd()
+ charm_branch = os.getcwd()
self.services[service] = {'branch': charm_branch}
if units > 1:
| amulet/deployer.py | ReplaceText(target='charm_branch' @(80,16)->(80,21)) | class Deployment(object):
pass # Copy the current parent directory to temp and deploy that
elif self.charm_name:
if charm_name == self.charm_name:
charm = os.getcwd()
self.services[service] = {'branch': charm_branch}
if units > 1: | class Deployment(object):
pass # Copy the current parent directory to temp and deploy that
elif self.charm_name:
if charm_name == self.charm_name:
charm_branch = os.getcwd()
self.services[service] = {'branch': charm_branch}
if units > 1: |
80 | https://:@github.com/gitpython-developers/gitdb.git | ca829e0b341dd5c3ae1408b24702f2c75db6ec73 | @@ -445,7 +445,7 @@ class DeltaApplyReader(LazyMixin):
#{ Configuration
- if not has_perf_mod:
+ if has_perf_mod:
_set_cache_ = _set_cache_brute_
else:
_set_cache_ = _set_cache_too_slow_without_c
| stream.py | ReplaceText(target='' @(448,4)->(448,8)) | class DeltaApplyReader(LazyMixin):
#{ Configuration
if not has_perf_mod:
_set_cache_ = _set_cache_brute_
else:
_set_cache_ = _set_cache_too_slow_without_c | class DeltaApplyReader(LazyMixin):
#{ Configuration
if has_perf_mod:
_set_cache_ = _set_cache_brute_
else:
_set_cache_ = _set_cache_too_slow_without_c |
81 | https://:@github.com/longld/peda.git | 82fcb5a12c92c27fc5722772a84df47b996d3d03 | @@ -4746,7 +4746,7 @@ class PEDACmd(object):
step = peda.intsize()
if not peda.is_address(address): # cannot determine address
- msg("Invalid $SP address: 0x%x" % sp, "red")
+ msg("Invalid $SP address: 0x%x" % address, "red")
return
for i in range(count):
if not peda.execute("x/%sx 0x%x" % ("g" if step == 8 else "w", address + i*step)):
| peda.py | ReplaceText(target='address' @(4749,46)->(4749,48)) | class PEDACmd(object):
step = peda.intsize()
if not peda.is_address(address): # cannot determine address
msg("Invalid $SP address: 0x%x" % sp, "red")
return
for i in range(count):
if not peda.execute("x/%sx 0x%x" % ("g" if step == 8 else "w", address + i*step)): | class PEDACmd(object):
step = peda.intsize()
if not peda.is_address(address): # cannot determine address
msg("Invalid $SP address: 0x%x" % address, "red")
return
for i in range(count):
if not peda.execute("x/%sx 0x%x" % ("g" if step == 8 else "w", address + i*step)): |
82 | https://:@github.com/TheGhouls/oct.git | 1f9ea29181962353fe0ea275cb4ba4ec9ae93142 | @@ -18,7 +18,7 @@ class Report(object):
self.set_statics()
def set_statics(self):
- if os.path.exists(self.results_dir):
+ if not os.path.exists(self.results_dir):
return
try:
shutil.copytree(os.path.join(self.templates_dir, 'css'), os.path.join(self.results_dir, 'css'))
| oct/results/reportwriter.py | ReplaceText(target='not ' @(21,11)->(21,11)) | class Report(object):
self.set_statics()
def set_statics(self):
if os.path.exists(self.results_dir):
return
try:
shutil.copytree(os.path.join(self.templates_dir, 'css'), os.path.join(self.results_dir, 'css')) | class Report(object):
self.set_statics()
def set_statics(self):
if not os.path.exists(self.results_dir):
return
try:
shutil.copytree(os.path.join(self.templates_dir, 'css'), os.path.join(self.results_dir, 'css')) |
83 | https://:@github.com/ASPP/pelita.git | bee6872dbd95a1e526305ef39f42ac537fd2f708 | @@ -105,7 +105,7 @@ def create_maze(layout_mesh):
Mesh of lists of MazeComponents
"""
- maze_mesh = Mesh(layout_mesh.height, layout_mesh.width,
+ maze_mesh = Mesh(layout_mesh.width, layout_mesh.height,
data=[[] for i in range(len(layout_mesh))])
for index in maze_mesh.iterkeys():
if layout_mesh[index] == CTFUniverse.wall:
| pelita/universe.py | ArgSwap(idxs=0<->1 @(108,16)->(108,20)) | def create_maze(layout_mesh):
Mesh of lists of MazeComponents
"""
maze_mesh = Mesh(layout_mesh.height, layout_mesh.width,
data=[[] for i in range(len(layout_mesh))])
for index in maze_mesh.iterkeys():
if layout_mesh[index] == CTFUniverse.wall: | def create_maze(layout_mesh):
Mesh of lists of MazeComponents
"""
maze_mesh = Mesh(layout_mesh.width, layout_mesh.height,
data=[[] for i in range(len(layout_mesh))])
for index in maze_mesh.iterkeys():
if layout_mesh[index] == CTFUniverse.wall: |
84 | https://:@github.com/ASPP/pelita.git | 508cd180dce7b72ab248211c977c8525a9c023de | @@ -31,7 +31,7 @@ def __init__(self, index, initial_pos, team, homezone,
@property
def in_own_zone(self):
- return self.homezone[0] <= self.current_pos[1] <= self.homezone[1]
+ return self.homezone[0] <= self.current_pos[0] <= self.homezone[1]
def move(self, new_pos):
self.current_pos = new_pos
| pelita/universe.py | ReplaceText(target='0' @(34,52)->(34,53)) | def __init__(self, index, initial_pos, team, homezone,
@property
def in_own_zone(self):
return self.homezone[0] <= self.current_pos[1] <= self.homezone[1]
def move(self, new_pos):
self.current_pos = new_pos | def __init__(self, index, initial_pos, team, homezone,
@property
def in_own_zone(self):
return self.homezone[0] <= self.current_pos[0] <= self.homezone[1]
def move(self, new_pos):
self.current_pos = new_pos |
85 | https://:@github.com/ASPP/pelita.git | 6b76e416da2dc0d18224e47d7b176dad967e15b2 | @@ -182,7 +182,7 @@ def a_star(self, initial, target):
else:
seen.append(current)
for pos in self.adjacency[current]:
- heapq.heappush(to_visit, (datamodel.manhattan_dist(current, pos), (pos)))
+ heapq.heappush(to_visit, (datamodel.manhattan_dist(target, pos), (pos)))
# Now back-track using seen to determine how we got here.
# Initialise the path with current node, i.e. position of food.
| pelita/game_master.py | ReplaceText(target='target' @(185,71)->(185,78)) | def a_star(self, initial, target):
else:
seen.append(current)
for pos in self.adjacency[current]:
heapq.heappush(to_visit, (datamodel.manhattan_dist(current, pos), (pos)))
# Now back-track using seen to determine how we got here.
# Initialise the path with current node, i.e. position of food. | def a_star(self, initial, target):
else:
seen.append(current)
for pos in self.adjacency[current]:
heapq.heappush(to_visit, (datamodel.manhattan_dist(target, pos), (pos)))
# Now back-track using seen to determine how we got here.
# Initialise the path with current node, i.e. position of food. |
86 | https://:@github.com/ASPP/pelita.git | fa2505d44ae3d3724f7fa979c0167f03bf7424f7 | @@ -136,7 +136,7 @@ def play(self):
if self.universe.teams[0].score < self.universe.teams[1].score:
events.append(datamodel.TeamWins(1))
elif self.universe.teams[0].score > self.universe.teams[1].score:
- events.append(datamodel.TeamWins(1))
+ events.append(datamodel.TeamWins(0))
else:
events.append(datamodel.GameDraw())
self.send_to_viewers(round_index, None, events)
| pelita/game_master.py | ReplaceText(target='0' @(139,45)->(139,46)) | def play(self):
if self.universe.teams[0].score < self.universe.teams[1].score:
events.append(datamodel.TeamWins(1))
elif self.universe.teams[0].score > self.universe.teams[1].score:
events.append(datamodel.TeamWins(1))
else:
events.append(datamodel.GameDraw())
self.send_to_viewers(round_index, None, events) | def play(self):
if self.universe.teams[0].score < self.universe.teams[1].score:
events.append(datamodel.TeamWins(1))
elif self.universe.teams[0].score > self.universe.teams[1].score:
events.append(datamodel.TeamWins(0))
else:
events.append(datamodel.GameDraw())
self.send_to_viewers(round_index, None, events) |
87 | https://:@github.com/ASPP/pelita.git | 4044f845e54c2077d6896010c25fcc123fc10203 | @@ -78,7 +78,7 @@ def test_equal_positions(self):
layout = create_layout(layout_str)
assert layout.bots == [(1, 1), (1, 1)]
assert layout.enemy == [(1, 1), (1, 1)]
- setup_test_game(layout=layout)
+ setup_test_game(layout=layout_str)
def test_define_after(self):
layout = create_layout(self.layout, food=[(1, 1)], bots=[None, None], enemy=None)
| test/test_team.py | ReplaceText(target='layout_str' @(81,31)->(81,37)) | def test_equal_positions(self):
layout = create_layout(layout_str)
assert layout.bots == [(1, 1), (1, 1)]
assert layout.enemy == [(1, 1), (1, 1)]
setup_test_game(layout=layout)
def test_define_after(self):
layout = create_layout(self.layout, food=[(1, 1)], bots=[None, None], enemy=None) | def test_equal_positions(self):
layout = create_layout(layout_str)
assert layout.bots == [(1, 1), (1, 1)]
assert layout.enemy == [(1, 1), (1, 1)]
setup_test_game(layout=layout_str)
def test_define_after(self):
layout = create_layout(self.layout, food=[(1, 1)], bots=[None, None], enemy=None) |
88 | https://:@github.com/ASPP/pelita.git | 6fd0a9d2af44c491c1cc6774c3a169e97e2040be | @@ -398,7 +398,7 @@ def _team(self):
@property
def turn(self):
""" The turn of our bot. """
- return self.bot_index // 2
+ return self.bot_index % 2
@property
def other(self):
| pelita/player/team.py | ReplaceText(target='%' @(401,30)->(401,32)) | def _team(self):
@property
def turn(self):
""" The turn of our bot. """
return self.bot_index // 2
@property
def other(self): | def _team(self):
@property
def turn(self):
""" The turn of our bot. """
return self.bot_index % 2
@property
def other(self): |
89 | https://:@github.com/iotaledger/ccurl.interface.py.git | eb7f9190d24995d3f8d03a8350382ab6045a6e67 | @@ -44,7 +44,7 @@ gta = api.get_transactions_to_approve(depth=3) # get tips to be approved by your
mwm = 14 # target is mainnet
-bundle = entangled_interface.local_attach_to_tangle(pb, gta['trunkTransaction'], gta['branchTransaction'], mwm)
+bundle = entangled_interface.local_attach_to_tangle(pb, gta['branchTransaction'],gta['trunkTransaction'], mwm)
bundle_trytes = [ x.as_tryte_string() for x in pb._transactions ]
| examples/with_entangled.py | ArgSwap(idxs=1<->2 @(47,9)->(47,51)) | gta = api.get_transactions_to_approve(depth=3) # get tips to be approved by your
mwm = 14 # target is mainnet
bundle = entangled_interface.local_attach_to_tangle(pb, gta['trunkTransaction'], gta['branchTransaction'], mwm)
bundle_trytes = [ x.as_tryte_string() for x in pb._transactions ]
| gta = api.get_transactions_to_approve(depth=3) # get tips to be approved by your
mwm = 14 # target is mainnet
bundle = entangled_interface.local_attach_to_tangle(pb, gta['branchTransaction'],gta['trunkTransaction'], mwm)
bundle_trytes = [ x.as_tryte_string() for x in pb._transactions ]
|
90 | https://:@github.com/softlayer/softlayer-python.git | 53731de7e51d31475cc224aceb0f3ff7217cdafd | @@ -153,7 +153,7 @@ class NetworkManager(object):
('privateResidenceFlag', private_residence),
('state', state),
('postalCode', postal_code)]:
- if key is not None:
+ if value is not None:
update[key] = value
# If there's anything to update, update it
| SoftLayer/managers/network.py | ReplaceText(target='value' @(156,15)->(156,18)) | class NetworkManager(object):
('privateResidenceFlag', private_residence),
('state', state),
('postalCode', postal_code)]:
if key is not None:
update[key] = value
# If there's anything to update, update it | class NetworkManager(object):
('privateResidenceFlag', private_residence),
('state', state),
('postalCode', postal_code)]:
if value is not None:
update[key] = value
# If there's anything to update, update it |
91 | https://:@github.com/softlayer/softlayer-python.git | dcf66e15711e47c594f20ffac7605bfc6d1a8746 | @@ -15,7 +15,7 @@ import click
type=click.Choice(['vs', 'vlan', 'server']),
help='Firewall type',
required=True)
[email protected]('--high-availability', '--ha',
[email protected]('--ha', '--high-availability',
is_flag=True,
help='High available firewall option')
@environment.pass_env
| SoftLayer/CLI/firewall/add.py | ArgSwap(idxs=0<->1 @(18,1)->(18,13)) | import click
type=click.Choice(['vs', 'vlan', 'server']),
help='Firewall type',
required=True)
@click.option('--high-availability', '--ha',
is_flag=True,
help='High available firewall option')
@environment.pass_env | import click
type=click.Choice(['vs', 'vlan', 'server']),
help='Firewall type',
required=True)
@click.option('--ha', '--high-availability',
is_flag=True,
help='High available firewall option')
@environment.pass_env |
92 | https://:@github.com/softlayer/softlayer-python.git | f0840e302d486d6002a14419bbde85c1deedaf6a | @@ -271,7 +271,7 @@ class BlockStorageManager(utils.IdentifierMixin, object):
package,
'performance_storage_iscsi'
),
- storage_utils.find_performance_space_price(package, iops),
+ storage_utils.find_performance_space_price(package, size),
storage_utils.find_performance_iops_price(package, size, iops),
]
elif storage_type == 'storage_service_enterprise':
| SoftLayer/managers/block.py | ReplaceText(target='size' @(274,68)->(274,72)) | class BlockStorageManager(utils.IdentifierMixin, object):
package,
'performance_storage_iscsi'
),
storage_utils.find_performance_space_price(package, iops),
storage_utils.find_performance_iops_price(package, size, iops),
]
elif storage_type == 'storage_service_enterprise': | class BlockStorageManager(utils.IdentifierMixin, object):
package,
'performance_storage_iscsi'
),
storage_utils.find_performance_space_price(package, size),
storage_utils.find_performance_iops_price(package, size, iops),
]
elif storage_type == 'storage_service_enterprise': |
93 | https://:@github.com/softlayer/softlayer-python.git | 4418057fc0e3632aba2d89b6e42494c79cadd16a | @@ -367,7 +367,7 @@ class VSManager(utils.IdentifierMixin, object):
if datacenter:
data["datacenter"] = {"name": datacenter}
- if private_vlan and public_vlan:
+ if private_vlan or public_vlan:
network_components = self._create_network_components(public_vlan, private_vlan,
private_subnet, public_subnet)
data.update(network_components)
| SoftLayer/managers/vs.py | ReplaceText(target='or' @(370,24)->(370,27)) | class VSManager(utils.IdentifierMixin, object):
if datacenter:
data["datacenter"] = {"name": datacenter}
if private_vlan and public_vlan:
network_components = self._create_network_components(public_vlan, private_vlan,
private_subnet, public_subnet)
data.update(network_components) | class VSManager(utils.IdentifierMixin, object):
if datacenter:
data["datacenter"] = {"name": datacenter}
if private_vlan or public_vlan:
network_components = self._create_network_components(public_vlan, private_vlan,
private_subnet, public_subnet)
data.update(network_components) |
94 | https://:@github.com/softlayer/softlayer-python.git | 58b27c6bf5400a717acd00b7866964ef11f36e59 | @@ -87,6 +87,6 @@ def cli(env, identifier):
for guest in guests:
real_guest = guest.get('virtualGuest')
member_table.add_row([
- guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('provisionDate'))
+ real_guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('provisionDate'))
])
env.fout(member_table)
| SoftLayer/CLI/autoscale/detail.py | ReplaceText(target='real_guest' @(90,12)->(90,17)) | def cli(env, identifier):
for guest in guests:
real_guest = guest.get('virtualGuest')
member_table.add_row([
guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('provisionDate'))
])
env.fout(member_table) | def cli(env, identifier):
for guest in guests:
real_guest = guest.get('virtualGuest')
member_table.add_row([
real_guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('provisionDate'))
])
env.fout(member_table) |
95 | https://:@github.com/data-8/datascience.git | fd9aceb598290fb89a0f3131c3fb39dde18ef543 | @@ -446,7 +446,7 @@ class Table(collections.abc.Mapping):
count | points
9 | 10
"""
- percentiles = [percentile(self[column_name], p) for column_name in self]
+ percentiles = [percentile(p, self[column_name]) for column_name in self]
return Table(percentiles, self.column_labels)
##################
# Export/Display #
| datascience/tables.py | ArgSwap(idxs=0<->1 @(449,23)->(449,33)) | class Table(collections.abc.Mapping):
count | points
9 | 10
"""
percentiles = [percentile(self[column_name], p) for column_name in self]
return Table(percentiles, self.column_labels)
##################
# Export/Display # | class Table(collections.abc.Mapping):
count | points
9 | 10
"""
percentiles = [percentile(p, self[column_name]) for column_name in self]
return Table(percentiles, self.column_labels)
##################
# Export/Display # |
96 | https://:@github.com/data-8/datascience.git | 084450f127ecc490b887cad82fa43cda5f9b32fe | @@ -2255,7 +2255,7 @@ class Table(collections.abc.MutableMapping):
space_count[labels[i]] += 1
return updated_labels
return labels
- yticks = make_unique_labels(labels)
+ yticks = make_unique_labels(yticks)
print("yticks: " + str(yticks))
print("ylabel: " + str(ylabel))
| datascience/tables.py | ReplaceText(target='yticks' @(2258,36)->(2258,42)) | class Table(collections.abc.MutableMapping):
space_count[labels[i]] += 1
return updated_labels
return labels
yticks = make_unique_labels(labels)
print("yticks: " + str(yticks))
print("ylabel: " + str(ylabel)) | class Table(collections.abc.MutableMapping):
space_count[labels[i]] += 1
return updated_labels
return labels
yticks = make_unique_labels(yticks)
print("yticks: " + str(yticks))
print("ylabel: " + str(ylabel)) |
97 | https://:@github.com/dnaeon/py-vpoller.git | 81769f6f8d9cb0dfc8cbc39a44027afa7d459636 | @@ -51,6 +51,6 @@ def task(name, required=None):
result = {'success': 1, 'msg': e.message}
finally:
return result
- registry.register(name=name, fn=fn, required=required)
+ registry.register(name=name, fn=wrapper, required=required)
return wrapper
return decorator
| src/vpoller/decorators.py | ReplaceText(target='wrapper' @(54,40)->(54,42)) | def task(name, required=None):
result = {'success': 1, 'msg': e.message}
finally:
return result
registry.register(name=name, fn=fn, required=required)
return wrapper
return decorator | def task(name, required=None):
result = {'success': 1, 'msg': e.message}
finally:
return result
registry.register(name=name, fn=wrapper, required=required)
return wrapper
return decorator |
98 | https://:@github.com/enthought/qt_binder.git | 68381b406035f2ce9666cb8ef1ab2e8e57cf8bf8 | @@ -58,4 +58,4 @@ else:
loader = RecordingUiLoader()
ui = loader.load(path)
- return ui, ui.to_be_bound()
+ return ui, loader.to_be_bound()
| qt_binder/qt/ui_loader.py | ReplaceText(target='loader' @(61,19)->(61,21)) | else:
loader = RecordingUiLoader()
ui = loader.load(path)
return ui, ui.to_be_bound() | else:
loader = RecordingUiLoader()
ui = loader.load(path)
return ui, loader.to_be_bound() |
99 | https://:@github.com/ggozad/behaving.git | 1bc546aa03f9d42ff78a0a79e0894e488edc9add | @@ -40,7 +40,7 @@ def should_receive_email(context, address):
def click_link_in_email(context, address):
mails = context.mail.user_messages(address)
assert mails, u'message not found'
- mail = email.message_from_string(mails[-1])
+ mail = email.message_from_string(mails[0])
links = URL_RE.findall(str(mail).replace('=\n', ''))
assert links, u'link not found'
url = links[0]
| src/behaving/mail/steps.py | ReplaceText(target='0' @(43,43)->(43,45)) | def should_receive_email(context, address):
def click_link_in_email(context, address):
mails = context.mail.user_messages(address)
assert mails, u'message not found'
mail = email.message_from_string(mails[-1])
links = URL_RE.findall(str(mail).replace('=\n', ''))
assert links, u'link not found'
url = links[0] | def should_receive_email(context, address):
def click_link_in_email(context, address):
mails = context.mail.user_messages(address)
assert mails, u'message not found'
mail = email.message_from_string(mails[0])
links = URL_RE.findall(str(mail).replace('=\n', ''))
assert links, u'link not found'
url = links[0] |
End of preview. Expand
in Dataset Viewer.
See Allamanis et al., 2021 (NeurIPS 2021) for more information.
- Downloads last month
- 46