,repo,hash,diff,old_path,rewrite,initial_state,final_state 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) -@click.option('--high-availability', '--ha', +@click.option('--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]" 100,https://:@github.com/allenai/SciSpaCy.git,d0d1d525943e051762ea5482ba82c9a4718285c0,"@@ -58,7 +58,7 @@ def train_parser_and_tagger(train_json_path: str, parser = nlp.get_pipe('parser') train_corpus = GoldCorpus(train_json_path, dev_json_path) - test_corpus = GoldCorpus(train_json_path, dev_json_path) + test_corpus = GoldCorpus(train_json_path, test_json_path) if ontonotes_path: onto_train_path = os.path.join(ontonotes_path, ""train"") ",scripts/train_parser_and_tagger.py,"ReplaceText(target='test_json_path' @(61,46)->(61,59))","def train_parser_and_tagger(train_json_path: str, parser = nlp.get_pipe('parser') train_corpus = GoldCorpus(train_json_path, dev_json_path) test_corpus = GoldCorpus(train_json_path, dev_json_path) if ontonotes_path: onto_train_path = os.path.join(ontonotes_path, ""train"")","def train_parser_and_tagger(train_json_path: str, parser = nlp.get_pipe('parser') train_corpus = GoldCorpus(train_json_path, dev_json_path) test_corpus = GoldCorpus(train_json_path, test_json_path) if ontonotes_path: onto_train_path = os.path.join(ontonotes_path, ""train"")" 101,https://:@github.com/allenai/SciSpaCy.git,e15e9b7913459b6139d4f30030a502f30479cfd5,"@@ -190,7 +190,7 @@ def train_parser_and_tagger(train_json_path: str, print(""Token acc:"", scorer_onto_retrained.token_acc) with open(os.path.join(model_output_dir, ""ontonotes_test.json"")) as metric_file: - json.dump(scorer.scores, metric_file) + json.dump(scorer_onto_retrained.scores, metric_file) if __name__ == ""__main__"": parser = argparse.ArgumentParser() ",scripts/train_parser_and_tagger.py,"ReplaceText(target='scorer_onto_retrained' @(193,22)->(193,28))","def train_parser_and_tagger(train_json_path: str, print(""Token acc:"", scorer_onto_retrained.token_acc) with open(os.path.join(model_output_dir, ""ontonotes_test.json"")) as metric_file: json.dump(scorer.scores, metric_file) if __name__ == ""__main__"": parser = argparse.ArgumentParser() ","def train_parser_and_tagger(train_json_path: str, print(""Token acc:"", scorer_onto_retrained.token_acc) with open(os.path.join(model_output_dir, ""ontonotes_test.json"")) as metric_file: json.dump(scorer_onto_retrained.scores, metric_file) if __name__ == ""__main__"": parser = argparse.ArgumentParser() " 102,https://:@github.com/allenai/SciSpaCy.git,47400cbed4d4943f6bba7ed013bf80110f738f2e,"@@ -679,7 +679,7 @@ def eval_candidate_generation_and_linking(examples: List[data_util.MedMentionExa if generate_linking_classifier_training_data: for candidates, mention_types_for_mention in zip(candidates_by_mention, mention_types_by_mention): for candidate_id, candidate in candidates.items(): - classifier_example = linker.classifier_example(candidate_id, candidate, mention_text, mention_types) + classifier_example = linker.classifier_example(candidate_id, candidate, mention_text, mention_types_for_mention) classifier_example['label'] = int(gold_entity.umls_id == candidate_id) linking_classifier_training_data.append(classifier_example) ",scripts/linking.py,"ReplaceText(target='mention_types_for_mention' @(682,118)->(682,131))","def eval_candidate_generation_and_linking(examples: List[data_util.MedMentionExa if generate_linking_classifier_training_data: for candidates, mention_types_for_mention in zip(candidates_by_mention, mention_types_by_mention): for candidate_id, candidate in candidates.items(): classifier_example = linker.classifier_example(candidate_id, candidate, mention_text, mention_types) classifier_example['label'] = int(gold_entity.umls_id == candidate_id) linking_classifier_training_data.append(classifier_example) ","def eval_candidate_generation_and_linking(examples: List[data_util.MedMentionExa if generate_linking_classifier_training_data: for candidates, mention_types_for_mention in zip(candidates_by_mention, mention_types_by_mention): for candidate_id, candidate in candidates.items(): classifier_example = linker.classifier_example(candidate_id, candidate, mention_text, mention_types_for_mention) classifier_example['label'] = int(gold_entity.umls_id == candidate_id) linking_classifier_training_data.append(classifier_example) " 103,https://:@github.com/Burnysc2/python-sc2.git,c3f5b0de304727914a2a59d5cfde6dda04071686,"@@ -381,7 +381,7 @@ class BotAI(object): return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) - if unit is None or self.can_afford(building): + if unit is None or not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) ",sc2/bot_ai.py,"ReplaceText(target='not ' @(384,27)->(384,27))","class BotAI(object): return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if unit is None or self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) ","class BotAI(object): return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if unit is None or not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) " 104,https://:@github.com/Burnysc2/python-sc2.git,20468d57d6fd5cc80c9e7757d75e987bd81e632a,"@@ -185,7 +185,7 @@ class Point2(Pointlike): Used in ramp finding """""" assert self != p distanceBetweenPoints = self.distance_to(p) - assert r > distanceBetweenPoints / 2 + assert r >= distanceBetweenPoints / 2 # remaining distance from center towards the intersection, using pythagoras remainingDistanceFromCenter = (r ** 2 - (distanceBetweenPoints / 2) ** 2) ** 0.5 # center of both points ",sc2/position.py,"ReplaceText(target='>=' @(188,17)->(188,18))","class Point2(Pointlike): Used in ramp finding """""" assert self != p distanceBetweenPoints = self.distance_to(p) assert r > distanceBetweenPoints / 2 # remaining distance from center towards the intersection, using pythagoras remainingDistanceFromCenter = (r ** 2 - (distanceBetweenPoints / 2) ** 2) ** 0.5 # center of both points","class Point2(Pointlike): Used in ramp finding """""" assert self != p distanceBetweenPoints = self.distance_to(p) assert r >= distanceBetweenPoints / 2 # remaining distance from center towards the intersection, using pythagoras remainingDistanceFromCenter = (r ** 2 - (distanceBetweenPoints / 2) ** 2) ** 0.5 # center of both points" 105,https://:@github.com/Burnysc2/python-sc2.git,9470180d3caaa18098ebffea220719ad6083afbe,"@@ -185,7 +185,7 @@ class Point2(Pointlike): Used in ramp finding """""" assert self != p distanceBetweenPoints = self.distance_to(p) - assert r > distanceBetweenPoints / 2 + assert r >= distanceBetweenPoints / 2 # remaining distance from center towards the intersection, using pythagoras remainingDistanceFromCenter = (r ** 2 - (distanceBetweenPoints / 2) ** 2) ** 0.5 # center of both points ",sc2/position.py,"ReplaceText(target='>=' @(188,17)->(188,18))","class Point2(Pointlike): Used in ramp finding """""" assert self != p distanceBetweenPoints = self.distance_to(p) assert r > distanceBetweenPoints / 2 # remaining distance from center towards the intersection, using pythagoras remainingDistanceFromCenter = (r ** 2 - (distanceBetweenPoints / 2) ** 2) ** 0.5 # center of both points","class Point2(Pointlike): Used in ramp finding """""" assert self != p distanceBetweenPoints = self.distance_to(p) assert r >= distanceBetweenPoints / 2 # remaining distance from center towards the intersection, using pythagoras remainingDistanceFromCenter = (r ** 2 - (distanceBetweenPoints / 2) ** 2) ** 0.5 # center of both points" 106,https://:@github.com/Burnysc2/python-sc2.git,9c59f42e1722e1141a51300d472b0385d64f1640,"@@ -86,7 +86,7 @@ class Units(list): return self[0] def take(self, n: int) -> ""Units"": - if self.amount >= n: + if self.amount <= n: return self else: return self.subgroup(self[:n]) ",sc2/units.py,"ReplaceText(target='<=' @(89,23)->(89,25))","class Units(list): return self[0] def take(self, n: int) -> ""Units"": if self.amount >= n: return self else: return self.subgroup(self[:n])","class Units(list): return self[0] def take(self, n: int) -> ""Units"": if self.amount <= n: return self else: return self.subgroup(self[:n])" 107,https://:@github.com/kenjyco/beu.git,4aea6146fc5f01df3e344b9fadddf28b795dac89,"@@ -36,7 +36,7 @@ def _get_settings_file(): if not os.path.exists(home_config_dir): os.makedirs(home_config_dir) copyfile(sample_file, settings_file) - print('\nCopied settings to {}'.format(repr(home_config_dir))) + print('\nCopied settings to {}'.format(repr(settings_file))) return settings_file ",beu/__init__.py,"ReplaceText(target='settings_file' @(39,48)->(39,63))","def _get_settings_file(): if not os.path.exists(home_config_dir): os.makedirs(home_config_dir) copyfile(sample_file, settings_file) print('\nCopied settings to {}'.format(repr(home_config_dir))) return settings_file ","def _get_settings_file(): if not os.path.exists(home_config_dir): os.makedirs(home_config_dir) copyfile(sample_file, settings_file) print('\nCopied settings to {}'.format(repr(settings_file))) return settings_file " 108,https://:@github.com/WattTime/pyiso.git,009316799f872c90f50b73e41f3a6f9021f8b2cc,"@@ -111,7 +111,7 @@ class BaseClient(object): self.options.update(kwargs) # check start_at and end_at args - if self.options.get('start_at', None) and self.options.get('end_at', None): + if self.options.get('start_at', None) or self.options.get('end_at', None): assert self.options['start_at'] < self.options['end_at'] self.options['start_at'] = self.utcify(self.options['start_at']) self.options['end_at'] = self.utcify(self.options['end_at']) ",pyiso/base.py,"ReplaceText(target='or' @(114,46)->(114,49))","class BaseClient(object): self.options.update(kwargs) # check start_at and end_at args if self.options.get('start_at', None) and self.options.get('end_at', None): assert self.options['start_at'] < self.options['end_at'] self.options['start_at'] = self.utcify(self.options['start_at']) self.options['end_at'] = self.utcify(self.options['end_at'])","class BaseClient(object): self.options.update(kwargs) # check start_at and end_at args if self.options.get('start_at', None) or self.options.get('end_at', None): assert self.options['start_at'] < self.options['end_at'] self.options['start_at'] = self.utcify(self.options['start_at']) self.options['end_at'] = self.utcify(self.options['end_at'])" 109,https://:@github.com/WattTime/pyiso.git,31c2680f1e96d6affbbef6dc75b9ab3724a7d8b9,"@@ -117,7 +117,7 @@ class BaseClient(object): self.options.update(kwargs) # check start_at and end_at args - if self.options.get('start_at', None) or self.options.get('end_at', None): + if self.options.get('start_at', None) and self.options.get('end_at', None): assert self.options['start_at'] < self.options['end_at'] self.options['start_at'] = self.utcify(self.options['start_at']) self.options['end_at'] = self.utcify(self.options['end_at']) ",pyiso/base.py,"ReplaceText(target='and' @(120,46)->(120,48))","class BaseClient(object): self.options.update(kwargs) # check start_at and end_at args if self.options.get('start_at', None) or self.options.get('end_at', None): assert self.options['start_at'] < self.options['end_at'] self.options['start_at'] = self.utcify(self.options['start_at']) self.options['end_at'] = self.utcify(self.options['end_at'])","class BaseClient(object): self.options.update(kwargs) # check start_at and end_at args if self.options.get('start_at', None) and self.options.get('end_at', None): assert self.options['start_at'] < self.options['end_at'] self.options['start_at'] = self.utcify(self.options['start_at']) self.options['end_at'] = self.utcify(self.options['end_at'])" 110,https://:@github.com/WattTime/pyiso.git,14fd34daa69230352ecb651ee8f30a4566ab6c59,"@@ -18,7 +18,7 @@ class TestGenerationTask(TestCase): expected = client_factory(ba).get_generation(**kwargs) received = tasks.get_generation(ba, **kwargs) - for i in range(len(expected)): + for i in range(len(received)): if expected[i]['timestamp'] == received[i]['timestamp']: self.assertEqual(expected[i]['gen_MW'], received[i]['gen_MW']) self.assertEqual(expected[i]['fuel_name'], received[i]['fuel_name']) ",tests/test_tasks.py,"ReplaceText(target='received' @(21,27)->(21,35))","class TestGenerationTask(TestCase): expected = client_factory(ba).get_generation(**kwargs) received = tasks.get_generation(ba, **kwargs) for i in range(len(expected)): if expected[i]['timestamp'] == received[i]['timestamp']: self.assertEqual(expected[i]['gen_MW'], received[i]['gen_MW']) self.assertEqual(expected[i]['fuel_name'], received[i]['fuel_name'])","class TestGenerationTask(TestCase): expected = client_factory(ba).get_generation(**kwargs) received = tasks.get_generation(ba, **kwargs) for i in range(len(received)): if expected[i]['timestamp'] == received[i]['timestamp']: self.assertEqual(expected[i]['gen_MW'], received[i]['gen_MW']) self.assertEqual(expected[i]['fuel_name'], received[i]['fuel_name'])" 111,https://:@github.com/TTWShell/hobbit-core.git,b51217f7fc8cb238c1dc09e8932178cda40cf2b4,"@@ -133,4 +133,4 @@ class TestTransaction(BaseTest): with pytest.raises(Exception): view_func2() - assert len(User.query.all()) == 1 + assert len(User.query.all()) == 0 ",tests/test_db.py,"ReplaceText(target='0' @(136,40)->(136,41))","class TestTransaction(BaseTest): with pytest.raises(Exception): view_func2() assert len(User.query.all()) == 1","class TestTransaction(BaseTest): with pytest.raises(Exception): view_func2() assert len(User.query.all()) == 0" 112,https://:@github.com/ktdreyer/jenkins-job-wrecker.git,3be4ea2d49a46cec8223361142305107b88ca889,"@@ -162,7 +162,7 @@ def prebuildcleanup(top, parent): pass else: raise NotImplementedError(""cannot handle "" - ""XML %s"" % subelement.tag) + ""XML %s"" % element.tag) for rule in preclean_patterns: if preclean_patterns[rule] is not None and len(preclean_patterns[rule]) > 0: ",jenkins_job_wrecker/modules/buildwrappers.py,"ReplaceText(target='element' @(165,49)->(165,59))","def prebuildcleanup(top, parent): pass else: raise NotImplementedError(""cannot handle "" ""XML %s"" % subelement.tag) for rule in preclean_patterns: if preclean_patterns[rule] is not None and len(preclean_patterns[rule]) > 0:","def prebuildcleanup(top, parent): pass else: raise NotImplementedError(""cannot handle "" ""XML %s"" % element.tag) for rule in preclean_patterns: if preclean_patterns[rule] is not None and len(preclean_patterns[rule]) > 0:" 113,https://:@github.com/Sage-Bionetworks/Genie.git,7a6ff590425d32fd596687bd0d35bc98680fc5b8,"@@ -379,7 +379,7 @@ class clinical(example_filetype_format.FileTypeFormat): patient_patients = clinicalDF[patientId][clinicalDF[patientId] != """"] # #CHECK: All samples must have associated patient data (GENIE requires patient data) if not all(sample_patients.isin(patient_patients)): - total_error += ""Sample: All samples must have associated patient information. These samples are missing patient data: %s\n"" % "", "".join(clinicalSampleDF[patientId][~clinicalSampleDF[patientId].isin(clinicalDF[patientId])]) + total_error += ""Sample: All samples must have associated patient information. These samples are missing patient data: %s\n"" % "", "".join(clinicalSampleDF[sampleId][~clinicalSampleDF[patientId].isin(clinicalDF[patientId])]) #CHECK: All patients must have associated sample data if not all(patient_patients.isin(sample_patients)): ### MAKE WARNING FOR NOW### ",processing/clinical.py,"ReplaceText(target='sampleId' @(382,157)->(382,166))","class clinical(example_filetype_format.FileTypeFormat): patient_patients = clinicalDF[patientId][clinicalDF[patientId] != """"] # #CHECK: All samples must have associated patient data (GENIE requires patient data) if not all(sample_patients.isin(patient_patients)): total_error += ""Sample: All samples must have associated patient information. These samples are missing patient data: %s\n"" % "", "".join(clinicalSampleDF[patientId][~clinicalSampleDF[patientId].isin(clinicalDF[patientId])]) #CHECK: All patients must have associated sample data if not all(patient_patients.isin(sample_patients)): ### MAKE WARNING FOR NOW###","class clinical(example_filetype_format.FileTypeFormat): patient_patients = clinicalDF[patientId][clinicalDF[patientId] != """"] # #CHECK: All samples must have associated patient data (GENIE requires patient data) if not all(sample_patients.isin(patient_patients)): total_error += ""Sample: All samples must have associated patient information. These samples are missing patient data: %s\n"" % "", "".join(clinicalSampleDF[sampleId][~clinicalSampleDF[patientId].isin(clinicalDF[patientId])]) #CHECK: All patients must have associated sample data if not all(patient_patients.isin(sample_patients)): ### MAKE WARNING FOR NOW###" 114,https://:@github.com/Sage-Bionetworks/Genie.git,b5b670e4a5797ba2a66caa517bbe2160fec645f7,"@@ -209,7 +209,7 @@ def createMafDatabase(syn, databaseToSynIdMappingDf,testing=False,staging=False) #Make sure to store the newly created maf db synid into the staging synapse mapping databaseToSynIdMapping = syn.tableQuery(""SELECT * FROM syn12094210 where Database = 'vcf2maf'"") databaseToSynIdMappingDf = databaseToSynIdMapping.asDataFrame() - databaseToSynIdMapping['Id'][0] = newMafDb.id + databaseToSynIdMappingDf['Id'][0] = newMafDb.id syn.store(synapseclient.Table(""syn12094210"",databaseToSynIdMappingDf)) #Move and archive old mafdatabase mafDatabaseEnt.parentId = ""syn7208886"" ",processing/input_to_database.py,"ReplaceText(target='databaseToSynIdMappingDf' @(212,2)->(212,24))","def createMafDatabase(syn, databaseToSynIdMappingDf,testing=False,staging=False) #Make sure to store the newly created maf db synid into the staging synapse mapping databaseToSynIdMapping = syn.tableQuery(""SELECT * FROM syn12094210 where Database = 'vcf2maf'"") databaseToSynIdMappingDf = databaseToSynIdMapping.asDataFrame() databaseToSynIdMapping['Id'][0] = newMafDb.id syn.store(synapseclient.Table(""syn12094210"",databaseToSynIdMappingDf)) #Move and archive old mafdatabase mafDatabaseEnt.parentId = ""syn7208886""","def createMafDatabase(syn, databaseToSynIdMappingDf,testing=False,staging=False) #Make sure to store the newly created maf db synid into the staging synapse mapping databaseToSynIdMapping = syn.tableQuery(""SELECT * FROM syn12094210 where Database = 'vcf2maf'"") databaseToSynIdMappingDf = databaseToSynIdMapping.asDataFrame() databaseToSynIdMappingDf['Id'][0] = newMafDb.id syn.store(synapseclient.Table(""syn12094210"",databaseToSynIdMappingDf)) #Move and archive old mafdatabase mafDatabaseEnt.parentId = ""syn7208886""" 115,https://:@github.com/Sage-Bionetworks/Genie.git,78fcacd10d4c44c90f41893a161de24ff13ea774,"@@ -311,7 +311,7 @@ class clinical(FileTypeFormat): haveColumn = process_functions.checkColExist(clinicalDF, ""SEQ_ASSAY_ID"") if haveColumn: if not all([i != """" for i in clinicalDF['SEQ_ASSAY_ID']]): - total_error += ""Sample: Please double check your SEQ_ASSAY_ID columns, there are empty rows.\n"" + warning += ""Sample: Please double check your SEQ_ASSAY_ID columns, there are empty rows.\n"" #must remove empty seq assay ids first #Checking if seq assay ids start with the center name seqAssayIds = clinicalDF.SEQ_ASSAY_ID[clinicalDF.SEQ_ASSAY_ID != """"] ",genie/clinical.py,"ReplaceText(target='warning' @(314,4)->(314,15))","class clinical(FileTypeFormat): haveColumn = process_functions.checkColExist(clinicalDF, ""SEQ_ASSAY_ID"") if haveColumn: if not all([i != """" for i in clinicalDF['SEQ_ASSAY_ID']]): total_error += ""Sample: Please double check your SEQ_ASSAY_ID columns, there are empty rows.\n"" #must remove empty seq assay ids first #Checking if seq assay ids start with the center name seqAssayIds = clinicalDF.SEQ_ASSAY_ID[clinicalDF.SEQ_ASSAY_ID != """"]","class clinical(FileTypeFormat): haveColumn = process_functions.checkColExist(clinicalDF, ""SEQ_ASSAY_ID"") if haveColumn: if not all([i != """" for i in clinicalDF['SEQ_ASSAY_ID']]): warning += ""Sample: Please double check your SEQ_ASSAY_ID columns, there are empty rows.\n"" #must remove empty seq assay ids first #Checking if seq assay ids start with the center name seqAssayIds = clinicalDF.SEQ_ASSAY_ID[clinicalDF.SEQ_ASSAY_ID != """"]" 116,https://:@github.com/Sage-Bionetworks/Genie.git,e115f3884db224a231c87b346f04d6edbf66d6bb,"@@ -87,7 +87,7 @@ class vcf(maf.maf): tumor = ""TUMOR"" normal = ""NORMAL"" # ### If the tumor name isn't TUMOR, set the sample id to be the tumor name - if tumor != ""TUMOR"": + if tumor == ""TUMOR"": tumorName = vcfName.replace("".vcf"","""") else: tumorName = tumor ",genie/vcf.py,"ReplaceText(target='==' @(90,12)->(90,14))","class vcf(maf.maf): tumor = ""TUMOR"" normal = ""NORMAL"" # ### If the tumor name isn't TUMOR, set the sample id to be the tumor name if tumor != ""TUMOR"": tumorName = vcfName.replace("".vcf"","""") else: tumorName = tumor","class vcf(maf.maf): tumor = ""TUMOR"" normal = ""NORMAL"" # ### If the tumor name isn't TUMOR, set the sample id to be the tumor name if tumor == ""TUMOR"": tumorName = vcfName.replace("".vcf"","""") else: tumorName = tumor" 117,https://:@github.com/Sage-Bionetworks/Genie.git,4c861c5eccebb0d0a402d85b658924df1e6a8819,"@@ -247,7 +247,7 @@ def validation(syn, center, process, center_mapping_df, databaseToSynIdMappingDf duplicatedFiles = duplicatedFiles.append(cbsSegFiles) clinical_bool = [""clinical"" in i for i in inputValidStatus['name']] clinical_files = inputValidStatus[clinical_bool] - if len(clinical_bool) > 2: + if len(clinical_files) > 2: duplicatedFiles = duplicatedFiles.append(clinical_files) # nodups = [""data_mutations_extended""] ",genie/input_to_database.py,"ReplaceText(target='clinical_files' @(250,15)->(250,28))","def validation(syn, center, process, center_mapping_df, databaseToSynIdMappingDf duplicatedFiles = duplicatedFiles.append(cbsSegFiles) clinical_bool = [""clinical"" in i for i in inputValidStatus['name']] clinical_files = inputValidStatus[clinical_bool] if len(clinical_bool) > 2: duplicatedFiles = duplicatedFiles.append(clinical_files) # nodups = [""data_mutations_extended""]","def validation(syn, center, process, center_mapping_df, databaseToSynIdMappingDf duplicatedFiles = duplicatedFiles.append(cbsSegFiles) clinical_bool = [""clinical"" in i for i in inputValidStatus['name']] clinical_files = inputValidStatus[clinical_bool] if len(clinical_files) > 2: duplicatedFiles = duplicatedFiles.append(clinical_files) # nodups = [""data_mutations_extended""]" 118,https://:@github.com/Sage-Bionetworks/Genie.git,39f33cd754223ee515b8d790c0cd96b32f36b88e,"@@ -270,7 +270,7 @@ def validatefile(syn, entities, validation_status_table, error_tracker_table, input_status_list, invalid_errors_list = _get_status_and_error_list( valid, message, entities) # Send email the first time the file is invalid - if invalid_errors_list: + if not invalid_errors_list: _send_validation_error_email(syn, filenames, message, file_users) else: input_status_list = [ ",genie/input_to_database.py,"ReplaceText(target='not ' @(273,11)->(273,11))","def validatefile(syn, entities, validation_status_table, error_tracker_table, input_status_list, invalid_errors_list = _get_status_and_error_list( valid, message, entities) # Send email the first time the file is invalid if invalid_errors_list: _send_validation_error_email(syn, filenames, message, file_users) else: input_status_list = [","def validatefile(syn, entities, validation_status_table, error_tracker_table, input_status_list, invalid_errors_list = _get_status_and_error_list( valid, message, entities) # Send email the first time the file is invalid if not invalid_errors_list: _send_validation_error_email(syn, filenames, message, file_users) else: input_status_list = [" 119,https://:@github.com/Sage-Bionetworks/Genie.git,e140dee708542afa35c5d1e30671d8083fcbcd29,"@@ -512,7 +512,7 @@ class bed(FileTypeFormat): string: Path to new bed file """""" final_beddf = self._process(beddf, seq_assay_id, newPath, parentId) - process_functions.updateData(self.syn, databaseSynId, beddf, + process_functions.updateData(self.syn, databaseSynId, final_beddf, seq_assay_id, filterByColumn=""SEQ_ASSAY_ID"", toDelete=True) ",genie/bed.py,"ReplaceText(target='final_beddf' @(515,62)->(515,67))","class bed(FileTypeFormat): string: Path to new bed file """""" final_beddf = self._process(beddf, seq_assay_id, newPath, parentId) process_functions.updateData(self.syn, databaseSynId, beddf, seq_assay_id, filterByColumn=""SEQ_ASSAY_ID"", toDelete=True)","class bed(FileTypeFormat): string: Path to new bed file """""" final_beddf = self._process(beddf, seq_assay_id, newPath, parentId) process_functions.updateData(self.syn, databaseSynId, final_beddf, seq_assay_id, filterByColumn=""SEQ_ASSAY_ID"", toDelete=True)" 120,https://:@github.com/Libensemble/libensemble.git,a7175c6bf59803deb4a52aaf8c0185b93874ff21,"@@ -96,7 +96,7 @@ def decide_work_and_resources(active_w, idle_w, H, H_ind, sim_specs, gen_specs): 'form_subcomm': [], 'calc_in': H[sim_specs['in']][inds_to_send], 'calc_out': sim_specs['out'], - 'calc_info': {'type':'sim', 'pt_ids': q_inds}, + 'calc_info': {'type':'sim', 'pt_ids': inds_to_send}, } update_history_x_out(H, q_inds, Work[i]['calc_in'], i, sim_specs['params']) ",code/src/libE_manager.py,"ReplaceText(target='inds_to_send' @(99,61)->(99,67))","def decide_work_and_resources(active_w, idle_w, H, H_ind, sim_specs, gen_specs): 'form_subcomm': [], 'calc_in': H[sim_specs['in']][inds_to_send], 'calc_out': sim_specs['out'], 'calc_info': {'type':'sim', 'pt_ids': q_inds}, } update_history_x_out(H, q_inds, Work[i]['calc_in'], i, sim_specs['params'])","def decide_work_and_resources(active_w, idle_w, H, H_ind, sim_specs, gen_specs): 'form_subcomm': [], 'calc_in': H[sim_specs['in']][inds_to_send], 'calc_out': sim_specs['out'], 'calc_info': {'type':'sim', 'pt_ids': inds_to_send}, } update_history_x_out(H, q_inds, Work[i]['calc_in'], i, sim_specs['params'])" 121,https://:@github.com/Libensemble/libensemble.git,ad5e021d040efd28a61d6afa2be908e25f363bd4,"@@ -52,7 +52,7 @@ def worker_main(c, sim_specs, gen_specs): if tag_out == STOP_TAG: break - comm.send(obj=data_out, dest=0, tag=calc_tag) + comm.send(obj=data_out, dest=0, tag=tag_out) # Clean up for loc in locations.values(): ",code/src/libE_worker.py,"ReplaceText(target='tag_out' @(55,44)->(55,52))","def worker_main(c, sim_specs, gen_specs): if tag_out == STOP_TAG: break comm.send(obj=data_out, dest=0, tag=calc_tag) # Clean up for loc in locations.values():","def worker_main(c, sim_specs, gen_specs): if tag_out == STOP_TAG: break comm.send(obj=data_out, dest=0, tag=tag_out) # Clean up for loc in locations.values():" 122,https://:@github.com/Libensemble/libensemble.git,2b33970bdac3034cc7799c2849eae09f9c22fcf6,"@@ -40,7 +40,7 @@ class MPIComm(Comm): def kill_pending(self): ""Make sure pending requests are cancelled if the comm is killed."" for req in self._outbox: - if req.Test(): + if not req.Test(): req.Cancel() self._outbox = [] ",libensemble/mpi_comms.py,"ReplaceText(target='not ' @(43,15)->(43,15))","class MPIComm(Comm): def kill_pending(self): ""Make sure pending requests are cancelled if the comm is killed."" for req in self._outbox: if req.Test(): req.Cancel() self._outbox = [] ","class MPIComm(Comm): def kill_pending(self): ""Make sure pending requests are cancelled if the comm is killed."" for req in self._outbox: if not req.Test(): req.Cancel() self._outbox = [] " 123,https://:@github.com/Libensemble/libensemble.git,155ba0c0517046e8ec305e76862bc6f0a44fafc7,"@@ -136,7 +136,7 @@ class EnvResources: nidstr = splitstr[1].strip(""]"") nidlst = EnvResources._noderange_append(prefix, nidstr) else: # Multiple Partitions - splitgroups = [str.split('[', 1) for str in splitstr] + splitgroups = [str.split('[', 1) for str in part_splitstr] prefixgroups = [group[0] for group in splitgroups] nodegroups = [group[1].strip(']') for group in splitgroups] nidlst = [] ",libensemble/env_resources.py,"ReplaceText(target='part_splitstr' @(139,56)->(139,64))","class EnvResources: nidstr = splitstr[1].strip(""]"") nidlst = EnvResources._noderange_append(prefix, nidstr) else: # Multiple Partitions splitgroups = [str.split('[', 1) for str in splitstr] prefixgroups = [group[0] for group in splitgroups] nodegroups = [group[1].strip(']') for group in splitgroups] nidlst = []","class EnvResources: nidstr = splitstr[1].strip(""]"") nidlst = EnvResources._noderange_append(prefix, nidstr) else: # Multiple Partitions splitgroups = [str.split('[', 1) for str in part_splitstr] prefixgroups = [group[0] for group in splitgroups] nodegroups = [group[1].strip(']') for group in splitgroups] nidlst = []" 124,https://:@github.com/Libensemble/libensemble.git,c89e4f0b72361ba84884a3c691d73d8f62b98014,"@@ -108,7 +108,7 @@ def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): last_size = persis_info.get('last_size') if len(H): # Don't give gen instances in batch mode if points are unfinished - if (gen_specs['user'].get('batch_mode') + if (alloc_specs['user'].get('batch_mode') and not all(np.logical_or(H['returned'][last_size:], H['paused'][last_size:]))): break ",libensemble/alloc_funcs/fast_alloc_and_pausing.py,"ReplaceText(target='alloc_specs' @(111,20)->(111,29))","def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): last_size = persis_info.get('last_size') if len(H): # Don't give gen instances in batch mode if points are unfinished if (gen_specs['user'].get('batch_mode') and not all(np.logical_or(H['returned'][last_size:], H['paused'][last_size:]))): break","def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): last_size = persis_info.get('last_size') if len(H): # Don't give gen instances in batch mode if points are unfinished if (alloc_specs['user'].get('batch_mode') and not all(np.logical_or(H['returned'][last_size:], H['paused'][last_size:]))): break" 125,https://:@github.com/Libensemble/libensemble.git,c89e4f0b72361ba84884a3c691d73d8f62b98014,"@@ -33,7 +33,7 @@ def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): last_size = persis_info.get('last_size') if len(H): # Don't give gen instances in batch mode if points are unfinished - if (gen_specs['user'].get('batch_mode') + if (alloc_specs['user'].get('batch_mode') and not all(np.logical_or(H['returned'][last_size:], H['paused'][last_size:]))): break ",libensemble/alloc_funcs/fast_alloc_to_aposmm.py,"ReplaceText(target='alloc_specs' @(36,20)->(36,29))","def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): last_size = persis_info.get('last_size') if len(H): # Don't give gen instances in batch mode if points are unfinished if (gen_specs['user'].get('batch_mode') and not all(np.logical_or(H['returned'][last_size:], H['paused'][last_size:]))): break","def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): last_size = persis_info.get('last_size') if len(H): # Don't give gen instances in batch mode if points are unfinished if (alloc_specs['user'].get('batch_mode') and not all(np.logical_or(H['returned'][last_size:], H['paused'][last_size:]))): break" 126,https://:@github.com/Libensemble/libensemble.git,c89e4f0b72361ba84884a3c691d73d8f62b98014,"@@ -73,7 +73,7 @@ def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): # No gen instances in batch mode if workers still working still_working = ~H['returned'] - if gen_specs['user'].get('batch_mode') and np.any(still_working): + if alloc_specs['user'].get('batch_mode') and np.any(still_working): break # Give gen work ",libensemble/alloc_funcs/give_sim_work_first.py,"ReplaceText(target='alloc_specs' @(76,15)->(76,24))","def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): # No gen instances in batch mode if workers still working still_working = ~H['returned'] if gen_specs['user'].get('batch_mode') and np.any(still_working): break # Give gen work","def give_sim_work_first(W, H, sim_specs, gen_specs, alloc_specs, persis_info): # No gen instances in batch mode if workers still working still_working = ~H['returned'] if alloc_specs['user'].get('batch_mode') and np.any(still_working): break # Give gen work" 127,https://:@github.com/Libensemble/libensemble.git,55f4a8f05ade4709b53cbe9ef92fe00a0e2e9a79,"@@ -59,7 +59,7 @@ def try_and_run_nlopt(H, gen_specs, libE_info): gen_specs['user']['ub'], gen_specs['user']['lb'], local=True, active=True) tag, Work, calc_in = sendrecv_mgr_worker_msg(comm, H_o) if tag in [STOP_TAG, PERSIS_STOP]: - nlopt.forced_stop.message = 'tag=' + str(tag) + nlopt.forced_stop.message = 'tag=' + str(Work) raise nlopt.forced_stop # Return function value (and maybe gradient) ",libensemble/gen_funcs/uniform_or_localopt.py,"ReplaceText(target='Work' @(62,53)->(62,56))","def try_and_run_nlopt(H, gen_specs, libE_info): gen_specs['user']['ub'], gen_specs['user']['lb'], local=True, active=True) tag, Work, calc_in = sendrecv_mgr_worker_msg(comm, H_o) if tag in [STOP_TAG, PERSIS_STOP]: nlopt.forced_stop.message = 'tag=' + str(tag) raise nlopt.forced_stop # Return function value (and maybe gradient)","def try_and_run_nlopt(H, gen_specs, libE_info): gen_specs['user']['ub'], gen_specs['user']['lb'], local=True, active=True) tag, Work, calc_in = sendrecv_mgr_worker_msg(comm, H_o) if tag in [STOP_TAG, PERSIS_STOP]: nlopt.forced_stop.message = 'tag=' + str(Work) raise nlopt.forced_stop # Return function value (and maybe gradient)" 128,https://:@github.com/Libensemble/libensemble.git,c090514bb370c6960db4c8be2ae643534def8d2b,"@@ -24,4 +24,4 @@ def persistent_uniform(H, persis_info, gen_specs, libE_info): H_o['x'] = persis_info['rand_stream'].uniform(lb, ub, (b, n)) tag, Work, calc_in = sendrecv_mgr_worker_msg(libE_info['comm'], H_o) - return H_o, persis_info, tag + return H_o, persis_info, Work ",libensemble/gen_funcs/persistent_uniform_sampling.py,"ReplaceText(target='Work' @(27,29)->(27,32))","def persistent_uniform(H, persis_info, gen_specs, libE_info): H_o['x'] = persis_info['rand_stream'].uniform(lb, ub, (b, n)) tag, Work, calc_in = sendrecv_mgr_worker_msg(libE_info['comm'], H_o) return H_o, persis_info, tag","def persistent_uniform(H, persis_info, gen_specs, libE_info): H_o['x'] = persis_info['rand_stream'].uniform(lb, ub, (b, n)) tag, Work, calc_in = sendrecv_mgr_worker_msg(libE_info['comm'], H_o) return H_o, persis_info, Work" 129,https://:@github.com/davedittrich/python_secrets.git,3a477f63bb9d0417e63254ba993025a8666c3e1d,"@@ -181,7 +181,7 @@ class PythonSecretsApp(App): self.environment = self.options.environment self.secrets_basedir = self.options.secrets_basedir # Don't output error messages when ""complete"" command used - if cmd.cmd_name == 'complete': + if cmd.cmd_name != 'complete': SecretsEnvironment.permissions_check( self.secrets_basedir, verbose_level=self.options.verbose_level, ",psec/main.py,"ReplaceText(target='!=' @(184,24)->(184,26))","class PythonSecretsApp(App): self.environment = self.options.environment self.secrets_basedir = self.options.secrets_basedir # Don't output error messages when ""complete"" command used if cmd.cmd_name == 'complete': SecretsEnvironment.permissions_check( self.secrets_basedir, verbose_level=self.options.verbose_level,","class PythonSecretsApp(App): self.environment = self.options.environment self.secrets_basedir = self.options.secrets_basedir # Don't output error messages when ""complete"" command used if cmd.cmd_name != 'complete': SecretsEnvironment.permissions_check( self.secrets_basedir, verbose_level=self.options.verbose_level," 130,https://:@github.com/junzis/pyModeS.git,b2940af6efe4cb6d99bca8a1f1f214292acf3e6a,"@@ -79,7 +79,7 @@ def cpr2position(cprlat0, cprlat1, cprlon0, cprlon1, t0, t1): cprlat_even = cprlat0 / 131072.0 cprlat_odd = cprlat1 / 131072.0 cprlon_even = cprlon0 / 131072.0 - cprlon_odd = cprlon0 / 131072.0 + cprlon_odd = cprlon1 / 131072.0 air_d_lat_even = 360.0 / 60 air_d_lat_odd = 360.0 / 59 ",decoder.py,"ReplaceText(target='cprlon1' @(82,18)->(82,25))","def cpr2position(cprlat0, cprlat1, cprlon0, cprlon1, t0, t1): cprlat_even = cprlat0 / 131072.0 cprlat_odd = cprlat1 / 131072.0 cprlon_even = cprlon0 / 131072.0 cprlon_odd = cprlon0 / 131072.0 air_d_lat_even = 360.0 / 60 air_d_lat_odd = 360.0 / 59 ","def cpr2position(cprlat0, cprlat1, cprlon0, cprlon1, t0, t1): cprlat_even = cprlat0 / 131072.0 cprlat_odd = cprlat1 / 131072.0 cprlon_even = cprlon0 / 131072.0 cprlon_odd = cprlon1 / 131072.0 air_d_lat_even = 360.0 / 60 air_d_lat_odd = 360.0 / 59 " 131,https://:@github.com/icb-dcm/pyabc.git,2df9fbbc034ecad45cde0e14d0205fc70ae9b90b,"@@ -456,5 +456,5 @@ class ABCSMC: return for m in self.history.alive_models(t - 1): - particles, w = self.history.get_distribution(t - 1, m) + particles, w = self.history.get_distribution(m, t - 1) self.transitions[m].fit(particles, w) ",pyabc/smc.py,"ArgSwap(idxs=0<->1 @(459,27)->(459,56))","class ABCSMC: return for m in self.history.alive_models(t - 1): particles, w = self.history.get_distribution(t - 1, m) self.transitions[m].fit(particles, w)","class ABCSMC: return for m in self.history.alive_models(t - 1): particles, w = self.history.get_distribution(m, t - 1) self.transitions[m].fit(particles, w)" 132,https://:@github.com/icb-dcm/pyabc.git,2df9fbbc034ecad45cde0e14d0205fc70ae9b90b,"@@ -108,7 +108,7 @@ def abc_model(abc_id, model_id, t): t = history.max_t else: t = int(t) - df, w = history.get_distribution(t, model_id) + df, w = history.get_distribution(model_id, t) df[""CDF""] = w tabs = [] ",pyabc/visserver/server.py,"ArgSwap(idxs=0<->1 @(111,12)->(111,36))","def abc_model(abc_id, model_id, t): t = history.max_t else: t = int(t) df, w = history.get_distribution(t, model_id) df[""CDF""] = w tabs = [] ","def abc_model(abc_id, model_id, t): t = history.max_t else: t = int(t) df, w = history.get_distribution(model_id, t) df[""CDF""] = w tabs = [] " 133,https://:@github.com/icb-dcm/pyabc.git,2df9fbbc034ecad45cde0e14d0205fc70ae9b90b,"@@ -122,7 +122,7 @@ def test_dataframe_storage_readout(): for m in range(5): pop = pops[(h, m, t)] expected_particles_list = [p.parameter for p in pop] - pars_df, w = h.get_distribution(t, m) + pars_df, w = h.get_distribution(m, t) # use range(len and not zip on dataframe to not stop early # in case of population not completely stored assert np.isclose(w.sum(), 1) ",test/test_storage.py,"ArgSwap(idxs=0<->1 @(125,29)->(125,47))","def test_dataframe_storage_readout(): for m in range(5): pop = pops[(h, m, t)] expected_particles_list = [p.parameter for p in pop] pars_df, w = h.get_distribution(t, m) # use range(len and not zip on dataframe to not stop early # in case of population not completely stored assert np.isclose(w.sum(), 1)","def test_dataframe_storage_readout(): for m in range(5): pop = pops[(h, m, t)] expected_particles_list = [p.parameter for p in pop] pars_df, w = h.get_distribution(m, t) # use range(len and not zip on dataframe to not stop early # in case of population not completely stored assert np.isclose(w.sum(), 1)" 134,https://:@github.com/llllllllll/codetransformer.git,7c327683df810265d01a995d2704c9f8218b0ef7,"@@ -141,7 +141,7 @@ class Instruction(InstructionMeta._marker, metaclass=InstructionMeta): 'little', ) - yield cls(arg) + yield instr(arg) @classmethod def from_opcode(cls, opcode): ",codetransformer/instructions.py,"ReplaceText(target='instr' @(144,18)->(144,21))","class Instruction(InstructionMeta._marker, metaclass=InstructionMeta): 'little', ) yield cls(arg) @classmethod def from_opcode(cls, opcode):","class Instruction(InstructionMeta._marker, metaclass=InstructionMeta): 'little', ) yield instr(arg) @classmethod def from_opcode(cls, opcode):" 135,https://:@github.com/richardkiss/pycoin.git,c6b3b2e0d7167d4566dc1d90258d6b98dba8bb65,"@@ -197,7 +197,7 @@ def eval_script(script, signature_for_hash_type_f, lock_time, expected_hash_type # Subset of script starting at the most recent codeseparator op_checksig(stack, signature_for_hash_type_f, expected_hash_type, script[begin_code_hash:], flags) if opcode == opcodes.OP_CHECKSIGVERIFY: - if bool_from_script_bytes(stack.pop()): + if not bool_from_script_bytes(stack.pop()): raise ScriptError(""VERIFY failed at %d"" % (pc-1)) continue ",pycoin/tx/script/vm.py,"ReplaceText(target='not ' @(200,23)->(200,23))","def eval_script(script, signature_for_hash_type_f, lock_time, expected_hash_type # Subset of script starting at the most recent codeseparator op_checksig(stack, signature_for_hash_type_f, expected_hash_type, script[begin_code_hash:], flags) if opcode == opcodes.OP_CHECKSIGVERIFY: if bool_from_script_bytes(stack.pop()): raise ScriptError(""VERIFY failed at %d"" % (pc-1)) continue ","def eval_script(script, signature_for_hash_type_f, lock_time, expected_hash_type # Subset of script starting at the most recent codeseparator op_checksig(stack, signature_for_hash_type_f, expected_hash_type, script[begin_code_hash:], flags) if opcode == opcodes.OP_CHECKSIGVERIFY: if not bool_from_script_bytes(stack.pop()): raise ScriptError(""VERIFY failed at %d"" % (pc-1)) continue " 136,https://:@github.com/richardkiss/pycoin.git,6d1df60ddb054d1510f38231a529ccf35a73525a,"@@ -302,7 +302,7 @@ def generate_output(args, output_dict, output_order): if len(output_order) == 0: print(""no output: use -j option to see keys"") - elif len(output_order) == 1: + elif len(output_dict) == 1: print(output_dict[output_order[0][0]]) else: dump_output(output_dict, output_order) ",pycoin/cmds/ku.py,"ReplaceText(target='output_dict' @(305,13)->(305,25))","def generate_output(args, output_dict, output_order): if len(output_order) == 0: print(""no output: use -j option to see keys"") elif len(output_order) == 1: print(output_dict[output_order[0][0]]) else: dump_output(output_dict, output_order)","def generate_output(args, output_dict, output_order): if len(output_order) == 0: print(""no output: use -j option to see keys"") elif len(output_dict) == 1: print(output_dict[output_order[0][0]]) else: dump_output(output_dict, output_order)" 137,https://:@github.com/richardkiss/pycoin.git,02a225ef6056cc5a7fa19a731e14fbda94522c55,"@@ -37,7 +37,7 @@ def deterministic_generate_k(generator_order, secret_exponent, val, hash_f=hashl shift = 8 * hash_size - bln if shift > 0: val >>= shift - if val > n: + if val >= n: val -= n h1 = intstream.to_bytes(val, length=order_size) k = hmac.new(k, v + b'\x00' + priv + h1, hash_f).digest() ",pycoin/ecdsa/rfc6979.py,"ReplaceText(target='>=' @(40,11)->(40,12))","def deterministic_generate_k(generator_order, secret_exponent, val, hash_f=hashl shift = 8 * hash_size - bln if shift > 0: val >>= shift if val > n: val -= n h1 = intstream.to_bytes(val, length=order_size) k = hmac.new(k, v + b'\x00' + priv + h1, hash_f).digest()","def deterministic_generate_k(generator_order, secret_exponent, val, hash_f=hashl shift = 8 * hash_size - bln if shift > 0: val >>= shift if val >= n: val -= n h1 = intstream.to_bytes(val, length=order_size) k = hmac.new(k, v + b'\x00' + priv + h1, hash_f).digest()" 138,https://:@github.com/er1iang/hfut-stu-lib.git,6bdc0e5591564da7b5fe2acd60bde0cb8b2b46f6,"@@ -60,7 +60,7 @@ class TestUtil(TestBase): '172.18.6.98', '172.18.6.99' ]) - assert len(r) == 1 + assert len(r) <= 1 with pytest.raises(ValueError): util.get_host_speed_rank(['qq.com']) assert util.get_host_speed_rank(timeout=0) == [] ",tests/test_util.py,"ReplaceText(target='<=' @(63,22)->(63,24))","class TestUtil(TestBase): '172.18.6.98', '172.18.6.99' ]) assert len(r) == 1 with pytest.raises(ValueError): util.get_host_speed_rank(['qq.com']) assert util.get_host_speed_rank(timeout=0) == []","class TestUtil(TestBase): '172.18.6.98', '172.18.6.99' ]) assert len(r) <= 1 with pytest.raises(ValueError): util.get_host_speed_rank(['qq.com']) assert util.get_host_speed_rank(timeout=0) == []" 139,https://:@github.com/acorg/dark-matter.git,7837baf17ff17925b5a56178358b3ec478635c9b,"@@ -109,7 +109,7 @@ def main(): consensus.id = args.id elif args.idLambda is not None: idLambda = eval(args.idLambda) - consensus.id = idLambda(args.id) + consensus.id = idLambda(consensus.id) print(consensus.toString('fasta'), end='') ",bin/make-consensus.py,"ReplaceText(target='consensus' @(112,32)->(112,36))","def main(): consensus.id = args.id elif args.idLambda is not None: idLambda = eval(args.idLambda) consensus.id = idLambda(args.id) print(consensus.toString('fasta'), end='') ","def main(): consensus.id = args.id elif args.idLambda is not None: idLambda = eval(args.idLambda) consensus.id = idLambda(consensus.id) print(consensus.toString('fasta'), end='') " 140,https://:@github.com/Netflix/security_monkey.git,b6356189f8c9e407e4c017bbbf31d8f32aa004a9,"@@ -122,7 +122,7 @@ class SNSAuditor(Auditor): else: arn = ARN(princ_aws) if arn.error: - self.add_issue(3, 'Auditor could not parse ARN', snsitem, notes=entry) + self.add_issue(3, 'Auditor could not parse ARN', snsitem, notes=princ_aws) else: account_numbers.append(arn.account_number) ",security_monkey/auditors/sns.py,"ReplaceText(target='princ_aws' @(125,88)->(125,93))","class SNSAuditor(Auditor): else: arn = ARN(princ_aws) if arn.error: self.add_issue(3, 'Auditor could not parse ARN', snsitem, notes=entry) else: account_numbers.append(arn.account_number) ","class SNSAuditor(Auditor): else: arn = ARN(princ_aws) if arn.error: self.add_issue(3, 'Auditor could not parse ARN', snsitem, notes=princ_aws) else: account_numbers.append(arn.account_number) " 141,https://:@github.com/SetBased/py-stratum.git,0a4f1f580810e466e6384395832353a77b8e909f,"@@ -26,7 +26,7 @@ class Connection: else: return_value = config.get(section, option, fallback=fallback) - if fallback is not None and return_value is None: + if fallback is None and return_value is None: raise KeyError(""Option '%s' is not found in section '%s'."" % (option, section)) return return_value ",pystratum/Connection.py,"ReplaceText(target=' is ' @(29,19)->(29,27))","class Connection: else: return_value = config.get(section, option, fallback=fallback) if fallback is not None and return_value is None: raise KeyError(""Option '%s' is not found in section '%s'."" % (option, section)) return return_value","class Connection: else: return_value = config.get(section, option, fallback=fallback) if fallback is None and return_value is None: raise KeyError(""Option '%s' is not found in section '%s'."" % (option, section)) return return_value" 142,https://:@github.com/awslabs/aws-service-catalog-puppet-framework.git,8ec184735fbc4d8f72484d5baa0e357bbdbeb9d8,"@@ -85,7 +85,7 @@ def test_deploy_launches_task_builder_for_account_launch_region(sut, mocker, sha assert len(actual_all_tasks.keys()) == 1 assert actual_all_tasks == expected_all_tasks mocked_get_required_params.assert_called_once_with( - region_name, launch_details.get('portfolio'), launch_details.get('product'), launch_details.get('version'), puppet_account_id + region_name, launch_details.get('portfolio'), launch_details.get('product'), launch_details.get('version'), account_id ) mocked_get_parameters_for_launch.assert_called_once_with( required_parameters, ",servicecatalog_puppet/cli_command_helpers_unit_test.py,"ReplaceText(target='account_id' @(88,116)->(88,133))","def test_deploy_launches_task_builder_for_account_launch_region(sut, mocker, sha assert len(actual_all_tasks.keys()) == 1 assert actual_all_tasks == expected_all_tasks mocked_get_required_params.assert_called_once_with( region_name, launch_details.get('portfolio'), launch_details.get('product'), launch_details.get('version'), puppet_account_id ) mocked_get_parameters_for_launch.assert_called_once_with( required_parameters,","def test_deploy_launches_task_builder_for_account_launch_region(sut, mocker, sha assert len(actual_all_tasks.keys()) == 1 assert actual_all_tasks == expected_all_tasks mocked_get_required_params.assert_called_once_with( region_name, launch_details.get('portfolio'), launch_details.get('product'), launch_details.get('version'), account_id ) mocked_get_parameters_for_launch.assert_called_once_with( required_parameters," 143,https://:@github.com/kivy-garden/graph.git,b6ec8765b231bfbc1cf0c585243eb43379bb8946,"@@ -448,7 +448,7 @@ class Graph(Widget): ymin = self.ymin ymax = self.ymax if ylog: - xmin = log10(ymin) + ymin = log10(ymin) ymax = log10(ymax) if len(xpoints): top = size[3] if self.x_grid else metrics.dp(12) + size[1] ",__init__.py,"ReplaceText(target='ymin' @(451,12)->(451,16))","class Graph(Widget): ymin = self.ymin ymax = self.ymax if ylog: xmin = log10(ymin) ymax = log10(ymax) if len(xpoints): top = size[3] if self.x_grid else metrics.dp(12) + size[1]","class Graph(Widget): ymin = self.ymin ymax = self.ymax if ylog: ymin = log10(ymin) ymax = log10(ymax) if len(xpoints): top = size[3] if self.x_grid else metrics.dp(12) + size[1]" 144,https://:@github.com/irmen/synthesizer.git,e1da70408c0fce248edc4542e2f94e8ea6ea72b9,"@@ -31,7 +31,7 @@ class DecodedSoundFile: self.sample_format = sample_format # one of the ma_format_ values self.sample_format_name = ffi.string(lib.ma_get_format_name(sample_format)).decode() self.samples = samples - self.num_frames = len(samples) / self.nchannels + self.num_frames = len(samples) // self.nchannels self.duration = self.num_frames / self.sample_rate ",pyminiaudio/miniaudio.py,"ReplaceText(target='//' @(34,39)->(34,40))","class DecodedSoundFile: self.sample_format = sample_format # one of the ma_format_ values self.sample_format_name = ffi.string(lib.ma_get_format_name(sample_format)).decode() self.samples = samples self.num_frames = len(samples) / self.nchannels self.duration = self.num_frames / self.sample_rate ","class DecodedSoundFile: self.sample_format = sample_format # one of the ma_format_ values self.sample_format_name = ffi.string(lib.ma_get_format_name(sample_format)).decode() self.samples = samples self.num_frames = len(samples) // self.nchannels self.duration = self.num_frames / self.sample_rate " 145,https://:@github.com/pydata/numexpr.git,d11ef8a9dec059b679e773ad8fa54dd4f462d2e8,"@@ -304,7 +304,7 @@ class test_numexpr(TestCase): assert_equal(res, b) a = False res = evaluate('where(a, b, c)') - assert_equal(res, b) + assert_equal(res, c) ",numexpr/tests/test_numexpr.py,"ReplaceText(target='c' @(307,26)->(307,27))","class test_numexpr(TestCase): assert_equal(res, b) a = False res = evaluate('where(a, b, c)') assert_equal(res, b) ","class test_numexpr(TestCase): assert_equal(res, b) a = False res = evaluate('where(a, b, c)') assert_equal(res, c) " 146,https://:@github.com/aio-libs/aiozipkin.git,73a9594e475a65d11f32ae1ec48d3a324d2cb2b2,"@@ -23,7 +23,7 @@ class Transport: self._queue.append(data) async def _sender_loop(self): - while self._ender.done(): + while not self._ender.done(): if len(self._queue) != 0: await self._send() ",aiozipkin/transport.py,"ReplaceText(target='not ' @(26,14)->(26,14))","class Transport: self._queue.append(data) async def _sender_loop(self): while self._ender.done(): if len(self._queue) != 0: await self._send() ","class Transport: self._queue.append(data) async def _sender_loop(self): while not self._ender.done(): if len(self._queue) != 0: await self._send() " 147,https://:@gitlab.com/deliberist/xdgenvpy.git,cce7b99c90cd770aee31195f98e23169405d31c2,"@@ -96,7 +96,7 @@ def print_vars(xdg, variables): :param list variables: A sequence of XDG variables to print. """""" for var in variables: - if not (str(var).startswith('XDG_') or hasattr(xdg, var)): + if not (str(var).startswith('XDG_') and hasattr(xdg, var)): LOG.error('Invalid XDG variable: %s', var) else: value = getattr(xdg, var) ",xdgenvpy/__main__.py,"ReplaceText(target='and' @(99,44)->(99,46))","def print_vars(xdg, variables): :param list variables: A sequence of XDG variables to print. """""" for var in variables: if not (str(var).startswith('XDG_') or hasattr(xdg, var)): LOG.error('Invalid XDG variable: %s', var) else: value = getattr(xdg, var)","def print_vars(xdg, variables): :param list variables: A sequence of XDG variables to print. """""" for var in variables: if not (str(var).startswith('XDG_') and hasattr(xdg, var)): LOG.error('Invalid XDG variable: %s', var) else: value = getattr(xdg, var)" 148,https://:@github.com/theislab/anndata.git,908bbbd7c0ad3e61e7db0441fbe9ec93091a0dd5,"@@ -850,7 +850,7 @@ class AnnData(IndexMixin): categories=ddata[k]) if k_stripped in var: var[k_stripped] = pd.Categorical.from_codes( - codes=smp[k_stripped].values, + codes=var[k_stripped].values, categories=ddata[k]) k_to_delete.append(k) ",anndata/anndata.py,"ReplaceText(target='var' @(853,34)->(853,37))","class AnnData(IndexMixin): categories=ddata[k]) if k_stripped in var: var[k_stripped] = pd.Categorical.from_codes( codes=smp[k_stripped].values, categories=ddata[k]) k_to_delete.append(k) ","class AnnData(IndexMixin): categories=ddata[k]) if k_stripped in var: var[k_stripped] = pd.Categorical.from_codes( codes=var[k_stripped].values, categories=ddata[k]) k_to_delete.append(k) " 149,https://:@github.com/theislab/anndata.git,0c6ad8700a028675f25e6a769aaf39db3f2b8893,"@@ -104,7 +104,7 @@ def write_loom( elif len(adata.obsm.keys()) > 0 or len(adata.varm.keys()) > 0: logger.warning( f'The loom file will lack these fields:\n' - f'{adata.obsm.keys() + adata.varm.keys()}\n' + f'{adata.obsm.keys() | adata.varm.keys()}\n' f'Use write_obsm_varm=True to export multi-dimensional annotations' ) ",anndata/readwrite/write.py,"ReplaceText(target='|' @(107,33)->(107,34))","def write_loom( elif len(adata.obsm.keys()) > 0 or len(adata.varm.keys()) > 0: logger.warning( f'The loom file will lack these fields:\n' f'{adata.obsm.keys() + adata.varm.keys()}\n' f'Use write_obsm_varm=True to export multi-dimensional annotations' ) ","def write_loom( elif len(adata.obsm.keys()) > 0 or len(adata.varm.keys()) > 0: logger.warning( f'The loom file will lack these fields:\n' f'{adata.obsm.keys() | adata.varm.keys()}\n' f'Use write_obsm_varm=True to export multi-dimensional annotations' ) " 150,https://:@github.com/atarashansky/self-assembling-manifold.git,a8a2172a308d8fb99fc3981e64c1cc358d4d3355,"@@ -965,7 +965,7 @@ class SAMGUI(object): else: return; #quit - markers = ut.find_corr_genes(s,txt).flatten() + markers = ut.find_corr_genes(gene,txt).flatten() _,i = np.unique(markers,return_index=True) markers=markers[np.sort(i)] self.marker_genes[self.stab.selected_index] = markers ",SAMGUI.py,"ReplaceText(target='gene' @(968,37)->(968,38))","class SAMGUI(object): else: return; #quit markers = ut.find_corr_genes(s,txt).flatten() _,i = np.unique(markers,return_index=True) markers=markers[np.sort(i)] self.marker_genes[self.stab.selected_index] = markers","class SAMGUI(object): else: return; #quit markers = ut.find_corr_genes(gene,txt).flatten() _,i = np.unique(markers,return_index=True) markers=markers[np.sort(i)] self.marker_genes[self.stab.selected_index] = markers" 151,https://:@github.com/atarashansky/self-assembling-manifold.git,6539b0d87edc6dd18bd1bd3709fc41ad2c51b3f3,"@@ -248,7 +248,7 @@ def search_string(vec, s, case_sensitive=False, invert=False): i = len(V) V = np.concatenate(V); M = np.concatenate(M); if i > 1: - ix = np.sort(np.unique(V,return_index=True)[1]) + ix = np.sort(np.unique(M,return_index=True)[1]) V=V[ix]; M=M[ix]; return V,M else: ",samalg/utilities.py,"ReplaceText(target='M' @(251,35)->(251,36))","def search_string(vec, s, case_sensitive=False, invert=False): i = len(V) V = np.concatenate(V); M = np.concatenate(M); if i > 1: ix = np.sort(np.unique(V,return_index=True)[1]) V=V[ix]; M=M[ix]; return V,M else:","def search_string(vec, s, case_sensitive=False, invert=False): i = len(V) V = np.concatenate(V); M = np.concatenate(M); if i > 1: ix = np.sort(np.unique(M,return_index=True)[1]) V=V[ix]; M=M[ix]; return V,M else:" 152,https://:@github.com/den4uk/andriller.git,a5af3433a9caa6f05d8d43aef5abc8f405349f67,"@@ -379,7 +379,7 @@ class MainWindow(BaseWindow): self.menubar.add_cascade(menu=menu_help, label='Help', underline=0) menu_help.add_command(label='Visit website') menu_help.add_separator() - if getattr(sys, 'frozen', False): + if not getattr(sys, 'frozen', False): menu_help.add_command(label='Run Update', command=lambda: self.conf.upgrade_package(logger=self.logger)) menu_help.add_separator() menu_help.add_command(label='About', command=self.about_msg) ",andriller/windows.py,"ReplaceText(target='not ' @(382,11)->(382,11))","class MainWindow(BaseWindow): self.menubar.add_cascade(menu=menu_help, label='Help', underline=0) menu_help.add_command(label='Visit website') menu_help.add_separator() if getattr(sys, 'frozen', False): menu_help.add_command(label='Run Update', command=lambda: self.conf.upgrade_package(logger=self.logger)) menu_help.add_separator() menu_help.add_command(label='About', command=self.about_msg)","class MainWindow(BaseWindow): self.menubar.add_cascade(menu=menu_help, label='Help', underline=0) menu_help.add_command(label='Visit website') menu_help.add_separator() if not getattr(sys, 'frozen', False): menu_help.add_command(label='Run Update', command=lambda: self.conf.upgrade_package(logger=self.logger)) menu_help.add_separator() menu_help.add_command(label='About', command=self.about_msg)" 153,https://:@github.com/fabiencro/knmt.git,26b7b1ed8dfbc0e82804e86c149926fc96cd8d84,"@@ -699,7 +699,7 @@ def do_eval(config_eval): assert len(encdec_list) == 1 scorer = encdec_list[0].nbest_scorer(src_batch, src_mask) - nb_batches = (len(tgt_list) + mb_size - 1) / mb_size + nb_batches = (len(tgt_list) + mb_size - 1) // mb_size for num_batch in six.moves.range(nb_batches): tgt_batch, arg_sort = utils.make_batch_tgt(tgt_list[num_batch * nb_batches: (num_batch + 1) * nb_batches], eos_idx=eos_idx, gpu=gpu, volatile=""on"", need_arg_sort=True) ",nmt_chainer/translation/eval.py,"ReplaceText(target='//' @(702,55)->(702,56))","def do_eval(config_eval): assert len(encdec_list) == 1 scorer = encdec_list[0].nbest_scorer(src_batch, src_mask) nb_batches = (len(tgt_list) + mb_size - 1) / mb_size for num_batch in six.moves.range(nb_batches): tgt_batch, arg_sort = utils.make_batch_tgt(tgt_list[num_batch * nb_batches: (num_batch + 1) * nb_batches], eos_idx=eos_idx, gpu=gpu, volatile=""on"", need_arg_sort=True)","def do_eval(config_eval): assert len(encdec_list) == 1 scorer = encdec_list[0].nbest_scorer(src_batch, src_mask) nb_batches = (len(tgt_list) + mb_size - 1) // mb_size for num_batch in six.moves.range(nb_batches): tgt_batch, arg_sort = utils.make_batch_tgt(tgt_list[num_batch * nb_batches: (num_batch + 1) * nb_batches], eos_idx=eos_idx, gpu=gpu, volatile=""on"", need_arg_sort=True)" 154,https://:@github.com/fabiencro/knmt.git,8ca17b7d3b52100a3c36ae7a380efbf0ce42107d,"@@ -699,7 +699,7 @@ def do_eval(config_eval): assert len(encdec_list) == 1 scorer = encdec_list[0].nbest_scorer(src_batch, src_mask) - nb_batches = (len(tgt_list) + mb_size - 1) / mb_size + nb_batches = (len(tgt_list) + mb_size - 1) // mb_size for num_batch in six.moves.range(nb_batches): tgt_batch, arg_sort = utils.make_batch_tgt(tgt_list[num_batch * nb_batches: (num_batch + 1) * nb_batches], eos_idx=eos_idx, gpu=gpu, volatile=""on"", need_arg_sort=True) ",nmt_chainer/translation/eval.py,"ReplaceText(target='//' @(702,55)->(702,56))","def do_eval(config_eval): assert len(encdec_list) == 1 scorer = encdec_list[0].nbest_scorer(src_batch, src_mask) nb_batches = (len(tgt_list) + mb_size - 1) / mb_size for num_batch in six.moves.range(nb_batches): tgt_batch, arg_sort = utils.make_batch_tgt(tgt_list[num_batch * nb_batches: (num_batch + 1) * nb_batches], eos_idx=eos_idx, gpu=gpu, volatile=""on"", need_arg_sort=True)","def do_eval(config_eval): assert len(encdec_list) == 1 scorer = encdec_list[0].nbest_scorer(src_batch, src_mask) nb_batches = (len(tgt_list) + mb_size - 1) // mb_size for num_batch in six.moves.range(nb_batches): tgt_batch, arg_sort = utils.make_batch_tgt(tgt_list[num_batch * nb_batches: (num_batch + 1) * nb_batches], eos_idx=eos_idx, gpu=gpu, volatile=""on"", need_arg_sort=True)" 155,https://:@github.com/fabiencro/knmt.git,b091633d528161ceba3b63c501774627a2c927aa,"@@ -1127,7 +1127,7 @@ def build_dataset_one_side_pp(src_fn, src_pp, max_nb_ex=None, make_constraints=N # print(len(sentence_tgt), len(sentence_src)) seq_src = src_pp.convert(sentence_src, stats=stats_src) if make_constraints is not None: - constraints_fn = make_constraints(src, seq_src) + constraints_fn = make_constraints(sentence_src, seq_src) constraints_list.append(constraints_fn) res.append(seq_src) if make_constraints is not None: ",nmt_chainer/dataprocessing/processors.py,"ReplaceText(target='sentence_src' @(1130,46)->(1130,49))","def build_dataset_one_side_pp(src_fn, src_pp, max_nb_ex=None, make_constraints=N # print(len(sentence_tgt), len(sentence_src)) seq_src = src_pp.convert(sentence_src, stats=stats_src) if make_constraints is not None: constraints_fn = make_constraints(src, seq_src) constraints_list.append(constraints_fn) res.append(seq_src) if make_constraints is not None:","def build_dataset_one_side_pp(src_fn, src_pp, max_nb_ex=None, make_constraints=N # print(len(sentence_tgt), len(sentence_src)) seq_src = src_pp.convert(sentence_src, stats=stats_src) if make_constraints is not None: constraints_fn = make_constraints(sentence_src, seq_src) constraints_list.append(constraints_fn) res.append(seq_src) if make_constraints is not None:" 156,https://:@github.com/biocore/emperor.git,dedef9ab8d8578dd9d8d002dfa2dde254f27b133,"@@ -100,7 +100,7 @@ def main(): sids_intersection = len(set(zip(*mapping_data)[0]) & set(parsed_coords[0])) # sample ids must be shared between files - if sids_intersection > 0: + if sids_intersection <= 0: option_parser.error('The sample identifiers in the coordinates file ' 'must have at least one match with the data contained in mapping ' 'file. Verify you are using a coordinates file and a mapping file ' ",scripts/make_emperor.py,"ReplaceText(target='<=' @(103,25)->(103,26))","def main(): sids_intersection = len(set(zip(*mapping_data)[0]) & set(parsed_coords[0])) # sample ids must be shared between files if sids_intersection > 0: option_parser.error('The sample identifiers in the coordinates file ' 'must have at least one match with the data contained in mapping ' 'file. Verify you are using a coordinates file and a mapping file '","def main(): sids_intersection = len(set(zip(*mapping_data)[0]) & set(parsed_coords[0])) # sample ids must be shared between files if sids_intersection <= 0: option_parser.error('The sample identifiers in the coordinates file ' 'must have at least one match with the data contained in mapping ' 'file. Verify you are using a coordinates file and a mapping file '" 157,https://:@github.com/juanpex/django-model-report.git,0aa6d98497f25d178fe48ed9185b77e8d62e722b,"@@ -58,7 +58,7 @@ class ExcelExporter(Exporter): for g, rows in report_rows: if g: - sheet1.write(row_index, 0, u'%s' % x, stylebold) + sheet1.write(row_index, 0, u'%s' % g, stylebold) row_index += 1 for row in list(rows): if row.is_value(): ",model_report/exporters/excel.py,"ReplaceText(target='g' @(61,51)->(61,52))","class ExcelExporter(Exporter): for g, rows in report_rows: if g: sheet1.write(row_index, 0, u'%s' % x, stylebold) row_index += 1 for row in list(rows): if row.is_value():","class ExcelExporter(Exporter): for g, rows in report_rows: if g: sheet1.write(row_index, 0, u'%s' % g, stylebold) row_index += 1 for row in list(rows): if row.is_value():" 158,https://:@github.com/hclivess/Bismuth.git,a969c471f3d255e9cd139c100ac942c441c51aa0,"@@ -120,7 +120,7 @@ def difficulty(c): time_now = time.time() if time_now > timestamp_last + 300: #if 5 minutes have passed - difficulty2 = percentage(97,diff_block_previous) + difficulty2 = percentage(97,difficulty) else: difficulty2 = difficulty ",gui.py,"ReplaceText(target='difficulty' @(123,36)->(123,55))","def difficulty(c): time_now = time.time() if time_now > timestamp_last + 300: #if 5 minutes have passed difficulty2 = percentage(97,diff_block_previous) else: difficulty2 = difficulty ","def difficulty(c): time_now = time.time() if time_now > timestamp_last + 300: #if 5 minutes have passed difficulty2 = percentage(97,difficulty) else: difficulty2 = difficulty " 159,https://:@github.com/hclivess/Bismuth.git,75e47ec06ac2c83df3fbe413086393d265f27f1c,"@@ -1097,7 +1097,7 @@ def manager(c, conn): app_log.warning(""Only {} connections active, resetting the connection history"".format(len(connection_pool))) del tried[:] - if nodes_ban_reset and len(connection_pool) < len(banlist) and int(time.time() - reset_time) > 60*10: #do not reset too often. 10 minutes here + if nodes_ban_reset and len(connection_pool) <= len(banlist) and int(time.time() - reset_time) > 60*10: #do not reset too often. 10 minutes here app_log.warning(""Less active connections ({}) than banlist ({}), resetting banlist and tried"" .format(len(connection_pool), len(banlist))) del banlist[:] banlist.extend(config.banlist) # reset to config version ",node.py,"ReplaceText(target='<=' @(1100,52)->(1100,53))","def manager(c, conn): app_log.warning(""Only {} connections active, resetting the connection history"".format(len(connection_pool))) del tried[:] if nodes_ban_reset and len(connection_pool) < len(banlist) and int(time.time() - reset_time) > 60*10: #do not reset too often. 10 minutes here app_log.warning(""Less active connections ({}) than banlist ({}), resetting banlist and tried"" .format(len(connection_pool), len(banlist))) del banlist[:] banlist.extend(config.banlist) # reset to config version","def manager(c, conn): app_log.warning(""Only {} connections active, resetting the connection history"".format(len(connection_pool))) del tried[:] if nodes_ban_reset and len(connection_pool) <= len(banlist) and int(time.time() - reset_time) > 60*10: #do not reset too often. 10 minutes here app_log.warning(""Less active connections ({}) than banlist ({}), resetting banlist and tried"" .format(len(connection_pool), len(banlist))) del banlist[:] banlist.extend(config.banlist) # reset to config version" 160,https://:@github.com/hclivess/Bismuth.git,34d72e31b605ce74fc26bd9dac9cedd0c659d5b0,"@@ -204,7 +204,7 @@ class MainHandler(tornado.web.RequestHandler): html.append("""") html.append("""") - html.append("""".format(transferred_total)) + html.append("""".format(data_total)) html.append("""".format(tx_count)) html.append("""".format(tx_count/500)) html.append("""".format(transferred_total)) ",ledger_explorer.py,"ReplaceText(target='data_total' @(207,77)->(207,94))","class MainHandler(tornado.web.RequestHandler): html.append(""
Statistics for the last 500 blocks
Kilobytes transferred: {}
Kilobytes transferred: {}
Transactions: {}
Transactions per block: {}
Total BIS transferred {}
"") html.append("""") html.append("""".format(transferred_total)) html.append("""".format(tx_count)) html.append("""".format(tx_count/500)) html.append("""".format(transferred_total))","class MainHandler(tornado.web.RequestHandler): html.append(""
Statistics for the last 500 blocks
Kilobytes transferred: {}
Transactions: {}
Transactions per block: {}
Total BIS transferred {}
"") html.append("""") html.append("""".format(data_total)) html.append("""".format(tx_count)) html.append("""".format(tx_count/500)) html.append("""".format(transferred_total))" 161,https://:@github.com/hclivess/Bismuth.git,e6dd78e38707d04ea401ef86960e9deb08ea59b7,"@@ -520,7 +520,7 @@ def difficulty(c, mode): block_height = int(result[0]) timestamp_before_last = Decimal(c.fetchone()[1]) - if block_height > 427000: #remove code ABOVE after hf + if block_height >= 427000: #remove code ABOVE after hf execute(c, ""SELECT * FROM transactions WHERE reward != 0 ORDER BY block_height DESC LIMIT 2"") result = c.fetchone() timestamp_last = Decimal(result[1]) ",node.py,"ReplaceText(target='>=' @(523,20)->(523,21))","def difficulty(c, mode): block_height = int(result[0]) timestamp_before_last = Decimal(c.fetchone()[1]) if block_height > 427000: #remove code ABOVE after hf execute(c, ""SELECT * FROM transactions WHERE reward != 0 ORDER BY block_height DESC LIMIT 2"") result = c.fetchone() timestamp_last = Decimal(result[1])","def difficulty(c, mode): block_height = int(result[0]) timestamp_before_last = Decimal(c.fetchone()[1]) if block_height >= 427000: #remove code ABOVE after hf execute(c, ""SELECT * FROM transactions WHERE reward != 0 ORDER BY block_height DESC LIMIT 2"") result = c.fetchone() timestamp_last = Decimal(result[1])" 162,https://:@github.com/hclivess/Bismuth.git,01139c3f9457e2c4dbe7e143c47aa8475f7433cc,"@@ -9,7 +9,7 @@ def keys_load(privkey_file, pubkey_file): pubkey_loaded = open(pubkey_file, 'rb').read() pubkey = VerifyingKey.from_string(pubkey_loaded, curve=SECP256k1) - address = blake2b(privkey.to_string(), digest_size=20).hexdigest() + address = blake2b(pubkey.to_string(), digest_size=20).hexdigest() return privkey, pubkey, address ",bisecdsa.py,"ReplaceText(target='pubkey' @(12,22)->(12,29))","def keys_load(privkey_file, pubkey_file): pubkey_loaded = open(pubkey_file, 'rb').read() pubkey = VerifyingKey.from_string(pubkey_loaded, curve=SECP256k1) address = blake2b(privkey.to_string(), digest_size=20).hexdigest() return privkey, pubkey, address ","def keys_load(privkey_file, pubkey_file): pubkey_loaded = open(pubkey_file, 'rb').read() pubkey = VerifyingKey.from_string(pubkey_loaded, curve=SECP256k1) address = blake2b(pubkey.to_string(), digest_size=20).hexdigest() return privkey, pubkey, address " 163,https://:@github.com/hclivess/Bismuth.git,b4f1e59d63db962b8f674dc2f4e6e0df34e8404d,"@@ -9,7 +9,7 @@ def keys_load(privkey_file, pubkey_file): pubkey_loaded = open(pubkey_file, 'rb').read() pubkey = VerifyingKey.from_string(pubkey_loaded, curve=SECP256k1) - address = blake2b(pubkey.to_string(), digest_size=20).hexdigest() + address = blake2b(privkey.to_string(), digest_size=20).hexdigest() return privkey, pubkey, address ",bisecdsa.py,"ReplaceText(target='privkey' @(12,22)->(12,28))","def keys_load(privkey_file, pubkey_file): pubkey_loaded = open(pubkey_file, 'rb').read() pubkey = VerifyingKey.from_string(pubkey_loaded, curve=SECP256k1) address = blake2b(pubkey.to_string(), digest_size=20).hexdigest() return privkey, pubkey, address ","def keys_load(privkey_file, pubkey_file): pubkey_loaded = open(pubkey_file, 'rb').read() pubkey = VerifyingKey.from_string(pubkey_loaded, curve=SECP256k1) address = blake2b(privkey.to_string(), digest_size=20).hexdigest() return privkey, pubkey, address " 164,https://:@github.com/hclivess/Bismuth.git,081200edc97ae9d5e35156d634037844835c7205,"@@ -1192,7 +1192,7 @@ def digest_block(data, sdef, peer_ip, conn, c, hdd, h, hdd2, h2, h3, index, inde # if (q_time_now < q_received_timestamp + 432000) and not quicksync: # balance_pre = quantize_eight(credit_ledger - debit_ledger - fees + rewards) # without projection - balance_pre = ledger_balance3(db_address, h2, balances) + balance_pre = ledger_balance3(db_address, c, balances) # balance = quantize_eight(credit - debit - fees + rewards) balance = quantize_eight(balance_pre - block_debit_address) # app_log.info(""Digest: Projected transaction address balance: "" + str(balance)) ",node.py,"ReplaceText(target='c' @(1195,62)->(1195,64))","def digest_block(data, sdef, peer_ip, conn, c, hdd, h, hdd2, h2, h3, index, inde # if (q_time_now < q_received_timestamp + 432000) and not quicksync: # balance_pre = quantize_eight(credit_ledger - debit_ledger - fees + rewards) # without projection balance_pre = ledger_balance3(db_address, h2, balances) # balance = quantize_eight(credit - debit - fees + rewards) balance = quantize_eight(balance_pre - block_debit_address) # app_log.info(""Digest: Projected transaction address balance: "" + str(balance))","def digest_block(data, sdef, peer_ip, conn, c, hdd, h, hdd2, h2, h3, index, inde # if (q_time_now < q_received_timestamp + 432000) and not quicksync: # balance_pre = quantize_eight(credit_ledger - debit_ledger - fees + rewards) # without projection balance_pre = ledger_balance3(db_address, c, balances) # balance = quantize_eight(credit - debit - fees + rewards) balance = quantize_eight(balance_pre - block_debit_address) # app_log.info(""Digest: Projected transaction address balance: "" + str(balance))" 165,https://:@github.com/RDCH106/parallel_foreach_submodule.git,714ddc620894fbc6fefac093fe9323a9429f85a8,"@@ -23,7 +23,7 @@ class PFSProcess(object): if self.__output_filter == """": self.__output += self.__p.communicate()[0].decode('utf-8') # stdoutdata else: - if str(self.__p.communicate()[0].decode('utf-8')).find(self.__output_filter) != -1: + if str(self.__p.communicate()[0].decode('utf-8')).find(self.__output_filter) == -1: self.__output += self.__p.communicate()[0].decode('utf-8') if self.__p.communicate()[1]: # stderrdata ",parallelforeachsubmodule/process.py,"ReplaceText(target='==' @(26,89)->(26,91))","class PFSProcess(object): if self.__output_filter == """": self.__output += self.__p.communicate()[0].decode('utf-8') # stdoutdata else: if str(self.__p.communicate()[0].decode('utf-8')).find(self.__output_filter) != -1: self.__output += self.__p.communicate()[0].decode('utf-8') if self.__p.communicate()[1]: # stderrdata","class PFSProcess(object): if self.__output_filter == """": self.__output += self.__p.communicate()[0].decode('utf-8') # stdoutdata else: if str(self.__p.communicate()[0].decode('utf-8')).find(self.__output_filter) == -1: self.__output += self.__p.communicate()[0].decode('utf-8') if self.__p.communicate()[1]: # stderrdata" 166,https://:@github.com/rsokl/noggin.git,2f9ec33b6807cf8ff00169a284a2e1c3a77db137,"@@ -71,7 +71,7 @@ class LivePlot(LiveLogger): if ( not isinstance(size, Sequence) or len(size) != 2 - or not all(isinstance(x, Real) and x >= 0 for x in size) + or not all(isinstance(x, Real) and x > 0 for x in size) ): raise ValueError( f""`size` must be a length-2 sequence of "" ",src/liveplot/plotter.py,"ReplaceText(target='>' @(74,49)->(74,51))","class LivePlot(LiveLogger): if ( not isinstance(size, Sequence) or len(size) != 2 or not all(isinstance(x, Real) and x >= 0 for x in size) ): raise ValueError( f""`size` must be a length-2 sequence of ""","class LivePlot(LiveLogger): if ( not isinstance(size, Sequence) or len(size) != 2 or not all(isinstance(x, Real) and x > 0 for x in size) ): raise ValueError( f""`size` must be a length-2 sequence of """ 167,https://:@github.com/ome/ome-model.git,99bf44c7c5f8661d4c073b98dcafa980abd44920,"@@ -366,5 +366,5 @@ class OMEModel(object): substitutionGroupName = self.opts.lang.substitutionGroup(element.getName()) self.substitutionElement_map[substitutionGroupName] = element continue - if len(self.opts.lang.getSubstitutionTypes()) >= 0: + if len(self.opts.lang.getSubstitutionTypes()) > 0: config.METADATA_OBJECT_IGNORE.remove('BinData') ",components/xsd-fu/python/ome/modeltools/model.py,"ReplaceText(target='>' @(369,54)->(369,56))","class OMEModel(object): substitutionGroupName = self.opts.lang.substitutionGroup(element.getName()) self.substitutionElement_map[substitutionGroupName] = element continue if len(self.opts.lang.getSubstitutionTypes()) >= 0: config.METADATA_OBJECT_IGNORE.remove('BinData')","class OMEModel(object): substitutionGroupName = self.opts.lang.substitutionGroup(element.getName()) self.substitutionElement_map[substitutionGroupName] = element continue if len(self.opts.lang.getSubstitutionTypes()) > 0: config.METADATA_OBJECT_IGNORE.remove('BinData')" 168,https://:@github.com/ome/ome-model.git,49d212302bd30541e55ef64409b14377b069cd3a,"@@ -135,7 +135,7 @@ class Image(object): assert (len(self.data[""Channels""]) <= sizeC), str(self.data) channel_samples = sum([int(x.data['SamplesPerPixel']) for x in self.data[""Channels""]]) - assert channel_samples < sizeC, str(self.data) + assert channel_samples <= sizeC, str(self.data) return self.data ",ome_model/experimental.py,"ReplaceText(target='<=' @(138,31)->(138,32))","class Image(object): assert (len(self.data[""Channels""]) <= sizeC), str(self.data) channel_samples = sum([int(x.data['SamplesPerPixel']) for x in self.data[""Channels""]]) assert channel_samples < sizeC, str(self.data) return self.data ","class Image(object): assert (len(self.data[""Channels""]) <= sizeC), str(self.data) channel_samples = sum([int(x.data['SamplesPerPixel']) for x in self.data[""Channels""]]) assert channel_samples <= sizeC, str(self.data) return self.data " 169,https://:@github.com/uber/causalml.git,3c085167f8fbf6a07ef53ad84f36682e015ff320,"@@ -966,7 +966,7 @@ class UpliftTreeClassifier: rightNodeSummary = self.tree_node_summary(w_r, y_r, min_samples_treatment=min_samples_treatment, n_reg=n_reg, - parentNodeSummary=parentNodeSummary) + parentNodeSummary=currentNodeSummary) # check the split validity on min_samples_treatment if set(leftNodeSummary.keys()) != set(rightNodeSummary.keys()): ",causalml/inference/tree/models.py,"ReplaceText(target='currentNodeSummary' @(969,76)->(969,93))","class UpliftTreeClassifier: rightNodeSummary = self.tree_node_summary(w_r, y_r, min_samples_treatment=min_samples_treatment, n_reg=n_reg, parentNodeSummary=parentNodeSummary) # check the split validity on min_samples_treatment if set(leftNodeSummary.keys()) != set(rightNodeSummary.keys()):","class UpliftTreeClassifier: rightNodeSummary = self.tree_node_summary(w_r, y_r, min_samples_treatment=min_samples_treatment, n_reg=n_reg, parentNodeSummary=currentNodeSummary) # check the split validity on min_samples_treatment if set(leftNodeSummary.keys()) != set(rightNodeSummary.keys()):" 170,https://:@github.com/pypa/setuptools_scm.git,3e2ee4c2c77900f2d20241f489a670f7cb512e98,"@@ -77,7 +77,7 @@ def test_version_from_hg_id(tmpdir, get_log_version): hg('add test.txt', cwd) hg('commit -m commit -u test -d ""0 0""', cwd) - after_first_commit = get_log_version(tmpdir) + after_first_commit = get_log_version(cwd) assert after_first_commit.startswith('0.0.post1-') ",test_hgdistver.py,"ReplaceText(target='cwd' @(80,41)->(80,47))","def test_version_from_hg_id(tmpdir, get_log_version): hg('add test.txt', cwd) hg('commit -m commit -u test -d ""0 0""', cwd) after_first_commit = get_log_version(tmpdir) assert after_first_commit.startswith('0.0.post1-') ","def test_version_from_hg_id(tmpdir, get_log_version): hg('add test.txt', cwd) hg('commit -m commit -u test -d ""0 0""', cwd) after_first_commit = get_log_version(cwd) assert after_first_commit.startswith('0.0.post1-') " 171,https://:@github.com/pypa/setuptools_scm.git,340b2356e8ab2e6525ef1a07d17155db2788ed50,"@@ -50,6 +50,6 @@ def scm_find_files(path, scm_files, scm_dirs): # dirpath + filename with symlinks preserved fullfilename = os.path.join(dirpath, filename) if os.path.normcase(os.path.realpath(fullfilename)) in scm_files: - res.append(os.path.join(path, os.path.relpath(fullfilename, path))) + res.append(os.path.join(path, os.path.relpath(fullfilename, realpath))) seen.add(realdirpath) return res ",src/setuptools_scm/file_finder.py,"ReplaceText(target='realpath' @(53,76)->(53,80))","def scm_find_files(path, scm_files, scm_dirs): # dirpath + filename with symlinks preserved fullfilename = os.path.join(dirpath, filename) if os.path.normcase(os.path.realpath(fullfilename)) in scm_files: res.append(os.path.join(path, os.path.relpath(fullfilename, path))) seen.add(realdirpath) return res","def scm_find_files(path, scm_files, scm_dirs): # dirpath + filename with symlinks preserved fullfilename = os.path.join(dirpath, filename) if os.path.normcase(os.path.realpath(fullfilename)) in scm_files: res.append(os.path.join(path, os.path.relpath(fullfilename, realpath))) seen.add(realdirpath) return res" 172,https://:@github.com/alphaomega-technology/Equation.git,66e92f5b6ab584b7e7ac3bb7c328ff4ea410f88e,"@@ -600,7 +600,7 @@ class Expression( object ): continue fs = self.__getfunction(op) while True: - if (fn['prec'] <= fs['prec']): + if (fn['prec'] >= fs['prec']): self.__expr.append(ExpressionFunction(fs['func'],fs['args'],fs['str'],fs['latex'],op[0],False)) if len(stack) == 0: stack.append(v) ",Equation/core.py,"ReplaceText(target='>=' @(603,35)->(603,37))","class Expression( object ): continue fs = self.__getfunction(op) while True: if (fn['prec'] <= fs['prec']): self.__expr.append(ExpressionFunction(fs['func'],fs['args'],fs['str'],fs['latex'],op[0],False)) if len(stack) == 0: stack.append(v)","class Expression( object ): continue fs = self.__getfunction(op) while True: if (fn['prec'] >= fs['prec']): self.__expr.append(ExpressionFunction(fs['func'],fs['args'],fs['str'],fs['latex'],op[0],False)) if len(stack) == 0: stack.append(v)" 173,https://:@github.com/Azure/azure-uamqp-python.git,29706fc2599f09f186f85fd15bf243b5ed60477f,"@@ -499,7 +499,7 @@ class SendClient(AMQPClient): message.state = constants.MessageState.SendComplete message._response = errors.MessageAlreadySettled() # pylint: disable=protected-access if message.on_send_complete: - message.on_send_complete(result, delivery_state) + message.on_send_complete(result, exception) def _filter_pending(self, message): if message.state in constants.DONE_STATES: ",uamqp/client.py,"ReplaceText(target='exception' @(502,45)->(502,59))","class SendClient(AMQPClient): message.state = constants.MessageState.SendComplete message._response = errors.MessageAlreadySettled() # pylint: disable=protected-access if message.on_send_complete: message.on_send_complete(result, delivery_state) def _filter_pending(self, message): if message.state in constants.DONE_STATES:","class SendClient(AMQPClient): message.state = constants.MessageState.SendComplete message._response = errors.MessageAlreadySettled() # pylint: disable=protected-access if message.on_send_complete: message.on_send_complete(result, exception) def _filter_pending(self, message): if message.state in constants.DONE_STATES:" 174,https://:@github.com/MITHaystack/digital_rf.git,fe9ab29c4bc9584474f264516130c1c92b43e0d3,"@@ -418,7 +418,7 @@ class Thor(object): # set master clock rate clock_rate = op.clock_rates[mb_num] if clock_rate is not None: - op.set_clock_rate(clock_rate, mb_num) + u.set_clock_rate(clock_rate, mb_num) op.clock_rates[mb_num] = u.get_clock_rate(mb_num) # set clock source ",python/tools/thor.py,"ReplaceText(target='u' @(421,16)->(421,18))","class Thor(object): # set master clock rate clock_rate = op.clock_rates[mb_num] if clock_rate is not None: op.set_clock_rate(clock_rate, mb_num) op.clock_rates[mb_num] = u.get_clock_rate(mb_num) # set clock source","class Thor(object): # set master clock rate clock_rate = op.clock_rates[mb_num] if clock_rate is not None: u.set_clock_rate(clock_rate, mb_num) op.clock_rates[mb_num] = u.get_clock_rate(mb_num) # set clock source" 175,https://:@github.com/rm-hull/luma.core.git,dca2765dc5f02941a5f5668ed65f60650a95d929,"@@ -40,7 +40,7 @@ def show_message(device, msg, y_offset=0, fill=None, font=None, scroll_delay=0.0 text(draw, (x, y_offset), msg, font=font, fill=fill) i = 0 - while i < w + x: + while i <= w + x: virtual.set_position((i, 0)) regulator.sleep() i += 1 ",luma/core/legacy/__init__.py,"ReplaceText(target='<=' @(43,12)->(43,13))","def show_message(device, msg, y_offset=0, fill=None, font=None, scroll_delay=0.0 text(draw, (x, y_offset), msg, font=font, fill=fill) i = 0 while i < w + x: virtual.set_position((i, 0)) regulator.sleep() i += 1","def show_message(device, msg, y_offset=0, fill=None, font=None, scroll_delay=0.0 text(draw, (x, y_offset), msg, font=font, fill=fill) i = 0 while i <= w + x: virtual.set_position((i, 0)) regulator.sleep() i += 1" 176,https://:@github.com/gforcada/flake8-builtins.git,da932110850fae82bdc56cb2e5b5fed2ff228e3c,"@@ -211,7 +211,7 @@ class BuiltinsChecker(object): if not message: message = self.assign_msg if not variable: - column = statement.id + variable = statement.id if not line: line = statement.lineno if not column: ",flake8_builtins.py,"ReplaceText(target='variable' @(214,12)->(214,18))","class BuiltinsChecker(object): if not message: message = self.assign_msg if not variable: column = statement.id if not line: line = statement.lineno if not column:","class BuiltinsChecker(object): if not message: message = self.assign_msg if not variable: variable = statement.id if not line: line = statement.lineno if not column:" 177,https://:@github.com/European-XFEL/h5glance.git,23bcd02f8a36c9fd1f623e6627a7d6960669e06c,"@@ -157,7 +157,7 @@ class TreeViewBuilder: if obj.id.get_create_plist().get_layout() == h5py.h5d.VIRTUAL: detail += ' virtual' elif isinstance(obj, h5py.Group): - if max_depth > 1: + if max_depth >= 1: children += [self.group_item_node(obj, key, max_depth - 1) for key in obj] else: ",h5glance/terminal.py,"ReplaceText(target='>=' @(160,25)->(160,26))","class TreeViewBuilder: if obj.id.get_create_plist().get_layout() == h5py.h5d.VIRTUAL: detail += ' virtual' elif isinstance(obj, h5py.Group): if max_depth > 1: children += [self.group_item_node(obj, key, max_depth - 1) for key in obj] else:","class TreeViewBuilder: if obj.id.get_create_plist().get_layout() == h5py.h5d.VIRTUAL: detail += ' virtual' elif isinstance(obj, h5py.Group): if max_depth >= 1: children += [self.group_item_node(obj, key, max_depth - 1) for key in obj] else:" 178,https://:@github.com/camptocamp/c2cgeoform.git,98126ec7859b1bc5b1b2b720fea1c5d5ca9bbbef,"@@ -224,7 +224,7 @@ class AbstractViews(): if field.id() == sort: criterion = field.sort_column() if order == 'desc': - criterion = desc(sort) + criterion = desc(criterion) criteria.append(criterion) # Sort on primary key as subqueryload with limit need deterministic order ",c2cgeoform/views/abstract_views.py,"ReplaceText(target='criterion' @(227,37)->(227,41))","class AbstractViews(): if field.id() == sort: criterion = field.sort_column() if order == 'desc': criterion = desc(sort) criteria.append(criterion) # Sort on primary key as subqueryload with limit need deterministic order","class AbstractViews(): if field.id() == sort: criterion = field.sort_column() if order == 'desc': criterion = desc(criterion) criteria.append(criterion) # Sort on primary key as subqueryload with limit need deterministic order" 179,https://:@github.com/HumanCellAtlas/data-store.git,a28a6a38433fa3ead01ba5bd7e9289caf9c905b0,"@@ -114,7 +114,7 @@ def _verify_checkout( ) -> typing.Tuple[str, bool]: decoded_token: dict if token is None: - execution_id = start_file_checkout(blob_path, replica) + execution_id = start_file_checkout(replica, blob_path) start_time = time.time() attempts = 0 ",dss/api/files.py,"ArgSwap(idxs=0<->1 @(117,23)->(117,42))","def _verify_checkout( ) -> typing.Tuple[str, bool]: decoded_token: dict if token is None: execution_id = start_file_checkout(blob_path, replica) start_time = time.time() attempts = 0 ","def _verify_checkout( ) -> typing.Tuple[str, bool]: decoded_token: dict if token is None: execution_id = start_file_checkout(replica, blob_path) start_time = time.time() attempts = 0 " 180,https://:@github.com/HumanCellAtlas/data-store.git,6ab718c4aef36abe12b10556e27d5943176f7314,"@@ -53,7 +53,7 @@ class ElasticsearchIndexBackend(IndexBackend): tombstone_doc = BundleTombstoneDocument.from_tombstone(tombstone) modified, index_name = doc.entomb(tombstone_doc, dryrun=self.dryrun) if self.notify or modified and self.notify is None: - self._notify(doc, index_name) + self._notify(tombstone_doc, index_name) def _notify(self, bundle, index_name): subscription_ids = self._find_matching_subscriptions(bundle, index_name) ",dss/index/es/backend.py,"ReplaceText(target='tombstone_doc' @(56,25)->(56,28))","class ElasticsearchIndexBackend(IndexBackend): tombstone_doc = BundleTombstoneDocument.from_tombstone(tombstone) modified, index_name = doc.entomb(tombstone_doc, dryrun=self.dryrun) if self.notify or modified and self.notify is None: self._notify(doc, index_name) def _notify(self, bundle, index_name): subscription_ids = self._find_matching_subscriptions(bundle, index_name)","class ElasticsearchIndexBackend(IndexBackend): tombstone_doc = BundleTombstoneDocument.from_tombstone(tombstone) modified, index_name = doc.entomb(tombstone_doc, dryrun=self.dryrun) if self.notify or modified and self.notify is None: self._notify(tombstone_doc, index_name) def _notify(self, bundle, index_name): subscription_ids = self._find_matching_subscriptions(bundle, index_name)" 181,https://:@github.com/oemof/tespy.git,b6c36317886f435ae4dda9a8459788fabbfe85a8,"@@ -330,7 +330,7 @@ class bus: 'This bus accepts components of type ' + str(type(c).__bases__[0]) + '.') raise TypeError(msg) - return False + return True return True ",tespy/connections.py,"ReplaceText(target='True' @(333,23)->(333,28))","class bus: 'This bus accepts components of type ' + str(type(c).__bases__[0]) + '.') raise TypeError(msg) return False return True ","class bus: 'This bus accepts components of type ' + str(type(c).__bases__[0]) + '.') raise TypeError(msg) return True return True " 182,https://:@github.com/oemof/tespy.git,d69bd568bde4209be5aff37328ca422171ce3467,"@@ -1318,7 +1318,7 @@ class separator(node): res = x * self.inl[0].m.val_SI for o in self.outl: res -= o.fluid.val[fluid] * o.m.val_SI - self.vec_res[k] += res + self.vec_res[k] = res k += 1 ###################################################################### ",tespy/components/nodes.py,"ReplaceText(target='=' @(1321,28)->(1321,30))","class separator(node): res = x * self.inl[0].m.val_SI for o in self.outl: res -= o.fluid.val[fluid] * o.m.val_SI self.vec_res[k] += res k += 1 ######################################################################","class separator(node): res = x * self.inl[0].m.val_SI for o in self.outl: res -= o.fluid.val[fluid] * o.m.val_SI self.vec_res[k] = res k += 1 ######################################################################" 183,https://:@github.com/uber/tchannel-python.git,867364eea67d8da34f5f84a2d9fa02203f02aa95,"@@ -222,7 +222,7 @@ class TChannelClientOperation(object): message = CallRequestMessage( service=self.service, - args=[safebytes(arg_1), arg_3, arg_3], + args=[safebytes(arg_1), arg_2, arg_3], ) response_future = peer_connection.send(message, message_id) ",tchannel/tornado/tchannel.py,"ReplaceText(target='arg_2' @(225,36)->(225,41))","class TChannelClientOperation(object): message = CallRequestMessage( service=self.service, args=[safebytes(arg_1), arg_3, arg_3], ) response_future = peer_connection.send(message, message_id)","class TChannelClientOperation(object): message = CallRequestMessage( service=self.service, args=[safebytes(arg_1), arg_2, arg_3], ) response_future = peer_connection.send(message, message_id)" 184,https://:@github.com/arrrlo/Google-Images-Search.git,26df6441928bc8d69224fe7bf5fc52741a3404a7,"@@ -109,7 +109,7 @@ class FetchResizeSave(object): for i, page in enumerate(range(start, end, IMAGES_NUM_LIMIT)): start = page+1 - if self._number_of_images > IMAGES_NUM_LIMIT*(i+1): + if self._number_of_images >= IMAGES_NUM_LIMIT*(i+1): num = IMAGES_NUM_LIMIT else: num = (self._number_of_images % IMAGES_NUM_LIMIT) or \ ",google_images_search/fetch_resize_save.py,"ReplaceText(target='>=' @(112,38)->(112,39))","class FetchResizeSave(object): for i, page in enumerate(range(start, end, IMAGES_NUM_LIMIT)): start = page+1 if self._number_of_images > IMAGES_NUM_LIMIT*(i+1): num = IMAGES_NUM_LIMIT else: num = (self._number_of_images % IMAGES_NUM_LIMIT) or \","class FetchResizeSave(object): for i, page in enumerate(range(start, end, IMAGES_NUM_LIMIT)): start = page+1 if self._number_of_images >= IMAGES_NUM_LIMIT*(i+1): num = IMAGES_NUM_LIMIT else: num = (self._number_of_images % IMAGES_NUM_LIMIT) or \" 185,https://:@github.com/Parsl/parsl.git,794ea182f61a9626a84aa58be11952c8bb148ccd,"@@ -278,7 +278,7 @@ class EC2Provider(ExecutionProvider): try: with open(credfile, 'r') as f: - creds = json.load(credfile) + creds = json.load(f) except json.JSONDecodeError as e: logger.error( ""Site[{0}]: Json decode error in credential file {1}"".format(self, credfile) ",libsubmit/providers/aws/aws.py,"ReplaceText(target='f' @(281,38)->(281,46))","class EC2Provider(ExecutionProvider): try: with open(credfile, 'r') as f: creds = json.load(credfile) except json.JSONDecodeError as e: logger.error( ""Site[{0}]: Json decode error in credential file {1}"".format(self, credfile)","class EC2Provider(ExecutionProvider): try: with open(credfile, 'r') as f: creds = json.load(f) except json.JSONDecodeError as e: logger.error( ""Site[{0}]: Json decode error in credential file {1}"".format(self, credfile)" 186,https://:@github.com/Parsl/parsl.git,547ef33559003eddb8206bb01d9bbc22bc07aba7,"@@ -83,7 +83,7 @@ def update_config(config, rundir): ""maxThreads"": 8 } } - config[""sites""].append(data_manager_site) + config_base[""sites""].append(data_manager_site) # Update the config datastructure _config = copy.deepcopy(config) ",parsl/dataflow/config_defaults.py,"ReplaceText(target='config_base' @(86,4)->(86,10))","def update_config(config, rundir): ""maxThreads"": 8 } } config[""sites""].append(data_manager_site) # Update the config datastructure _config = copy.deepcopy(config)","def update_config(config, rundir): ""maxThreads"": 8 } } config_base[""sites""].append(data_manager_site) # Update the config datastructure _config = copy.deepcopy(config)" 187,https://:@github.com/Parsl/parsl.git,be25fe238b3269947cd6c882dfba88a147304937,"@@ -76,6 +76,6 @@ class PythonApp(AppBase): fn_hash=self.func_hash, cache=self.cache, ignore_for_cache=self.ignore_for_cache, - app_kwargs=kwargs) + app_kwargs=invocation_kwargs) return app_fut ",parsl/app/python.py,"ReplaceText(target='invocation_kwargs' @(79,40)->(79,46))","class PythonApp(AppBase): fn_hash=self.func_hash, cache=self.cache, ignore_for_cache=self.ignore_for_cache, app_kwargs=kwargs) return app_fut","class PythonApp(AppBase): fn_hash=self.func_hash, cache=self.cache, ignore_for_cache=self.ignore_for_cache, app_kwargs=invocation_kwargs) return app_fut" 188,https://:@github.com/qutang/padar.git,afb839dec2306e76355a03bc5b5602838e1a9201,"@@ -63,7 +63,7 @@ class OrientationFeatureComputer(SensorProcessor): ] windows = mw.get_sliding_window_boundaries(start_time=st, stop_time=et, window_duration=ws, step_size=ss) - chunk_windows_mask = (windows[:,0] >= data_start_indicator) & (windows[:,0] <= data_stop_indicator) + chunk_windows_mask = (windows[:,0] >= data_start_indicator) & (windows[:,0] < data_stop_indicator) chunk_windows = windows[chunk_windows_mask,:] if len(chunk_windows) == 0: return pd.DataFrame() ",mhealth/scripts/OrientationFeatureComputer.py,"ReplaceText(target='<' @(66,84)->(66,86))","class OrientationFeatureComputer(SensorProcessor): ] windows = mw.get_sliding_window_boundaries(start_time=st, stop_time=et, window_duration=ws, step_size=ss) chunk_windows_mask = (windows[:,0] >= data_start_indicator) & (windows[:,0] <= data_stop_indicator) chunk_windows = windows[chunk_windows_mask,:] if len(chunk_windows) == 0: return pd.DataFrame()","class OrientationFeatureComputer(SensorProcessor): ] windows = mw.get_sliding_window_boundaries(start_time=st, stop_time=et, window_duration=ws, step_size=ss) chunk_windows_mask = (windows[:,0] >= data_start_indicator) & (windows[:,0] < data_stop_indicator) chunk_windows = windows[chunk_windows_mask,:] if len(chunk_windows) == 0: return pd.DataFrame()" 189,https://:@github.com/mozman/ezdxf.git,a4c290a333b51772ecb0b9184506596d49183690,"@@ -22,7 +22,7 @@ class Drawing: self.encoding = 'cp1252' # read/write self.filename = None # read/write self.entitydb = EntityDB() - self.sections = Sections(self, tagreader) + self.sections = Sections(tagreader, self) self._dxfversion = self.header['$ACADVER'] self.encoding = self._get_encoding() nexthandle = int(self.header.get('$HANDSEED', '500'), 16) ",ezdxf/drawing.py,"ArgSwap(idxs=0<->1 @(25,24)->(25,32))","class Drawing: self.encoding = 'cp1252' # read/write self.filename = None # read/write self.entitydb = EntityDB() self.sections = Sections(self, tagreader) self._dxfversion = self.header['$ACADVER'] self.encoding = self._get_encoding() nexthandle = int(self.header.get('$HANDSEED', '500'), 16)","class Drawing: self.encoding = 'cp1252' # read/write self.filename = None # read/write self.entitydb = EntityDB() self.sections = Sections(tagreader, self) self._dxfversion = self.header['$ACADVER'] self.encoding = self._get_encoding() nexthandle = int(self.header.get('$HANDSEED', '500'), 16)" 190,https://:@github.com/mozman/ezdxf.git,d2bcbe493b5300e97913a1a13772a19547436239,"@@ -212,7 +212,7 @@ class GroupCollection(ObjectCollection): raise DXFTypeError(group.dxftype()) if name in self: - super().delete(group) + super().delete(name) else: raise DXFValueError(""GROUP not in group table registered."") ",ezdxf/entities/dxfgroups.py,"ReplaceText(target='name' @(215,27)->(215,32))","class GroupCollection(ObjectCollection): raise DXFTypeError(group.dxftype()) if name in self: super().delete(group) else: raise DXFValueError(""GROUP not in group table registered."") ","class GroupCollection(ObjectCollection): raise DXFTypeError(group.dxftype()) if name in self: super().delete(name) else: raise DXFValueError(""GROUP not in group table registered."") " 191,https://:@github.com/mozman/ezdxf.git,f6517755bbaeb24096de1f6fb8294b36c21cb769,"@@ -116,7 +116,7 @@ class Face3d(_Base): def set_edge_visibilty(self, num, status=False): """""" Set visibility of edge `num`, status `True` for visible, status `False` for invisible. """""" - if status: + if not status: self.dxf.invisible = self.dxf.invisible | (1 << num) else: self.dxf.invisible = self.dxf.invisible & ~(1 << num) ",src/ezdxf/entities/solid.py,"ReplaceText(target='not ' @(119,11)->(119,11))","class Face3d(_Base): def set_edge_visibilty(self, num, status=False): """""" Set visibility of edge `num`, status `True` for visible, status `False` for invisible. """""" if status: self.dxf.invisible = self.dxf.invisible | (1 << num) else: self.dxf.invisible = self.dxf.invisible & ~(1 << num)","class Face3d(_Base): def set_edge_visibilty(self, num, status=False): """""" Set visibility of edge `num`, status `True` for visible, status `False` for invisible. """""" if not status: self.dxf.invisible = self.dxf.invisible | (1 << num) else: self.dxf.invisible = self.dxf.invisible & ~(1 << num)" 192,https://:@github.com/mozman/ezdxf.git,516fbb01d55b9dc86b20b3d2263496560ad74415,"@@ -195,7 +195,7 @@ def virtual_block_reference_entities(block_ref: 'Insert', if block_ref.has_uniform_scaling and xscale < 0: # handle reflection about all three axis -x, -y, -z explicit as non uniform scaling - has_non_uniform_scaling = True + has_non_uniform_scaling = False if uniform_scaling_factor is not None: uniform_scaling_factor = float(uniform_scaling_factor) ",src/ezdxf/explode.py,"ReplaceText(target='False' @(198,38)->(198,42))","def virtual_block_reference_entities(block_ref: 'Insert', if block_ref.has_uniform_scaling and xscale < 0: # handle reflection about all three axis -x, -y, -z explicit as non uniform scaling has_non_uniform_scaling = True if uniform_scaling_factor is not None: uniform_scaling_factor = float(uniform_scaling_factor)","def virtual_block_reference_entities(block_ref: 'Insert', if block_ref.has_uniform_scaling and xscale < 0: # handle reflection about all three axis -x, -y, -z explicit as non uniform scaling has_non_uniform_scaling = False if uniform_scaling_factor is not None: uniform_scaling_factor = float(uniform_scaling_factor)" 193,https://:@github.com/mozman/ezdxf.git,ba0c909bdfc0c64d4909b15c9e12a54b9a36d7a4,"@@ -264,7 +264,7 @@ class Frontend: last_vertex = end if vertices: - if last_vertex.isclose(vertices[0]): + if not last_vertex.isclose(vertices[0]): vertices.append(last_vertex) self.out.draw_filled_polygon(vertices, properties) ",src/ezdxf/addons/drawing/frontend.py,"ReplaceText(target='not ' @(267,19)->(267,19))","class Frontend: last_vertex = end if vertices: if last_vertex.isclose(vertices[0]): vertices.append(last_vertex) self.out.draw_filled_polygon(vertices, properties) ","class Frontend: last_vertex = end if vertices: if not last_vertex.isclose(vertices[0]): vertices.append(last_vertex) self.out.draw_filled_polygon(vertices, properties) " 194,https://:@github.com/mozman/ezdxf.git,637cf54b973fb9bda6e4b0612b439ee69f04cf15,"@@ -184,7 +184,7 @@ def has_clockwise_orientation(vertices: Iterable['Vertex']) -> bool: return sum( (p2.x - p1.x) * (p2.y + p1.y) for p1, p2 in zip(vertices, vertices[1:]) - ) < 0 + ) > 0 def enclosing_angles(angle, start_angle, end_angle, ccw=True, ",src/ezdxf/math/construct2d.py,"ReplaceText(target='>' @(187,6)->(187,7))","def has_clockwise_orientation(vertices: Iterable['Vertex']) -> bool: return sum( (p2.x - p1.x) * (p2.y + p1.y) for p1, p2 in zip(vertices, vertices[1:]) ) < 0 def enclosing_angles(angle, start_angle, end_angle, ccw=True,","def has_clockwise_orientation(vertices: Iterable['Vertex']) -> bool: return sum( (p2.x - p1.x) * (p2.y + p1.y) for p1, p2 in zip(vertices, vertices[1:]) ) > 0 def enclosing_angles(angle, start_angle, end_angle, ccw=True," 195,https://:@github.com/Parsely/pykafka.git,676b3119ff9f4cd2a5bebf1ee0e3e52071cd65af,"@@ -198,7 +198,7 @@ class Producer(): else: key, value = message value = str(value) - yield (key, value), self._partitioner(partitions, message).id + yield (key, value), self._partitioner(partitions, key).id def _produce(self, message_partition_tups, attempt): """"""Publish a set of messages to relevant brokers. ",pykafka/producer.py,"ReplaceText(target='key' @(201,62)->(201,69))","class Producer(): else: key, value = message value = str(value) yield (key, value), self._partitioner(partitions, message).id def _produce(self, message_partition_tups, attempt): """"""Publish a set of messages to relevant brokers.","class Producer(): else: key, value = message value = str(value) yield (key, value), self._partitioner(partitions, key).id def _produce(self, message_partition_tups, attempt): """"""Publish a set of messages to relevant brokers." 196,https://:@github.com/Parsely/pykafka.git,559679443462fa62b4378453c5dfff14df85654f,"@@ -816,7 +816,7 @@ class OwnedPartition(object): :type messages: Iterable of :class:`pykafka.common.Message` """""" for message in messages: - if message.offset < self.last_offset_consumed: + if message.offset <= self.last_offset_consumed: log.debug(""Skipping enqueue for offset (%s) "" ""less than last_offset_consumed (%s)"", message.offset, self.last_offset_consumed) ",pykafka/simpleconsumer.py,"ReplaceText(target='<=' @(819,30)->(819,31))","class OwnedPartition(object): :type messages: Iterable of :class:`pykafka.common.Message` """""" for message in messages: if message.offset < self.last_offset_consumed: log.debug(""Skipping enqueue for offset (%s) "" ""less than last_offset_consumed (%s)"", message.offset, self.last_offset_consumed)","class OwnedPartition(object): :type messages: Iterable of :class:`pykafka.common.Message` """""" for message in messages: if message.offset <= self.last_offset_consumed: log.debug(""Skipping enqueue for offset (%s) "" ""less than last_offset_consumed (%s)"", message.offset, self.last_offset_consumed)" 197,https://:@github.com/Parsely/pykafka.git,e515296f6b130acb930ddc9f97e84a7997aedb2f,"@@ -137,7 +137,7 @@ class ProducerIntegrationTests(unittest2.TestCase): start = time.time() producer.produce(uuid4().bytes) producer.produce(uuid4().bytes) - self.assertTrue(int(time.time() - start) > int(linger)) + self.assertTrue(int(time.time() - start) >= int(linger)) self.consumer.consume() self.consumer.consume() ",tests/pykafka/test_producer.py,"ReplaceText(target='>=' @(140,49)->(140,50))","class ProducerIntegrationTests(unittest2.TestCase): start = time.time() producer.produce(uuid4().bytes) producer.produce(uuid4().bytes) self.assertTrue(int(time.time() - start) > int(linger)) self.consumer.consume() self.consumer.consume() ","class ProducerIntegrationTests(unittest2.TestCase): start = time.time() producer.produce(uuid4().bytes) producer.produce(uuid4().bytes) self.assertTrue(int(time.time() - start) >= int(linger)) self.consumer.consume() self.consumer.consume() " 198,https://:@github.com/Parsely/pykafka.git,ad8f2d457b8ca3b7dc7a75360f00becd7f0484a4,"@@ -595,7 +595,7 @@ class OwnedBroker(object): # bind the MessageSizeTooLarge error the delivery # report and remove it from the producer queue message = self.queue.pop() - self._delivery_reports.put(peeked_message, exc=exc) + self._delivery_reports.put(message, exc=exc) # remove from pending message count self.increment_messages_pending(-1) continue ",pykafka/producer.py,"ReplaceText(target='message' @(598,51)->(598,65))","class OwnedBroker(object): # bind the MessageSizeTooLarge error the delivery # report and remove it from the producer queue message = self.queue.pop() self._delivery_reports.put(peeked_message, exc=exc) # remove from pending message count self.increment_messages_pending(-1) continue","class OwnedBroker(object): # bind the MessageSizeTooLarge error the delivery # report and remove it from the producer queue message = self.queue.pop() self._delivery_reports.put(message, exc=exc) # remove from pending message count self.increment_messages_pending(-1) continue" 199,https://:@github.com/Parsely/pykafka.git,217865b12c58addc95c419f159b477bc5636c6a9,"@@ -594,7 +594,7 @@ class SimpleConsumer(object): to_retry = [pair for err in itervalues(parts_by_error) for pair in err] reqs = [p.build_offset_fetch_request() for p, _ in to_retry] - if len(parts_by_error) > 1: + if len(parts_by_error) > 0: raise KafkaException(parts_by_error) def reset_offsets(self, partition_offsets=None): ",pykafka/simpleconsumer.py,"ReplaceText(target='0' @(597,33)->(597,34))","class SimpleConsumer(object): to_retry = [pair for err in itervalues(parts_by_error) for pair in err] reqs = [p.build_offset_fetch_request() for p, _ in to_retry] if len(parts_by_error) > 1: raise KafkaException(parts_by_error) def reset_offsets(self, partition_offsets=None):","class SimpleConsumer(object): to_retry = [pair for err in itervalues(parts_by_error) for pair in err] reqs = [p.build_offset_fetch_request() for p, _ in to_retry] if len(parts_by_error) > 0: raise KafkaException(parts_by_error) def reset_offsets(self, partition_offsets=None):" 200,https://:@github.com/Timidger/Wikia.git,ff74a5711925274af13738f4b588a46356a1fa98,"@@ -395,7 +395,7 @@ class WikiaPage(object): # Remove the /revision/ fluff after the image url image = image.partition(""/revision/"")[0] image_type = mimetypes.guess_type(image)[0] - if image_type is None: + if image_type is not None: image_type = ""."" + image_type.split(""/"")[-1] else: image_type = "".png"" # in case mimetypes.guess cant find it it will return None ",wikia/wikia.py,"ReplaceText(target=' is not ' @(398,23)->(398,27))","class WikiaPage(object): # Remove the /revision/ fluff after the image url image = image.partition(""/revision/"")[0] image_type = mimetypes.guess_type(image)[0] if image_type is None: image_type = ""."" + image_type.split(""/"")[-1] else: image_type = "".png"" # in case mimetypes.guess cant find it it will return None","class WikiaPage(object): # Remove the /revision/ fluff after the image url image = image.partition(""/revision/"")[0] image_type = mimetypes.guess_type(image)[0] if image_type is not None: image_type = ""."" + image_type.split(""/"")[-1] else: image_type = "".png"" # in case mimetypes.guess cant find it it will return None" 201,https://:@github.com/meetshah1995/pytorch-semseg.git,81997cd5af36759773a67b11cf148d3876b13a69,"@@ -156,7 +156,7 @@ def train(cfg, writer, logger): labels_val = labels_val.to(device) outputs = model(images_val) - val_loss = loss_fn(input=outputs, target=labels) + val_loss = loss_fn(input=outputs, target=labels_val) pred = outputs.data.max(1)[1].cpu().numpy() gt = labels_val.data.cpu().numpy() ",train.py,"ReplaceText(target='labels_val' @(159,65)->(159,71))","def train(cfg, writer, logger): labels_val = labels_val.to(device) outputs = model(images_val) val_loss = loss_fn(input=outputs, target=labels) pred = outputs.data.max(1)[1].cpu().numpy() gt = labels_val.data.cpu().numpy()","def train(cfg, writer, logger): labels_val = labels_val.to(device) outputs = model(images_val) val_loss = loss_fn(input=outputs, target=labels_val) pred = outputs.data.max(1)[1].cpu().numpy() gt = labels_val.data.cpu().numpy()" 202,https://:@github.com/meetshah1995/pytorch-semseg.git,801fb200547caa5b0d91b8dde56b837da029f746,"@@ -27,7 +27,7 @@ def multi_scale_cross_entropy2d(input, target, weight=None, size_average=True, s n_inp = len(input) scale = 0.4 scale_weight = torch.pow(scale * torch.ones(n_inp), torch.arange(n_inp).float()).to( - input.device + target.device ) loss = 0.0 ",ptsemseg/loss/loss.py,"ReplaceText(target='target' @(30,12)->(30,17))","def multi_scale_cross_entropy2d(input, target, weight=None, size_average=True, s n_inp = len(input) scale = 0.4 scale_weight = torch.pow(scale * torch.ones(n_inp), torch.arange(n_inp).float()).to( input.device ) loss = 0.0","def multi_scale_cross_entropy2d(input, target, weight=None, size_average=True, s n_inp = len(input) scale = 0.4 scale_weight = torch.pow(scale * torch.ones(n_inp), torch.arange(n_inp).float()).to( target.device ) loss = 0.0" 203,https://:@github.com/bhmm/bhmm.git,34f1e00dc49a99094b5c492381d9f711e96fc4d9,"@@ -192,7 +192,7 @@ def estimate_initial_hmm(observations, nstates, reversible=True, eps_A=None, eps # does the count matrix too few closed sets to give nstates metastable states? Then we need a prior if len(_tmatrix_disconnected.closed_sets(C)) < nstates: msm_prior = 0.001 - B = msm_prior * np.eye(C_full.shape[0]) # diagonal prior + B = msm_prior * np.eye(C.shape[0]) # diagonal prior B += msmtools.estimation.prior_neighbor(C, alpha=msm_prior) # neighbor prior C_post = C + B # posterior P_for_pcca = _tmatrix_disconnected.estimate_P(C_post, reversible=True) ",bhmm/init/discrete.py,"ReplaceText(target='C' @(195,31)->(195,37))","def estimate_initial_hmm(observations, nstates, reversible=True, eps_A=None, eps # does the count matrix too few closed sets to give nstates metastable states? Then we need a prior if len(_tmatrix_disconnected.closed_sets(C)) < nstates: msm_prior = 0.001 B = msm_prior * np.eye(C_full.shape[0]) # diagonal prior B += msmtools.estimation.prior_neighbor(C, alpha=msm_prior) # neighbor prior C_post = C + B # posterior P_for_pcca = _tmatrix_disconnected.estimate_P(C_post, reversible=True)","def estimate_initial_hmm(observations, nstates, reversible=True, eps_A=None, eps # does the count matrix too few closed sets to give nstates metastable states? Then we need a prior if len(_tmatrix_disconnected.closed_sets(C)) < nstates: msm_prior = 0.001 B = msm_prior * np.eye(C.shape[0]) # diagonal prior B += msmtools.estimation.prior_neighbor(C, alpha=msm_prior) # neighbor prior C_post = C + B # posterior P_for_pcca = _tmatrix_disconnected.estimate_P(C_post, reversible=True)" 204,https://:@github.com/rackspace/pyrax.git,71a7f1924e2c53a4caac54e2b8eb985c207869c7,"@@ -220,7 +220,7 @@ class ManagerTest(unittest.TestCase): ret = mgr.findall(some_att=""ok"") self.assertTrue(o1 in ret) self.assertFalse(o2 in ret) - self.assertTrue(o1 in ret) + self.assertTrue(o3 in ret) mgr.list = sav def test_findall_bad_att(self): ",tests/unit/test_manager.py,"ReplaceText(target='o3' @(223,24)->(223,26))","class ManagerTest(unittest.TestCase): ret = mgr.findall(some_att=""ok"") self.assertTrue(o1 in ret) self.assertFalse(o2 in ret) self.assertTrue(o1 in ret) mgr.list = sav def test_findall_bad_att(self):","class ManagerTest(unittest.TestCase): ret = mgr.findall(some_att=""ok"") self.assertTrue(o1 in ret) self.assertFalse(o2 in ret) self.assertTrue(o3 in ret) mgr.list = sav def test_findall_bad_att(self):" 205,https://:@github.com/deckbsd/glouton-satnogs-data-downloader.git,7b3982a3ac4c7ecb086cf6ce504aa766a54f1211,"@@ -25,7 +25,7 @@ class ObservationRepo: self.__read_page(r.json(), self.__cmd.start_date, self.__cmd.end_date) page += 1 - params['page'] += str(page) + params['page'] = str(page) print('\ndownloading started (Ctrl + F5 to stop)...\t~( ^o^)~') self.__create_workers_and_wait() ",repositories/observation/observationsRepo.py,"ReplaceText(target='=' @(28,27)->(28,29))","class ObservationRepo: self.__read_page(r.json(), self.__cmd.start_date, self.__cmd.end_date) page += 1 params['page'] += str(page) print('\ndownloading started (Ctrl + F5 to stop)...\t~( ^o^)~') self.__create_workers_and_wait()","class ObservationRepo: self.__read_page(r.json(), self.__cmd.start_date, self.__cmd.end_date) page += 1 params['page'] = str(page) print('\ndownloading started (Ctrl + F5 to stop)...\t~( ^o^)~') self.__create_workers_and_wait()" 206,https://:@github.com/vmware/pyvcloud.git,e250911c7ba7666c42c2fa197f32744424d647ff,"@@ -121,7 +121,7 @@ class VCA(object): #todo: check if vcloud session can be cached as well... vCloudSession = self.create_vCloudSession(vdcReference[1]) if vCloudSession: - vcd = VCD(vCloudSession, serviceId, serviceId) + vcd = VCD(vCloudSession, serviceId, vdcId) return vcd return None ",pyvcloud/vcloudair.py,"ReplaceText(target='vdcId' @(124,52)->(124,61))","class VCA(object): #todo: check if vcloud session can be cached as well... vCloudSession = self.create_vCloudSession(vdcReference[1]) if vCloudSession: vcd = VCD(vCloudSession, serviceId, serviceId) return vcd return None ","class VCA(object): #todo: check if vcloud session can be cached as well... vCloudSession = self.create_vCloudSession(vdcReference[1]) if vCloudSession: vcd = VCD(vCloudSession, serviceId, vdcId) return vcd return None " 207,https://:@github.com/vmware/pyvcloud.git,0b7926b141b58afbf94168ac95f1ab3f00f14e71,"@@ -2129,7 +2129,7 @@ class VDC(object): policy_list = [] for policy_reference in policy_references.VdcComputePolicyReference: policy_list.append(policy_reference) - return policy_reference + return policy_list def add_compute_policy(self, href): """"""Add a VdcComputePolicy. ",pyvcloud/vcd/vdc.py,"ReplaceText(target='policy_list' @(2132,15)->(2132,31))","class VDC(object): policy_list = [] for policy_reference in policy_references.VdcComputePolicyReference: policy_list.append(policy_reference) return policy_reference def add_compute_policy(self, href): """"""Add a VdcComputePolicy.","class VDC(object): policy_list = [] for policy_reference in policy_references.VdcComputePolicyReference: policy_list.append(policy_reference) return policy_list def add_compute_policy(self, href): """"""Add a VdcComputePolicy." 208,https://:@github.com/springer-math/Mathematics-of-Epidemics-on-Networks.git,1f069443a464955c87cfa926c0ad8c8ce66bc424,"@@ -851,7 +851,7 @@ def get_infected_nodes(G, tau, gamma, initial_infecteds=None): elif G.has_node(initial_infecteds): initial_infecteds=[initial_infecteds] H = directed_percolate_network(G, tau, gamma) - infected_nodes = _out_component_(G, initial_infecteds) + infected_nodes = _out_component_(H, initial_infecteds) return infected_nodes ",EoN/simulation.py,"ReplaceText(target='H' @(854,37)->(854,38))","def get_infected_nodes(G, tau, gamma, initial_infecteds=None): elif G.has_node(initial_infecteds): initial_infecteds=[initial_infecteds] H = directed_percolate_network(G, tau, gamma) infected_nodes = _out_component_(G, initial_infecteds) return infected_nodes ","def get_infected_nodes(G, tau, gamma, initial_infecteds=None): elif G.has_node(initial_infecteds): initial_infecteds=[initial_infecteds] H = directed_percolate_network(G, tau, gamma) infected_nodes = _out_component_(H, initial_infecteds) return infected_nodes " 209,https://:@github.com/waipbmtd/python-client.git,3d95fa3fb3d85c14d1b92da348b4f2f0b007424b,"@@ -135,7 +135,7 @@ def show(path): def validate_params(ctx, param, value): if any(['=' not in item for item in value]): raise click.BadParameter('Parameters need to be in format =') - return dict([tuple(item.split('=', 1)) for item in param]) + return dict([tuple(item.split('=', 1)) for item in value]) def validate_inplace(ctx, param, value): ",coreapi/commandline.py,"ReplaceText(target='value' @(138,55)->(138,60))","def show(path): def validate_params(ctx, param, value): if any(['=' not in item for item in value]): raise click.BadParameter('Parameters need to be in format =') return dict([tuple(item.split('=', 1)) for item in param]) def validate_inplace(ctx, param, value):","def show(path): def validate_params(ctx, param, value): if any(['=' not in item for item in value]): raise click.BadParameter('Parameters need to be in format =') return dict([tuple(item.split('=', 1)) for item in value]) def validate_inplace(ctx, param, value):" 210,https://:@github.com/waipbmtd/python-client.git,e630971368e28989484272ca7774af385ce3ddd6,"@@ -436,7 +436,7 @@ def credentials_show(): @click.option('--auth', metavar=""AUTH_SCHEME"", help='Auth scheme to apply to the credentials string. Options: ""none"", ""basic"". Default is ""none"".', default='none', type=click.Choice(['none', 'basic'])) def credentials_add(domain, credentials_string, auth): if auth == 'none': - header = auth + header = credentials_string elif auth == 'basic': header = 'Basic ' + b64encode(credentials_string) credentials = get_credentials() ",coreapi/commandline.py,"ReplaceText(target='credentials_string' @(439,17)->(439,21))","def credentials_show(): @click.option('--auth', metavar=""AUTH_SCHEME"", help='Auth scheme to apply to the credentials string. Options: ""none"", ""basic"". Default is ""none"".', default='none', type=click.Choice(['none', 'basic'])) def credentials_add(domain, credentials_string, auth): if auth == 'none': header = auth elif auth == 'basic': header = 'Basic ' + b64encode(credentials_string) credentials = get_credentials()","def credentials_show(): @click.option('--auth', metavar=""AUTH_SCHEME"", help='Auth scheme to apply to the credentials string. Options: ""none"", ""basic"". Default is ""none"".', default='none', type=click.Choice(['none', 'basic'])) def credentials_add(domain, credentials_string, auth): if auth == 'none': header = credentials_string elif auth == 'basic': header = 'Basic ' + b64encode(credentials_string) credentials = get_credentials()" 211,https://:@github.com/openfisca/openfisca-survey-manager.git,b1c6e08ca7ddd546171b5623ce0ae04ed9f597fd,"@@ -24,7 +24,7 @@ def temporary_store_decorator(config_files_directory = default_config_files_dire 'tmp_directory is not set: {!r} in {}'.format(tmp_directory, read_config_file_name) assert os.path.isabs(tmp_directory), \ 'tmp_directory should be an absolut path: {!r} in {}'.format(tmp_directory, read_config_file_name) - if os.path.isdir(tmp_directory): + if not os.path.isdir(tmp_directory): 'tmp_directory does not exist: {!r} in {}. Creating it.'.format(tmp_directory, read_config_file_name) os.makedirs(tmp_directory) ",openfisca_survey_manager/temporary.py,"ReplaceText(target='not ' @(27,7)->(27,7))","def temporary_store_decorator(config_files_directory = default_config_files_dire 'tmp_directory is not set: {!r} in {}'.format(tmp_directory, read_config_file_name) assert os.path.isabs(tmp_directory), \ 'tmp_directory should be an absolut path: {!r} in {}'.format(tmp_directory, read_config_file_name) if os.path.isdir(tmp_directory): 'tmp_directory does not exist: {!r} in {}. Creating it.'.format(tmp_directory, read_config_file_name) os.makedirs(tmp_directory) ","def temporary_store_decorator(config_files_directory = default_config_files_dire 'tmp_directory is not set: {!r} in {}'.format(tmp_directory, read_config_file_name) assert os.path.isabs(tmp_directory), \ 'tmp_directory should be an absolut path: {!r} in {}'.format(tmp_directory, read_config_file_name) if not os.path.isdir(tmp_directory): 'tmp_directory does not exist: {!r} in {}. Creating it.'.format(tmp_directory, read_config_file_name) os.makedirs(tmp_directory) " 212,https://:@github.com/ARMmbed/yotta.git,e948620774774810165b28968ce0324b1f5bb953,"@@ -329,7 +329,7 @@ def satisfyTarget(name, version_required, working_directory, update_installed=No # must rm the old target before continuing fsutils.rmRf(target_path) - if not v and update_installed is None: + if not v and update_installed is not None: v = latestSuitableVersion(name, version_required, registry='target') if not v: ",yotta/lib/access.py,"ReplaceText(target=' is not ' @(332,33)->(332,37))","def satisfyTarget(name, version_required, working_directory, update_installed=No # must rm the old target before continuing fsutils.rmRf(target_path) if not v and update_installed is None: v = latestSuitableVersion(name, version_required, registry='target') if not v:","def satisfyTarget(name, version_required, working_directory, update_installed=No # must rm the old target before continuing fsutils.rmRf(target_path) if not v and update_installed is not None: v = latestSuitableVersion(name, version_required, registry='target') if not v:" 213,https://:@github.com/ARMmbed/yotta.git,06a9d7e69861044818b5a5de490336f6be65d6f1,"@@ -371,7 +371,7 @@ def generateTest(**kwargs): test_method.__name__ = test_name setattr(TestCLITestGenerated, test_name, test_method) -if not util.canBuildNatively(): +if util.canBuildNatively(): forAllReporterTests(generateTest) else: print('WARNING: skipping test reporter tests (cannot build natively on this platform)') ",yotta/test/cli/test_test.py,"ReplaceText(target='' @(374,3)->(374,7))","def generateTest(**kwargs): test_method.__name__ = test_name setattr(TestCLITestGenerated, test_name, test_method) if not util.canBuildNatively(): forAllReporterTests(generateTest) else: print('WARNING: skipping test reporter tests (cannot build natively on this platform)')","def generateTest(**kwargs): test_method.__name__ = test_name setattr(TestCLITestGenerated, test_name, test_method) if util.canBuildNatively(): forAllReporterTests(generateTest) else: print('WARNING: skipping test reporter tests (cannot build natively on this platform)')" 214,https://:@github.com/b1naryth1ef/disco.git,bd75deb29adcc42f8de451d51e7dbc02eb360b1e,"@@ -112,7 +112,7 @@ class Plugin(LoggingClass, PluginDeco): def register_command(self, func, *args, **kwargs): wrapped = functools.partial(self._dispatch, 'command', func) - self.commands[func.__name__] = Command(self, func, *args, **kwargs) + self.commands[func.__name__] = Command(self, wrapped, *args, **kwargs) def destroy(self): map(lambda k: k.remove(), self._events) ",disco/bot/plugin.py,"ReplaceText(target='wrapped' @(115,53)->(115,57))","class Plugin(LoggingClass, PluginDeco): def register_command(self, func, *args, **kwargs): wrapped = functools.partial(self._dispatch, 'command', func) self.commands[func.__name__] = Command(self, func, *args, **kwargs) def destroy(self): map(lambda k: k.remove(), self._events)","class Plugin(LoggingClass, PluginDeco): def register_command(self, func, *args, **kwargs): wrapped = functools.partial(self._dispatch, 'command', func) self.commands[func.__name__] = Command(self, wrapped, *args, **kwargs) def destroy(self): map(lambda k: k.remove(), self._events)" 215,https://:@github.com/b1naryth1ef/disco.git,c5848dbe8b66295598b4e6cad1c5ec8f5cc3a5fb,"@@ -305,7 +305,7 @@ class Channel(SlottedModel, Permissible): return if self.can(self.client.state.me, Permissions.MANAGE_MESSAGES) and len(messages) > 2: - for chunk in chunks(messages, 100): + for chunk in chunks(message_ids, 100): self.client.api.channels_messages_delete_bulk(self.id, chunk) else: for msg in messages: ",disco/types/channel.py,"ReplaceText(target='message_ids' @(308,32)->(308,40))","class Channel(SlottedModel, Permissible): return if self.can(self.client.state.me, Permissions.MANAGE_MESSAGES) and len(messages) > 2: for chunk in chunks(messages, 100): self.client.api.channels_messages_delete_bulk(self.id, chunk) else: for msg in messages:","class Channel(SlottedModel, Permissible): return if self.can(self.client.state.me, Permissions.MANAGE_MESSAGES) and len(messages) > 2: for chunk in chunks(message_ids, 100): self.client.api.channels_messages_delete_bulk(self.id, chunk) else: for msg in messages:" 216,https://:@github.com/yuru-yuri/manga-dl.git,5cbcbd37c4f904720d08074241a890851b94a7dd,"@@ -26,7 +26,7 @@ if __name__ == '__main__': if parse_args.cli: cli = Cli(args) # cli - exit(0 if cli.status else 0) + exit(0 if cli.status else 1) # else run GUI app = QApplication(argv) ",manga.py,"ReplaceText(target='1' @(29,34)->(29,35))","if __name__ == '__main__': if parse_args.cli: cli = Cli(args) # cli exit(0 if cli.status else 0) # else run GUI app = QApplication(argv)","if __name__ == '__main__': if parse_args.cli: cli = Cli(args) # cli exit(0 if cli.status else 1) # else run GUI app = QApplication(argv)" 217,https://:@github.com/yuru-yuri/manga-dl.git,f10777831c4c128a6f6a9bb1d9903889a43ad1df,"@@ -44,7 +44,7 @@ class WebDriver: driver_path = self._driver_path() if not is_file(driver_path): self.download_drivder() - self.is_win() and chmod(driver_path, 0o755) + self.is_win() or chmod(driver_path, 0o755) driver = webdriver.Chrome(executable_path=driver_path) driver.set_window_size(500, 600) return driver ",src/base_classes/web_driver.py,"ReplaceText(target='or' @(47,22)->(47,25))","class WebDriver: driver_path = self._driver_path() if not is_file(driver_path): self.download_drivder() self.is_win() and chmod(driver_path, 0o755) driver = webdriver.Chrome(executable_path=driver_path) driver.set_window_size(500, 600) return driver","class WebDriver: driver_path = self._driver_path() if not is_file(driver_path): self.download_drivder() self.is_win() or chmod(driver_path, 0o755) driver = webdriver.Chrome(executable_path=driver_path) driver.set_window_size(500, 600) return driver" 218,https://:@github.com/veg/bioext.git,5fbb2b3fb52d1e59b787713f9d9521124cb2f24b,"@@ -217,7 +217,7 @@ def _translate_gapped(seq, *args, **kwds): elif gaps: protein += '-' * gaps gaps = 0 - lwr = j + lwr = i if gaps: protein += '-' * gaps else: ",lib/BioExt/_util.py,"ReplaceText(target='i' @(220,18)->(220,19))","def _translate_gapped(seq, *args, **kwds): elif gaps: protein += '-' * gaps gaps = 0 lwr = j if gaps: protein += '-' * gaps else:","def _translate_gapped(seq, *args, **kwds): elif gaps: protein += '-' * gaps gaps = 0 lwr = i if gaps: protein += '-' * gaps else:" 219,https://:@github.com/python-trio/trio.git,82253caa8bd59b5b3bbb0ba61d196289c967f838,"@@ -371,7 +371,7 @@ def test_waitid_eintr(): sync_wait_reapable(sleeper.pid) assert sleeper.wait(timeout=1) == -9 finally: - if sleeper.returncode is not None: + if sleeper.returncode is None: sleeper.kill() sleeper.wait() signal.signal(signal.SIGALRM, old_sigalrm) ",trio/tests/test_subprocess.py,"ReplaceText(target=' is ' @(374,29)->(374,37))","def test_waitid_eintr(): sync_wait_reapable(sleeper.pid) assert sleeper.wait(timeout=1) == -9 finally: if sleeper.returncode is not None: sleeper.kill() sleeper.wait() signal.signal(signal.SIGALRM, old_sigalrm)","def test_waitid_eintr(): sync_wait_reapable(sleeper.pid) assert sleeper.wait(timeout=1) == -9 finally: if sleeper.returncode is None: sleeper.kill() sleeper.wait() signal.signal(signal.SIGALRM, old_sigalrm)" 220,https://:@github.com/python-trio/trio.git,94a587f758f0597cd790505ca7bfbec17a247fb1,"@@ -37,7 +37,7 @@ def test_warn_deprecated(recwarn_always): assert ""water instead"" in got.message.args[0] assert ""/issues/1"" in got.message.args[0] assert got.filename == filename - assert got.lineno == lineno + 1 + assert got.lineno == lineno - 1 def test_warn_deprecated_no_instead_or_issue(recwarn_always): ",trio/tests/test_deprecate.py,"ReplaceText(target='-' @(40,32)->(40,33))","def test_warn_deprecated(recwarn_always): assert ""water instead"" in got.message.args[0] assert ""/issues/1"" in got.message.args[0] assert got.filename == filename assert got.lineno == lineno + 1 def test_warn_deprecated_no_instead_or_issue(recwarn_always):","def test_warn_deprecated(recwarn_always): assert ""water instead"" in got.message.args[0] assert ""/issues/1"" in got.message.args[0] assert got.filename == filename assert got.lineno == lineno - 1 def test_warn_deprecated_no_instead_or_issue(recwarn_always):" 221,https://:@github.com/python-trio/trio.git,8d9effc1d32b8ef2f7a7a02c1b02a4de3f5f8e3d,"@@ -90,7 +90,7 @@ def ki_protection_enabled(frame): if frame.f_code.co_name == ""__del__"": return True frame = frame.f_back - return False + return True def currently_ki_protected(): ",trio/_core/_ki.py,"ReplaceText(target='True' @(93,11)->(93,16))","def ki_protection_enabled(frame): if frame.f_code.co_name == ""__del__"": return True frame = frame.f_back return False def currently_ki_protected():","def ki_protection_enabled(frame): if frame.f_code.co_name == ""__del__"": return True frame = frame.f_back return True def currently_ki_protected():" 222,https://:@github.com/tkrajina/srtm.py.git,b1e1c673b613780c6a7151ab3db53461e2b668c7,"@@ -187,7 +187,7 @@ class GeoElevationData: for row in range(height): for column in range(width): latitude = latitude_from + float(row) / height * (latitude_to - latitude_from) - longitude = longitude_from + float(column) / height * (longitude_to - longitude_from) + longitude = longitude_from + float(column) / width * (longitude_to - longitude_from) elevation = self.get_elevation(latitude, longitude) array[row,column] = elevation ",srtm/data.py,"ReplaceText(target='width' @(190,65)->(190,71))","class GeoElevationData: for row in range(height): for column in range(width): latitude = latitude_from + float(row) / height * (latitude_to - latitude_from) longitude = longitude_from + float(column) / height * (longitude_to - longitude_from) elevation = self.get_elevation(latitude, longitude) array[row,column] = elevation ","class GeoElevationData: for row in range(height): for column in range(width): latitude = latitude_from + float(row) / height * (latitude_to - latitude_from) longitude = longitude_from + float(column) / width * (longitude_to - longitude_from) elevation = self.get_elevation(latitude, longitude) array[row,column] = elevation " 223,https://:@github.com/tkrajina/srtm.py.git,771bb0e73e7b478603f73644a8c8f441b0e02e9f,"@@ -208,7 +208,7 @@ class GeoElevationData: for row in range(height): for column in range(width): latitude = latitude_from + float(row) / height * (latitude_to - latitude_from) - longitude = longitude_from + float(column) / height * (longitude_to - longitude_from) + longitude = longitude_from + float(column) / width * (longitude_to - longitude_from) elevation = self.get_elevation(latitude, longitude) if elevation == None: color = unknown_color ",srtm/data.py,"ReplaceText(target='width' @(211,65)->(211,71))","class GeoElevationData: for row in range(height): for column in range(width): latitude = latitude_from + float(row) / height * (latitude_to - latitude_from) longitude = longitude_from + float(column) / height * (longitude_to - longitude_from) elevation = self.get_elevation(latitude, longitude) if elevation == None: color = unknown_color","class GeoElevationData: for row in range(height): for column in range(width): latitude = latitude_from + float(row) / height * (latitude_to - latitude_from) longitude = longitude_from + float(column) / width * (longitude_to - longitude_from) elevation = self.get_elevation(latitude, longitude) if elevation == None: color = unknown_color" 224,https://:@github.com/mwouts/nbrmd.git,628e3f952bb786220efc1e14b976809bf8ea96be,"@@ -218,7 +218,7 @@ def readf(nb_file): 'Expected extensions are {}'.format(nb_file, notebook_extensions)) with io.open(nb_file, encoding='utf-8') as fp: - return read(nb_file, as_version=4, ext=ext) + return read(fp, as_version=4, ext=ext) def writef(nb, nb_file): ",nbrmd/nbrmd.py,"ReplaceText(target='fp' @(221,20)->(221,27))","def readf(nb_file): 'Expected extensions are {}'.format(nb_file, notebook_extensions)) with io.open(nb_file, encoding='utf-8') as fp: return read(nb_file, as_version=4, ext=ext) def writef(nb, nb_file):","def readf(nb_file): 'Expected extensions are {}'.format(nb_file, notebook_extensions)) with io.open(nb_file, encoding='utf-8') as fp: return read(fp, as_version=4, ext=ext) def writef(nb, nb_file):" 225,https://:@github.com/mwouts/nbrmd.git,366614bce3dc65c6e88bcf37c4e2cd31ea36de92,"@@ -63,7 +63,7 @@ def test_load_save_rename_nbpy(nb_file, tmpdir): cm.save(model=dict(type='notebook', content=nb), path=tmp_ipynb) # rename nbpy - cm.rename(tmp_ipynb, 'new.nb.py') + cm.rename(tmp_nbpy, 'new.nb.py') assert not os.path.isfile(str(tmpdir.join(tmp_ipynb))) assert not os.path.isfile(str(tmpdir.join(tmp_nbpy))) ",tests/test_contentsmanager.py,"ReplaceText(target='tmp_nbpy' @(66,14)->(66,23))","def test_load_save_rename_nbpy(nb_file, tmpdir): cm.save(model=dict(type='notebook', content=nb), path=tmp_ipynb) # rename nbpy cm.rename(tmp_ipynb, 'new.nb.py') assert not os.path.isfile(str(tmpdir.join(tmp_ipynb))) assert not os.path.isfile(str(tmpdir.join(tmp_nbpy))) ","def test_load_save_rename_nbpy(nb_file, tmpdir): cm.save(model=dict(type='notebook', content=nb), path=tmp_ipynb) # rename nbpy cm.rename(tmp_nbpy, 'new.nb.py') assert not os.path.isfile(str(tmpdir.join(tmp_ipynb))) assert not os.path.isfile(str(tmpdir.join(tmp_nbpy))) " 226,https://:@github.com/mwouts/nbrmd.git,171256b67818ab86f43e35065fc828234e9abf98,"@@ -163,7 +163,7 @@ class CellExporter(): return True if all([line.startswith('#') for line in self.source]): return True - if CellReader(self.ext).read(source)[1] != len(source): + if CellReader(self.ext).read(source)[1] < len(source): return True return False ",jupytext/cell_to_text.py,"ReplaceText(target='<' @(166,48)->(166,50))","class CellExporter(): return True if all([line.startswith('#') for line in self.source]): return True if CellReader(self.ext).read(source)[1] != len(source): return True return False","class CellExporter(): return True if all([line.startswith('#') for line in self.source]): return True if CellReader(self.ext).read(source)[1] < len(source): return True return False" 227,https://:@github.com/mwouts/nbrmd.git,8048c8d0a09eab875376c7a4d1efb3cd886b8d3c,"@@ -122,7 +122,7 @@ def metadata_and_cell_to_header(notebook, text_format, ext): if lines_to_next_cell is None and notebook.cells: lines_to_next_cell = pep8_lines_between_cells(header, notebook.cells[0], ext) else: - lines_to_next_cell = 0 + lines_to_next_cell = 1 header.extend([''] * lines_to_next_cell) ",jupytext/header.py,"ReplaceText(target='1' @(125,29)->(125,30))","def metadata_and_cell_to_header(notebook, text_format, ext): if lines_to_next_cell is None and notebook.cells: lines_to_next_cell = pep8_lines_between_cells(header, notebook.cells[0], ext) else: lines_to_next_cell = 0 header.extend([''] * lines_to_next_cell) ","def metadata_and_cell_to_header(notebook, text_format, ext): if lines_to_next_cell is None and notebook.cells: lines_to_next_cell = pep8_lines_between_cells(header, notebook.cells[0], ext) else: lines_to_next_cell = 1 header.extend([''] * lines_to_next_cell) " 228,https://:@github.com/mwouts/nbrmd.git,120bebc0d37792cfa1418476d5f26809b996dca8,"@@ -615,7 +615,7 @@ def test_sync(nb_file, tmpdir): compare_notebooks(nb, nb2) # ipynb must be older than py file, otherwise our Contents Manager will complain - assert os.path.getmtime(tmp_ipynb) < os.path.getmtime(tmp_py) + assert os.path.getmtime(tmp_ipynb) <= os.path.getmtime(tmp_py) @pytest.mark.parametrize('nb_file,ext', ",tests/test_cli.py,"ReplaceText(target='<=' @(618,39)->(618,40))","def test_sync(nb_file, tmpdir): compare_notebooks(nb, nb2) # ipynb must be older than py file, otherwise our Contents Manager will complain assert os.path.getmtime(tmp_ipynb) < os.path.getmtime(tmp_py) @pytest.mark.parametrize('nb_file,ext',","def test_sync(nb_file, tmpdir): compare_notebooks(nb, nb2) # ipynb must be older than py file, otherwise our Contents Manager will complain assert os.path.getmtime(tmp_ipynb) <= os.path.getmtime(tmp_py) @pytest.mark.parametrize('nb_file,ext'," 229,https://:@github.com/mwouts/nbrmd.git,dfa96996445cbc7514b93337dbf94d592ba06bad,"@@ -19,4 +19,4 @@ def test_identity_source_write_read(nb_file, ext): R = jupytext.writes(nb1, ext) nb2 = jupytext.reads(R, ext) - compare_notebooks(nb1, nb2) + compare_notebooks(nb2, nb1) ",tests/test_ipynb_to_R.py,"ArgSwap(idxs=0<->1 @(22,4)->(22,21))","def test_identity_source_write_read(nb_file, ext): R = jupytext.writes(nb1, ext) nb2 = jupytext.reads(R, ext) compare_notebooks(nb1, nb2)","def test_identity_source_write_read(nb_file, ext): R = jupytext.writes(nb1, ext) nb2 = jupytext.reads(R, ext) compare_notebooks(nb2, nb1)" 230,https://:@github.com/mwouts/nbrmd.git,dfa96996445cbc7514b93337dbf94d592ba06bad,"@@ -16,4 +16,4 @@ def test_identity_source_write_read(nb_file): py = jupytext.writes(nb1, 'py') nb2 = jupytext.reads(py, 'py') - compare_notebooks(nb1, nb2) + compare_notebooks(nb2, nb1) ",tests/test_ipynb_to_py.py,"ArgSwap(idxs=0<->1 @(19,4)->(19,21))","def test_identity_source_write_read(nb_file): py = jupytext.writes(nb1, 'py') nb2 = jupytext.reads(py, 'py') compare_notebooks(nb1, nb2)","def test_identity_source_write_read(nb_file): py = jupytext.writes(nb1, 'py') nb2 = jupytext.reads(py, 'py') compare_notebooks(nb2, nb1)" 231,https://:@github.com/mwouts/nbrmd.git,dfa96996445cbc7514b93337dbf94d592ba06bad,"@@ -16,4 +16,4 @@ def test_identity_source_write_read(nb_file): rmd = jupytext.writes(nb1, 'Rmd') nb2 = jupytext.reads(rmd, 'Rmd') - compare_notebooks(nb1, nb2, 'Rmd') + compare_notebooks(nb2, nb1, 'Rmd') ",tests/test_ipynb_to_rmd.py,"ArgSwap(idxs=0<->1 @(19,4)->(19,21))","def test_identity_source_write_read(nb_file): rmd = jupytext.writes(nb1, 'Rmd') nb2 = jupytext.reads(rmd, 'Rmd') compare_notebooks(nb1, nb2, 'Rmd')","def test_identity_source_write_read(nb_file): rmd = jupytext.writes(nb1, 'Rmd') nb2 = jupytext.reads(rmd, 'Rmd') compare_notebooks(nb2, nb1, 'Rmd')" 232,https://:@github.com/splunk/splunk-sdk-python.git,68f87378d5bac7efc97cf118f6754b5a6de73fa3,"@@ -48,7 +48,7 @@ class EventWriter(object): else: self._out = TextIOWrapper(output) - if isinstance(output, TextIOBase): + if isinstance(error, TextIOBase): self._err = error else: self._err = TextIOWrapper(error) ",splunklib/modularinput/event_writer.py,"ReplaceText(target='error' @(51,22)->(51,28))","class EventWriter(object): else: self._out = TextIOWrapper(output) if isinstance(output, TextIOBase): self._err = error else: self._err = TextIOWrapper(error)","class EventWriter(object): else: self._out = TextIOWrapper(output) if isinstance(error, TextIOBase): self._err = error else: self._err = TextIOWrapper(error)" 233,https://:@github.com/tgbugs/pyontutils.git,78db71bb8b163794ef9bafb5a0ee50453d29971a,"@@ -56,7 +56,7 @@ def sysidpath(ignore_options=False): ) for option in options: if (option.exists() and - os.access(options, os.R_OK) and + os.access(option, os.R_OK) and option.stat().st_size > 0): return option ",pyontutils/utils.py,"ReplaceText(target='option' @(59,26)->(59,33))","def sysidpath(ignore_options=False): ) for option in options: if (option.exists() and os.access(options, os.R_OK) and option.stat().st_size > 0): return option ","def sysidpath(ignore_options=False): ) for option in options: if (option.exists() and os.access(option, os.R_OK) and option.stat().st_size > 0): return option " 234,https://:@github.com/holgern/beem.git,45ae6dc0380434d3544f5588fa24b379f5a62541,"@@ -224,7 +224,7 @@ class Blockchain(object): else: self.steem.rpc.get_block(blocknum, add_to_queue=True) latest_block = blocknum - if batches > 1: + if batches >= 1: latest_block += 1 if latest_block <= head_block: if self.steem.rpc.get_use_appbase(): ",beem/blockchain.py,"ReplaceText(target='>=' @(227,31)->(227,32))","class Blockchain(object): else: self.steem.rpc.get_block(blocknum, add_to_queue=True) latest_block = blocknum if batches > 1: latest_block += 1 if latest_block <= head_block: if self.steem.rpc.get_use_appbase():","class Blockchain(object): else: self.steem.rpc.get_block(blocknum, add_to_queue=True) latest_block = blocknum if batches >= 1: latest_block += 1 if latest_block <= head_block: if self.steem.rpc.get_use_appbase():" 235,https://:@github.com/holgern/beem.git,9eb381d23d582979934e0d3256447aef7d67de55,"@@ -509,7 +509,7 @@ class Testcases(unittest.TestCase): op_num = account.estimate_virtual_op_num(block_num, stop_diff=0.1, max_count=100) if op_num > 0: op_num -= 1 - self.assertTrue(op_num < i) + self.assertTrue(op_num <= i) i += 1 last_block = new_block ",tests/beem/test_account.py,"ReplaceText(target='<=' @(512,35)->(512,36))","class Testcases(unittest.TestCase): op_num = account.estimate_virtual_op_num(block_num, stop_diff=0.1, max_count=100) if op_num > 0: op_num -= 1 self.assertTrue(op_num < i) i += 1 last_block = new_block ","class Testcases(unittest.TestCase): op_num = account.estimate_virtual_op_num(block_num, stop_diff=0.1, max_count=100) if op_num > 0: op_num -= 1 self.assertTrue(op_num <= i) i += 1 last_block = new_block " 236,https://:@github.com/holgern/beem.git,5f156fdf5a75367c32d85efb02e456abfa2719f6,"@@ -714,6 +714,6 @@ class RecentByPath(list): comments = [] for reply in replies: post = state[""content""][reply] - if category is None or (category is not None and post[""category""] != category): + if category is None or (category is not None and post[""category""] == category): comments.append(Comment(post, lazy=True, steem_instance=self.steem)) super(RecentByPath, self).__init__(comments) ",beem/comment.py,"ReplaceText(target='==' @(717,78)->(717,80))","class RecentByPath(list): comments = [] for reply in replies: post = state[""content""][reply] if category is None or (category is not None and post[""category""] != category): comments.append(Comment(post, lazy=True, steem_instance=self.steem)) super(RecentByPath, self).__init__(comments)","class RecentByPath(list): comments = [] for reply in replies: post = state[""content""][reply] if category is None or (category is not None and post[""category""] == category): comments.append(Comment(post, lazy=True, steem_instance=self.steem)) super(RecentByPath, self).__init__(comments)" 237,https://:@github.com/holgern/beem.git,7b9ee9c75cbf285d18c1b4913cffe3798444ac30,"@@ -50,7 +50,7 @@ class RC(object): resource_count[""resource_state_bytes""] += state_bytes_count resource_count[""resource_new_accounts""] = new_account_op_count if market_op_count > 0: - resource_count[""resource_market_bytes""] = market_op_count + resource_count[""resource_market_bytes""] = tx_size return resource_count def comment_dict(self, comment_dict): ",beem/rc.py,"ReplaceText(target='tx_size' @(53,54)->(53,69))","class RC(object): resource_count[""resource_state_bytes""] += state_bytes_count resource_count[""resource_new_accounts""] = new_account_op_count if market_op_count > 0: resource_count[""resource_market_bytes""] = market_op_count return resource_count def comment_dict(self, comment_dict):","class RC(object): resource_count[""resource_state_bytes""] += state_bytes_count resource_count[""resource_new_accounts""] = new_account_op_count if market_op_count > 0: resource_count[""resource_market_bytes""] = tx_size return resource_count def comment_dict(self, comment_dict):" 238,https://:@github.com/holgern/beem.git,9e96dc84f9965b25b6b2a56a1bca7b7652b93be8,"@@ -1456,7 +1456,7 @@ class Steem(object): 'key_auths': active_key_authority, ""address_auths"": [], 'weight_threshold': 1}, - 'posting': {'account_auths': active_accounts_authority, + 'posting': {'account_auths': posting_accounts_authority, 'key_auths': posting_key_authority, ""address_auths"": [], 'weight_threshold': 1}, ",beem/steem.py,"ReplaceText(target='posting_accounts_authority' @(1459,41)->(1459,66))","class Steem(object): 'key_auths': active_key_authority, ""address_auths"": [], 'weight_threshold': 1}, 'posting': {'account_auths': active_accounts_authority, 'key_auths': posting_key_authority, ""address_auths"": [], 'weight_threshold': 1},","class Steem(object): 'key_auths': active_key_authority, ""address_auths"": [], 'weight_threshold': 1}, 'posting': {'account_auths': posting_accounts_authority, 'key_auths': posting_key_authority, ""address_auths"": [], 'weight_threshold': 1}," 239,https://:@github.com/holgern/beem.git,8e4214f27e746be7ed01c5d644911c830bfe988a,"@@ -135,7 +135,7 @@ class Block(BlockchainObject): if ops_ops is None: ops = None else: - ops = ops[""ops""] + ops = ops_ops[""ops""] except ApiNotSupported: ops = self.steem.rpc.get_ops_in_block(self.identifier, self.only_virtual_ops, api=""condenser"") else: ",beem/block.py,"ReplaceText(target='ops_ops' @(138,30)->(138,33))","class Block(BlockchainObject): if ops_ops is None: ops = None else: ops = ops[""ops""] except ApiNotSupported: ops = self.steem.rpc.get_ops_in_block(self.identifier, self.only_virtual_ops, api=""condenser"") else:","class Block(BlockchainObject): if ops_ops is None: ops = None else: ops = ops_ops[""ops""] except ApiNotSupported: ops = self.steem.rpc.get_ops_in_block(self.identifier, self.only_virtual_ops, api=""condenser"") else:" 240,https://:@github.com/holgern/beem.git,d19894c85464f2bc5221e15f858326c4e8efdaf3,"@@ -367,7 +367,7 @@ class ActiveVotes(VotesObject): elif isinstance(authorperm, string_types): [author, permlink] = resolve_authorperm(authorperm) if self.steem.rpc.get_use_appbase(): - self.steem.rpc.set_next_node_on_empty_reply(True) + self.steem.rpc.set_next_node_on_empty_reply(False) try: votes = self.steem.rpc.get_active_votes(author, permlink, api=""condenser"") except: ",beem/vote.py,"ReplaceText(target='False' @(370,60)->(370,64))","class ActiveVotes(VotesObject): elif isinstance(authorperm, string_types): [author, permlink] = resolve_authorperm(authorperm) if self.steem.rpc.get_use_appbase(): self.steem.rpc.set_next_node_on_empty_reply(True) try: votes = self.steem.rpc.get_active_votes(author, permlink, api=""condenser"") except:","class ActiveVotes(VotesObject): elif isinstance(authorperm, string_types): [author, permlink] = resolve_authorperm(authorperm) if self.steem.rpc.get_use_appbase(): self.steem.rpc.set_next_node_on_empty_reply(False) try: votes = self.steem.rpc.get_active_votes(author, permlink, api=""condenser"") except:" 241,https://:@github.com/holgern/beem.git,8f173f0ab272a57a5c036589dcc19b8543026b3e,"@@ -780,7 +780,7 @@ def keygen(import_word_list, strength, passphrase, path, network, role, account_ t.add_row([""Key role"", role]) t.add_row([""path"", path]) pubkey = ledgertx.ledgertx.get_pubkey(path, request_screen_approval=False) - aprove_key = PrettyTable([""Approve %s Key"" % r]) + aprove_key = PrettyTable([""Approve %s Key"" % role]) aprove_key.align = ""l"" aprove_key.add_row([format(pubkey, ""STM"")]) print(aprove_key) ",beem/cli.py,"ReplaceText(target='role' @(783,57)->(783,58))","def keygen(import_word_list, strength, passphrase, path, network, role, account_ t.add_row([""Key role"", role]) t.add_row([""path"", path]) pubkey = ledgertx.ledgertx.get_pubkey(path, request_screen_approval=False) aprove_key = PrettyTable([""Approve %s Key"" % r]) aprove_key.align = ""l"" aprove_key.add_row([format(pubkey, ""STM"")]) print(aprove_key)","def keygen(import_word_list, strength, passphrase, path, network, role, account_ t.add_row([""Key role"", role]) t.add_row([""path"", path]) pubkey = ledgertx.ledgertx.get_pubkey(path, request_screen_approval=False) aprove_key = PrettyTable([""Approve %s Key"" % role]) aprove_key.align = ""l"" aprove_key.add_row([format(pubkey, ""STM"")]) print(aprove_key)" 242,https://:@github.com/BlackLight/platypush.git,56b87f343693e89131b3b30930acfeeaec4915fe,"@@ -101,7 +101,7 @@ class MqttBackend(Backend): format(response_topic, response)) client = get_plugin('mqtt') - client.send_message(topic=self.topic, msg=msg, host=self.host, + client.send_message(topic=self.topic, msg=response, host=self.host, port=self.port, username=self.username, password=self.password, tls_cafile=self.tls_cafile, tls_certfile=self.tls_certfile, ",platypush/backend/mqtt.py,"ReplaceText(target='response' @(104,58)->(104,61))","class MqttBackend(Backend): format(response_topic, response)) client = get_plugin('mqtt') client.send_message(topic=self.topic, msg=msg, host=self.host, port=self.port, username=self.username, password=self.password, tls_cafile=self.tls_cafile, tls_certfile=self.tls_certfile,","class MqttBackend(Backend): format(response_topic, response)) client = get_plugin('mqtt') client.send_message(topic=self.topic, msg=response, host=self.host, port=self.port, username=self.username, password=self.password, tls_cafile=self.tls_cafile, tls_certfile=self.tls_certfile," 243,https://:@github.com/BlackLight/platypush.git,c9dc1aac44ec4df76071092f4a17601d97955a38,"@@ -47,7 +47,7 @@ class SensorEnvirophatBackend(SensorBackend): if enabled and sensor in sensors and sensors[sensor] != self._last_read.get(sensor) } - self._last_read = ret + self._last_read = sensors return ret ",platypush/backend/sensor/envirophat.py,"ReplaceText(target='sensors' @(50,26)->(50,29))","class SensorEnvirophatBackend(SensorBackend): if enabled and sensor in sensors and sensors[sensor] != self._last_read.get(sensor) } self._last_read = ret return ret ","class SensorEnvirophatBackend(SensorBackend): if enabled and sensor in sensors and sensors[sensor] != self._last_read.get(sensor) } self._last_read = sensors return ret " 244,https://:@github.com/BlackLight/platypush.git,7f440a9160619c699f7e8e58b3c0fad3c80ceaf3,"@@ -46,7 +46,7 @@ class GpioPlugin(Plugin): import RPi.GPIO as GPIO with self._init_lock: - if self._initialized or GPIO.getmode(): + if self._initialized and GPIO.getmode(): return GPIO.setmode(self.mode) ",platypush/plugins/gpio/__init__.py,"ReplaceText(target='and' @(49,33)->(49,35))","class GpioPlugin(Plugin): import RPi.GPIO as GPIO with self._init_lock: if self._initialized or GPIO.getmode(): return GPIO.setmode(self.mode)","class GpioPlugin(Plugin): import RPi.GPIO as GPIO with self._init_lock: if self._initialized and GPIO.getmode(): return GPIO.setmode(self.mode)" 245,https://:@github.com/BlackLight/platypush.git,c26d456109fea166f8fb5da25aed1d4fb7fc94ab,"@@ -175,7 +175,7 @@ class SensorBackend(Backend): def process_data(self, data, new_data): if new_data: - self.bus.post(SensorDataChangeEvent(data=data, source=self.plugin or self.__class__.__name__)) + self.bus.post(SensorDataChangeEvent(data=new_data, source=self.plugin or self.__class__.__name__)) def run(self): super().run() ",platypush/backend/sensor/__init__.py,"ReplaceText(target='new_data' @(178,53)->(178,57))","class SensorBackend(Backend): def process_data(self, data, new_data): if new_data: self.bus.post(SensorDataChangeEvent(data=data, source=self.plugin or self.__class__.__name__)) def run(self): super().run()","class SensorBackend(Backend): def process_data(self, data, new_data): if new_data: self.bus.post(SensorDataChangeEvent(data=new_data, source=self.plugin or self.__class__.__name__)) def run(self): super().run()" 246,https://:@github.com/chrisjsewell/ipypublish.git,cfb66fb74d48cbcc99c695b64fe6336213877e04,"@@ -52,7 +52,7 @@ class LatexDocLinks(Preprocessor): ': {}'.format(bib)) else: external_files.append(bib) - resources['bibliopath'] = external_files + resources['bibliopath'] = bib nb.metadata.latex_doc.bibliography = os.path.join(self.filesfolder, os.path.basename(bib)) ",ipypublish/preprocessors/latex_doc.py,"ReplaceText(target='bib' @(55,46)->(55,60))","class LatexDocLinks(Preprocessor): ': {}'.format(bib)) else: external_files.append(bib) resources['bibliopath'] = external_files nb.metadata.latex_doc.bibliography = os.path.join(self.filesfolder, os.path.basename(bib))","class LatexDocLinks(Preprocessor): ': {}'.format(bib)) else: external_files.append(bib) resources['bibliopath'] = bib nb.metadata.latex_doc.bibliography = os.path.join(self.filesfolder, os.path.basename(bib))" 247,https://:@github.com/pazz/alot.git,dd7b2a15495ce5fddcac0d34c14e5ef9f1032482,"@@ -64,7 +64,7 @@ class ThreadlineWidget(urwid.AttrMap): mailcountstring = ""(%d)"" % self.thread.get_total_messages() else: mailcountstring = ""(?)"" - datestring = pad(mailcountstring) + mailcountstring = pad(mailcountstring) width = len(mailcountstring) mailcount_w = AttrFlipWidget(urwid.Text(mailcountstring), struct['mailcount']) ",alot/widgets/search.py,"ReplaceText(target='mailcountstring' @(67,12)->(67,22))","class ThreadlineWidget(urwid.AttrMap): mailcountstring = ""(%d)"" % self.thread.get_total_messages() else: mailcountstring = ""(?)"" datestring = pad(mailcountstring) width = len(mailcountstring) mailcount_w = AttrFlipWidget(urwid.Text(mailcountstring), struct['mailcount'])","class ThreadlineWidget(urwid.AttrMap): mailcountstring = ""(%d)"" % self.thread.get_total_messages() else: mailcountstring = ""(?)"" mailcountstring = pad(mailcountstring) width = len(mailcountstring) mailcount_w = AttrFlipWidget(urwid.Text(mailcountstring), struct['mailcount'])" 248,https://:@github.com/luozhouyang/python-string-similarity.git,5f6717fe6d7cae48a664eaa76a47e3388ffd0cf2,"@@ -33,7 +33,7 @@ class Levenshtein(MetricStringDistance): if len(s0) == 0: return len(s1) if len(s1) == 0: - return len(s1) + return len(s0) v0 = [0] * (len(s1) + 1) v1 = [0] * (len(s1) + 1) ",strsimpy/levenshtein.py,"ReplaceText(target='s0' @(36,23)->(36,25))","class Levenshtein(MetricStringDistance): if len(s0) == 0: return len(s1) if len(s1) == 0: return len(s1) v0 = [0] * (len(s1) + 1) v1 = [0] * (len(s1) + 1)","class Levenshtein(MetricStringDistance): if len(s0) == 0: return len(s1) if len(s1) == 0: return len(s0) v0 = [0] * (len(s1) + 1) v1 = [0] * (len(s1) + 1)" 249,https://:@github.com/ElementsProject/lightning.git,84b9e3e72b2bf8590603072d709a3ea294dd5483,"@@ -943,7 +943,7 @@ def test_logging(node_factory): def check_new_log(): log2 = open(logpath).readlines() - return len(log2) > 1 and log2[0].endswith(""Started log due to SIGHUP\n"") + return len(log2) > 0 and log2[0].endswith(""Started log due to SIGHUP\n"") wait_for(check_new_log) ",tests/test_misc.py,"ReplaceText(target='0' @(946,27)->(946,28))","def test_logging(node_factory): def check_new_log(): log2 = open(logpath).readlines() return len(log2) > 1 and log2[0].endswith(""Started log due to SIGHUP\n"") wait_for(check_new_log) ","def test_logging(node_factory): def check_new_log(): log2 = open(logpath).readlines() return len(log2) > 0 and log2[0].endswith(""Started log due to SIGHUP\n"") wait_for(check_new_log) " 250,https://:@github.com/ElementsProject/lightning.git,c8579b99d01d8b738feadd2d9f541daba5230a63,"@@ -305,7 +305,7 @@ other types. Since 'msgtype' is almost identical, it inherits from this too. def read(self, io_in: BufferedIOBase, otherfields: Dict[str, Any]) -> Optional[Dict[str, Any]]: vals = {} for field in self.fields: - val = field.fieldtype.read(io_in, otherfields) + val = field.fieldtype.read(io_in, vals) if val is None: # If first field fails to read, we return None. if field == self.fields[0]: ",contrib/pyln-proto/pyln/proto/message/message.py,"ReplaceText(target='vals' @(308,46)->(308,57))","other types. Since 'msgtype' is almost identical, it inherits from this too. def read(self, io_in: BufferedIOBase, otherfields: Dict[str, Any]) -> Optional[Dict[str, Any]]: vals = {} for field in self.fields: val = field.fieldtype.read(io_in, otherfields) if val is None: # If first field fails to read, we return None. if field == self.fields[0]:","other types. Since 'msgtype' is almost identical, it inherits from this too. def read(self, io_in: BufferedIOBase, otherfields: Dict[str, Any]) -> Optional[Dict[str, Any]]: vals = {} for field in self.fields: val = field.fieldtype.read(io_in, vals) if val is None: # If first field fails to read, we return None. if field == self.fields[0]:" 251,https://:@github.com/funilrys/PyFunceble.git,c766732abdf31c0c1ce283ee9aa2ec32f0ac7829,"@@ -301,7 +301,7 @@ class Generate(object): # pragma: no cover regex_blogger = [""create-blog.g?"", ""87065"", ""doesn’t exist""] if self.tested == PyFunceble.CONFIGURATION[""domain""]: - url_to_get = ""http://%s"" & self.tested + url_to_get = ""http://%s"" % self.tested else: url_to_get = self.tested ",PyFunceble/generate.py,"ReplaceText(target='%' @(304,37)->(304,38))","class Generate(object): # pragma: no cover regex_blogger = [""create-blog.g?"", ""87065"", ""doesn’t exist""] if self.tested == PyFunceble.CONFIGURATION[""domain""]: url_to_get = ""http://%s"" & self.tested else: url_to_get = self.tested ","class Generate(object): # pragma: no cover regex_blogger = [""create-blog.g?"", ""87065"", ""doesn’t exist""] if self.tested == PyFunceble.CONFIGURATION[""domain""]: url_to_get = ""http://%s"" % self.tested else: url_to_get = self.tested " 252,https://:@github.com/funilrys/PyFunceble.git,08400b05f5f3e20c24c9222a9cb9216d1a76aea5,"@@ -80,7 +80,7 @@ class Load(object): # pylint: disable=too-few-public-methods def __init__(self, path_to_config): self.path_to_config = path_to_config - if path_to_config.endswith(directory_separator): + if not path_to_config.endswith(directory_separator): self.path_to_config += directory_separator self.path_to_config += PyFunceble.CONFIGURATION_FILENAME ",PyFunceble/config.py,"ReplaceText(target='not ' @(83,11)->(83,11))","class Load(object): # pylint: disable=too-few-public-methods def __init__(self, path_to_config): self.path_to_config = path_to_config if path_to_config.endswith(directory_separator): self.path_to_config += directory_separator self.path_to_config += PyFunceble.CONFIGURATION_FILENAME","class Load(object): # pylint: disable=too-few-public-methods def __init__(self, path_to_config): self.path_to_config = path_to_config if not path_to_config.endswith(directory_separator): self.path_to_config += directory_separator self.path_to_config += PyFunceble.CONFIGURATION_FILENAME" 253,https://:@github.com/funilrys/PyFunceble.git,fb9465acb6a7124aa84b8c419c9709243e001f94,"@@ -96,7 +96,7 @@ class Clean: if ( number_of_tested == 0 or list_to_test[number_of_tested - 1] == list_to_test[-1] - or number_of_tested == len(list_to_test) + or number_of_tested >= len(list_to_test) ): # * If the number of tested is null, # or ",PyFunceble/clean.py,"ReplaceText(target='>=' @(99,40)->(99,42))","class Clean: if ( number_of_tested == 0 or list_to_test[number_of_tested - 1] == list_to_test[-1] or number_of_tested == len(list_to_test) ): # * If the number of tested is null, # or","class Clean: if ( number_of_tested == 0 or list_to_test[number_of_tested - 1] == list_to_test[-1] or number_of_tested >= len(list_to_test) ): # * If the number of tested is null, # or" 254,https://:@github.com/funilrys/PyFunceble.git,a9e45c83e13eca92389d0be56634cc45ef601bc1,"@@ -92,7 +92,7 @@ class DBTypeDownloader(DownloaderBase): f""{PyFunceble.OUTPUTS.db_type.files[PyFunceble.CONFIGURATION.db_type]}"" ) - if is_cloned_version and ( + if not is_cloned_version and ( PyFunceble.CONFIGURATION.db_type not in not_supported_db_types ): destination_dir_instance.delete() ",PyFunceble/downloader/db_type.py,"ReplaceText(target='not ' @(95,11)->(95,11))","class DBTypeDownloader(DownloaderBase): f""{PyFunceble.OUTPUTS.db_type.files[PyFunceble.CONFIGURATION.db_type]}"" ) if is_cloned_version and ( PyFunceble.CONFIGURATION.db_type not in not_supported_db_types ): destination_dir_instance.delete()","class DBTypeDownloader(DownloaderBase): f""{PyFunceble.OUTPUTS.db_type.files[PyFunceble.CONFIGURATION.db_type]}"" ) if not is_cloned_version and ( PyFunceble.CONFIGURATION.db_type not in not_supported_db_types ): destination_dir_instance.delete()" 255,https://:@github.com/funilrys/PyFunceble.git,76bc73c57f4ac2865fc89d70ad330be2aa501c08,"@@ -154,7 +154,7 @@ class Credential: regex = f""{name}=.*"" if not content: - content += f""{to_write}\n"" + content = f""{to_write}\n"" continue if PyFunceble.helpers.Regex(f""^{regex}"").get_matching_list( ",PyFunceble/engine/database/loader/credential.py,"ReplaceText(target='=' @(157,28)->(157,30))","class Credential: regex = f""{name}=.*"" if not content: content += f""{to_write}\n"" continue if PyFunceble.helpers.Regex(f""^{regex}"").get_matching_list(","class Credential: regex = f""{name}=.*"" if not content: content = f""{to_write}\n"" continue if PyFunceble.helpers.Regex(f""^{regex}"").get_matching_list(" 256,https://:@github.com/valassis-digital-media/conda-mirror.git,e0b34555d779f9b440512f850da39aa5a0e29ece,"@@ -85,5 +85,5 @@ def test_handling_bad_package(tmpdir, repodata): with bz2.BZ2File(bad_pkg_path, 'wb') as f: f.write(""This is a fake package"".encode()) assert bad_pkg_name in os.listdir(bad_pkg_root) - conda_mirror._validate_packages(repodata, local_repo_root) + conda_mirror._validate_packages(repodata, bad_pkg_root) assert bad_pkg_name not in os.listdir(bad_pkg_root) \ No newline at end of file ",test/test_conda_mirror.py,"ReplaceText(target='bad_pkg_root' @(88,46)->(88,61))","def test_handling_bad_package(tmpdir, repodata): with bz2.BZ2File(bad_pkg_path, 'wb') as f: f.write(""This is a fake package"".encode()) assert bad_pkg_name in os.listdir(bad_pkg_root) conda_mirror._validate_packages(repodata, local_repo_root) assert bad_pkg_name not in os.listdir(bad_pkg_root) \ No newline at end of file","def test_handling_bad_package(tmpdir, repodata): with bz2.BZ2File(bad_pkg_path, 'wb') as f: f.write(""This is a fake package"".encode()) assert bad_pkg_name in os.listdir(bad_pkg_root) conda_mirror._validate_packages(repodata, bad_pkg_root) assert bad_pkg_name not in os.listdir(bad_pkg_root) \ No newline at end of file" 257,https://:@github.com/fact-project/pycustos.git,e2432cee5bba6dc97b30d0b640c0c92f3bdd6961,"@@ -8,7 +8,7 @@ class Notifier(metaclass=ABCMeta): self.categories = set(categories) def handle_message(self, msg): - if self.categories.intersection(msg.categories) and msg.level > self.level: + if self.categories.intersection(msg.categories) and msg.level >= self.level: self.notify(msg) @abstractmethod ",custos/notify/base.py,"ReplaceText(target='>=' @(11,70)->(11,71))","class Notifier(metaclass=ABCMeta): self.categories = set(categories) def handle_message(self, msg): if self.categories.intersection(msg.categories) and msg.level > self.level: self.notify(msg) @abstractmethod","class Notifier(metaclass=ABCMeta): self.categories = set(categories) def handle_message(self, msg): if self.categories.intersection(msg.categories) and msg.level >= self.level: self.notify(msg) @abstractmethod" 258,https://:@github.com/danilobellini/audiolazy.git,3119b12f8f0b175b3f55aecf3053ed6a0d1a477a,"@@ -249,4 +249,4 @@ def gammatone(freq, bandwidth): freqs = tee(freq, 4) resons = [resonator.z_exp, resonator.poles_exp] * 2 return CascadeFilter(reson(f, bw) - for reson, f, bw in zip(bws, freqs, resons)) + for reson, f, bw in zip(resons, freqs, bws)) ",audiolazy/lazy_auditory.py,"ArgSwap(idxs=0<->2 @(252,43)->(252,46))","def gammatone(freq, bandwidth): freqs = tee(freq, 4) resons = [resonator.z_exp, resonator.poles_exp] * 2 return CascadeFilter(reson(f, bw) for reson, f, bw in zip(bws, freqs, resons))","def gammatone(freq, bandwidth): freqs = tee(freq, 4) resons = [resonator.z_exp, resonator.poles_exp] * 2 return CascadeFilter(reson(f, bw) for reson, f, bw in zip(resons, freqs, bws))" 259,https://:@github.com/ojii/django-sekizai.git,b0b50e0713a90e84acabe1ab39e951421fd4aa7a,"@@ -91,6 +91,6 @@ class CSSSingleFileFilter(BaseMinifierFilter): mtime = os.path.getmtime(master) for f in files: fpath = media_url_to_filepath(f) - if os.path.getmtime(fpath) > mtime: + if os.path.getmtime(fpath) >= mtime: return True return False \ No newline at end of file ",sekizai/filters/css.py,"ReplaceText(target='>=' @(94,39)->(94,40))","class CSSSingleFileFilter(BaseMinifierFilter): mtime = os.path.getmtime(master) for f in files: fpath = media_url_to_filepath(f) if os.path.getmtime(fpath) > mtime: return True return False \ No newline at end of file","class CSSSingleFileFilter(BaseMinifierFilter): mtime = os.path.getmtime(master) for f in files: fpath = media_url_to_filepath(f) if os.path.getmtime(fpath) >= mtime: return True return False \ No newline at end of file" 260,https://:@github.com/websocket-client/websocket-client.git,6410340fca47f258d50a34646138ba03b2b2783b,"@@ -183,7 +183,7 @@ def _tunnel(sock, host, port, auth): if status != 200: raise WebSocketProxyException( - ""failed CONNECT via proxy status: %r"" + status) + ""failed CONNECT via proxy status: %r"" % status) return sock ",websocket/_http.py,"ReplaceText(target='%' @(186,50)->(186,51))","def _tunnel(sock, host, port, auth): if status != 200: raise WebSocketProxyException( ""failed CONNECT via proxy status: %r"" + status) return sock ","def _tunnel(sock, host, port, auth): if status != 200: raise WebSocketProxyException( ""failed CONNECT via proxy status: %r"" % status) return sock " 261,https://:@github.com/getsentry/raven-python.git,dedca8e5c98124f6a43a18986e142e8cb7ecc3cf,"@@ -59,7 +59,7 @@ def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() - if handler.__class__ not in map(type, logger.handlers): + if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler) ",raven/conf/__init__.py,"ReplaceText(target=' in ' @(62,24)->(62,32))","def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() if handler.__class__ not in map(type, logger.handlers): return False logger.addHandler(handler)","def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler)" 262,https://:@github.com/getsentry/raven-python.git,f0ad0ca6a9de44128982de50c30157b779b69d71,"@@ -16,7 +16,7 @@ class TransportRegistry(object): self.register_transport(transport) def register_transport(self, transport): - if not hasattr(transport, 'scheme') and not hasattr(transport.scheme, '__iter__'): + if not hasattr(transport, 'scheme') or not hasattr(transport.scheme, '__iter__'): raise AttributeError('Transport %s must have a scheme list', transport.__class__.__name__) for scheme in transport.scheme: ",raven/transport/registry.py,"ReplaceText(target='or' @(19,44)->(19,47))","class TransportRegistry(object): self.register_transport(transport) def register_transport(self, transport): if not hasattr(transport, 'scheme') and not hasattr(transport.scheme, '__iter__'): raise AttributeError('Transport %s must have a scheme list', transport.__class__.__name__) for scheme in transport.scheme:","class TransportRegistry(object): self.register_transport(transport) def register_transport(self, transport): if not hasattr(transport, 'scheme') or not hasattr(transport.scheme, '__iter__'): raise AttributeError('Transport %s must have a scheme list', transport.__class__.__name__) for scheme in transport.scheme:" 263,https://:@github.com/ilius/pyglossary.git,8ad925bbb4ce19207322471c4c758d1a66f0db9d,"@@ -186,7 +186,7 @@ def write( with open(filePathBase + "".xml"", ""w"", encoding=""utf8"") as toFile: write_header(glos, toFile, frontBackMatter) for entryI, entry in enumerate(glos): - if glos.isData(): + if entry.isData(): entry.save(myResDir) continue ",pyglossary/plugins/appledict/__init__.py,"ReplaceText(target='entry' @(189,6)->(189,10))","def write( with open(filePathBase + "".xml"", ""w"", encoding=""utf8"") as toFile: write_header(glos, toFile, frontBackMatter) for entryI, entry in enumerate(glos): if glos.isData(): entry.save(myResDir) continue ","def write( with open(filePathBase + "".xml"", ""w"", encoding=""utf8"") as toFile: write_header(glos, toFile, frontBackMatter) for entryI, entry in enumerate(glos): if entry.isData(): entry.save(myResDir) continue " 264,https://:@github.com/ilius/pyglossary.git,194fea3e176f5c9caf090a58bee3c5b04fd483ef,"@@ -450,7 +450,7 @@ class Glossary(GlossaryType): wordCount = len(reader) except Exception: log.exception("""") - if wordCount > 0: + if wordCount >= 0: progressbar = True if progressbar: self.progressInit(""Converting"") ",pyglossary/glossary.py,"ReplaceText(target='>=' @(453,17)->(453,18))","class Glossary(GlossaryType): wordCount = len(reader) except Exception: log.exception("""") if wordCount > 0: progressbar = True if progressbar: self.progressInit(""Converting"")","class Glossary(GlossaryType): wordCount = len(reader) except Exception: log.exception("""") if wordCount >= 0: progressbar = True if progressbar: self.progressInit(""Converting"")" 265,https://:@github.com/ilius/pyglossary.git,a7237c6749dcd2f2cf34b5f8ec385b6ba0b5565a,"@@ -99,7 +99,7 @@ class TextGlossaryReader(object): try: wordDefi = self.nextPair() except StopIteration as e: - if self._fileIndex < self._fileCount + 1: + if self._fileIndex < self._fileCount - 1: if self.openNextFile(): return self.__next__() self._wordCount = self._pos ",pyglossary/text_reader.py,"ReplaceText(target='-' @(102,40)->(102,41))","class TextGlossaryReader(object): try: wordDefi = self.nextPair() except StopIteration as e: if self._fileIndex < self._fileCount + 1: if self.openNextFile(): return self.__next__() self._wordCount = self._pos","class TextGlossaryReader(object): try: wordDefi = self.nextPair() except StopIteration as e: if self._fileIndex < self._fileCount - 1: if self.openNextFile(): return self.__next__() self._wordCount = self._pos" 266,https://:@github.com/GOVCERT-LU/eml_parser.git,5a129fd37081de0c3483a317e4eefced52fed44d,"@@ -636,7 +636,7 @@ def parse_email(msg, include_raw_body=False, include_attachment_data=False): if list_observed_dom: bodie['domain'] = list(set(list_observed_dom)) - if list_observed_dom: + if list_observed_ip: bodie['ip'] = list(set(list_observed_ip)) else: ",eml_parser/eml_parser.py,"ReplaceText(target='list_observed_ip' @(639,15)->(639,32))","def parse_email(msg, include_raw_body=False, include_attachment_data=False): if list_observed_dom: bodie['domain'] = list(set(list_observed_dom)) if list_observed_dom: bodie['ip'] = list(set(list_observed_ip)) else:","def parse_email(msg, include_raw_body=False, include_attachment_data=False): if list_observed_dom: bodie['domain'] = list(set(list_observed_dom)) if list_observed_ip: bodie['ip'] = list(set(list_observed_ip)) else:" 267,https://:@github.com/noripyt/wagtail-react-streamfield.git,fcd366318ffd0f20f93efcc58e00658f1334899c,"@@ -75,4 +75,4 @@ class NewListBlock(ListBlock): _('The maximum number of items is %d') % self.meta.max_num ) - return value + return result ",wagtail_react_streamfield/blocks/list_block.py,"ReplaceText(target='result' @(78,15)->(78,20))","class NewListBlock(ListBlock): _('The maximum number of items is %d') % self.meta.max_num ) return value","class NewListBlock(ListBlock): _('The maximum number of items is %d') % self.meta.max_num ) return result" 268,https://:@github.com/noripyt/wagtail-react-streamfield.git,4a33dab16bc9665349e6aaa011df3a47eea25277,"@@ -43,7 +43,7 @@ class NewBlock(Block): else errors.as_data()[0].params.get(NON_FIELD_ERRORS, ())) else: non_block_errors = errors - if help_text and non_block_errors: + if help_text or non_block_errors: return render_to_string( 'wagtailadmin/block_forms/blocks_container.html', { ",wagtail_react_streamfield/blocks/block.py,"ReplaceText(target='or' @(46,21)->(46,24))","class NewBlock(Block): else errors.as_data()[0].params.get(NON_FIELD_ERRORS, ())) else: non_block_errors = errors if help_text and non_block_errors: return render_to_string( 'wagtailadmin/block_forms/blocks_container.html', {","class NewBlock(Block): else errors.as_data()[0].params.get(NON_FIELD_ERRORS, ())) else: non_block_errors = errors if help_text or non_block_errors: return render_to_string( 'wagtailadmin/block_forms/blocks_container.html', {" 269,https://:@github.com/PMBio/MOFA.git,f7cd442f209ce679001b67e2ed439016bdef6991,"@@ -82,7 +82,7 @@ class initModel(object): elif qmean == ""pca"": # Latent variables are initialised from PCA in the concatenated matrix pca = sklearn.decomposition.PCA(n_components=self.K, copy=True, whiten=True) - pca.fit(s.concatenate(self.data,axis=0).T) + pca.fit(s.concatenate(self.data,axis=1).T) qmean = pca.components_.T elif isinstance(qmean,s.ndarray): ",mofa/core/init_nodes.py,"ReplaceText(target='1' @(85,57)->(85,58))","class initModel(object): elif qmean == ""pca"": # Latent variables are initialised from PCA in the concatenated matrix pca = sklearn.decomposition.PCA(n_components=self.K, copy=True, whiten=True) pca.fit(s.concatenate(self.data,axis=0).T) qmean = pca.components_.T elif isinstance(qmean,s.ndarray):","class initModel(object): elif qmean == ""pca"": # Latent variables are initialised from PCA in the concatenated matrix pca = sklearn.decomposition.PCA(n_components=self.K, copy=True, whiten=True) pca.fit(s.concatenate(self.data,axis=1).T) qmean = pca.components_.T elif isinstance(qmean,s.ndarray):" 270,https://:@github.com/twisted/tubes.git,836d6021f14ad923bb595dffb0a6ca39f0b884b5,"@@ -168,7 +168,7 @@ class _SiphonFount(_SiphonPiece): def _actuallyPause(): fount = self._siphon._tdrain.fount self._siphon._pending.suspend() - if fount is None: + if fount is not None: pbpc = fount.pauseFlow() else: pbpc = NoPause() ",tubes/_siphon.py,"ReplaceText(target=' is not ' @(171,20)->(171,24))","class _SiphonFount(_SiphonPiece): def _actuallyPause(): fount = self._siphon._tdrain.fount self._siphon._pending.suspend() if fount is None: pbpc = fount.pauseFlow() else: pbpc = NoPause()","class _SiphonFount(_SiphonPiece): def _actuallyPause(): fount = self._siphon._tdrain.fount self._siphon._pending.suspend() if fount is not None: pbpc = fount.pauseFlow() else: pbpc = NoPause()" 271,https://:@github.com/deschler/django-modeltranslation.git,656dca3e4031d8f030a0aae833fc43c0c09cb51c,"@@ -57,7 +57,7 @@ class TranslationBaseModelAdmin(BaseModelAdmin): else: orig_formfield = self.formfield_for_dbfield(orig_field, **kwargs) field.widget = deepcopy(orig_formfield.widget) - if orig_field.null and isinstance(field.widget, (forms.TextInput, forms.Textarea)): + if db_field.null and isinstance(field.widget, (forms.TextInput, forms.Textarea)): field.widget = ClearableWidgetWrapper(field.widget) css_classes = field.widget.attrs.get('class', '').split(' ') css_classes.append('mt') ",modeltranslation/admin.py,"ReplaceText(target='db_field' @(60,15)->(60,25))","class TranslationBaseModelAdmin(BaseModelAdmin): else: orig_formfield = self.formfield_for_dbfield(orig_field, **kwargs) field.widget = deepcopy(orig_formfield.widget) if orig_field.null and isinstance(field.widget, (forms.TextInput, forms.Textarea)): field.widget = ClearableWidgetWrapper(field.widget) css_classes = field.widget.attrs.get('class', '').split(' ') css_classes.append('mt')","class TranslationBaseModelAdmin(BaseModelAdmin): else: orig_formfield = self.formfield_for_dbfield(orig_field, **kwargs) field.widget = deepcopy(orig_formfield.widget) if db_field.null and isinstance(field.widget, (forms.TextInput, forms.Textarea)): field.widget = ClearableWidgetWrapper(field.widget) css_classes = field.widget.attrs.get('class', '').split(' ') css_classes.append('mt')" 272,https://:@github.com/xcgspring/AXUI.git,82f7d6f7f2565d28553fda3c12bb1a2aafb5bab9,"@@ -123,7 +123,7 @@ class AppMap(object): UI_element_group.stop_func = self.get_func_by_name(xml_element.attrib[""stop_func""]) if xml_element.attrib.has_key(""identifier""): UI_element_group.identifier_string = xml_element.attrib[""identifier""] - UI_element_group.identifier = identifier_parser.parse(UI_element.identifier_string, lexer=identifier_lexer) + UI_element_group.identifier = identifier_parser.parse(UI_element_group.identifier_string, lexer=identifier_lexer) return UI_element_group ",AXUI/XML/app_map.py,"ReplaceText(target='UI_element_group' @(126,70)->(126,80))","class AppMap(object): UI_element_group.stop_func = self.get_func_by_name(xml_element.attrib[""stop_func""]) if xml_element.attrib.has_key(""identifier""): UI_element_group.identifier_string = xml_element.attrib[""identifier""] UI_element_group.identifier = identifier_parser.parse(UI_element.identifier_string, lexer=identifier_lexer) return UI_element_group ","class AppMap(object): UI_element_group.stop_func = self.get_func_by_name(xml_element.attrib[""stop_func""]) if xml_element.attrib.has_key(""identifier""): UI_element_group.identifier_string = xml_element.attrib[""identifier""] UI_element_group.identifier = identifier_parser.parse(UI_element_group.identifier_string, lexer=identifier_lexer) return UI_element_group " 273,https://:@github.com/docker/compose.git,0e19c92e82c75f821c231367b5cda88eefdf1427,"@@ -577,7 +577,7 @@ class VolumeConfigTest(unittest.TestCase): def test_volume_path_with_non_ascii_directory(self): volume = u'/Füü/data:/data' - container_path = config.resolve_volume_path(volume, ""."", ""test"") + container_path = config.resolve_volume_path(""."", volume, ""test"") self.assertEqual(container_path, volume) ",tests/unit/config/config_test.py,"ArgSwap(idxs=0<->1 @(580,25)->(580,51))","class VolumeConfigTest(unittest.TestCase): def test_volume_path_with_non_ascii_directory(self): volume = u'/Füü/data:/data' container_path = config.resolve_volume_path(volume, ""."", ""test"") self.assertEqual(container_path, volume) ","class VolumeConfigTest(unittest.TestCase): def test_volume_path_with_non_ascii_directory(self): volume = u'/Füü/data:/data' container_path = config.resolve_volume_path(""."", volume, ""test"") self.assertEqual(container_path, volume) " 274,https://:@github.com/docker/compose.git,c4f59e731d540780a767d105bcb8d7d164ba4cd5,"@@ -577,7 +577,7 @@ class VolumeConfigTest(unittest.TestCase): def test_volume_path_with_non_ascii_directory(self): volume = u'/Füü/data:/data' - container_path = config.resolve_volume_path(volume, ""."", ""test"") + container_path = config.resolve_volume_path(""."", volume, ""test"") self.assertEqual(container_path, volume) ",tests/unit/config/config_test.py,"ArgSwap(idxs=0<->1 @(580,25)->(580,51))","class VolumeConfigTest(unittest.TestCase): def test_volume_path_with_non_ascii_directory(self): volume = u'/Füü/data:/data' container_path = config.resolve_volume_path(volume, ""."", ""test"") self.assertEqual(container_path, volume) ","class VolumeConfigTest(unittest.TestCase): def test_volume_path_with_non_ascii_directory(self): volume = u'/Füü/data:/data' container_path = config.resolve_volume_path(""."", volume, ""test"") self.assertEqual(container_path, volume) " 275,https://:@github.com/ranaroussi/qtpylib.git,e5eac01b67e908823c80b1bdeac57dcb68dbb164,"@@ -65,7 +65,7 @@ def _gen_symbol_group(sym): def _gen_asset_class(sym): sym_class = str(sym).split(""_"") - if len(sym_class) > 0: + if len(sym_class) > 1: return sym_class[1] return ""STK"" ",qtpylib/blotter.py,"ReplaceText(target='1' @(68,24)->(68,25))","def _gen_symbol_group(sym): def _gen_asset_class(sym): sym_class = str(sym).split(""_"") if len(sym_class) > 0: return sym_class[1] return ""STK"" ","def _gen_symbol_group(sym): def _gen_asset_class(sym): sym_class = str(sym).split(""_"") if len(sym_class) > 1: return sym_class[1] return ""STK"" " 276,https://:@github.com/lmjohns3/theanets.git,507eac0d7fe007cdc93d89ca6cb0db9521908eac,"@@ -253,7 +253,7 @@ class Network(object): h = self.hiddens[-1] a, b = self.weights[i].get_value(borrow=True).shape logging.info('tied weights from layer %d: %s x %s', i, b, a) - o = theano.shared(np.zeros((b, ), FLOAT), name='b_out{}'.format(i)) + o = theano.shared(np.zeros((a, ), FLOAT), name='b_out{}'.format(i)) self.preacts.append(TT.dot(h, self.weights[i].T) + o) func = self._output_func if i == 0 else self._hidden_func self.hiddens.append(func(self.preacts[-1])) ",theanets/feedforward.py,"ReplaceText(target='a' @(256,44)->(256,45))","class Network(object): h = self.hiddens[-1] a, b = self.weights[i].get_value(borrow=True).shape logging.info('tied weights from layer %d: %s x %s', i, b, a) o = theano.shared(np.zeros((b, ), FLOAT), name='b_out{}'.format(i)) self.preacts.append(TT.dot(h, self.weights[i].T) + o) func = self._output_func if i == 0 else self._hidden_func self.hiddens.append(func(self.preacts[-1]))","class Network(object): h = self.hiddens[-1] a, b = self.weights[i].get_value(borrow=True).shape logging.info('tied weights from layer %d: %s x %s', i, b, a) o = theano.shared(np.zeros((a, ), FLOAT), name='b_out{}'.format(i)) self.preacts.append(TT.dot(h, self.weights[i].T) + o) func = self._output_func if i == 0 else self._hidden_func self.hiddens.append(func(self.preacts[-1]))" 277,https://:@github.com/lmjohns3/theanets.git,62f7125e1b179df846fdcd5d213c8bca18595648,"@@ -83,7 +83,7 @@ class SequenceDataset: slices = [slice(None), slice(None)] self.batches = [] i = 0 - while i + size < shape[axis]: + while i + size <= shape[axis]: slices[axis] = slice(i, i + size) self.batches.append([d[tuple(slices)] for d in data]) i += size ",theanets/dataset.py,"ReplaceText(target='<=' @(86,27)->(86,28))","class SequenceDataset: slices = [slice(None), slice(None)] self.batches = [] i = 0 while i + size < shape[axis]: slices[axis] = slice(i, i + size) self.batches.append([d[tuple(slices)] for d in data]) i += size","class SequenceDataset: slices = [slice(None), slice(None)] self.batches = [] i = 0 while i + size <= shape[axis]: slices[axis] = slice(i, i + size) self.batches.append([d[tuple(slices)] for d in data]) i += size" 278,https://:@github.com/lmjohns3/theanets.git,8fa4792eaae89e4da7d041178fdcb341f5313914,"@@ -834,4 +834,4 @@ class Classifier(Network): k : ndarray (num-examples, ) A vector of class index values, one per row of input data. ''' - return self.predict(x).argmax(axis=1) + return self.predict(x).argmax(axis=-1) ",theanets/feedforward.py,"ReplaceText(target='-1' @(837,43)->(837,44))","class Classifier(Network): k : ndarray (num-examples, ) A vector of class index values, one per row of input data. ''' return self.predict(x).argmax(axis=1)","class Classifier(Network): k : ndarray (num-examples, ) A vector of class index values, one per row of input data. ''' return self.predict(x).argmax(axis=-1)" 279,https://:@github.com/lmjohns3/theanets.git,114f37976b5c00330da9c5fed75ecf7b727eff58,"@@ -338,7 +338,7 @@ class Network(object): if i == 0: noise = kwargs.get('input_noise', 0) dropout = kwargs.get('input_dropouts', 0) - elif i == len(self.layers) - 1: + elif i != len(self.layers) - 1: noise = kwargs.get('hidden_noise', 0) dropout = kwargs.get('hidden_dropouts', 0) out, mon, upd = layer.connect(inputs, noise=noise, dropout=dropout) ",theanets/graph.py,"ReplaceText(target='!=' @(341,23)->(341,25))","class Network(object): if i == 0: noise = kwargs.get('input_noise', 0) dropout = kwargs.get('input_dropouts', 0) elif i == len(self.layers) - 1: noise = kwargs.get('hidden_noise', 0) dropout = kwargs.get('hidden_dropouts', 0) out, mon, upd = layer.connect(inputs, noise=noise, dropout=dropout)","class Network(object): if i == 0: noise = kwargs.get('input_noise', 0) dropout = kwargs.get('input_dropouts', 0) elif i != len(self.layers) - 1: noise = kwargs.get('hidden_noise', 0) dropout = kwargs.get('hidden_dropouts', 0) out, mon, upd = layer.connect(inputs, noise=noise, dropout=dropout)" 280,https://:@github.com/pyiron/pyiron_base.git,f9ea8a31ec8fe36704c4c8f73e127ee3e077ca3a,"@@ -98,7 +98,7 @@ class Vasprun(object): d[""cells""] = np.array(d[""cells""]) d[""positions""] = np.array(d[""positions""]) # Check if the parsed coordinates are in absolute/relative coordinates. If absolute, convert to relative - if len(np.argwhere(d[""positions""].flatten() > 1).flatten()) / len(d[""positions""].flatten()) < 0.01: + if len(np.argwhere(d[""positions""].flatten() > 1).flatten()) / len(d[""positions""].flatten()) > 0.01: pos_new = d[""positions""].copy() for i, pos in enumerate(pos_new): d[""positions""][i] = np.dot(pos, np.linalg.inv(d[""cells""][i])) ",pyiron_vasp/vasprun.py,"ReplaceText(target='>' @(101,100)->(101,101))","class Vasprun(object): d[""cells""] = np.array(d[""cells""]) d[""positions""] = np.array(d[""positions""]) # Check if the parsed coordinates are in absolute/relative coordinates. If absolute, convert to relative if len(np.argwhere(d[""positions""].flatten() > 1).flatten()) / len(d[""positions""].flatten()) < 0.01: pos_new = d[""positions""].copy() for i, pos in enumerate(pos_new): d[""positions""][i] = np.dot(pos, np.linalg.inv(d[""cells""][i]))","class Vasprun(object): d[""cells""] = np.array(d[""cells""]) d[""positions""] = np.array(d[""positions""]) # Check if the parsed coordinates are in absolute/relative coordinates. If absolute, convert to relative if len(np.argwhere(d[""positions""].flatten() > 1).flatten()) / len(d[""positions""].flatten()) > 0.01: pos_new = d[""positions""].copy() for i, pos in enumerate(pos_new): d[""positions""][i] = np.dot(pos, np.linalg.inv(d[""cells""][i]))" 281,https://:@github.com/pyiron/pyiron_base.git,5d9677db9fcbca5fce348a7208830467381cd643,"@@ -487,7 +487,7 @@ class ParallelMaster(GenericMaster): job_lst.append(ham._process) ham = next(self._job_generator, None) if ham is None and self.server.run_mode.modal: - while ham is not None: + while ham is None: time.sleep(10) ham = next(self._job_generator, None) else: ",pyiron_base/objects/job/parallel.py,"ReplaceText(target=' is ' @(490,29)->(490,37))","class ParallelMaster(GenericMaster): job_lst.append(ham._process) ham = next(self._job_generator, None) if ham is None and self.server.run_mode.modal: while ham is not None: time.sleep(10) ham = next(self._job_generator, None) else:","class ParallelMaster(GenericMaster): job_lst.append(ham._process) ham = next(self._job_generator, None) if ham is None and self.server.run_mode.modal: while ham is None: time.sleep(10) ham = next(self._job_generator, None) else:" 282,https://:@github.com/pyiron/pyiron_base.git,a4ed8375fa375ff740a8334f7ce5eb5bf9d7d4a2,"@@ -477,7 +477,7 @@ class Settings(with_metaclass(Singleton)): else: # SQLite is raising ugly error messages when the database directory does not exist. if config[""sql_file""] is None: - if len(config[""resource_paths""]) > 1: + if len(config[""resource_paths""]) >= 1: config[""sql_file""] = ""/"".join( [config[""resource_paths""][0], ""pyiron.db""] ) ",pyiron_base/settings/generic.py,"ReplaceText(target='>=' @(480,49)->(480,50))","class Settings(with_metaclass(Singleton)): else: # SQLite is raising ugly error messages when the database directory does not exist. if config[""sql_file""] is None: if len(config[""resource_paths""]) > 1: config[""sql_file""] = ""/"".join( [config[""resource_paths""][0], ""pyiron.db""] )","class Settings(with_metaclass(Singleton)): else: # SQLite is raising ugly error messages when the database directory does not exist. if config[""sql_file""] is None: if len(config[""resource_paths""]) >= 1: config[""sql_file""] = ""/"".join( [config[""resource_paths""][0], ""pyiron.db""] )" 283,https://:@github.com/ESSolutions/django-mssql-backend.git,06578347a5e775088cfe3a2c2e9c528c5ffb7de0,"@@ -201,7 +201,7 @@ class DatabaseWrapper(BaseDatabaseWrapper): # Only append DRIVER if DATABASE_ODBC_DSN hasn't been set cstr_parts.append('DRIVER={%s}' % driver) if ms_drivers.match(driver) or driver == 'FreeTDS' and \ - conn_params.get('host_is_server', False): + options.get('host_is_server', False): if port: host += ';PORT=%s' % port cstr_parts.append('SERVER=%s' % host) ",sql_server/pyodbc/base.py,"ReplaceText(target='options' @(204,16)->(204,27))","class DatabaseWrapper(BaseDatabaseWrapper): # Only append DRIVER if DATABASE_ODBC_DSN hasn't been set cstr_parts.append('DRIVER={%s}' % driver) if ms_drivers.match(driver) or driver == 'FreeTDS' and \ conn_params.get('host_is_server', False): if port: host += ';PORT=%s' % port cstr_parts.append('SERVER=%s' % host)","class DatabaseWrapper(BaseDatabaseWrapper): # Only append DRIVER if DATABASE_ODBC_DSN hasn't been set cstr_parts.append('DRIVER={%s}' % driver) if ms_drivers.match(driver) or driver == 'FreeTDS' and \ options.get('host_is_server', False): if port: host += ';PORT=%s' % port cstr_parts.append('SERVER=%s' % host)" 284,https://:@github.com/bykof/billomapy.git,29dc1fcd8f491c158a713b07680ea1305748c959,"@@ -112,7 +112,7 @@ todo_include_todos = False # a list of builtin themes. on_rtd = os.environ.get('READTHEDOCS', None) == 'True' -if not on_rtd: # only import and set the theme if we're building docs locally +if on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] ",docs/source/conf.py,"ReplaceText(target='' @(115,3)->(115,7))","todo_include_todos = False # a list of builtin themes. on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]","todo_include_todos = False # a list of builtin themes. on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]" 285,https://:@github.com/quva-lab/artemis.git,26ae4a7049b0f6ac2aef7daf4c2a5184748be516,"@@ -76,7 +76,7 @@ def get_new_positions(fixed_positions, layout, n_plots): positions.append(fixed_positions[i]) else: while True: - row, col = ix/n_cols, ix%n_cols + row, col = ix//n_cols, ix%n_cols if (row, col) not in taken_positions: positions.append((row, col)) taken_positions.add((row, col)) ",artemis/plotting/expanding_subplots.py,"ReplaceText(target='//' @(79,29)->(79,30))","def get_new_positions(fixed_positions, layout, n_plots): positions.append(fixed_positions[i]) else: while True: row, col = ix/n_cols, ix%n_cols if (row, col) not in taken_positions: positions.append((row, col)) taken_positions.add((row, col))","def get_new_positions(fixed_positions, layout, n_plots): positions.append(fixed_positions[i]) else: while True: row, col = ix//n_cols, ix%n_cols if (row, col) not in taken_positions: positions.append((row, col)) taken_positions.add((row, col))" 286,https://:@github.com/OCR-D/core.git,e82299a48e4cf4677535819f81bb944ad4f64f8a,"@@ -312,7 +312,7 @@ def validate_consistency(node, page_textequiv_consistency, page_textequiv_strate pass # already reported in recursive call above elif not child_poly.within(node_poly.buffer(PARENT_SLACK)): # TODO: automatic repair? - report.add_error(CoordinateConsistencyError(tag, child.id, file_id, + report.add_error(CoordinateConsistencyError(child_tag, child.id, file_id, parent_points, child_points)) log.debug(""Inconsistent coords of %s %s"", child_tag, child.id) consistent = False ",ocrd_validators/ocrd_validators/page_validator.py,"ReplaceText(target='child_tag' @(315,64)->(315,67))","def validate_consistency(node, page_textequiv_consistency, page_textequiv_strate pass # already reported in recursive call above elif not child_poly.within(node_poly.buffer(PARENT_SLACK)): # TODO: automatic repair? report.add_error(CoordinateConsistencyError(tag, child.id, file_id, parent_points, child_points)) log.debug(""Inconsistent coords of %s %s"", child_tag, child.id) consistent = False","def validate_consistency(node, page_textequiv_consistency, page_textequiv_strate pass # already reported in recursive call above elif not child_poly.within(node_poly.buffer(PARENT_SLACK)): # TODO: automatic repair? report.add_error(CoordinateConsistencyError(child_tag, child.id, file_id, parent_points, child_points)) log.debug(""Inconsistent coords of %s %s"", child_tag, child.id) consistent = False" 287,https://:@github.com/jhuapl-boss/heaviside.git,3adb4902a04dc3e1d9a325ab1752c4b2d856b677,"@@ -69,7 +69,7 @@ class ASTCompAndOr(ASTNode): super(ASTCompAndOr, self).__init__(comp.token) self.comps = [comp] for c in comps: - self.comps.append(comp) + self.comps.append(c) class ASTCompAnd(ASTCompAndOr): op = 'And' ",heaviside/ast.py,"ReplaceText(target='c' @(72,30)->(72,34))","class ASTCompAndOr(ASTNode): super(ASTCompAndOr, self).__init__(comp.token) self.comps = [comp] for c in comps: self.comps.append(comp) class ASTCompAnd(ASTCompAndOr): op = 'And'","class ASTCompAndOr(ASTNode): super(ASTCompAndOr, self).__init__(comp.token) self.comps = [comp] for c in comps: self.comps.append(c) class ASTCompAnd(ASTCompAndOr): op = 'And'" 288,https://:@github.com/google-research/text-to-text-transfer-transformer.git,d2c010b48b702f22fb665d2e5723c7baaf4f6a1c,"@@ -98,7 +98,7 @@ def main(_): "" "".join(str(i) for i in v) if FLAGS.tokenize else v.decode(""utf-8"")) else: - v[k] = """" + key_to_string[k] = """" return FLAGS.format_string.format(**key_to_string) for shard_path in files: ",t5/scripts/dump_task.py,"ReplaceText(target='key_to_string' @(101,8)->(101,9))","def main(_): "" "".join(str(i) for i in v) if FLAGS.tokenize else v.decode(""utf-8"")) else: v[k] = """" return FLAGS.format_string.format(**key_to_string) for shard_path in files:","def main(_): "" "".join(str(i) for i in v) if FLAGS.tokenize else v.decode(""utf-8"")) else: key_to_string[k] = """" return FLAGS.format_string.format(**key_to_string) for shard_path in files:" 289,https://:@github.com/lvieirajr/mongorest.git,470f17173b63b14ab60bbc99db7ca3b3f93afdac,"@@ -401,4 +401,4 @@ class CoercionError(SchemaValidationError): self['collection'] = collection self['field'] = field - self['coercion_type'] = coercion_type + self['coercion_type'] = coercion_type_repr ",mongorest/errors.py,"ReplaceText(target='coercion_type_repr' @(404,32)->(404,45))","class CoercionError(SchemaValidationError): self['collection'] = collection self['field'] = field self['coercion_type'] = coercion_type","class CoercionError(SchemaValidationError): self['collection'] = collection self['field'] = field self['coercion_type'] = coercion_type_repr" 290,https://:@github.com/internetarchive/fatcat.git,89b729feac30a272b557542c5c4149d3611f869a,"@@ -295,7 +295,7 @@ def container_to_elasticsearch(entity): t['in_sherpa_romeo'] = in_sherpa_romeo t['is_oa'] = in_doaj or in_road or is_longtail_oa or is_oa t['is_longtail_oa'] = is_longtail_oa - t['any_kbart'] = any_ia_sim + t['any_kbart'] = any_kbart t['any_jstor'] = any_jstor t['any_ia_sim'] = bool(any_ia_sim) return t ",python/fatcat_tools/transforms.py,"ReplaceText(target='any_kbart' @(298,21)->(298,31))","def container_to_elasticsearch(entity): t['in_sherpa_romeo'] = in_sherpa_romeo t['is_oa'] = in_doaj or in_road or is_longtail_oa or is_oa t['is_longtail_oa'] = is_longtail_oa t['any_kbart'] = any_ia_sim t['any_jstor'] = any_jstor t['any_ia_sim'] = bool(any_ia_sim) return t","def container_to_elasticsearch(entity): t['in_sherpa_romeo'] = in_sherpa_romeo t['is_oa'] = in_doaj or in_road or is_longtail_oa or is_oa t['is_longtail_oa'] = is_longtail_oa t['any_kbart'] = any_kbart t['any_jstor'] = any_jstor t['any_ia_sim'] = bool(any_ia_sim) return t" 291,https://:@github.com/internetarchive/fatcat.git,11dfac5f8f9ced9b56cf277d0e3adeccc572b251,"@@ -57,7 +57,7 @@ class ArabesqueMatchImporter(EntityImporter): eg_extra = kwargs.get('editgroup_extra', dict()) eg_extra['agent'] = eg_extra.get('agent', 'fatcat_tools.ArabesqueMatchImporter') if kwargs.get('crawl_id'): - eg_extra['crawl_id'] = eg_extra.get('crawl_id') + eg_extra['crawl_id'] = kwargs.get('crawl_id') super().__init__(api, editgroup_description=eg_desc, editgroup_extra=eg_extra, ",python/fatcat_tools/importers/arabesque.py,"ReplaceText(target='kwargs' @(60,35)->(60,43))","class ArabesqueMatchImporter(EntityImporter): eg_extra = kwargs.get('editgroup_extra', dict()) eg_extra['agent'] = eg_extra.get('agent', 'fatcat_tools.ArabesqueMatchImporter') if kwargs.get('crawl_id'): eg_extra['crawl_id'] = eg_extra.get('crawl_id') super().__init__(api, editgroup_description=eg_desc, editgroup_extra=eg_extra,","class ArabesqueMatchImporter(EntityImporter): eg_extra = kwargs.get('editgroup_extra', dict()) eg_extra['agent'] = eg_extra.get('agent', 'fatcat_tools.ArabesqueMatchImporter') if kwargs.get('crawl_id'): eg_extra['crawl_id'] = kwargs.get('crawl_id') super().__init__(api, editgroup_description=eg_desc, editgroup_extra=eg_extra," 292,https://:@github.com/internetarchive/fatcat.git,7104e6dfb99717353e3819853ae61ac6387a02a1,"@@ -128,7 +128,7 @@ class EntityUpdatesWorker(FatcatWorker): # update release when a file changes # TODO: fetch old revision as well, and only update # releases for which list changed - release_ids.extend(e['release_ids']) + release_ids.extend(file_entity['release_ids']) file_dict = self.api.api_client.sanitize_for_serialization(file_entity) file_producer.produce( message=json.dumps(file_dict).encode('utf-8'), ",python/fatcat_tools/workers/changelog.py,"ReplaceText(target='file_entity' @(131,35)->(131,36))","class EntityUpdatesWorker(FatcatWorker): # update release when a file changes # TODO: fetch old revision as well, and only update # releases for which list changed release_ids.extend(e['release_ids']) file_dict = self.api.api_client.sanitize_for_serialization(file_entity) file_producer.produce( message=json.dumps(file_dict).encode('utf-8'),","class EntityUpdatesWorker(FatcatWorker): # update release when a file changes # TODO: fetch old revision as well, and only update # releases for which list changed release_ids.extend(file_entity['release_ids']) file_dict = self.api.api_client.sanitize_for_serialization(file_entity) file_producer.produce( message=json.dumps(file_dict).encode('utf-8')," 293,https://:@github.com/internetarchive/fatcat.git,80b756d6feec3f66225287b9ca73c8b02d012027,"@@ -167,7 +167,7 @@ class IngestFileResultImporter(EntityImporter): urls=urls, ) if request.get('edit_extra'): - fe.edit_extra = fatcat['edit_extra'] + fe.edit_extra = request['edit_extra'] else: fe.edit_extra = dict() if request.get('ingest_request_source'): ",python/fatcat_tools/importers/ingest.py,"ReplaceText(target='request' @(170,28)->(170,34))","class IngestFileResultImporter(EntityImporter): urls=urls, ) if request.get('edit_extra'): fe.edit_extra = fatcat['edit_extra'] else: fe.edit_extra = dict() if request.get('ingest_request_source'):","class IngestFileResultImporter(EntityImporter): urls=urls, ) if request.get('edit_extra'): fe.edit_extra = request['edit_extra'] else: fe.edit_extra = dict() if request.get('ingest_request_source'):" 294,https://:@github.com/pallets/flask-ext-migrate.git,ea6a0666e08ce176031456dced635ca3c92c1386,"@@ -43,7 +43,7 @@ def fix_from_imports(red): modules = node.value if (len(modules) < 2 or - modules[0].value != 'flask' and modules[1].value != 'ext'): + modules[0].value != 'flask' or modules[1].value != 'ext'): continue if len(modules) >= 3: ",flask_ext_migrate/__init__.py,"ReplaceText(target='or' @(46,44)->(46,47))","def fix_from_imports(red): modules = node.value if (len(modules) < 2 or modules[0].value != 'flask' and modules[1].value != 'ext'): continue if len(modules) >= 3:","def fix_from_imports(red): modules = node.value if (len(modules) < 2 or modules[0].value != 'flask' or modules[1].value != 'ext'): continue if len(modules) >= 3:" 295,https://:@github.com/SpockBotMC/SpockBot.git,6c8e63b97e3d9617ce0ca9bea9a677902b5ef2fb,"@@ -42,7 +42,7 @@ class SelectSocket: else: slist = [(self.sock,), (), (self.sock,)] timeout = self.timer.get_timeout() - if timeout>0: + if timeout>=0: slist.append(timeout) try: rlist, wlist, xlist = select.select(*slist) ",spock/plugins/core/net.py,"ReplaceText(target='>=' @(45,12)->(45,13))","class SelectSocket: else: slist = [(self.sock,), (), (self.sock,)] timeout = self.timer.get_timeout() if timeout>0: slist.append(timeout) try: rlist, wlist, xlist = select.select(*slist)","class SelectSocket: else: slist = [(self.sock,), (), (self.sock,)] timeout = self.timer.get_timeout() if timeout>=0: slist.append(timeout) try: rlist, wlist, xlist = select.select(*slist)" 296,https://:@github.com/SpockBotMC/SpockBot.git,bebe1187dd6432ec3b4b6dddb8246baef83c2203,"@@ -15,7 +15,7 @@ class PloaderFetch: @pl_announce('PloaderFetch') class SettingsPlugin: def __init__(self, ploader, kwargs): - settings = get_settings(kwargs, kwargs.get('settings', {})) + settings = get_settings(kwargs.get('settings', {}), kwargs) plugin_list = settings.get('plugins', DefaultPlugins) plugins = [] plugin_settings = {} ",spock/plugins/core/settings.py,"ArgSwap(idxs=0<->1 @(18,13)->(18,25))","class PloaderFetch: @pl_announce('PloaderFetch') class SettingsPlugin: def __init__(self, ploader, kwargs): settings = get_settings(kwargs, kwargs.get('settings', {})) plugin_list = settings.get('plugins', DefaultPlugins) plugins = [] plugin_settings = {}","class PloaderFetch: @pl_announce('PloaderFetch') class SettingsPlugin: def __init__(self, ploader, kwargs): settings = get_settings(kwargs.get('settings', {}), kwargs) plugin_list = settings.get('plugins', DefaultPlugins) plugins = [] plugin_settings = {}" 297,https://:@github.com/SpockBotMC/SpockBot.git,bebe1187dd6432ec3b4b6dddb8246baef83c2203,"@@ -19,7 +19,7 @@ default_settings = { class StartPlugin: def __init__(self, ploader, settings): - self.settings = utils.get_settings(settings, default_settings) + self.settings = utils.get_settings(default_settings, settings) self.event = ploader.requires('Event') self.net = ploader.requires('Net') self.auth = ploader.requires('Auth') ",spock/plugins/helpers/start.py,"ArgSwap(idxs=0<->1 @(22,18)->(22,36))","default_settings = { class StartPlugin: def __init__(self, ploader, settings): self.settings = utils.get_settings(settings, default_settings) self.event = ploader.requires('Event') self.net = ploader.requires('Net') self.auth = ploader.requires('Auth')","default_settings = { class StartPlugin: def __init__(self, ploader, settings): self.settings = utils.get_settings(default_settings, settings) self.event = ploader.requires('Event') self.net = ploader.requires('Net') self.auth = ploader.requires('Auth')" 298,https://:@github.com/hungpham2511/toppra.git,fefd8430ad55fb09414a1d4c6d8be41e81977842,"@@ -19,7 +19,7 @@ def _find_left_index(ss_waypoints, s): for i in range(1, len(ss_waypoints)): if ss_waypoints[i - 1] <= s and s < ss_waypoints[i]: return i - 1 - return len(ss_waypoints) - 1 + return len(ss_waypoints) - 2 class Interpolator(object): ",toppra/interpolator.py,"ReplaceText(target='2' @(22,31)->(22,32))","def _find_left_index(ss_waypoints, s): for i in range(1, len(ss_waypoints)): if ss_waypoints[i - 1] <= s and s < ss_waypoints[i]: return i - 1 return len(ss_waypoints) - 1 class Interpolator(object):","def _find_left_index(ss_waypoints, s): for i in range(1, len(ss_waypoints)): if ss_waypoints[i - 1] <= s and s < ss_waypoints[i]: return i - 1 return len(ss_waypoints) - 2 class Interpolator(object):" 299,https://:@github.com/cmrivers/epipy.git,c541e6f7f559c92279623aa3c2cb7f644247280e,"@@ -34,7 +34,7 @@ def generate_example_data(cluster_size, outbreak_len, clusters, gen_time, attrib for i in range(clusters): cluster_letter = np.random.choice([i for i in string.ascii_uppercase if i not in used])[0] cluster_name = 'Cluster' + cluster_letter - used.append(cluster_name) + used.append(cluster_letter) ix_rng = pd.date_range('1/1/2014', periods=outbreak_len, freq='D') ix_date = np.random.choice(ix_rng, size=1) ",epipy/data_generator.py,"ReplaceText(target='cluster_letter' @(37,20)->(37,32))","def generate_example_data(cluster_size, outbreak_len, clusters, gen_time, attrib for i in range(clusters): cluster_letter = np.random.choice([i for i in string.ascii_uppercase if i not in used])[0] cluster_name = 'Cluster' + cluster_letter used.append(cluster_name) ix_rng = pd.date_range('1/1/2014', periods=outbreak_len, freq='D') ix_date = np.random.choice(ix_rng, size=1)","def generate_example_data(cluster_size, outbreak_len, clusters, gen_time, attrib for i in range(clusters): cluster_letter = np.random.choice([i for i in string.ascii_uppercase if i not in used])[0] cluster_name = 'Cluster' + cluster_letter used.append(cluster_letter) ix_rng = pd.date_range('1/1/2014', periods=outbreak_len, freq='D') ix_date = np.random.choice(ix_rng, size=1)" 300,https://:@github.com/parmed/ParmEd.git,9eda010f0342ace7a3ccc6452a8c8014c73bd130,"@@ -282,7 +282,7 @@ class AmberFormat(object): rawdata = self.parm_data[flag] self.parm_data[flag] = [] for line in rawdata: - self.parm_data[flag].extend(self.formats[key].read(line)) + self.parm_data[flag].extend(self.formats[flag].read(line)) try: for i, chg in enumerate(self.parm_data[self.charge_flag]): ",chemistry/amber/amberformat.py,"ReplaceText(target='flag' @(285,61)->(285,64))","class AmberFormat(object): rawdata = self.parm_data[flag] self.parm_data[flag] = [] for line in rawdata: self.parm_data[flag].extend(self.formats[key].read(line)) try: for i, chg in enumerate(self.parm_data[self.charge_flag]):","class AmberFormat(object): rawdata = self.parm_data[flag] self.parm_data[flag] = [] for line in rawdata: self.parm_data[flag].extend(self.formats[flag].read(line)) try: for i, chg in enumerate(self.parm_data[self.charge_flag]):" 301,https://:@github.com/parmed/ParmEd.git,9167bf221e4fe5d71ccaa6bf310fce60f09dc873,"@@ -192,7 +192,7 @@ def diff_files(file1, file2, ignore_whitespace=True, i = 1 same = True if ignore_whitespace: - while l1 and l2: + while l1 or l2: if l1.strip() != l2.strip(): if l1.startswith('%VERSION') and l2.startswith('%VERSION'): l1 = f1.readline() ",test/utils.py,"ReplaceText(target='or' @(195,21)->(195,24))","def diff_files(file1, file2, ignore_whitespace=True, i = 1 same = True if ignore_whitespace: while l1 and l2: if l1.strip() != l2.strip(): if l1.startswith('%VERSION') and l2.startswith('%VERSION'): l1 = f1.readline()","def diff_files(file1, file2, ignore_whitespace=True, i = 1 same = True if ignore_whitespace: while l1 or l2: if l1.strip() != l2.strip(): if l1.startswith('%VERSION') and l2.startswith('%VERSION'): l1 = f1.readline()" 302,https://:@github.com/parmed/ParmEd.git,b5fdf3d9b7095b96bcb8ac0bdbdfb3694d1d5220,"@@ -334,7 +334,7 @@ class ChamberParm(AmberParm): for i, j, k, l, m, n in zip(it, it, it, it, it, it): self.cmaps.append( Cmap(self.atoms[i-1], self.atoms[j-1], self.atoms[k-1], - self.atoms[k-1], self.atoms[m-1], self.cmap_types[n-1]) + self.atoms[l-1], self.atoms[m-1], self.cmap_types[n-1]) ) #=================================================== ",chemistry/amber/_chamberparm.py,"ReplaceText(target='l' @(337,36)->(337,37))","class ChamberParm(AmberParm): for i, j, k, l, m, n in zip(it, it, it, it, it, it): self.cmaps.append( Cmap(self.atoms[i-1], self.atoms[j-1], self.atoms[k-1], self.atoms[k-1], self.atoms[m-1], self.cmap_types[n-1]) ) #===================================================","class ChamberParm(AmberParm): for i, j, k, l, m, n in zip(it, it, it, it, it, it): self.cmaps.append( Cmap(self.atoms[i-1], self.atoms[j-1], self.atoms[k-1], self.atoms[l-1], self.atoms[m-1], self.cmap_types[n-1]) ) #===================================================" 303,https://:@github.com/parmed/ParmEd.git,820a80ccad22ee881042f03b83a0f07b5f1b537d,"@@ -1272,7 +1272,7 @@ class Structure(object): break elif a2.residue is None: break - elif a1.residue.name != a1.residue.name: + elif a1.residue.name != a2.residue.name: break if not a1.type and not a2.type: if a1.name != a2.name: break ",chemistry/structure.py,"ReplaceText(target='a2' @(1275,48)->(1275,50))","class Structure(object): break elif a2.residue is None: break elif a1.residue.name != a1.residue.name: break if not a1.type and not a2.type: if a1.name != a2.name: break","class Structure(object): break elif a2.residue is None: break elif a1.residue.name != a2.residue.name: break if not a1.type and not a2.type: if a1.name != a2.name: break" 304,https://:@github.com/parmed/ParmEd.git,4cba8197ae90a1af4abe0dee3f19e1c8c61c959f,"@@ -313,7 +313,7 @@ class Mol2File(object): if a == '0': continue for atom in res: if atom.name == a: - atom.connections.append(atom) + res.connections.append(atom) break else: raise Mol2Error('Residue connection atom %s not ' ",parmed/formats/mol2.py,"ReplaceText(target='res' @(316,32)->(316,36))","class Mol2File(object): if a == '0': continue for atom in res: if atom.name == a: atom.connections.append(atom) break else: raise Mol2Error('Residue connection atom %s not '","class Mol2File(object): if a == '0': continue for atom in res: if atom.name == a: res.connections.append(atom) break else: raise Mol2Error('Residue connection atom %s not '" 305,https://:@github.com/parmed/ParmEd.git,9be43ac3521aca71f84de9b2b11740b00dfdb1b6,"@@ -696,6 +696,6 @@ def _set_owner(atoms, owner_array, atm, mol_id): if not partner.marked: owner_array.append(partner.idx) _set_owner(atoms, owner_array, partner.idx, mol_id) - assert partner.marked != mol_id, 'Atom in multiple molecules!' + assert partner.marked == mol_id, 'Atom in multiple molecules!' # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ",parmed/charmm/psf.py,"ReplaceText(target='==' @(699,30)->(699,32))","def _set_owner(atoms, owner_array, atm, mol_id): if not partner.marked: owner_array.append(partner.idx) _set_owner(atoms, owner_array, partner.idx, mol_id) assert partner.marked != mol_id, 'Atom in multiple molecules!' # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++","def _set_owner(atoms, owner_array, atm, mol_id): if not partner.marked: owner_array.append(partner.idx) _set_owner(atoms, owner_array, partner.idx, mol_id) assert partner.marked == mol_id, 'Atom in multiple molecules!' # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" 306,https://:@github.com/parmed/ParmEd.git,8f1dc98d485ea57e4046494ad1e6f84cfbd17f4f,"@@ -449,7 +449,7 @@ class ParameterSet(object): for name, residue in iteritems(self.residues): if isinstance(residue, ResidueTemplateContainer): for res in residue: - for atom in residue: + for atom in res: atom.atom_type = self.atom_types[atom.type] else: assert isinstance(residue, ResidueTemplate), 'Wrong type!' ",parmed/parameters.py,"ReplaceText(target='res' @(452,32)->(452,39))","class ParameterSet(object): for name, residue in iteritems(self.residues): if isinstance(residue, ResidueTemplateContainer): for res in residue: for atom in residue: atom.atom_type = self.atom_types[atom.type] else: assert isinstance(residue, ResidueTemplate), 'Wrong type!'","class ParameterSet(object): for name, residue in iteritems(self.residues): if isinstance(residue, ResidueTemplateContainer): for res in residue: for atom in res: atom.atom_type = self.atom_types[atom.type] else: assert isinstance(residue, ResidueTemplate), 'Wrong type!'" 307,https://:@github.com/parmed/ParmEd.git,403c2874c1826cbe182386959a23118b33d1e27c,"@@ -219,7 +219,7 @@ class OpenMMParameterSet(ParameterSet): if tag not in sub_content: raise KeyError('Content of an attribute-containing element ' 'specified incorrectly.') - attributes = [key for key in content if key != tag] + attributes = [key for key in sub_content if key != tag] element_content = sub_content[tag] dest.write(' <%s' % tag) for attribute in attributes: ",parmed/openmm/parameters.py,"ReplaceText(target='sub_content' @(222,49)->(222,56))","class OpenMMParameterSet(ParameterSet): if tag not in sub_content: raise KeyError('Content of an attribute-containing element ' 'specified incorrectly.') attributes = [key for key in content if key != tag] element_content = sub_content[tag] dest.write(' <%s' % tag) for attribute in attributes:","class OpenMMParameterSet(ParameterSet): if tag not in sub_content: raise KeyError('Content of an attribute-containing element ' 'specified incorrectly.') attributes = [key for key in sub_content if key != tag] element_content = sub_content[tag] dest.write(' <%s' % tag) for attribute in attributes:" 308,https://:@github.com/parmed/ParmEd.git,657ba99e2338df75ef118155d95d144c7b33ab32,"@@ -281,7 +281,7 @@ T = RNAResidue('Thymine', 'T', ['THY', 'T3', 'T5', 'TN', WATER_NAMES = set(['WAT', 'HOH', 'TIP3', 'TIP4', 'TIP5', 'SPCE', 'SPC']) -SOLVENT_NAMES = WATER_NAMES ^ set({'SOL'}) +SOLVENT_NAMES = WATER_NAMES | set({'SOL'}) EXTRA_POINT_NAMES = set(['EP', 'LP']) CATION_NAMES = set(['Na+', 'Li+', 'Mg+', 'Rb+', 'MG', 'Cs+', 'POT', 'SOD', 'MG2', 'CAL', 'RUB', 'LIT', 'ZN2', 'CD2', 'NA', 'K+', 'K', ",parmed/residue.py,"ReplaceText(target='|' @(284,28)->(284,29))","T = RNAResidue('Thymine', 'T', ['THY', 'T3', 'T5', 'TN', WATER_NAMES = set(['WAT', 'HOH', 'TIP3', 'TIP4', 'TIP5', 'SPCE', 'SPC']) SOLVENT_NAMES = WATER_NAMES ^ set({'SOL'}) EXTRA_POINT_NAMES = set(['EP', 'LP']) CATION_NAMES = set(['Na+', 'Li+', 'Mg+', 'Rb+', 'MG', 'Cs+', 'POT', 'SOD', 'MG2', 'CAL', 'RUB', 'LIT', 'ZN2', 'CD2', 'NA', 'K+', 'K',","T = RNAResidue('Thymine', 'T', ['THY', 'T3', 'T5', 'TN', WATER_NAMES = set(['WAT', 'HOH', 'TIP3', 'TIP4', 'TIP5', 'SPCE', 'SPC']) SOLVENT_NAMES = WATER_NAMES | set({'SOL'}) EXTRA_POINT_NAMES = set(['EP', 'LP']) CATION_NAMES = set(['Na+', 'Li+', 'Mg+', 'Rb+', 'MG', 'Cs+', 'POT', 'SOD', 'MG2', 'CAL', 'RUB', 'LIT', 'ZN2', 'CD2', 'NA', 'K+', 'K'," 309,https://:@github.com/parmed/ParmEd.git,bd2a1120adf53ab364dda802a272c19c7d335fdd,"@@ -374,7 +374,7 @@ class OpenMMParameterSet(ParameterSet): for attribute in attributes: dest.write(' %s=""%s""' % (attribute, sub_content[attribute])) escaped_element_content = escape(element_content, XML_ESCAPES) - dest.write('>%s\n' % (element_content, tag)) + dest.write('>%s\n' % (escaped_element_content, tag)) else: raise TypeError('Incorrect type of the %s element content' % tag) dest.write(' \n') ",parmed/openmm/parameters.py,"ReplaceText(target='escaped_element_content' @(377,47)->(377,62))","class OpenMMParameterSet(ParameterSet): for attribute in attributes: dest.write(' %s=""%s""' % (attribute, sub_content[attribute])) escaped_element_content = escape(element_content, XML_ESCAPES) dest.write('>%s\n' % (element_content, tag)) else: raise TypeError('Incorrect type of the %s element content' % tag) dest.write(' \n')","class OpenMMParameterSet(ParameterSet): for attribute in attributes: dest.write(' %s=""%s""' % (attribute, sub_content[attribute])) escaped_element_content = escape(element_content, XML_ESCAPES) dest.write('>%s\n' % (escaped_element_content, tag)) else: raise TypeError('Incorrect type of the %s element content' % tag) dest.write(' \n')" 310,https://:@github.com/parmed/ParmEd.git,62e0c8aa4561628d005e84bbe97b1ef37f32dee5,"@@ -502,7 +502,7 @@ class OpenMMParameterSet(ParameterSet): patched_residue = residue.apply_patch(patch) for atom in patch.atoms: - if atom.name not in patched_residue: + if atom.name not in residue: dest.write(' \n' % (atom.name, atom.type, atom.charge)) else: ",parmed/openmm/parameters.py,"ReplaceText(target='residue' @(505,36)->(505,51))","class OpenMMParameterSet(ParameterSet): patched_residue = residue.apply_patch(patch) for atom in patch.atoms: if atom.name not in patched_residue: dest.write(' \n' % (atom.name, atom.type, atom.charge)) else:","class OpenMMParameterSet(ParameterSet): patched_residue = residue.apply_patch(patch) for atom in patch.atoms: if atom.name not in residue: dest.write(' \n' % (atom.name, atom.type, atom.charge)) else:" 311,https://:@github.com/parmed/ParmEd.git,90fa4626c3db158047991044f4dd4619a7cc2599,"@@ -502,7 +502,7 @@ class AmberFormat(object): own_handle = True elif hasattr(fname, 'read'): prm = fname - own_handle = True + own_handle = False else: raise TypeError('%s must be a file name or file-like object' % fname) ",parmed/amber/amberformat.py,"ReplaceText(target='False' @(505,25)->(505,29))","class AmberFormat(object): own_handle = True elif hasattr(fname, 'read'): prm = fname own_handle = True else: raise TypeError('%s must be a file name or file-like object' % fname) ","class AmberFormat(object): own_handle = True elif hasattr(fname, 'read'): prm = fname own_handle = False else: raise TypeError('%s must be a file name or file-like object' % fname) " 312,https://:@github.com/xmunoz/sodapy.git,76bdcfd9670e94c833b66b8894ea4153c27004ee,"@@ -71,7 +71,7 @@ class Socrata(object): else: self.uri_prefix = ""https://"" - if isinstance(timeout, (int, long, float)): + if not isinstance(timeout, (int, long, float)): raise TypeError(""Timeout must be numeric."") self.timeout = timeout ",sodapy/__init__.py,"ReplaceText(target='not ' @(74,11)->(74,11))","class Socrata(object): else: self.uri_prefix = ""https://"" if isinstance(timeout, (int, long, float)): raise TypeError(""Timeout must be numeric."") self.timeout = timeout ","class Socrata(object): else: self.uri_prefix = ""https://"" if not isinstance(timeout, (int, long, float)): raise TypeError(""Timeout must be numeric."") self.timeout = timeout " 313,https://:@github.com/xmunoz/sodapy.git,be6804a7f566eda08af7bb5d67f9c75512581189,"@@ -129,7 +129,7 @@ class Socrata(object): next(iter(kwargs))) if order: - kwargs.append(('order', order)) + params.append(('order', order)) results = self._perform_request(""get"", DATASETS_PATH, params=params + [('offset', offset)]) ",sodapy/__init__.py,"ReplaceText(target='params' @(132,12)->(132,18))","class Socrata(object): next(iter(kwargs))) if order: kwargs.append(('order', order)) results = self._perform_request(""get"", DATASETS_PATH, params=params + [('offset', offset)])","class Socrata(object): next(iter(kwargs))) if order: params.append(('order', order)) results = self._perform_request(""get"", DATASETS_PATH, params=params + [('offset', offset)])" 314,https://:@github.com/visgence/teleceptor.git,4a8db10b79207b4bf8b48bbcaafdd03cc1166a2f,"@@ -397,7 +397,7 @@ def _updateCalibration(sensor, coefficients, timestamp, session): logging.debug(""Comparing coefficients."") # check if coefficients are different - if ""{}"".format(Cal.coefficients) == ""{}"".format(coefficients): + if ""{}"".format(Cal.coefficients) != ""{}"".format(coefficients): logging.debug(""Coefficients are different, updating..."") assert isinstance(coefficients, list) ",teleceptor/api/sensors.py,"ReplaceText(target='!=' @(400,49)->(400,51))","def _updateCalibration(sensor, coefficients, timestamp, session): logging.debug(""Comparing coefficients."") # check if coefficients are different if ""{}"".format(Cal.coefficients) == ""{}"".format(coefficients): logging.debug(""Coefficients are different, updating..."") assert isinstance(coefficients, list)","def _updateCalibration(sensor, coefficients, timestamp, session): logging.debug(""Comparing coefficients."") # check if coefficients are different if ""{}"".format(Cal.coefficients) != ""{}"".format(coefficients): logging.debug(""Coefficients are different, updating..."") assert isinstance(coefficients, list)" 315,https://:@github.com/projectmesa/mesa.git,0893a8f03d7f22f1b064e66c97da3dddd987b7ea,"@@ -50,7 +50,7 @@ class Schelling(Model): self.homophily = homophily self.schedule = RandomActivation(self) - self.grid = SingleGrid(height, width, torus=True) + self.grid = SingleGrid(width, height, torus=True) self.happy = 0 self.datacollector = DataCollector( ",examples/schelling/model.py,"ArgSwap(idxs=0<->1 @(53,20)->(53,30))","class Schelling(Model): self.homophily = homophily self.schedule = RandomActivation(self) self.grid = SingleGrid(height, width, torus=True) self.happy = 0 self.datacollector = DataCollector(","class Schelling(Model): self.homophily = homophily self.schedule = RandomActivation(self) self.grid = SingleGrid(width, height, torus=True) self.happy = 0 self.datacollector = DataCollector(" 316,https://:@github.com/projectmesa/mesa.git,9277b0f55ed63d3b8a32c7f3e52e3df1e7de6579,"@@ -31,7 +31,7 @@ class PdGrid(Model): Determines the agent activation regime. payoffs: (optional) Dictionary of (move, neighbor_move) payoffs. ''' - self.grid = SingleGrid(height, width, torus=True) + self.grid = SingleGrid(width, height, torus=True) self.schedule_type = schedule_type self.schedule = self.schedule_types[self.schedule_type](self) ",examples/pd_grid/pd_grid/model.py,"ArgSwap(idxs=0<->1 @(34,20)->(34,30))","class PdGrid(Model): Determines the agent activation regime. payoffs: (optional) Dictionary of (move, neighbor_move) payoffs. ''' self.grid = SingleGrid(height, width, torus=True) self.schedule_type = schedule_type self.schedule = self.schedule_types[self.schedule_type](self) ","class PdGrid(Model): Determines the agent activation regime. payoffs: (optional) Dictionary of (move, neighbor_move) payoffs. ''' self.grid = SingleGrid(width, height, torus=True) self.schedule_type = schedule_type self.schedule = self.schedule_types[self.schedule_type](self) " 317,https://:@github.com/iCHEF/queryfilter.git,96c25a4e5e750ae3415712d6812eee04d2187e64,"@@ -70,7 +70,7 @@ class DictFilterMixin(object): if not dictobj: # Point to which level doesn't exist exactly return handle_missing_field( - ""__"".join(level_field_names[:index+1]) + ""__"".join(parent_field_names[:index+1]) ) if final_field_name not in dictobj: return handle_missing_field(field_name) ",queryfilter/base.py,"ReplaceText(target='parent_field_names' @(73,30)->(73,47))","class DictFilterMixin(object): if not dictobj: # Point to which level doesn't exist exactly return handle_missing_field( ""__"".join(level_field_names[:index+1]) ) if final_field_name not in dictobj: return handle_missing_field(field_name)","class DictFilterMixin(object): if not dictobj: # Point to which level doesn't exist exactly return handle_missing_field( ""__"".join(parent_field_names[:index+1]) ) if final_field_name not in dictobj: return handle_missing_field(field_name)" 318,https://:@github.com/slaclab/paws.git,953037e723903e2213495189c9a99eb5445ecc9a,"@@ -293,7 +293,7 @@ class XRSDFitGUI(Operation): ubnd = xrsdkit.param_bound_defaults[param_nm][1] if xrsdkit.contains_param(self.inputs['param_bounds'],pop_nm,param_nm): lbnd = self.inputs['param_bounds'][pop_nm]['parameters'][param_nm][0] - lbnd = self.inputs['param_bounds'][pop_nm]['parameters'][param_nm][1] + ubnd = self.inputs['param_bounds'][pop_nm]['parameters'][param_nm][1] # TODO: the bounds entries need to be connected to DoubleVars. pbnde1.insert(0,str(lbnd)) pbnde2.insert(0,str(ubnd)) ",paws/core/operations/PROCESSING/FITTING/XRSDFitGUI.py,"ReplaceText(target='ubnd' @(296,16)->(296,20))","class XRSDFitGUI(Operation): ubnd = xrsdkit.param_bound_defaults[param_nm][1] if xrsdkit.contains_param(self.inputs['param_bounds'],pop_nm,param_nm): lbnd = self.inputs['param_bounds'][pop_nm]['parameters'][param_nm][0] lbnd = self.inputs['param_bounds'][pop_nm]['parameters'][param_nm][1] # TODO: the bounds entries need to be connected to DoubleVars. pbnde1.insert(0,str(lbnd)) pbnde2.insert(0,str(ubnd))","class XRSDFitGUI(Operation): ubnd = xrsdkit.param_bound_defaults[param_nm][1] if xrsdkit.contains_param(self.inputs['param_bounds'],pop_nm,param_nm): lbnd = self.inputs['param_bounds'][pop_nm]['parameters'][param_nm][0] ubnd = self.inputs['param_bounds'][pop_nm]['parameters'][param_nm][1] # TODO: the bounds entries need to be connected to DoubleVars. pbnde1.insert(0,str(lbnd)) pbnde2.insert(0,str(ubnd))" 319,https://:@github.com/PyFilesystem/pyfilesystem2.git,cd1a973dd80e4083502db51844981f3457d13760,"@@ -258,7 +258,7 @@ class OSFS(FS): with convert_os_errors(""getinfo"", path): _stat = os.stat(fsencode(sys_path)) if ""lstat"" in namespaces: - _stat = os.lstat(fsencode(sys_path)) + _lstat = os.lstat(fsencode(sys_path)) info = { ""basic"": {""name"": basename(_path), ""is_dir"": stat.S_ISDIR(_stat.st_mode)} ",fs/osfs.py,"ReplaceText(target='_lstat' @(261,16)->(261,21))","class OSFS(FS): with convert_os_errors(""getinfo"", path): _stat = os.stat(fsencode(sys_path)) if ""lstat"" in namespaces: _stat = os.lstat(fsencode(sys_path)) info = { ""basic"": {""name"": basename(_path), ""is_dir"": stat.S_ISDIR(_stat.st_mode)}","class OSFS(FS): with convert_os_errors(""getinfo"", path): _stat = os.stat(fsencode(sys_path)) if ""lstat"" in namespaces: _lstat = os.lstat(fsencode(sys_path)) info = { ""basic"": {""name"": basename(_path), ""is_dir"": stat.S_ISDIR(_stat.st_mode)}" 320,https://:@github.com/kevinzg/facebook-scraper.git,c11dffbc1beef25271fb5bc6d2aa3aeb5b2079aa,"@@ -83,7 +83,7 @@ def _get_posts(path, pages=10, timeout=5, sleep=0, credentials=None, extra_info= yield post pages -= 1 - if pages == 0: + if pages <= 0: return cursor = _find_cursor(cursor_blob) ",facebook_scraper.py,"ReplaceText(target='<=' @(86,17)->(86,19))","def _get_posts(path, pages=10, timeout=5, sleep=0, credentials=None, extra_info= yield post pages -= 1 if pages == 0: return cursor = _find_cursor(cursor_blob)","def _get_posts(path, pages=10, timeout=5, sleep=0, credentials=None, extra_info= yield post pages -= 1 if pages <= 0: return cursor = _find_cursor(cursor_blob)" 321,https://:@github.com/linkedin/naarad.git,897858ba0d80fb74bbad40bfc8f96b0f59b0900e,"@@ -75,10 +75,10 @@ class Report(object): for metric in self.metric_list: metric_stats = [] metric_stats_file, summary_stats, metric_plots, correlated_plots = self.discover_metric_data(self.output_directory, metric) - if metric_stats_file != '' and len(metric_plots) > 0: + if metric_stats_file != '' or len(metric_plots) > 0: metric_stats = self.get_summary_table(metric_stats_file) metric_html = template_environment.get_template(self.report_templates['header']).render(custom_javascript_includes=[""http://www.kryogenix.org/code/browser/sorttable/sorttable.js""]) metric_html += template_environment.get_template(self.report_templates['metric']).render(metric_stats=metric_stats, metric_plots=metric_plots, correlated_plots=correlated_plots, metric=metric) metric_html += template_environment.get_template(self.report_templates['footer']).render() - with open(os.path.join(self.output_directory, metric + '_report.html'),'w') as metric_report: + with open(os.path.join(self.output_directory, metric + '_report.html'), 'w') as metric_report: metric_report.write(metric_html) ",src/naarad/reporting/report.py,"ReplaceText(target='or' @(78,33)->(78,36))","class Report(object): for metric in self.metric_list: metric_stats = [] metric_stats_file, summary_stats, metric_plots, correlated_plots = self.discover_metric_data(self.output_directory, metric) if metric_stats_file != '' and len(metric_plots) > 0: metric_stats = self.get_summary_table(metric_stats_file) metric_html = template_environment.get_template(self.report_templates['header']).render(custom_javascript_includes=[""http://www.kryogenix.org/code/browser/sorttable/sorttable.js""]) metric_html += template_environment.get_template(self.report_templates['metric']).render(metric_stats=metric_stats, metric_plots=metric_plots, correlated_plots=correlated_plots, metric=metric) metric_html += template_environment.get_template(self.report_templates['footer']).render() with open(os.path.join(self.output_directory, metric + '_report.html'),'w') as metric_report: metric_report.write(metric_html)","class Report(object): for metric in self.metric_list: metric_stats = [] metric_stats_file, summary_stats, metric_plots, correlated_plots = self.discover_metric_data(self.output_directory, metric) if metric_stats_file != '' or len(metric_plots) > 0: metric_stats = self.get_summary_table(metric_stats_file) metric_html = template_environment.get_template(self.report_templates['header']).render(custom_javascript_includes=[""http://www.kryogenix.org/code/browser/sorttable/sorttable.js""]) metric_html += template_environment.get_template(self.report_templates['metric']).render(metric_stats=metric_stats, metric_plots=metric_plots, correlated_plots=correlated_plots, metric=metric) metric_html += template_environment.get_template(self.report_templates['footer']).render() with open(os.path.join(self.output_directory, metric + '_report.html'), 'w') as metric_report: metric_report.write(metric_html)" 322,https://:@github.com/linkedin/naarad.git,74c5928b9c26fb7bd708fb9480dd2014b4305b89,"@@ -67,7 +67,7 @@ def graph_data(list_of_plots, output_directory, output_filename): plot_count = len(plots) if plot_count == 0: - return True, None + return False, None graph_height, graph_width, graph_title = get_graph_metadata(list_of_plots) ",src/naarad/graphing/matplotlib_naarad.py,"ReplaceText(target='False' @(70,11)->(70,15))","def graph_data(list_of_plots, output_directory, output_filename): plot_count = len(plots) if plot_count == 0: return True, None graph_height, graph_width, graph_title = get_graph_metadata(list_of_plots) ","def graph_data(list_of_plots, output_directory, output_filename): plot_count = len(plots) if plot_count == 0: return False, None graph_height, graph_width, graph_title = get_graph_metadata(list_of_plots) " 323,https://:@github.com/linkedin/naarad.git,fa8753e74e301602fd50281ef36bc13cde421ac2,"@@ -204,7 +204,7 @@ class Metric(object): if i+1 in groupby_idxes: continue else: - out_csv = self.get_csv(groupby_names, self.columns[i]) + out_csv = self.get_csv(self.columns[i], groupby_names) if out_csv in data: data[out_csv].append(ts + ',' + words[i+1]) else: ",src/naarad/metrics/metric.py,"ArgSwap(idxs=0<->1 @(207,26)->(207,38))","class Metric(object): if i+1 in groupby_idxes: continue else: out_csv = self.get_csv(groupby_names, self.columns[i]) if out_csv in data: data[out_csv].append(ts + ',' + words[i+1]) else:","class Metric(object): if i+1 in groupby_idxes: continue else: out_csv = self.get_csv(self.columns[i], groupby_names) if out_csv in data: data[out_csv].append(ts + ',' + words[i+1]) else:" 324,https://:@gitlab.com/mailman/postorius.git,308434aa505637da8275150484943b2442bc4b3c,"@@ -232,6 +232,6 @@ class ListMembersTest(ViewTestCase): {'q': 'not_a_member'}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['members']), 0) - self.assertNotContains(response, member_2.email) + self.assertNotContains(response, member_1.email) self.assertNotContains(response, member_2.email) ",src/postorius/tests/mailman_api_tests/test_list_members.py,"ReplaceText(target='member_1' @(235,41)->(235,49))","class ListMembersTest(ViewTestCase): {'q': 'not_a_member'}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['members']), 0) self.assertNotContains(response, member_2.email) self.assertNotContains(response, member_2.email) ","class ListMembersTest(ViewTestCase): {'q': 'not_a_member'}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['members']), 0) self.assertNotContains(response, member_1.email) self.assertNotContains(response, member_2.email) " 325,https://:@github.com/crsmithdev/arrow.git,fa5bce04765198071c17fa2ee889c16b5dbe6377,"@@ -94,7 +94,7 @@ class DateTimeFormatter(object): tz = dateutil_tz.tzutc() if dt.tzinfo is None else dt.tzinfo total_minutes = int(util.total_seconds(tz.utcoffset(dt)) / 60) - sign = '+' if total_minutes > 0 else '-' + sign = '+' if total_minutes >= 0 else '-' total_minutes = abs(total_minutes) hour, minute = divmod(total_minutes, 60) ",arrow/formatter.py,"ReplaceText(target='>=' @(97,40)->(97,41))","class DateTimeFormatter(object): tz = dateutil_tz.tzutc() if dt.tzinfo is None else dt.tzinfo total_minutes = int(util.total_seconds(tz.utcoffset(dt)) / 60) sign = '+' if total_minutes > 0 else '-' total_minutes = abs(total_minutes) hour, minute = divmod(total_minutes, 60) ","class DateTimeFormatter(object): tz = dateutil_tz.tzutc() if dt.tzinfo is None else dt.tzinfo total_minutes = int(util.total_seconds(tz.utcoffset(dt)) / 60) sign = '+' if total_minutes >= 0 else '-' total_minutes = abs(total_minutes) hour, minute = divmod(total_minutes, 60) " 326,https://:@github.com/AICoE/log-anomaly-detector.git,cd462c169c77152ae10cf3b0b99adfa51d53c043,"@@ -37,4 +37,4 @@ class SOMPYModel(BaseModel): dist = np.linalg.norm(self.model[x][y] - log) if dist < dist_smallest: dist_smallest = dist - return dist + return dist_smallest ",anomaly_detector/model/sompy_model.py,"ReplaceText(target='dist_smallest' @(40,15)->(40,19))","class SOMPYModel(BaseModel): dist = np.linalg.norm(self.model[x][y] - log) if dist < dist_smallest: dist_smallest = dist return dist","class SOMPYModel(BaseModel): dist = np.linalg.norm(self.model[x][y] - log) if dist < dist_smallest: dist_smallest = dist return dist_smallest" 327,https://:@github.com/ksmet1977/luxpy.git,6b6e6f7dd1dd257c8394dcd439f2bbb39be46fef,"@@ -896,7 +896,7 @@ def plot_spectrum_colors(spd = None, spdmax = None,\ cmfs = _CMF[cieobs]['bar'] else: cmfs = cieobs - cmfs = cmfs[:,cmfs[1:].sum(axis=1)>0] # avoid div by zero in xyz-to-Yxy conversion + cmfs = cmfs[:,cmfs[1:].sum(axis=0)>0] # avoid div by zero in xyz-to-Yxy conversion wavs = cmfs[0:1].T SL = cmfs[1:4].T ",luxpy/color/utils/plotters.py,"ReplaceText(target='0' @(899,36)->(899,37))","def plot_spectrum_colors(spd = None, spdmax = None,\ cmfs = _CMF[cieobs]['bar'] else: cmfs = cieobs cmfs = cmfs[:,cmfs[1:].sum(axis=1)>0] # avoid div by zero in xyz-to-Yxy conversion wavs = cmfs[0:1].T SL = cmfs[1:4].T ","def plot_spectrum_colors(spd = None, spdmax = None,\ cmfs = _CMF[cieobs]['bar'] else: cmfs = cieobs cmfs = cmfs[:,cmfs[1:].sum(axis=0)>0] # avoid div by zero in xyz-to-Yxy conversion wavs = cmfs[0:1].T SL = cmfs[1:4].T " 328,https://:@github.com/melexis/sphinx-traceability-extension.git,64a00adbbbec4088a6e0bb88b1ed43e26c2776bd,"@@ -760,7 +760,7 @@ def process_item_nodes(app, doctree, fromdocname): for source in node['sources']: for target in node['targets']: try: - env.traceability_collection.add_relation(target, node['type'], source) + env.traceability_collection.add_relation(source, node['type'], target) except TraceabilityException as err: report_warning(env, err, env.docname, self.lineno) # The ItemLink node has no final representation, so is removed from the tree ",mlx/traceability.py,"ArgSwap(idxs=0<->2 @(763,20)->(763,60))","def process_item_nodes(app, doctree, fromdocname): for source in node['sources']: for target in node['targets']: try: env.traceability_collection.add_relation(target, node['type'], source) except TraceabilityException as err: report_warning(env, err, env.docname, self.lineno) # The ItemLink node has no final representation, so is removed from the tree","def process_item_nodes(app, doctree, fromdocname): for source in node['sources']: for target in node['targets']: try: env.traceability_collection.add_relation(source, node['type'], target) except TraceabilityException as err: report_warning(env, err, env.docname, self.lineno) # The ItemLink node has no final representation, so is removed from the tree" 329,https://:@github.com/rocky/python3-trepan.git,2ff3e8439122926251ef9e7e4b7b89018feb9892,"@@ -47,7 +47,7 @@ and recolor all source code output."""""" pass def run(self, args): - if len(args) >= 1 and 'reset' == args[0]: + if len(args) > 1 and 'reset' == args[0]: highlight_type = self.get_highlight_type(args[1]) if not highlight_type: return clear_file_format_cache() ",trepan/processor/command/set_subcmd/highlight.py,"ReplaceText(target='>' @(50,21)->(50,23))","and recolor all source code output."""""" pass def run(self, args): if len(args) >= 1 and 'reset' == args[0]: highlight_type = self.get_highlight_type(args[1]) if not highlight_type: return clear_file_format_cache()","and recolor all source code output."""""" pass def run(self, args): if len(args) > 1 and 'reset' == args[0]: highlight_type = self.get_highlight_type(args[1]) if not highlight_type: return clear_file_format_cache()" 330,https://:@github.com/rocky/python3-trepan.git,7fe5f2be86cf60c41b67ea4a6d24990b06dd536a,"@@ -4,7 +4,7 @@ from fn_helper import strarray_setup, compare_output class TestSkip(unittest.TestCase): - @unittest.skipIf('TRAVIS' not in os.environ, + @unittest.skipIf('TRAVIS' in os.environ, ""FIXME: figure out why this doesn't work in travis"") def test_skip(self): ",test/functional/test-skip.py,"ReplaceText(target=' in ' @(7,29)->(7,37))","from fn_helper import strarray_setup, compare_output class TestSkip(unittest.TestCase): @unittest.skipIf('TRAVIS' not in os.environ, ""FIXME: figure out why this doesn't work in travis"") def test_skip(self): ","from fn_helper import strarray_setup, compare_output class TestSkip(unittest.TestCase): @unittest.skipIf('TRAVIS' in os.environ, ""FIXME: figure out why this doesn't work in travis"") def test_skip(self): " 331,https://:@github.com/rocky/python3-trepan.git,ce7705f666154604fb580ca56cd22ec7cc6eae69,"@@ -183,7 +183,7 @@ dictionary that gets fed to trepan.Debugger.core.start(). Parameter ""step_ignore"" specifies how many line events to ignore after the debug() call. 0 means don't even wait for the debug() call to finish. """""" - if isinstance(Mdebugger.debugger_obj, Mdebugger.Trepan): + if not isinstance(Mdebugger.debugger_obj, Mdebugger.Trepan): Mdebugger.debugger_obj = Mdebugger.Trepan(dbg_opts) Mdebugger.debugger_obj.core.add_ignore(debug, stop) pass ",trepan/api.py,"ReplaceText(target='not ' @(186,7)->(186,7))","dictionary that gets fed to trepan.Debugger.core.start(). Parameter ""step_ignore"" specifies how many line events to ignore after the debug() call. 0 means don't even wait for the debug() call to finish. """""" if isinstance(Mdebugger.debugger_obj, Mdebugger.Trepan): Mdebugger.debugger_obj = Mdebugger.Trepan(dbg_opts) Mdebugger.debugger_obj.core.add_ignore(debug, stop) pass","dictionary that gets fed to trepan.Debugger.core.start(). Parameter ""step_ignore"" specifies how many line events to ignore after the debug() call. 0 means don't even wait for the debug() call to finish. """""" if not isinstance(Mdebugger.debugger_obj, Mdebugger.Trepan): Mdebugger.debugger_obj = Mdebugger.Trepan(dbg_opts) Mdebugger.debugger_obj.core.add_ignore(debug, stop) pass" 332,https://:@github.com/rocky/python3-trepan.git,342c05260ac86fcc4e6d711a3f579c71d1d53d64,"@@ -116,7 +116,7 @@ See also: pass sys_version = version_info.major + (version_info.minor / 10.0) - if len(args) >= 1 and args[1] == '.': + if len(args) >= 1 and args[0] == '.': try: if pretty: deparsed = deparse_code(sys_version, co) ",trepan/processor/command/deparse.py,"ReplaceText(target='0' @(119,35)->(119,36))","See also: pass sys_version = version_info.major + (version_info.minor / 10.0) if len(args) >= 1 and args[1] == '.': try: if pretty: deparsed = deparse_code(sys_version, co)","See also: pass sys_version = version_info.major + (version_info.minor / 10.0) if len(args) >= 1 and args[0] == '.': try: if pretty: deparsed = deparse_code(sys_version, co)" 333,https://:@github.com/kanaka/websockify.git,0da91c7fdb3a49873121594e1820eef7ac078595,"@@ -225,7 +225,7 @@ Sec-WebSocket-Accept: %s\r payload_len = len(buf) if payload_len <= 125: header = struct.pack('>BB', b1, payload_len) - elif payload_len > 125 and payload_len <= 65536: + elif payload_len > 125 and payload_len < 65536: header = struct.pack('>BBH', b1, 126, payload_len) elif payload_len >= 65536: header = struct.pack('>BBQ', b1, 127, payload_len) ",websocket.py,"ReplaceText(target='<' @(228,47)->(228,49))","Sec-WebSocket-Accept: %s\r payload_len = len(buf) if payload_len <= 125: header = struct.pack('>BB', b1, payload_len) elif payload_len > 125 and payload_len <= 65536: header = struct.pack('>BBH', b1, 126, payload_len) elif payload_len >= 65536: header = struct.pack('>BBQ', b1, 127, payload_len)","Sec-WebSocket-Accept: %s\r payload_len = len(buf) if payload_len <= 125: header = struct.pack('>BB', b1, payload_len) elif payload_len > 125 and payload_len < 65536: header = struct.pack('>BBH', b1, 126, payload_len) elif payload_len >= 65536: header = struct.pack('>BBQ', b1, 127, payload_len)" 334,https://:@github.com/annoviko/pyclustering.git,70597e34bed02d7c3cb4a3d2e2ed6b30cd6cb3df,"@@ -320,7 +320,7 @@ class hysteresis_network(network): if (collect_dynamic is False): dyn_state.append(self._states); - dyn_time.append(t); + dyn_time.append(time); return hysteresis_dynamic(dyn_state, dyn_time); ",pyclustering/nnet/hysteresis.py,"ReplaceText(target='time' @(323,28)->(323,29))","class hysteresis_network(network): if (collect_dynamic is False): dyn_state.append(self._states); dyn_time.append(t); return hysteresis_dynamic(dyn_state, dyn_time); ","class hysteresis_network(network): if (collect_dynamic is False): dyn_state.append(self._states); dyn_time.append(time); return hysteresis_dynamic(dyn_state, dyn_time); " 335,https://:@github.com/annoviko/pyclustering.git,7e1bf5ed9cc2817c00c7e5e216adb4cc9fa8fc49,"@@ -123,7 +123,7 @@ class ttsas(bsas): index_cluster, distance = self._find_nearest_cluster(point); - if distance < self._threshold: + if distance <= self._threshold: self.__append_to_cluster(index_cluster, index_point, point); elif distance > self._threshold2: self.__allocate_cluster(index_point, point); ",pyclustering/cluster/ttsas.py,"ReplaceText(target='<=' @(126,20)->(126,21))","class ttsas(bsas): index_cluster, distance = self._find_nearest_cluster(point); if distance < self._threshold: self.__append_to_cluster(index_cluster, index_point, point); elif distance > self._threshold2: self.__allocate_cluster(index_point, point);","class ttsas(bsas): index_cluster, distance = self._find_nearest_cluster(point); if distance <= self._threshold: self.__append_to_cluster(index_cluster, index_point, point); elif distance > self._threshold2: self.__allocate_cluster(index_point, point);" 336,https://:@github.com/annoviko/pyclustering.git,cdb0ca92c076282084f54816d681f7d0a1588066,"@@ -64,7 +64,7 @@ class XmeansTestTemplates: assertion.eq(expected_wce, wce) if expected_cluster_length is not None: - assertion.eq(len(centers), len(expected_cluster_length)) + assertion.eq(len(expected_cluster_length), len(centers)) obtained_cluster_sizes.sort() expected_cluster_length.sort() ",pyclustering/cluster/tests/xmeans_templates.py,"ArgSwap(idxs=0<->1 @(67,12)->(67,24))","class XmeansTestTemplates: assertion.eq(expected_wce, wce) if expected_cluster_length is not None: assertion.eq(len(centers), len(expected_cluster_length)) obtained_cluster_sizes.sort() expected_cluster_length.sort()","class XmeansTestTemplates: assertion.eq(expected_wce, wce) if expected_cluster_length is not None: assertion.eq(len(expected_cluster_length), len(centers)) obtained_cluster_sizes.sort() expected_cluster_length.sort()" 337,https://:@github.com/evolbioinfo/pastml.git,06384fd264d834bff88efdc6bf70a098b06f307d,"@@ -232,7 +232,7 @@ def parsimonious_acr(tree, feature, prediction_method, states, num_nodes, num_ti .format(feature, num_steps)) num_scenarios, unresolved_nodes = choose_parsimonious_states(tree, feature) logger.debug('{} node{} unresolved ({:.2f}%) for {}, leading to {:g} ancestral scenario{}.' - .format(unresolved_nodes, 's are' if unresolved_nodes > 1 else ' is', + .format(unresolved_nodes, 's are' if unresolved_nodes != 1 else ' is', unresolved_nodes * 100 / num_nodes, feature, num_scenarios, 's' if num_scenarios > 1 else '')) ",pastml/parsimony.py,"ReplaceText(target='!=' @(235,71)->(235,72))","def parsimonious_acr(tree, feature, prediction_method, states, num_nodes, num_ti .format(feature, num_steps)) num_scenarios, unresolved_nodes = choose_parsimonious_states(tree, feature) logger.debug('{} node{} unresolved ({:.2f}%) for {}, leading to {:g} ancestral scenario{}.' .format(unresolved_nodes, 's are' if unresolved_nodes > 1 else ' is', unresolved_nodes * 100 / num_nodes, feature, num_scenarios, 's' if num_scenarios > 1 else '')) ","def parsimonious_acr(tree, feature, prediction_method, states, num_nodes, num_ti .format(feature, num_steps)) num_scenarios, unresolved_nodes = choose_parsimonious_states(tree, feature) logger.debug('{} node{} unresolved ({:.2f}%) for {}, leading to {:g} ancestral scenario{}.' .format(unresolved_nodes, 's are' if unresolved_nodes != 1 else ' is', unresolved_nodes * 100 / num_nodes, feature, num_scenarios, 's' if num_scenarios > 1 else '')) " 338,https://:@github.com/jirifilip/pyARC.git,e18a6c280f30bc753192bfa83f311ce36915aca4,"@@ -42,7 +42,7 @@ class TestClassAssociationRule(unittest.TestCase): sorted_cars = sorted([car1, car2, car3, car4], reverse=True) assert car1 < car2 - assert car2 < car3 + assert car2 > car3 assert car3 < car2 assert car4 > car3 assert car1.antecedent <= transaction1 ",cba/test/test_class_association_rule.py,"ReplaceText(target='>' @(45,20)->(45,21))","class TestClassAssociationRule(unittest.TestCase): sorted_cars = sorted([car1, car2, car3, car4], reverse=True) assert car1 < car2 assert car2 < car3 assert car3 < car2 assert car4 > car3 assert car1.antecedent <= transaction1","class TestClassAssociationRule(unittest.TestCase): sorted_cars = sorted([car1, car2, car3, car4], reverse=True) assert car1 < car2 assert car2 > car3 assert car3 < car2 assert car4 > car3 assert car1.antecedent <= transaction1" 339,https://:@github.com/oblalex/verboselib.git,5ec91a09ae9f0674513f4953111009b93eaad74a,"@@ -123,4 +123,4 @@ class VerboselibTranslationTestCase(unittest.TestCase): t1.merge(t2) self.assertEqual(t1.ugettext(""Hello""), ""Вітаю"") - self.assertEqual(t2.ugettext(""Good bye""), ""До зустрічі"") + self.assertEqual(t1.ugettext(""Good bye""), ""До зустрічі"") ",tests/test_package.py,"ReplaceText(target='t1' @(126,25)->(126,27))","class VerboselibTranslationTestCase(unittest.TestCase): t1.merge(t2) self.assertEqual(t1.ugettext(""Hello""), ""Вітаю"") self.assertEqual(t2.ugettext(""Good bye""), ""До зустрічі"")","class VerboselibTranslationTestCase(unittest.TestCase): t1.merge(t2) self.assertEqual(t1.ugettext(""Hello""), ""Вітаю"") self.assertEqual(t1.ugettext(""Good bye""), ""До зустрічі"")" 340,https://:@github.com/lexndru/hap.git,5ef18f88572400983578d8723663562329066779,"@@ -87,7 +87,7 @@ class Cache(object): tuple: Boolean for success read and string for size or error. """""" - if len(cache) == 0: + if len(cache_path) == 0: return False, ""missing cache path"" if len(cache) == 0: return False, ""missing cache data"" ",hap/cache.py,"ReplaceText(target='cache_path' @(90,15)->(90,20))","class Cache(object): tuple: Boolean for success read and string for size or error. """""" if len(cache) == 0: return False, ""missing cache path"" if len(cache) == 0: return False, ""missing cache data""","class Cache(object): tuple: Boolean for success read and string for size or error. """""" if len(cache_path) == 0: return False, ""missing cache path"" if len(cache) == 0: return False, ""missing cache data""" 341,https://:@github.com/littlezz/island-backup.git,fed75aebccfa31e418e351492618a2d50c15b9cb,"@@ -103,7 +103,7 @@ class ImageManager: print('this is {} in busying'.format(len(self.busying))) urls = [] for i, url in enumerate(self.busying): - if i > 3: + if i >= 3: break urls.append(url) ",main.py,"ReplaceText(target='>=' @(106,17)->(106,18))","class ImageManager: print('this is {} in busying'.format(len(self.busying))) urls = [] for i, url in enumerate(self.busying): if i > 3: break urls.append(url) ","class ImageManager: print('this is {} in busying'.format(len(self.busying))) urls = [] for i, url in enumerate(self.busying): if i >= 3: break urls.append(url) " 342,https://:@github.com/parrt/dtreeviz.git,aa5b4811af5c5a5c9620705fc44ffd9e48377664,"@@ -1121,7 +1121,7 @@ def draw_legend(shadow_tree, target_name, filename, colors=None): boxes = [] for i, c in enumerate(class_values): box = patches.Rectangle((0, 0), 20, 10, linewidth=.4, edgecolor=colors['rect_edge'], - facecolor=color_map[c], label=class_names[c]) + facecolor=color_map[c], label=class_names[i]) boxes.append(box) fig, ax = plt.subplots(1, 1, figsize=(1,1)) ",dtreeviz/trees.py,"ReplaceText(target='i' @(1124,74)->(1124,75))","def draw_legend(shadow_tree, target_name, filename, colors=None): boxes = [] for i, c in enumerate(class_values): box = patches.Rectangle((0, 0), 20, 10, linewidth=.4, edgecolor=colors['rect_edge'], facecolor=color_map[c], label=class_names[c]) boxes.append(box) fig, ax = plt.subplots(1, 1, figsize=(1,1))","def draw_legend(shadow_tree, target_name, filename, colors=None): boxes = [] for i, c in enumerate(class_values): box = patches.Rectangle((0, 0), 20, 10, linewidth=.4, edgecolor=colors['rect_edge'], facecolor=color_map[c], label=class_names[i]) boxes.append(box) fig, ax = plt.subplots(1, 1, figsize=(1,1))" 343,https://:@github.com/parrt/dtreeviz.git,01cc13f495decbd6f8f716d7be586e02864f3434,"@@ -809,7 +809,7 @@ def dtreeviz(tree_model: (tree.DecisionTreeRegressor, tree.DecisionTreeClassifie lcolor = colors['highlight'] lpw = ""1.2"" if node.right.id in highlight_path: - lcolor = colors['highlight'] + rcolor = colors['highlight'] rpw = ""1.2"" edges.append( f'{nname} -> {left_node_name} [penwidth={lpw} color=""{lcolor}"" label=<{llabel}>]' ) edges.append( f'{nname} -> {right_node_name} [penwidth={rpw} color=""{rcolor}"" label=<{rlabel}>]' ) ",dtreeviz/trees.py,"ReplaceText(target='rcolor' @(812,12)->(812,18))","def dtreeviz(tree_model: (tree.DecisionTreeRegressor, tree.DecisionTreeClassifie lcolor = colors['highlight'] lpw = ""1.2"" if node.right.id in highlight_path: lcolor = colors['highlight'] rpw = ""1.2"" edges.append( f'{nname} -> {left_node_name} [penwidth={lpw} color=""{lcolor}"" label=<{llabel}>]' ) edges.append( f'{nname} -> {right_node_name} [penwidth={rpw} color=""{rcolor}"" label=<{rlabel}>]' )","def dtreeviz(tree_model: (tree.DecisionTreeRegressor, tree.DecisionTreeClassifie lcolor = colors['highlight'] lpw = ""1.2"" if node.right.id in highlight_path: rcolor = colors['highlight'] rpw = ""1.2"" edges.append( f'{nname} -> {left_node_name} [penwidth={lpw} color=""{lcolor}"" label=<{llabel}>]' ) edges.append( f'{nname} -> {right_node_name} [penwidth={rpw} color=""{rcolor}"" label=<{rlabel}>]' )" 344,https://:@github.com/4teamwork/ftw.workspace.git,b12970101f5ca213e4604c2c3cf2f767f911b71e,"@@ -75,7 +75,7 @@ class AssignableUsersVocabulary(object): if user not in groups: groups.add(user) - if getattr(aq_base(workspace), '__ac_local_roles_block__', None): + if getattr(aq_base(context), '__ac_local_roles_block__', None): cont = False else: context = aq_parent(context) ",ftw/workspace/vocabularies.py,"ReplaceText(target='context' @(78,31)->(78,40))","class AssignableUsersVocabulary(object): if user not in groups: groups.add(user) if getattr(aq_base(workspace), '__ac_local_roles_block__', None): cont = False else: context = aq_parent(context)","class AssignableUsersVocabulary(object): if user not in groups: groups.add(user) if getattr(aq_base(context), '__ac_local_roles_block__', None): cont = False else: context = aq_parent(context)" 345,https://:@github.com/regulusweb/wagtail-extensions.git,ea388649a0c6dc6fbc1ce018d767c8b583486523,"@@ -74,7 +74,7 @@ class ContactDetailsSetting(BaseSetting): today = date.today() cache_key = self.get_opening_today_cache_key(today) times = cache.get(cache_key) - if times is not None: + if times is None: opening_times = self.primary_opening_times if opening_times: specific_times = utils.first_true(opening_times, lambda x: x.get('date') == today) ",wagtail_extensions/models.py,"ReplaceText(target=' is ' @(77,16)->(77,24))","class ContactDetailsSetting(BaseSetting): today = date.today() cache_key = self.get_opening_today_cache_key(today) times = cache.get(cache_key) if times is not None: opening_times = self.primary_opening_times if opening_times: specific_times = utils.first_true(opening_times, lambda x: x.get('date') == today)","class ContactDetailsSetting(BaseSetting): today = date.today() cache_key = self.get_opening_today_cache_key(today) times = cache.get(cache_key) if times is None: opening_times = self.primary_opening_times if opening_times: specific_times = utils.first_true(opening_times, lambda x: x.get('date') == today)" 346,https://:@github.com/tjcsl/cslbot.git,eaa1165f7ceb19b8e98828fea2894d275ffe5743,"@@ -394,7 +394,7 @@ class MyHandler(): elif cmd[0] == ""get"": if cmd[1] == ""disabled"" and cmd[2] == ""modules"": send(str(self.disabled_mods)) - if cmd[2] == ""enabled"" and cmd[2] == ""modules"": + if cmd[1] == ""enabled"" and cmd[2] == ""modules"": send(str([i for i in self.modules if i not in self.disabled_mods])) def handle_msg(self, msgtype, c, e): ",handler.py,"ReplaceText(target='1' @(397,19)->(397,20))","class MyHandler(): elif cmd[0] == ""get"": if cmd[1] == ""disabled"" and cmd[2] == ""modules"": send(str(self.disabled_mods)) if cmd[2] == ""enabled"" and cmd[2] == ""modules"": send(str([i for i in self.modules if i not in self.disabled_mods])) def handle_msg(self, msgtype, c, e):","class MyHandler(): elif cmd[0] == ""get"": if cmd[1] == ""disabled"" and cmd[2] == ""modules"": send(str(self.disabled_mods)) if cmd[1] == ""enabled"" and cmd[2] == ""modules"": send(str([i for i in self.modules if i not in self.disabled_mods])) def handle_msg(self, msgtype, c, e):" 347,https://:@github.com/tjcsl/cslbot.git,6c801ad70e0a9d1a963b9b560f9c654616e64a3b,"@@ -260,7 +260,7 @@ class BotHandler(): if self.log_to_ctrlchan: # somewhat hacky fix if target != CTRLCHAN: - self.connection.send_raw((""PRIVMSG %s :(%s) <%s> %s"" % (CTRLCHAN, target, nick, log))\ + self.connection.send_raw((""PRIVMSG %s :(%s) <%s> %s"" % (CTRLCHAN, target, nick, msg))\ .replace(""\n"", """").replace(""\r"", """")) self.logs[target].append([day, log]) self.logfiles[target].write(log) ",handler.py,"ReplaceText(target='msg' @(263,96)->(263,99))","class BotHandler(): if self.log_to_ctrlchan: # somewhat hacky fix if target != CTRLCHAN: self.connection.send_raw((""PRIVMSG %s :(%s) <%s> %s"" % (CTRLCHAN, target, nick, log))\ .replace(""\n"", """").replace(""\r"", """")) self.logs[target].append([day, log]) self.logfiles[target].write(log)","class BotHandler(): if self.log_to_ctrlchan: # somewhat hacky fix if target != CTRLCHAN: self.connection.send_raw((""PRIVMSG %s :(%s) <%s> %s"" % (CTRLCHAN, target, nick, msg))\ .replace(""\n"", """").replace(""\r"", """")) self.logs[target].append([day, log]) self.logfiles[target].write(log)" 348,https://:@github.com/tjcsl/cslbot.git,b5c181736ff1adc6b665d2d4a80bd6141aaa549e,"@@ -331,7 +331,7 @@ class BotHandler(): return if cmdargs[0] != '#': cmdargs = '#' + cmdargs - if cmdargs in self.channels and len(cmd) > 0 and cmd[1] != ""force"": + if cmdargs in self.channels or len(cmd) > 0 and cmd[1] != ""force"": send(""%s is already a member of %s"" % (NICK, cmdargs)) return c.join(cmd[0]) ",handler.py,"ReplaceText(target='or' @(334,36)->(334,39))","class BotHandler(): return if cmdargs[0] != '#': cmdargs = '#' + cmdargs if cmdargs in self.channels and len(cmd) > 0 and cmd[1] != ""force"": send(""%s is already a member of %s"" % (NICK, cmdargs)) return c.join(cmd[0])","class BotHandler(): return if cmdargs[0] != '#': cmdargs = '#' + cmdargs if cmdargs in self.channels or len(cmd) > 0 and cmd[1] != ""force"": send(""%s is already a member of %s"" % (NICK, cmdargs)) return c.join(cmd[0])" 349,https://:@github.com/tjcsl/cslbot.git,20dab902837bb40599cb34afe152dfc780f2854e,"@@ -315,7 +315,7 @@ class BotHandler(): # -pub # -private #log to sqlite logger - self.logger.log(target, nick, isop, msg, msgtype) + self.logger.log(nick, target, isop, msg, msgtype) if self.log_to_ctrlchan: ctrlchan = self.config['core']['ctrlchan'] ",handler.py,"ArgSwap(idxs=0<->1 @(318,8)->(318,23))","class BotHandler(): # -pub # -private #log to sqlite logger self.logger.log(target, nick, isop, msg, msgtype) if self.log_to_ctrlchan: ctrlchan = self.config['core']['ctrlchan']","class BotHandler(): # -pub # -private #log to sqlite logger self.logger.log(nick, target, isop, msg, msgtype) if self.log_to_ctrlchan: ctrlchan = self.config['core']['ctrlchan']" 350,https://:@github.com/tjcsl/cslbot.git,7b544654a37dd0ca467157c76aaa51bb6e9a73e8,"@@ -442,7 +442,7 @@ class BotHandler(): if cmd_obj.is_limited() and self.abusecheck(send, nick, cmd_obj.limit, msgtype, cmd[len(cmdchar):]): return args = self.do_args(cmd_obj.args, send, nick, target, e.source, c, cmd_name, msgtype) - cmd_obj.run(send, cmdargs, args, cmd_name, target, nick, self.db.get()) + cmd_obj.run(send, cmdargs, args, cmd_name, nick, target, self.db.get()) # special commands if cmd.startswith(cmdchar): if cmd[len(cmdchar):] == 'reload': ",handler.py,"ArgSwap(idxs=4<->5 @(445,16)->(445,27))","class BotHandler(): if cmd_obj.is_limited() and self.abusecheck(send, nick, cmd_obj.limit, msgtype, cmd[len(cmdchar):]): return args = self.do_args(cmd_obj.args, send, nick, target, e.source, c, cmd_name, msgtype) cmd_obj.run(send, cmdargs, args, cmd_name, target, nick, self.db.get()) # special commands if cmd.startswith(cmdchar): if cmd[len(cmdchar):] == 'reload':","class BotHandler(): if cmd_obj.is_limited() and self.abusecheck(send, nick, cmd_obj.limit, msgtype, cmd[len(cmdchar):]): return args = self.do_args(cmd_obj.args, send, nick, target, e.source, c, cmd_name, msgtype) cmd_obj.run(send, cmdargs, args, cmd_name, nick, target, self.db.get()) # special commands if cmd.startswith(cmdchar): if cmd[len(cmdchar):] == 'reload':" 351,https://:@github.com/tjcsl/cslbot.git,8d5e5ff45a32d6849e0daf38414e818b4d8e4a96,"@@ -38,7 +38,7 @@ def cmd(send, msg, args): name = 'passthrough' else: name = name[4:] - names.append(i) + names.append(name) send(""Current filter(s): %s"" % "", "".join(names)) elif msg == 'list': send(""Available filters are %s"" % "", "".join(output_filters.keys())) ",commands/filter.py,"ReplaceText(target='name' @(41,25)->(41,26))","def cmd(send, msg, args): name = 'passthrough' else: name = name[4:] names.append(i) send(""Current filter(s): %s"" % "", "".join(names)) elif msg == 'list': send(""Available filters are %s"" % "", "".join(output_filters.keys()))","def cmd(send, msg, args): name = 'passthrough' else: name = name[4:] names.append(name) send(""Current filter(s): %s"" % "", "".join(names)) elif msg == 'list': send(""Available filters are %s"" % "", "".join(output_filters.keys()))" 352,https://:@github.com/tjcsl/cslbot.git,0e38c8226ab070d321cbed3ade449c2833d0f36e,"@@ -154,7 +154,7 @@ def handle_accept(handler, cmd): return ""Missing argument."" if not cmd[1].isdigit(): return ""Not A Valid Positive Integer"" - elif not handler.issues or len(handler.issues) < int(cmd[1]): + elif not handler.issues or len(handler.issues) <= int(cmd[1]): return ""Not a valid issue"" else: num = int(cmd[1]) ",helpers/control.py,"ReplaceText(target='<=' @(157,51)->(157,52))","def handle_accept(handler, cmd): return ""Missing argument."" if not cmd[1].isdigit(): return ""Not A Valid Positive Integer"" elif not handler.issues or len(handler.issues) < int(cmd[1]): return ""Not a valid issue"" else: num = int(cmd[1])","def handle_accept(handler, cmd): return ""Missing argument."" if not cmd[1].isdigit(): return ""Not A Valid Positive Integer"" elif not handler.issues or len(handler.issues) <= int(cmd[1]): return ""Not a valid issue"" else: num = int(cmd[1])" 353,https://:@github.com/tjcsl/cslbot.git,1694edfac9e6ee93ce648c78be52d19360b7e364,"@@ -54,7 +54,7 @@ def do_add_quote(cmd, conn, isadmin, send, args): cursor = conn.execute('INSERT INTO quotes(quote, nick, submitter) VALUES(?,?,?)', (quote[0], quote[1], args['nick'])) qid = cursor.lastrowid if isadmin: - cursor.execute('UPDATE quotes SET approved=1 WHERE id=?', (qid,)) + conn.execute('UPDATE quotes SET approved=1 WHERE id=?', (qid,)) send(""Added quote %d!"" % qid) else: send(""Quote submitted for approval."", target=args['nick']) ",commands/quote.py,"ReplaceText(target='conn' @(57,8)->(57,14))","def do_add_quote(cmd, conn, isadmin, send, args): cursor = conn.execute('INSERT INTO quotes(quote, nick, submitter) VALUES(?,?,?)', (quote[0], quote[1], args['nick'])) qid = cursor.lastrowid if isadmin: cursor.execute('UPDATE quotes SET approved=1 WHERE id=?', (qid,)) send(""Added quote %d!"" % qid) else: send(""Quote submitted for approval."", target=args['nick'])","def do_add_quote(cmd, conn, isadmin, send, args): cursor = conn.execute('INSERT INTO quotes(quote, nick, submitter) VALUES(?,?,?)', (quote[0], quote[1], args['nick'])) qid = cursor.lastrowid if isadmin: conn.execute('UPDATE quotes SET approved=1 WHERE id=?', (qid,)) send(""Added quote %d!"" % qid) else: send(""Quote submitted for approval."", target=args['nick'])" 354,https://:@github.com/tjcsl/cslbot.git,aa3079c68c6bfed92fe95cf92dbed87d1f3c91d2,"@@ -33,7 +33,7 @@ def handle_traceback(ex, c, target, config, source=""the bot""): errtarget = ctrlchan if prettyerrors else target if prettyerrors: if name == 'CSLException': - c.privmsg(target, ""%s -- %s"" % (name, output)) + c.privmsg(target, ""%s -- %s"" % (source, output)) else: c.privmsg(target, ""An %s has occured in %s. See the control channel for details."" % (name, source)) c.privmsg(errtarget, '%s -- %s in %s on line %s: %s' % (source, name, trace[0], trace[1], output)) ",helpers/traceback.py,"ReplaceText(target='source' @(36,44)->(36,48))","def handle_traceback(ex, c, target, config, source=""the bot""): errtarget = ctrlchan if prettyerrors else target if prettyerrors: if name == 'CSLException': c.privmsg(target, ""%s -- %s"" % (name, output)) else: c.privmsg(target, ""An %s has occured in %s. See the control channel for details."" % (name, source)) c.privmsg(errtarget, '%s -- %s in %s on line %s: %s' % (source, name, trace[0], trace[1], output))","def handle_traceback(ex, c, target, config, source=""the bot""): errtarget = ctrlchan if prettyerrors else target if prettyerrors: if name == 'CSLException': c.privmsg(target, ""%s -- %s"" % (source, output)) else: c.privmsg(target, ""An %s has occured in %s. See the control channel for details."" % (name, source)) c.privmsg(errtarget, '%s -- %s in %s on line %s: %s' % (source, name, trace[0], trace[1], output))" 355,https://:@github.com/tjcsl/cslbot.git,8bd3d1038ba16c4c097b51c1bdce1a54a5fb43af,"@@ -38,7 +38,7 @@ def get_definition(msg): elif not index.isdigit() or int(index) >= len(data) or int(index) == 0: output = ""Invalid Index"" else: - output = data[int(index)+1]['definition'] + output = data[int(index)-1]['definition'] output = output.splitlines() return ' '.join(output) ",commands/urban.py,"ReplaceText(target='-' @(41,32)->(41,33))","def get_definition(msg): elif not index.isdigit() or int(index) >= len(data) or int(index) == 0: output = ""Invalid Index"" else: output = data[int(index)+1]['definition'] output = output.splitlines() return ' '.join(output) ","def get_definition(msg): elif not index.isdigit() or int(index) >= len(data) or int(index) == 0: output = ""Invalid Index"" else: output = data[int(index)-1]['definition'] output = output.splitlines() return ' '.join(output) " 356,https://:@github.com/tjcsl/cslbot.git,a72f1944cc07392f2f1c023448bfc0eceb6cd8cd,"@@ -40,7 +40,7 @@ def get_definition(msg): output = ""UrbanDictionary doesn't have an answer for you."" elif index is None: output = data[0]['definition'] - elif not index.isdigit() or int(index) >= len(data) or int(index) == 0: + elif not index.isdigit() or int(index) > len(data) or int(index) == 0: output = ""Invalid Index"" else: output = data[int(index)-1]['definition'] ",commands/urban.py,"ReplaceText(target='>' @(43,43)->(43,45))","def get_definition(msg): output = ""UrbanDictionary doesn't have an answer for you."" elif index is None: output = data[0]['definition'] elif not index.isdigit() or int(index) >= len(data) or int(index) == 0: output = ""Invalid Index"" else: output = data[int(index)-1]['definition']","def get_definition(msg): output = ""UrbanDictionary doesn't have an answer for you."" elif index is None: output = data[0]['definition'] elif not index.isdigit() or int(index) > len(data) or int(index) == 0: output = ""Invalid Index"" else: output = data[int(index)-1]['definition']" 357,https://:@github.com/tjcsl/cslbot.git,ffc2cedcd394bf7076f4e8882d7f8773fc2a529b,"@@ -24,7 +24,7 @@ from helpers.command import Command def cmd(send, msg, args): """"""Finds a random quote from tjbash.org given search criteria """""" - if len(msg) < 0: + if len(msg) == 0: url = 'http://tjbash.org/random1' else: url = 'http://tjbash.org/search?query=' ",commands/tjbash.py,"ReplaceText(target='==' @(27,16)->(27,17))","from helpers.command import Command def cmd(send, msg, args): """"""Finds a random quote from tjbash.org given search criteria """""" if len(msg) < 0: url = 'http://tjbash.org/random1' else: url = 'http://tjbash.org/search?query='","from helpers.command import Command def cmd(send, msg, args): """"""Finds a random quote from tjbash.org given search criteria """""" if len(msg) == 0: url = 'http://tjbash.org/random1' else: url = 'http://tjbash.org/search?query='" 358,https://:@github.com/tjcsl/cslbot.git,0a9fcb6ce10d7d7dca87496e3abb02faa1c35794,"@@ -87,7 +87,7 @@ def build_markov(cursor, speaker, cmdchar, ctrlchan): def get_markov(cursor, speaker, handler, cmdchar, ctrlchan): markov = cursor.query(Babble).filter(Babble.nick == speaker).first() if not markov: - update_markov(cursor, speaker, cmdchar, ctrlchan) + update_markov(handler, speaker, cmdchar, ctrlchan) markov = cursor.query(Babble).filter(Babble.nick == speaker).first() elif time.time() - markov.time > CACHE_LIFE: handler.workers.defer(0, False, update_markov, handler, speaker, cmdchar, ctrlchan) ",commands/babble.py,"ReplaceText(target='handler' @(90,22)->(90,28))","def build_markov(cursor, speaker, cmdchar, ctrlchan): def get_markov(cursor, speaker, handler, cmdchar, ctrlchan): markov = cursor.query(Babble).filter(Babble.nick == speaker).first() if not markov: update_markov(cursor, speaker, cmdchar, ctrlchan) markov = cursor.query(Babble).filter(Babble.nick == speaker).first() elif time.time() - markov.time > CACHE_LIFE: handler.workers.defer(0, False, update_markov, handler, speaker, cmdchar, ctrlchan)","def build_markov(cursor, speaker, cmdchar, ctrlchan): def get_markov(cursor, speaker, handler, cmdchar, ctrlchan): markov = cursor.query(Babble).filter(Babble.nick == speaker).first() if not markov: update_markov(handler, speaker, cmdchar, ctrlchan) markov = cursor.query(Babble).filter(Babble.nick == speaker).first() elif time.time() - markov.time > CACHE_LIFE: handler.workers.defer(0, False, update_markov, handler, speaker, cmdchar, ctrlchan)" 359,https://:@github.com/ThibHlln/smartpy.git,6e02ac69689bff3802de8dcc5b15237996379aae,"@@ -26,7 +26,7 @@ def nash_sutcliffe(evaluation, simulation): def groundwater_constraint(evaluation, simulation): - if (evaluation[0] - 0.1 <= simulation[0]) or (simulation[0] <= evaluation[0] + 0.1): + if (evaluation[0] - 0.1 <= simulation[0]) and (simulation[0] <= evaluation[0] + 0.1): return 1.0 else: return 0.0 ",SMARTobjective.py,"ReplaceText(target='and' @(29,46)->(29,48))","def nash_sutcliffe(evaluation, simulation): def groundwater_constraint(evaluation, simulation): if (evaluation[0] - 0.1 <= simulation[0]) or (simulation[0] <= evaluation[0] + 0.1): return 1.0 else: return 0.0","def nash_sutcliffe(evaluation, simulation): def groundwater_constraint(evaluation, simulation): if (evaluation[0] - 0.1 <= simulation[0]) and (simulation[0] <= evaluation[0] + 0.1): return 1.0 else: return 0.0" 360,https://:@github.com/satellogic/orbit-predictor.git,672c75a9b64b6735c08bd5270855588e3d514065,"@@ -30,7 +30,7 @@ from orbit_predictor.predictors.base import CartesianPredictor, logger class TLEPredictor(CartesianPredictor): def __init__(self, sate_id, source): - super(TLEPredictor, self).__init__(source, sate_id) + super(TLEPredictor, self).__init__(sate_id, source) self._iterations = 0 def _propagate_eci(self, when_utc=None): ",orbit_predictor/predictors/tle.py,"ArgSwap(idxs=0<->1 @(33,8)->(33,42))","from orbit_predictor.predictors.base import CartesianPredictor, logger class TLEPredictor(CartesianPredictor): def __init__(self, sate_id, source): super(TLEPredictor, self).__init__(source, sate_id) self._iterations = 0 def _propagate_eci(self, when_utc=None):","from orbit_predictor.predictors.base import CartesianPredictor, logger class TLEPredictor(CartesianPredictor): def __init__(self, sate_id, source): super(TLEPredictor, self).__init__(sate_id, source) self._iterations = 0 def _propagate_eci(self, when_utc=None):" 361,https://:@github.com/dipu-bd/lightnovel-crawler.git,773695654f273c9f7191817c4dd64e8322325809,"@@ -39,7 +39,7 @@ class LightNovelOnline(Crawler): logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) - self.novel_id = urlparse(self.novel_url).path.split('/')[1] + self.novel_id = urlparse(self.novel_url).path.split('/')[-1] logger.info(""Novel Id: %s"", self.novel_id) self.novel_title = soup.select_one( ",lncrawl/sources/lightnovelonline.py,"ReplaceText(target='-1' @(42,65)->(42,66))","class LightNovelOnline(Crawler): logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) self.novel_id = urlparse(self.novel_url).path.split('/')[1] logger.info(""Novel Id: %s"", self.novel_id) self.novel_title = soup.select_one(","class LightNovelOnline(Crawler): logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) self.novel_id = urlparse(self.novel_url).path.split('/')[-1] logger.info(""Novel Id: %s"", self.novel_id) self.novel_title = soup.select_one(" 362,https://:@github.com/raphaelm/python-sepaxml.git,024a11dd1e26d08bbeb028a2a13dabcb509011ec,"@@ -54,7 +54,7 @@ def make_id(name): 12 char rand hex string. """""" r = get_rand_string(12) - if len(name) <= 22: + if len(name) > 22: name = name[:22] return name + ""-"" + r ",sepadd/utils.py,"ReplaceText(target='>' @(57,17)->(57,19))","def make_id(name): 12 char rand hex string. """""" r = get_rand_string(12) if len(name) <= 22: name = name[:22] return name + ""-"" + r ","def make_id(name): 12 char rand hex string. """""" r = get_rand_string(12) if len(name) > 22: name = name[:22] return name + ""-"" + r " 363,https://:@github.com/raphaelm/python-sepaxml.git,98934ba5c863ffbc2bc770a34dd9ddea8edf2577,"@@ -70,7 +70,7 @@ def int_to_decimal_str(integer): @return string The amount in currency with full stop decimal separator """""" int_string = str(integer) - if len(int_string) < 2: + if len(int_string) <= 2: return ""0."" + int_string.zfill(2) else: return int_string[:-2] + ""."" + int_string[-2:] ",sepaxml/utils.py,"ReplaceText(target='<=' @(73,23)->(73,24))","def int_to_decimal_str(integer): @return string The amount in currency with full stop decimal separator """""" int_string = str(integer) if len(int_string) < 2: return ""0."" + int_string.zfill(2) else: return int_string[:-2] + ""."" + int_string[-2:]","def int_to_decimal_str(integer): @return string The amount in currency with full stop decimal separator """""" int_string = str(integer) if len(int_string) <= 2: return ""0."" + int_string.zfill(2) else: return int_string[:-2] + ""."" + int_string[-2:]" 364,https://:@github.com/scikit-image/scikit-image.git,2585a323ac57004179b0ba643f953162650f39ee,"@@ -51,7 +51,7 @@ def peak_local_max(image, min_distance=10, threshold='deprecated', threshold_rel = threshold # find top corner candidates above a threshold corner_threshold = max(np.max(image.ravel()) * threshold_rel, threshold_abs) - image_t = (image >= corner_threshold) * 1 + image_t = (image > corner_threshold) * 1 # get coordinates of peaks coordinates = np.transpose(image_t.nonzero()) ",skimage/feature/peak.py,"ReplaceText(target='>' @(54,21)->(54,23))","def peak_local_max(image, min_distance=10, threshold='deprecated', threshold_rel = threshold # find top corner candidates above a threshold corner_threshold = max(np.max(image.ravel()) * threshold_rel, threshold_abs) image_t = (image >= corner_threshold) * 1 # get coordinates of peaks coordinates = np.transpose(image_t.nonzero())","def peak_local_max(image, min_distance=10, threshold='deprecated', threshold_rel = threshold # find top corner candidates above a threshold corner_threshold = max(np.max(image.ravel()) * threshold_rel, threshold_abs) image_t = (image > corner_threshold) * 1 # get coordinates of peaks coordinates = np.transpose(image_t.nonzero())" 365,https://:@github.com/scikit-image/scikit-image.git,8084faf1f69c2c4ba79b6e85c7a2a06e1e7c77b8,"@@ -133,7 +133,7 @@ def reconstruction(seed, mask, method='dilation', selem=None, offset=None): if offset == None: if not all([d % 2 == 1 for d in selem.shape]): ValueError(""Footprint dimensions must all be odd"") - offset = np.array([d / 2 for d in selem.shape]) + offset = np.array([d // 2 for d in selem.shape]) # Cross out the center of the selem selem[[slice(d, d + 1) for d in offset]] = False ",skimage/morphology/greyreconstruct.py,"ReplaceText(target='//' @(136,29)->(136,30))","def reconstruction(seed, mask, method='dilation', selem=None, offset=None): if offset == None: if not all([d % 2 == 1 for d in selem.shape]): ValueError(""Footprint dimensions must all be odd"") offset = np.array([d / 2 for d in selem.shape]) # Cross out the center of the selem selem[[slice(d, d + 1) for d in offset]] = False ","def reconstruction(seed, mask, method='dilation', selem=None, offset=None): if offset == None: if not all([d % 2 == 1 for d in selem.shape]): ValueError(""Footprint dimensions must all be odd"") offset = np.array([d // 2 for d in selem.shape]) # Cross out the center of the selem selem[[slice(d, d + 1) for d in offset]] = False " 366,https://:@github.com/scikit-image/scikit-image.git,d1629aec0f1a861106d54cb015b238e7fe542936,"@@ -28,7 +28,7 @@ def approximate_polygon(coords, tolerance): ---------- .. [1] http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm """""" - if tolerance == 0: + if tolerance <= 0: return coords chain = np.zeros(coords.shape[0], 'bool') ",skimage/measure/_polygon.py,"ReplaceText(target='<=' @(31,17)->(31,19))","def approximate_polygon(coords, tolerance): ---------- .. [1] http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm """""" if tolerance == 0: return coords chain = np.zeros(coords.shape[0], 'bool')","def approximate_polygon(coords, tolerance): ---------- .. [1] http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm """""" if tolerance <= 0: return coords chain = np.zeros(coords.shape[0], 'bool')" 367,https://:@github.com/scikit-image/scikit-image.git,22f94d8707d3d9d2a36493403cbaeb61213dd68b,"@@ -163,7 +163,7 @@ def rotate(image, angle, resize=False, order=1, mode='constant', cval=0.): tform = tform1 + tform2 + tform3 output_shape = None - if not resize: + if resize: # determine shape of output image corners = np.array([[1, 1], [1, rows], [cols, rows], [cols, 1]]) corners = tform(corners - 1) ",skimage/transform/_warps.py,"ReplaceText(target='' @(166,7)->(166,11))","def rotate(image, angle, resize=False, order=1, mode='constant', cval=0.): tform = tform1 + tform2 + tform3 output_shape = None if not resize: # determine shape of output image corners = np.array([[1, 1], [1, rows], [cols, rows], [cols, 1]]) corners = tform(corners - 1)","def rotate(image, angle, resize=False, order=1, mode='constant', cval=0.): tform = tform1 + tform2 + tform3 output_shape = None if resize: # determine shape of output image corners = np.array([[1, 1], [1, rows], [cols, rows], [cols, 1]]) corners = tform(corners - 1)" 368,https://:@github.com/scikit-image/scikit-image.git,794a4d7daebfdcb217fbf0a73b9d42e256ce45cd,"@@ -1085,7 +1085,7 @@ def _validate_lengths(narray, number_elements): normshp = _normalize_shape(narray, number_elements) for i in normshp: chk = [1 if x is None else x for x in i] - chk = [1 if x > 0 else -1 for x in chk] + chk = [1 if x >= 0 else -1 for x in chk] if (chk[0] < 0) or (chk[1] < 0): fmt = ""%s cannot contain negative values."" raise ValueError(fmt % (number_elements,)) ",skimage/util/arraypad.py,"ReplaceText(target='>=' @(1088,22)->(1088,23))","def _validate_lengths(narray, number_elements): normshp = _normalize_shape(narray, number_elements) for i in normshp: chk = [1 if x is None else x for x in i] chk = [1 if x > 0 else -1 for x in chk] if (chk[0] < 0) or (chk[1] < 0): fmt = ""%s cannot contain negative values."" raise ValueError(fmt % (number_elements,))","def _validate_lengths(narray, number_elements): normshp = _normalize_shape(narray, number_elements) for i in normshp: chk = [1 if x is None else x for x in i] chk = [1 if x >= 0 else -1 for x in chk] if (chk[0] < 0) or (chk[1] < 0): fmt = ""%s cannot contain negative values."" raise ValueError(fmt % (number_elements,))" 369,https://:@github.com/scikit-image/scikit-image.git,5f46fd01be76ac8c7252ab35ba58609e81ad0ca0,"@@ -124,7 +124,7 @@ def _star_filter_kernel(m, n): def _suppress_lines(feature_mask, image, sigma, line_threshold): Axx, Axy, Ayy = _compute_auto_correlation(image, sigma) feature_mask[(Axx + Ayy) * (Axx + Ayy) - < line_threshold * (Axx * Ayy - Axy * Axy)] = 0 + > line_threshold * (Axx * Ayy - Axy * Axy)] = 0 return feature_mask ",skimage/feature/censure.py,"ReplaceText(target='>' @(127,17)->(127,18))","def _star_filter_kernel(m, n): def _suppress_lines(feature_mask, image, sigma, line_threshold): Axx, Axy, Ayy = _compute_auto_correlation(image, sigma) feature_mask[(Axx + Ayy) * (Axx + Ayy) < line_threshold * (Axx * Ayy - Axy * Axy)] = 0 return feature_mask ","def _star_filter_kernel(m, n): def _suppress_lines(feature_mask, image, sigma, line_threshold): Axx, Axy, Ayy = _compute_auto_correlation(image, sigma) feature_mask[(Axx + Ayy) * (Axx + Ayy) > line_threshold * (Axx * Ayy - Axy * Axy)] = 0 return feature_mask " 370,https://:@github.com/scikit-image/scikit-image.git,05aeb7c7fe89a70fa18294d69c9e12dd58fa5c08,"@@ -159,7 +159,7 @@ def reconstruction(seed, mask, method='dilation', selem=None, offset=None): # Create a list of strides across the array to get the neighbors within # a flattened array value_stride = np.array(images.strides[1:]) / images.dtype.itemsize - image_stride = images.strides[0] / images.dtype.itemsize + image_stride = images.strides[0] // images.dtype.itemsize selem_mgrid = np.mgrid[[slice(-o, d - o) for d, o in zip(selem.shape, offset)]] selem_offsets = selem_mgrid[:, selem].transpose() ",skimage/morphology/greyreconstruct.py,"ReplaceText(target='//' @(162,37)->(162,38))","def reconstruction(seed, mask, method='dilation', selem=None, offset=None): # Create a list of strides across the array to get the neighbors within # a flattened array value_stride = np.array(images.strides[1:]) / images.dtype.itemsize image_stride = images.strides[0] / images.dtype.itemsize selem_mgrid = np.mgrid[[slice(-o, d - o) for d, o in zip(selem.shape, offset)]] selem_offsets = selem_mgrid[:, selem].transpose()","def reconstruction(seed, mask, method='dilation', selem=None, offset=None): # Create a list of strides across the array to get the neighbors within # a flattened array value_stride = np.array(images.strides[1:]) / images.dtype.itemsize image_stride = images.strides[0] // images.dtype.itemsize selem_mgrid = np.mgrid[[slice(-o, d - o) for d, o in zip(selem.shape, offset)]] selem_offsets = selem_mgrid[:, selem].transpose()" 371,https://:@github.com/scikit-image/scikit-image.git,05fbc3fbfcc00157841c18b15b171d6477bfb5da,"@@ -119,7 +119,7 @@ def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=None, spacing = np.array(spacing, np.double) if not isinstance(sigma, coll.Iterable): sigma = np.array([sigma, sigma, sigma], np.double) - elif isinstance(spacing, (list, tuple)): + elif isinstance(sigma, (list, tuple)): sigma = np.array(sigma, np.double) if (sigma > 0).any(): sigma /= spacing.astype(np.double) ",skimage/segmentation/slic_superpixels.py,"ReplaceText(target='sigma' @(122,20)->(122,27))","def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=None, spacing = np.array(spacing, np.double) if not isinstance(sigma, coll.Iterable): sigma = np.array([sigma, sigma, sigma], np.double) elif isinstance(spacing, (list, tuple)): sigma = np.array(sigma, np.double) if (sigma > 0).any(): sigma /= spacing.astype(np.double)","def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=None, spacing = np.array(spacing, np.double) if not isinstance(sigma, coll.Iterable): sigma = np.array([sigma, sigma, sigma], np.double) elif isinstance(sigma, (list, tuple)): sigma = np.array(sigma, np.double) if (sigma > 0).any(): sigma /= spacing.astype(np.double)" 372,https://:@github.com/scikit-image/scikit-image.git,1ca0eef825188ac5e9fc84b232b4783c166933ac,"@@ -94,7 +94,7 @@ def view_as_blocks(arr_in, block_shape): arr_in = np.ascontiguousarray(arr_in) - new_shape = tuple(arr_shape / block_shape) + tuple(block_shape) + new_shape = tuple(arr_shape // block_shape) + tuple(block_shape) new_strides = tuple(arr_in.strides * block_shape) + arr_in.strides arr_out = as_strided(arr_in, shape=new_shape, strides=new_strides) ",skimage/util/shape.py,"ReplaceText(target='//' @(97,32)->(97,33))","def view_as_blocks(arr_in, block_shape): arr_in = np.ascontiguousarray(arr_in) new_shape = tuple(arr_shape / block_shape) + tuple(block_shape) new_strides = tuple(arr_in.strides * block_shape) + arr_in.strides arr_out = as_strided(arr_in, shape=new_shape, strides=new_strides)","def view_as_blocks(arr_in, block_shape): arr_in = np.ascontiguousarray(arr_in) new_shape = tuple(arr_shape // block_shape) + tuple(block_shape) new_strides = tuple(arr_in.strides * block_shape) + arr_in.strides arr_out = as_strided(arr_in, shape=new_shape, strides=new_strides)" 373,https://:@github.com/scikit-image/scikit-image.git,a38b1c12579214cf77785e9c85f30202b2048c4f,"@@ -136,7 +136,7 @@ def _clahe(image, ntiles_x, ntiles_y, clip_limit, nbins=128): image = pad(image, ((0, h_pad), (0, w_pad)), mode='reflect') h_inner, w_inner = image.shape - bin_size = 1 + NR_OF_GREY / nbins + bin_size = 1 + NR_OF_GREY // nbins lut = np.arange(NR_OF_GREY) lut //= bin_size img_blocks = view_as_blocks(image, (height, width)) ",skimage/exposure/_adapthist.py,"ReplaceText(target='//' @(139,30)->(139,31))","def _clahe(image, ntiles_x, ntiles_y, clip_limit, nbins=128): image = pad(image, ((0, h_pad), (0, w_pad)), mode='reflect') h_inner, w_inner = image.shape bin_size = 1 + NR_OF_GREY / nbins lut = np.arange(NR_OF_GREY) lut //= bin_size img_blocks = view_as_blocks(image, (height, width))","def _clahe(image, ntiles_x, ntiles_y, clip_limit, nbins=128): image = pad(image, ((0, h_pad), (0, w_pad)), mode='reflect') h_inner, w_inner = image.shape bin_size = 1 + NR_OF_GREY // nbins lut = np.arange(NR_OF_GREY) lut //= bin_size img_blocks = view_as_blocks(image, (height, width))" 374,https://:@github.com/scikit-image/scikit-image.git,9a192bf1cb899632253619385ad9814dbd61f63a,"@@ -16,7 +16,7 @@ from skimage import graph, data, io, segmentation, color img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) -labels2 = graph.merge_hierarchical(g, labels, 40) +labels2 = graph.merge_hierarchical(labels, g, 40) g2 = graph.rag_mean_color(img, labels2) out = color.label2rgb(labels2, img, kind='avg') ",doc/examples/plot_rag_merge.py,"ArgSwap(idxs=0<->1 @(19,10)->(19,34))","from skimage import graph, data, io, segmentation, color img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) labels2 = graph.merge_hierarchical(g, labels, 40) g2 = graph.rag_mean_color(img, labels2) out = color.label2rgb(labels2, img, kind='avg')","from skimage import graph, data, io, segmentation, color img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) labels2 = graph.merge_hierarchical(labels, g, 40) g2 = graph.rag_mean_color(img, labels2) out = color.label2rgb(labels2, img, kind='avg')" 375,https://:@github.com/scikit-image/scikit-image.git,4bdde3d2aef2dd184e0b907983a15167326aec55,"@@ -254,7 +254,7 @@ class ImageCollection(object): if ((self.conserve_memory and n != self._cached) or (self.data[idx] is None)): if self._frame_index: - fname, img_num = self._frame_index[idx] + fname, img_num = self._frame_index[n] self.data[idx] = self.load_func(fname, img_num=img_num, **self.load_func_kwargs) else: ",skimage/io/collection.py,"ReplaceText(target='n' @(257,55)->(257,58))","class ImageCollection(object): if ((self.conserve_memory and n != self._cached) or (self.data[idx] is None)): if self._frame_index: fname, img_num = self._frame_index[idx] self.data[idx] = self.load_func(fname, img_num=img_num, **self.load_func_kwargs) else:","class ImageCollection(object): if ((self.conserve_memory and n != self._cached) or (self.data[idx] is None)): if self._frame_index: fname, img_num = self._frame_index[n] self.data[idx] = self.load_func(fname, img_num=img_num, **self.load_func_kwargs) else:" 376,https://:@github.com/scikit-image/scikit-image.git,84bcb583d76c1ec507b3d5794b6705d06383ced8,"@@ -288,7 +288,7 @@ def hessian_matrix_eigvals(Hxx, Hxy, Hyy): """""" - return _image_orthogonal_matrix22_eigvals(Hyy, Hxy, Hyy) + return _image_orthogonal_matrix22_eigvals(Hxx, Hxy, Hyy) def corner_kitchen_rosenfeld(image, mode='constant', cval=0): ",skimage/feature/corner.py,"ReplaceText(target='Hxx' @(291,46)->(291,49))","def hessian_matrix_eigvals(Hxx, Hxy, Hyy): """""" return _image_orthogonal_matrix22_eigvals(Hyy, Hxy, Hyy) def corner_kitchen_rosenfeld(image, mode='constant', cval=0):","def hessian_matrix_eigvals(Hxx, Hxy, Hyy): """""" return _image_orthogonal_matrix22_eigvals(Hxx, Hxy, Hyy) def corner_kitchen_rosenfeld(image, mode='constant', cval=0):" 377,https://:@github.com/scikit-image/scikit-image.git,33e36542d5f457a50c5fa00371fb9fe18a620f15,"@@ -84,7 +84,7 @@ def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, -min_angle:min_angle + 1] for dist_idx, angle_idx in coords: - accum = hspace[dist_idx, angle_idx] + accum = hspace_max[dist_idx, angle_idx] if accum > threshold: # absolute coordinate grid for local neighbourhood suppression dist_nh = dist_idx + dist_ext ",skimage/transform/hough_transform.py,"ReplaceText(target='hspace_max' @(87,16)->(87,22))","def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, -min_angle:min_angle + 1] for dist_idx, angle_idx in coords: accum = hspace[dist_idx, angle_idx] if accum > threshold: # absolute coordinate grid for local neighbourhood suppression dist_nh = dist_idx + dist_ext","def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, -min_angle:min_angle + 1] for dist_idx, angle_idx in coords: accum = hspace_max[dist_idx, angle_idx] if accum > threshold: # absolute coordinate grid for local neighbourhood suppression dist_nh = dist_idx + dist_ext" 378,https://:@github.com/scikit-image/scikit-image.git,bc52e4a411ab6d4aa10d38281e979158e6f21f19,"@@ -105,7 +105,7 @@ def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, angle_nh[angle_high] -= cols # suppress neighbourhood - hspace[dist_nh, angle_nh] = 0 + hspace_max[dist_nh, angle_nh] = 0 # add current line to peaks hspace_peaks.append(accum) ",skimage/transform/hough_transform.py,"ReplaceText(target='hspace_max' @(108,12)->(108,18))","def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, angle_nh[angle_high] -= cols # suppress neighbourhood hspace[dist_nh, angle_nh] = 0 # add current line to peaks hspace_peaks.append(accum)","def hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, angle_nh[angle_high] -= cols # suppress neighbourhood hspace_max[dist_nh, angle_nh] = 0 # add current line to peaks hspace_peaks.append(accum)" 379,https://:@github.com/scikit-image/scikit-image.git,2fb59b92435b9f67c091871cba701323b784ade7,"@@ -48,7 +48,7 @@ def imread(fname, dtype=None, img_num=None, **kwargs): im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: - im = Image.open(f) + im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) ",skimage/io/_plugins/pil_plugin.py,"ReplaceText(target='fname' @(51,24)->(51,25))","def imread(fname, dtype=None, img_num=None, **kwargs): im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) ","def imread(fname, dtype=None, img_num=None, **kwargs): im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) " 380,https://:@github.com/scikit-image/scikit-image.git,4ee3b2c5ac89f946a9b4bbf26665411bb7241ff4,"@@ -20,7 +20,7 @@ image = data.astronaut() rows, cols, dim = image.shape pyramid = tuple(pyramid_gaussian(image, downscale=2)) -composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) +composite_image = np.zeros((rows, cols + cols // 2, 3), dtype=np.double) composite_image[:rows, :cols, :] = pyramid[0] ",doc/examples/transform/plot_pyramid.py,"ReplaceText(target='//' @(23,46)->(23,47))","image = data.astronaut() rows, cols, dim = image.shape pyramid = tuple(pyramid_gaussian(image, downscale=2)) composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) composite_image[:rows, :cols, :] = pyramid[0] ","image = data.astronaut() rows, cols, dim = image.shape pyramid = tuple(pyramid_gaussian(image, downscale=2)) composite_image = np.zeros((rows, cols + cols // 2, 3), dtype=np.double) composite_image[:rows, :cols, :] = pyramid[0] " 381,https://:@github.com/scikit-image/scikit-image.git,472a420d86ff363cbb11df4e4b76ec090e0d015c,"@@ -634,7 +634,7 @@ def skeletonize_3d(image, *, img=None): raise ValueError(""skeletonize_3d can only handle 2D or 3D images; "" ""got image.ndim = %s instead."" % image.ndim) image = np.ascontiguousarray(image) - image = img_as_ubyte(img, force_copy=False) + image = img_as_ubyte(image, force_copy=False) # make an in image 3D and pad it w/ zeros to simplify dealing w/ boundaries # NB: careful here to not clobber the original *and* minimize copying ",skimage/morphology/_skeletonize.py,"ReplaceText(target='image' @(637,25)->(637,28))","def skeletonize_3d(image, *, img=None): raise ValueError(""skeletonize_3d can only handle 2D or 3D images; "" ""got image.ndim = %s instead."" % image.ndim) image = np.ascontiguousarray(image) image = img_as_ubyte(img, force_copy=False) # make an in image 3D and pad it w/ zeros to simplify dealing w/ boundaries # NB: careful here to not clobber the original *and* minimize copying","def skeletonize_3d(image, *, img=None): raise ValueError(""skeletonize_3d can only handle 2D or 3D images; "" ""got image.ndim = %s instead."" % image.ndim) image = np.ascontiguousarray(image) image = img_as_ubyte(image, force_copy=False) # make an in image 3D and pad it w/ zeros to simplify dealing w/ boundaries # NB: careful here to not clobber the original *and* minimize copying" 382,https://:@github.com/scikit-image/scikit-image.git,1539f238e52610f5e7607d5b447b5c491e3455eb,"@@ -242,7 +242,7 @@ def test_arraymap_update(): in_values = np.unique(np.random.randint(0, 200, size=5)) out_values = np.random.random(len(in_values)) m = ArrayMap(in_values, out_values) - image = np.random.randint(1, len(in_values), size=(512, 512)) + image = np.random.randint(1, len(m), size=(512, 512)) assert np.all(m[image] < 1) # missing values map to 0. m[1:] += 1 assert np.all(m[image] >= 1) ",skimage/segmentation/tests/test_join.py,"ReplaceText(target='m' @(245,37)->(245,46))","def test_arraymap_update(): in_values = np.unique(np.random.randint(0, 200, size=5)) out_values = np.random.random(len(in_values)) m = ArrayMap(in_values, out_values) image = np.random.randint(1, len(in_values), size=(512, 512)) assert np.all(m[image] < 1) # missing values map to 0. m[1:] += 1 assert np.all(m[image] >= 1)","def test_arraymap_update(): in_values = np.unique(np.random.randint(0, 200, size=5)) out_values = np.random.random(len(in_values)) m = ArrayMap(in_values, out_values) image = np.random.randint(1, len(m), size=(512, 512)) assert np.all(m[image] < 1) # missing values map to 0. m[1:] += 1 assert np.all(m[image] >= 1)" 383,https://:@github.com/globusonline/agamemnon.git,6460e336b2a3fd359364f85e39d6e3222077621e,"@@ -233,7 +233,7 @@ class DataStore(object): source_node_key = value elif column.startswith('source__'): source_attributes[column[8:]] = value - source = prim.Node(self, source_node_type, source_node_key, values) + source = prim.Node(self, source_node_type, source_node_key, source_attributes) rel_key = RELATIONSHIP_KEY_PATTERN % (rel_type, rel_key) return self.get_outgoing_relationship(rel_type, source, (rel_key, values)) ",agamemnon/factory.py,"ReplaceText(target='source_attributes' @(236,68)->(236,74))","class DataStore(object): source_node_key = value elif column.startswith('source__'): source_attributes[column[8:]] = value source = prim.Node(self, source_node_type, source_node_key, values) rel_key = RELATIONSHIP_KEY_PATTERN % (rel_type, rel_key) return self.get_outgoing_relationship(rel_type, source, (rel_key, values)) ","class DataStore(object): source_node_key = value elif column.startswith('source__'): source_attributes[column[8:]] = value source = prim.Node(self, source_node_type, source_node_key, source_attributes) rel_key = RELATIONSHIP_KEY_PATTERN % (rel_type, rel_key) return self.get_outgoing_relationship(rel_type, source, (rel_key, values)) " 384,https://:@github.com/chiptopher/guet.git,f95c54917b51e65f47789534ab88ecbede1838eb,"@@ -11,6 +11,6 @@ def _recursive_directory_find(path: Path, directory_name: str) -> str: raise FileNotFoundError() joined_with_driectory = path.joinpath(directory_name) if joined_with_driectory.is_dir(): - return str(joined_with_driectory) + return str(path) else: return _recursive_directory_find(path.parent, directory_name) ",guet/util/_recursive_directory_find.py,"ReplaceText(target='path' @(14,19)->(14,40))","def _recursive_directory_find(path: Path, directory_name: str) -> str: raise FileNotFoundError() joined_with_driectory = path.joinpath(directory_name) if joined_with_driectory.is_dir(): return str(joined_with_driectory) else: return _recursive_directory_find(path.parent, directory_name)","def _recursive_directory_find(path: Path, directory_name: str) -> str: raise FileNotFoundError() joined_with_driectory = path.joinpath(directory_name) if joined_with_driectory.is_dir(): return str(path) else: return _recursive_directory_find(path.parent, directory_name)" 385,https://:@github.com/justinsalamon/scaper.git,520ae608ebcbcc5e5438ca5c7967dc2479454038,"@@ -193,7 +193,7 @@ def generate_from_jams(jams_infile, audio_outfile, fg_path=None, bg_path=None, tfm.trim(sliceop['slice_start'], sliceop['slice_end']) tfm.build(audio_file, tmpfiles[-1].name) # Copy result back to original file - shutil.copyfile(tmpfiles[-1].name, audio_outfile) + shutil.copyfile(tmpfiles[-1].name, audio_file) # Optionally save new jams file if jams_outfile is not None: ",scaper/core.py,"ReplaceText(target='audio_file' @(196,55)->(196,68))","def generate_from_jams(jams_infile, audio_outfile, fg_path=None, bg_path=None, tfm.trim(sliceop['slice_start'], sliceop['slice_end']) tfm.build(audio_file, tmpfiles[-1].name) # Copy result back to original file shutil.copyfile(tmpfiles[-1].name, audio_outfile) # Optionally save new jams file if jams_outfile is not None:","def generate_from_jams(jams_infile, audio_outfile, fg_path=None, bg_path=None, tfm.trim(sliceop['slice_start'], sliceop['slice_end']) tfm.build(audio_file, tmpfiles[-1].name) # Copy result back to original file shutil.copyfile(tmpfiles[-1].name, audio_file) # Optionally save new jams file if jams_outfile is not None:" 386,https://:@github.com/markokr/rarfile.git,7fd6b2ca3efb81f7c4dffa6b6cef347b7d6ba043,"@@ -833,7 +833,7 @@ class RarFile: if dirs: dirs.sort(reverse=True) for dst, inf in dirs: - self._set_attrs(dst, inf) + self._set_attrs(inf, dst) def testrar(self, pwd=None): """"""Read all files and test CRC. ",rarfile.py,"ArgSwap(idxs=0<->1 @(836,16)->(836,31))","class RarFile: if dirs: dirs.sort(reverse=True) for dst, inf in dirs: self._set_attrs(dst, inf) def testrar(self, pwd=None): """"""Read all files and test CRC.","class RarFile: if dirs: dirs.sort(reverse=True) for dst, inf in dirs: self._set_attrs(inf, dst) def testrar(self, pwd=None): """"""Read all files and test CRC." 387,https://:@github.com/rougier/freetype-py.git,b21f15fb02eb44a656c250357665d1d7dc50bef6,"@@ -44,7 +44,7 @@ if __name__ == '__main__': y = height-baseline-top kerning = face.get_kerning(previous, c) x += (kerning.x >> 6) - Z[y:y+h,x:x+w] |= numpy.array(bitmap.buffer).reshape(h,w) + Z[y:y+h,x:x+w] += numpy.array(bitmap.buffer).reshape(h,w) x += (slot.advance.x >> 6) previous = c ",examples/hello-world.py,"ReplaceText(target='+=' @(47,23)->(47,25))","if __name__ == '__main__': y = height-baseline-top kerning = face.get_kerning(previous, c) x += (kerning.x >> 6) Z[y:y+h,x:x+w] |= numpy.array(bitmap.buffer).reshape(h,w) x += (slot.advance.x >> 6) previous = c ","if __name__ == '__main__': y = height-baseline-top kerning = face.get_kerning(previous, c) x += (kerning.x >> 6) Z[y:y+h,x:x+w] += numpy.array(bitmap.buffer).reshape(h,w) x += (slot.advance.x >> 6) previous = c " 388,https://:@github.com/piotrmaslanka/satella.git,24018c366401278a79da72097f1c594c188f5220,"@@ -15,7 +15,7 @@ def _merge(v1, v2): if isinstance(v1, list) and isinstance(v2, list): v1.extend(v2) - return v2 + return v1 raise TypeError ",satella/coding/algos.py,"ReplaceText(target='v1' @(18,15)->(18,17))","def _merge(v1, v2): if isinstance(v1, list) and isinstance(v2, list): v1.extend(v2) return v2 raise TypeError ","def _merge(v1, v2): if isinstance(v1, list) and isinstance(v2, list): v1.extend(v2) return v1 raise TypeError " 389,https://:@github.com/piotrmaslanka/satella.git,4828537442e39bd6592413a5b4a2421a079edc91,"@@ -194,7 +194,7 @@ class Heap(object): :return: Iterator """""" while self: - if self.heap[0] >= less: + if self.heap[0] < less: return yield self.pop() ",satella/coding/structures.py,"ReplaceText(target='<' @(197,28)->(197,30))","class Heap(object): :return: Iterator """""" while self: if self.heap[0] >= less: return yield self.pop() ","class Heap(object): :return: Iterator """""" while self: if self.heap[0] < less: return yield self.pop() " 390,https://:@github.com/piotrmaslanka/satella.git,fab19fa60841455e2ec0ec4493c618b7f5225f7d,"@@ -35,7 +35,7 @@ class MeasurableMixin: elapsed = value_getter() - future.old_value self.handle(logging_level, elapsed, **labels) - future.add_done_callback(future) + future.add_done_callback(on_future_done) def measure(self, include_exceptions: bool = True, logging_level: MetricLevel = MetricLevel.RUNTIME, ",satella/instrumentation/metrics/metric_types/measurable_mixin.py,"ReplaceText(target='on_future_done' @(38,33)->(38,39))","class MeasurableMixin: elapsed = value_getter() - future.old_value self.handle(logging_level, elapsed, **labels) future.add_done_callback(future) def measure(self, include_exceptions: bool = True, logging_level: MetricLevel = MetricLevel.RUNTIME,","class MeasurableMixin: elapsed = value_getter() - future.old_value self.handle(logging_level, elapsed, **labels) future.add_done_callback(on_future_done) def measure(self, include_exceptions: bool = True, logging_level: MetricLevel = MetricLevel.RUNTIME," 391,https://:@github.com/piotrmaslanka/satella.git,a9b866bd76586a440918130d52ca933529ac521a,"@@ -117,7 +117,7 @@ class Proxy(tp.Generic[T]): return self.__obj or other def __and__(self, other): - return self.__obj or other + return self.__obj and other def __le__(self, other): return self.__obj <= other ",satella/coding/structures/proxy.py,"ReplaceText(target='and' @(120,26)->(120,28))","class Proxy(tp.Generic[T]): return self.__obj or other def __and__(self, other): return self.__obj or other def __le__(self, other): return self.__obj <= other","class Proxy(tp.Generic[T]): return self.__obj or other def __and__(self, other): return self.__obj and other def __le__(self, other): return self.__obj <= other" 392,https://:@github.com/dmlc/keras.git,2662d81a9c925501831f0acb805c9e8adcde0a32,"@@ -160,7 +160,7 @@ class Adam(Optimizer): m_b_t = m_t / (1 - beta_1_t) v_b_t = v_t / (1 - beta_2_t) - p_t = p - self.lr * m_b_t / (T.sqrt(v_t) + self.epsilon) + p_t = p - self.lr * m_b_t / (T.sqrt(v_b_t) + self.epsilon) updates.append((m, m_t)) updates.append((v, v_t)) ",keras/optimizers.py,"ReplaceText(target='v_b_t' @(163,48)->(163,51))","class Adam(Optimizer): m_b_t = m_t / (1 - beta_1_t) v_b_t = v_t / (1 - beta_2_t) p_t = p - self.lr * m_b_t / (T.sqrt(v_t) + self.epsilon) updates.append((m, m_t)) updates.append((v, v_t))","class Adam(Optimizer): m_b_t = m_t / (1 - beta_1_t) v_b_t = v_t / (1 - beta_2_t) p_t = p - self.lr * m_b_t / (T.sqrt(v_b_t) + self.epsilon) updates.append((m, m_t)) updates.append((v, v_t))" 393,https://:@github.com/dmlc/keras.git,cc10c4d907d959eb9009ad502c727542a5259613,"@@ -69,7 +69,7 @@ def skipgrams(sequence, vocabulary_size, if not wi: continue if sampling_table is not None: - if sampling_table[i] < random.random(): + if sampling_table[wi] < random.random(): continue window_start = max(0, i-window_size) ",keras/preprocessing/sequence.py,"ReplaceText(target='wi' @(72,30)->(72,31))","def skipgrams(sequence, vocabulary_size, if not wi: continue if sampling_table is not None: if sampling_table[i] < random.random(): continue window_start = max(0, i-window_size)","def skipgrams(sequence, vocabulary_size, if not wi: continue if sampling_table is not None: if sampling_table[wi] < random.random(): continue window_start = max(0, i-window_size)" 394,https://:@github.com/dmlc/keras.git,e3695591704a21c6d0d6236c11c1bad7de4e314c,"@@ -58,7 +58,7 @@ class SimpleRNN(Layer): mask = T.addbroadcast(mask[:, :, np.newaxis], 2) mask_tm1 = alloc_zeros_matrix(*mask.shape) - mask_tm1 = T.addbroadcast(T.set_subtensor(mask[1:, :, :], mask[:-1, :, :]), 2) + mask_tm1 = T.addbroadcast(T.set_subtensor(mask_tm1[1:, :, :], mask[:-1, :, :]), 2) # scan = theano symbolic loop. # See: http://deeplearning.net/software/theano/library/scan.html ",keras/layers/recurrent.py,"ReplaceText(target='mask_tm1' @(61,50)->(61,54))","class SimpleRNN(Layer): mask = T.addbroadcast(mask[:, :, np.newaxis], 2) mask_tm1 = alloc_zeros_matrix(*mask.shape) mask_tm1 = T.addbroadcast(T.set_subtensor(mask[1:, :, :], mask[:-1, :, :]), 2) # scan = theano symbolic loop. # See: http://deeplearning.net/software/theano/library/scan.html","class SimpleRNN(Layer): mask = T.addbroadcast(mask[:, :, np.newaxis], 2) mask_tm1 = alloc_zeros_matrix(*mask.shape) mask_tm1 = T.addbroadcast(T.set_subtensor(mask_tm1[1:, :, :], mask[:-1, :, :]), 2) # scan = theano symbolic loop. # See: http://deeplearning.net/software/theano/library/scan.html" 395,https://:@github.com/dmlc/keras.git,c315b0d7a95b6677452300bdefd526b444951819,"@@ -218,7 +218,7 @@ class GaussianNoise(MaskedLayer): def get_output(self, train=False): X = self.get_input(train) - if train or self.sigma == 0: + if not train or self.sigma == 0: return X else: return X + srng.normal(size=X.shape, avg=0.0, std=self.sigma, ",keras/layers/core.py,"ReplaceText(target='not ' @(221,11)->(221,11))","class GaussianNoise(MaskedLayer): def get_output(self, train=False): X = self.get_input(train) if train or self.sigma == 0: return X else: return X + srng.normal(size=X.shape, avg=0.0, std=self.sigma,","class GaussianNoise(MaskedLayer): def get_output(self, train=False): X = self.get_input(train) if not train or self.sigma == 0: return X else: return X + srng.normal(size=X.shape, avg=0.0, std=self.sigma," 396,https://:@github.com/dmlc/keras.git,46a2fb6fd8e52b02df78f1416cc9fbd4b3156604,"@@ -42,7 +42,7 @@ class Optimizer(object): grads = [clip_norm(g, self.clipnorm, norm) for g in grads] if hasattr(self, 'clipvalue') and self.clipvalue > 0: - grads = [T.clip(g, self.clipvalue, -self.clipvalue) for g in grads] + grads = [T.clip(g, -self.clipvalue, self.clipvalue) for g in grads] return grads ",keras/optimizers.py,"ArgSwap(idxs=1<->2 @(45,21)->(45,27))","class Optimizer(object): grads = [clip_norm(g, self.clipnorm, norm) for g in grads] if hasattr(self, 'clipvalue') and self.clipvalue > 0: grads = [T.clip(g, self.clipvalue, -self.clipvalue) for g in grads] return grads ","class Optimizer(object): grads = [clip_norm(g, self.clipnorm, norm) for g in grads] if hasattr(self, 'clipvalue') and self.clipvalue > 0: grads = [T.clip(g, -self.clipvalue, self.clipvalue) for g in grads] return grads " 397,https://:@github.com/dmlc/keras.git,c2534964b76015eb3d76261b025c7556b354764c,"@@ -158,7 +158,7 @@ class SimpleRNN(Recurrent): assert len(states) == 1 prev_output = states[0] h = K.dot(x, self.W) + self.b - output = self.activation(h * K.dot(prev_output, self.U)) + output = self.activation(h + K.dot(prev_output, self.U)) return output, [output] def get_config(self): ",keras/layers/recurrent.py,"ReplaceText(target='+' @(161,35)->(161,36))","class SimpleRNN(Recurrent): assert len(states) == 1 prev_output = states[0] h = K.dot(x, self.W) + self.b output = self.activation(h * K.dot(prev_output, self.U)) return output, [output] def get_config(self):","class SimpleRNN(Recurrent): assert len(states) == 1 prev_output = states[0] h = K.dot(x, self.W) + self.b output = self.activation(h + K.dot(prev_output, self.U)) return output, [output] def get_config(self):" 398,https://:@github.com/dmlc/keras.git,3d51a26749937cb1a1aec40c20bc505e82809dce,"@@ -449,7 +449,7 @@ class Graph(Layer): self.namespace.add(sh_name) self.nodes[sh_name] = sh self.node_config.append({'name': sh_name, - 'inputs': [s], + 'inputs': [name], 'create_output': create_output}) if create_output: self.add_output(sh_name, input=sh_name) ",keras/layers/containers.py,"ReplaceText(target='name' @(452,52)->(452,53))","class Graph(Layer): self.namespace.add(sh_name) self.nodes[sh_name] = sh self.node_config.append({'name': sh_name, 'inputs': [s], 'create_output': create_output}) if create_output: self.add_output(sh_name, input=sh_name)","class Graph(Layer): self.namespace.add(sh_name) self.nodes[sh_name] = sh self.node_config.append({'name': sh_name, 'inputs': [name], 'create_output': create_output}) if create_output: self.add_output(sh_name, input=sh_name)" 399,https://:@github.com/dmlc/keras.git,42b3d37a54545882699283b5764cf3c997f8d9cd,"@@ -43,7 +43,7 @@ def test_skipgrams(): couples, labels = skipgrams(np.arange(5), vocabulary_size=5, window_size=1, categorical=True) for couple in couples: - assert couple[0] - couple[1] < 3 + assert couple[0] - couple[1] <= 3 for l in labels: assert len(l) == 2 ",tests/keras/preprocessing/test_sequence.py,"ReplaceText(target='<=' @(46,37)->(46,38))","def test_skipgrams(): couples, labels = skipgrams(np.arange(5), vocabulary_size=5, window_size=1, categorical=True) for couple in couples: assert couple[0] - couple[1] < 3 for l in labels: assert len(l) == 2 ","def test_skipgrams(): couples, labels = skipgrams(np.arange(5), vocabulary_size=5, window_size=1, categorical=True) for couple in couples: assert couple[0] - couple[1] <= 3 for l in labels: assert len(l) == 2 " 400,https://:@github.com/dmlc/keras.git,e2e281e14f619d9ade61c46567e2c599db070f16,"@@ -23,7 +23,7 @@ def test_unitnorm_constraint(): lookup.compile(loss='binary_crossentropy', optimizer='sgd', class_mode='binary') lookup.train_on_batch(X1, np.array([[1], [0]], dtype='int32')) - norm = np.linalg.norm(K.get_value(lookup.params[0]), axis=1) + norm = np.linalg.norm(K.get_value(lookup.params[0]), axis=0) assert_allclose(norm, np.ones_like(norm).astype('float32'), rtol=1e-05) ",tests/keras/layers/test_embeddings.py,"ReplaceText(target='0' @(26,62)->(26,63))","def test_unitnorm_constraint(): lookup.compile(loss='binary_crossentropy', optimizer='sgd', class_mode='binary') lookup.train_on_batch(X1, np.array([[1], [0]], dtype='int32')) norm = np.linalg.norm(K.get_value(lookup.params[0]), axis=1) assert_allclose(norm, np.ones_like(norm).astype('float32'), rtol=1e-05) ","def test_unitnorm_constraint(): lookup.compile(loss='binary_crossentropy', optimizer='sgd', class_mode='binary') lookup.train_on_batch(X1, np.array([[1], [0]], dtype='int32')) norm = np.linalg.norm(K.get_value(lookup.params[0]), axis=0) assert_allclose(norm, np.ones_like(norm).astype('float32'), rtol=1e-05) " 401,https://:@github.com/dmlc/keras.git,e2e281e14f619d9ade61c46567e2c599db070f16,"@@ -54,7 +54,7 @@ def test_identity_oddballs(): def test_unitnorm(): unitnorm_instance = constraints.unitnorm() normalized = unitnorm_instance(K.variable(example_array)) - norm_of_normalized = np.sqrt(np.sum(K.eval(normalized)**2, axis=1)) + norm_of_normalized = np.sqrt(np.sum(K.eval(normalized)**2, axis=0)) # in the unit norm constraint, it should be equal to 1. difference = norm_of_normalized - 1. largest_difference = np.max(np.abs(difference)) ",tests/keras/test_constraints.py,"ReplaceText(target='0' @(57,68)->(57,69))","def test_identity_oddballs(): def test_unitnorm(): unitnorm_instance = constraints.unitnorm() normalized = unitnorm_instance(K.variable(example_array)) norm_of_normalized = np.sqrt(np.sum(K.eval(normalized)**2, axis=1)) # in the unit norm constraint, it should be equal to 1. difference = norm_of_normalized - 1. largest_difference = np.max(np.abs(difference))","def test_identity_oddballs(): def test_unitnorm(): unitnorm_instance = constraints.unitnorm() normalized = unitnorm_instance(K.variable(example_array)) norm_of_normalized = np.sqrt(np.sum(K.eval(normalized)**2, axis=0)) # in the unit norm constraint, it should be equal to 1. difference = norm_of_normalized - 1. largest_difference = np.max(np.abs(difference))" 402,https://:@github.com/dmlc/keras.git,f4af11c7300816ca28b6b707fdf7d64b00430074,"@@ -52,7 +52,7 @@ def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncati elif truncating == 'post': trunc = s[:maxlen] else: - raise ValueError(""Truncating type '%s' not understood"" % padding) + raise ValueError(""Truncating type '%s' not understood"" % truncating) # check `trunc` has expected shape trunc = np.asarray(trunc, dtype=dtype) ",keras/preprocessing/sequence.py,"ReplaceText(target='truncating' @(55,69)->(55,76))","def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncati elif truncating == 'post': trunc = s[:maxlen] else: raise ValueError(""Truncating type '%s' not understood"" % padding) # check `trunc` has expected shape trunc = np.asarray(trunc, dtype=dtype)","def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncati elif truncating == 'post': trunc = s[:maxlen] else: raise ValueError(""Truncating type '%s' not understood"" % truncating) # check `trunc` has expected shape trunc = np.asarray(trunc, dtype=dtype)" 403,https://:@github.com/dmlc/keras.git,b61235b77f87288d62ddd8ce4aae88b76babf887,"@@ -153,7 +153,7 @@ def check_array_lengths(X, Y, W): raise Exception('All input arrays (x) should have ' 'the same number of samples.') set_y = set(y_lengths) - if len(set_x) != 1: + if len(set_y) != 1: raise Exception('All target arrays (y) should have ' 'the same number of samples.') set_w = set(w_lengths) ",keras/engine/training.py,"ReplaceText(target='set_y' @(156,11)->(156,16))","def check_array_lengths(X, Y, W): raise Exception('All input arrays (x) should have ' 'the same number of samples.') set_y = set(y_lengths) if len(set_x) != 1: raise Exception('All target arrays (y) should have ' 'the same number of samples.') set_w = set(w_lengths)","def check_array_lengths(X, Y, W): raise Exception('All input arrays (x) should have ' 'the same number of samples.') set_y = set(y_lengths) if len(set_y) != 1: raise Exception('All target arrays (y) should have ' 'the same number of samples.') set_w = set(w_lengths)" 404,https://:@github.com/dmlc/keras.git,98974efa5f51d6f55afbf2bc125d6fd090bcf782,"@@ -510,7 +510,7 @@ class Model(Container): 'it should have one entry per model outputs. ' 'The model has ' + str(len(self.outputs)) + ' outputs, but you passed loss_weights=' + - str(loss)) + str(loss_weights)) loss_weights_list = loss_weights else: raise Exception('Could not interpret loss_weights argument: ' + ",keras/engine/training.py,"ReplaceText(target='loss_weights' @(513,36)->(513,40))","class Model(Container): 'it should have one entry per model outputs. ' 'The model has ' + str(len(self.outputs)) + ' outputs, but you passed loss_weights=' + str(loss)) loss_weights_list = loss_weights else: raise Exception('Could not interpret loss_weights argument: ' +","class Model(Container): 'it should have one entry per model outputs. ' 'The model has ' + str(len(self.outputs)) + ' outputs, but you passed loss_weights=' + str(loss_weights)) loss_weights_list = loss_weights else: raise Exception('Could not interpret loss_weights argument: ' +" 405,https://:@github.com/dmlc/keras.git,48ae7217e482a1a3624d6e5380c972a653cacfaf,"@@ -1136,7 +1136,7 @@ def rnn(step_function, inputs, initial_states, if mask is not None: if go_backwards: - mask = tf.reverse(mask, [True] + [False] * (ndim - 1)) + mask = tf.reverse(mask, [True] + [False] * (ndim - 2)) # Transpose not supported by bool tensor types, hence round-trip to uint8. mask = tf.cast(mask, tf.uint8) ",keras/backend/tensorflow_backend.py,"ReplaceText(target='2' @(1139,67)->(1139,68))","def rnn(step_function, inputs, initial_states, if mask is not None: if go_backwards: mask = tf.reverse(mask, [True] + [False] * (ndim - 1)) # Transpose not supported by bool tensor types, hence round-trip to uint8. mask = tf.cast(mask, tf.uint8)","def rnn(step_function, inputs, initial_states, if mask is not None: if go_backwards: mask = tf.reverse(mask, [True] + [False] * (ndim - 2)) # Transpose not supported by bool tensor types, hence round-trip to uint8. mask = tf.cast(mask, tf.uint8)" 406,https://:@github.com/dmlc/keras.git,41741c38e5f29ebf69fe9bd82a604eba3c0b97e5,"@@ -1261,7 +1261,7 @@ def rnn(step_function, inputs, initial_states, new_state = new_states[0] else: # return dummy state, otherwise _dynamic_rnn_loop breaks - new_state = output + new_state = state return output, new_state _step.state_size = state_size * nb_states ",keras/backend/tensorflow_backend.py,"ReplaceText(target='state' @(1264,32)->(1264,38))","def rnn(step_function, inputs, initial_states, new_state = new_states[0] else: # return dummy state, otherwise _dynamic_rnn_loop breaks new_state = output return output, new_state _step.state_size = state_size * nb_states","def rnn(step_function, inputs, initial_states, new_state = new_states[0] else: # return dummy state, otherwise _dynamic_rnn_loop breaks new_state = state return output, new_state _step.state_size = state_size * nb_states" 407,https://:@github.com/dmlc/keras.git,80fbbc3a6a2a30f391bad2aa85e7558c50ca0709,"@@ -411,7 +411,7 @@ class ImageDataGenerator(object): if self.zca_whitening: flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3])) - sigma = np.dot(flatX.T, flatX) / flatX.shape[1] + sigma = np.dot(flatX.T, flatX) / flatX.shape[0] U, S, V = linalg.svd(sigma) self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T) ",keras/preprocessing/image.py,"ReplaceText(target='0' @(414,57)->(414,58))","class ImageDataGenerator(object): if self.zca_whitening: flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3])) sigma = np.dot(flatX.T, flatX) / flatX.shape[1] U, S, V = linalg.svd(sigma) self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T) ","class ImageDataGenerator(object): if self.zca_whitening: flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3])) sigma = np.dot(flatX.T, flatX) / flatX.shape[0] U, S, V = linalg.svd(sigma) self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T) " 408,https://:@github.com/dmlc/keras.git,7bd5c862a271f125a76fa1ada7f0d9ae27159549,"@@ -209,7 +209,7 @@ def check_loss_and_target_compatibility(targets, losses, output_shapes): 'which does expect integer targets.') if loss.__name__ in key_losses: for target_dim, out_dim in zip(y.shape[1:], shape[1:]): - if target_dim is not None and target_dim != out_dim: + if out_dim is not None and target_dim != out_dim: raise Exception('A target array with shape ' + str(y.shape) + ' was passed for an output of shape ' + str(shape) + ' while using as loss `' + loss.__name__ + '`. ' ",keras/engine/training.py,"ReplaceText(target='out_dim' @(212,19)->(212,29))","def check_loss_and_target_compatibility(targets, losses, output_shapes): 'which does expect integer targets.') if loss.__name__ in key_losses: for target_dim, out_dim in zip(y.shape[1:], shape[1:]): if target_dim is not None and target_dim != out_dim: raise Exception('A target array with shape ' + str(y.shape) + ' was passed for an output of shape ' + str(shape) + ' while using as loss `' + loss.__name__ + '`. '","def check_loss_and_target_compatibility(targets, losses, output_shapes): 'which does expect integer targets.') if loss.__name__ in key_losses: for target_dim, out_dim in zip(y.shape[1:], shape[1:]): if out_dim is not None and target_dim != out_dim: raise Exception('A target array with shape ' + str(y.shape) + ' was passed for an output of shape ' + str(shape) + ' while using as loss `' + loss.__name__ + '`. '" 409,https://:@github.com/dmlc/keras.git,cb4f93913eb871a5e234db0c31f885daff87ecdf,"@@ -67,7 +67,7 @@ def _obtain_input_shape(input_shape, default_size, min_size, dim_ordering, inclu if input_shape is not None: if len(input_shape) != 3: raise ValueError('`input_shape` must be a tuple of three integers.') - if input_shape[1] != 3: + if input_shape[0] != 3: raise ValueError('The input must have 3 channels; got ' '`input_shape=' + str(input_shape) + '`') if ((input_shape[1] is not None and input_shape[1] < min_size) or ",keras/applications/imagenet_utils.py,"ReplaceText(target='0' @(70,31)->(70,32))","def _obtain_input_shape(input_shape, default_size, min_size, dim_ordering, inclu if input_shape is not None: if len(input_shape) != 3: raise ValueError('`input_shape` must be a tuple of three integers.') if input_shape[1] != 3: raise ValueError('The input must have 3 channels; got ' '`input_shape=' + str(input_shape) + '`') if ((input_shape[1] is not None and input_shape[1] < min_size) or","def _obtain_input_shape(input_shape, default_size, min_size, dim_ordering, inclu if input_shape is not None: if len(input_shape) != 3: raise ValueError('`input_shape` must be a tuple of three integers.') if input_shape[0] != 3: raise ValueError('The input must have 3 channels; got ' '`input_shape=' + str(input_shape) + '`') if ((input_shape[1] is not None and input_shape[1] < min_size) or" 410,https://:@github.com/dmlc/keras.git,82ca6d418588ccd61d663ec8029937290b62d583,"@@ -120,7 +120,7 @@ X = X[indices] y = y[indices] # Explicitly set apart 10% for validation data that we never train over -split_at = len(X) - len(X) / 10 +split_at = len(X) - len(X) // 10 (X_train, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at)) (y_train, y_val) = (y[:split_at], y[split_at:]) ",examples/addition_rnn.py,"ReplaceText(target='//' @(123,27)->(123,28))","X = X[indices] y = y[indices] # Explicitly set apart 10% for validation data that we never train over split_at = len(X) - len(X) / 10 (X_train, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at)) (y_train, y_val) = (y[:split_at], y[split_at:]) ","X = X[indices] y = y[indices] # Explicitly set apart 10% for validation data that we never train over split_at = len(X) - len(X) // 10 (X_train, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at)) (y_train, y_val) = (y[:split_at], y[split_at:]) " 411,https://:@github.com/dmlc/keras.git,7c34add25d0f6a773f1c74d1d8bb50f4482afc76,"@@ -1875,7 +1875,7 @@ def set_value(x, value): """"""Sets the value of a variable, from a Numpy array. It returns `None`. """""" - if isinstance(x, Number): + if isinstance(value, Number): value = [value] x.bind(mx.nd.array(value)) ",keras/backend/mxnet_backend.py,"ReplaceText(target='value' @(1878,18)->(1878,19))","def set_value(x, value): """"""Sets the value of a variable, from a Numpy array. It returns `None`. """""" if isinstance(x, Number): value = [value] x.bind(mx.nd.array(value)) ","def set_value(x, value): """"""Sets the value of a variable, from a Numpy array. It returns `None`. """""" if isinstance(value, Number): value = [value] x.bind(mx.nd.array(value)) " 412,https://:@github.com/incountry/sdk-python.git,e98e4243dae300a5ae9cab87347fa61bb87b51a9,"@@ -28,6 +28,6 @@ storage = Storage( while not migration_complete: migration_res = storage.migrate(country=COUNTRY, limit=50) - if migration_res[""total_left""] <= 0: + if migration_res[""total_left""] == 0: migration_complete = True time.sleep(1) ",examples/full_migration.py,"ReplaceText(target='==' @(31,35)->(31,37))","storage = Storage( while not migration_complete: migration_res = storage.migrate(country=COUNTRY, limit=50) if migration_res[""total_left""] <= 0: migration_complete = True time.sleep(1)","storage = Storage( while not migration_complete: migration_res = storage.migrate(country=COUNTRY, limit=50) if migration_res[""total_left""] == 0: migration_complete = True time.sleep(1)" 413,https://:@github.com/knockrentals/scrapy-elasticsearch.git,1c5c20459e68544eeb8a0490b9f7b14895861b24,"@@ -96,7 +96,7 @@ class ElasticSearchPipeline(object): self.items_buffer.append(index_action) - if len(self.items_buffer) == self.settings.get('ELASTICSEARCH_BUFFER_LENGTH', 500): + if len(self.items_buffer) >= self.settings.get('ELASTICSEARCH_BUFFER_LENGTH', 500): self.send_items() self.items_buffer = [] ",scrapyelasticsearch/scrapyelasticsearch.py,"ReplaceText(target='>=' @(99,34)->(99,36))","class ElasticSearchPipeline(object): self.items_buffer.append(index_action) if len(self.items_buffer) == self.settings.get('ELASTICSEARCH_BUFFER_LENGTH', 500): self.send_items() self.items_buffer = [] ","class ElasticSearchPipeline(object): self.items_buffer.append(index_action) if len(self.items_buffer) >= self.settings.get('ELASTICSEARCH_BUFFER_LENGTH', 500): self.send_items() self.items_buffer = [] " 414,https://:@github.com/smithlabcode/ribotricer.git,805255ef81f4c94dcaf9f0c63ba39f0de7f14eea,"@@ -149,7 +149,7 @@ def detect_orfs_cmd(bam, ribocop_index, prefix, stranded, read_lengths, sys.exit('Error: cannot convert psite_offsets into integers') if len(read_lengths) != len(psite_offsets): sys.exit('Error: psite_offsets must match read_lengths') - if not all(x > 0 for x in psite_offsets): + if not all(x >= 0 for x in psite_offsets): sys.exit('Error: P-site offset must be >= 0') if not all(x > y for (x, y) in zip(read_lengths, psite_offsets)): sys.exit('Error: P-site offset must be smaller than read length') ",RiboCop/cli.py,"ReplaceText(target='>=' @(152,21)->(152,22))","def detect_orfs_cmd(bam, ribocop_index, prefix, stranded, read_lengths, sys.exit('Error: cannot convert psite_offsets into integers') if len(read_lengths) != len(psite_offsets): sys.exit('Error: psite_offsets must match read_lengths') if not all(x > 0 for x in psite_offsets): sys.exit('Error: P-site offset must be >= 0') if not all(x > y for (x, y) in zip(read_lengths, psite_offsets)): sys.exit('Error: P-site offset must be smaller than read length')","def detect_orfs_cmd(bam, ribocop_index, prefix, stranded, read_lengths, sys.exit('Error: cannot convert psite_offsets into integers') if len(read_lengths) != len(psite_offsets): sys.exit('Error: psite_offsets must match read_lengths') if not all(x >= 0 for x in psite_offsets): sys.exit('Error: P-site offset must be >= 0') if not all(x > y for (x, y) in zip(read_lengths, psite_offsets)): sys.exit('Error: P-site offset must be smaller than read length')" 415,https://:@github.com/smithlabcode/ribotricer.git,9e9c9497eb5c2669bd272729e19f47e2cbf2b3db,"@@ -321,7 +321,7 @@ def prepare_orfs(gtf, fasta, prefix, min_orf_length, start_codons, for orf in tqdm(candidate_orfs): coordinate = ','.join( ['{}-{}'.format(iv.start, iv.end) for iv in orf.intervals]) - to_write = formatter.format(orf.oid, orf.category, orf.tid, orf.ttype, + to_write += formatter.format(orf.oid, orf.category, orf.tid, orf.ttype, orf.gid, orf.gname, orf.gtype, orf.chrom, orf.strand, coordinate) ",RiboCop/prepare_orfs.py,"ReplaceText(target='+=' @(324,17)->(324,18))","def prepare_orfs(gtf, fasta, prefix, min_orf_length, start_codons, for orf in tqdm(candidate_orfs): coordinate = ','.join( ['{}-{}'.format(iv.start, iv.end) for iv in orf.intervals]) to_write = formatter.format(orf.oid, orf.category, orf.tid, orf.ttype, orf.gid, orf.gname, orf.gtype, orf.chrom, orf.strand, coordinate) ","def prepare_orfs(gtf, fasta, prefix, min_orf_length, start_codons, for orf in tqdm(candidate_orfs): coordinate = ','.join( ['{}-{}'.format(iv.start, iv.end) for iv in orf.intervals]) to_write += formatter.format(orf.oid, orf.category, orf.tid, orf.ttype, orf.gid, orf.gname, orf.gtype, orf.chrom, orf.strand, coordinate) " 416,https://:@github.com/pughlab/ConsensusCruncher.git,3622410b893b07afb4e423a4537eab33da26a55d,"@@ -147,7 +147,7 @@ def main(): sscs_bam = pysam.AlignmentFile(args.infile, ""rb"") dcs_bam = pysam.AlignmentFile(args.outfile, ""wb"", template=sscs_bam) - if re.search('dcs.sc', args.outfile) is None: + if re.search('dcs.sc', args.outfile) is not None: sscs_singleton_bam = pysam.AlignmentFile('{}.sscs.sc.singleton.bam'.format(args.outfile.split('.dcs.sc')[0]), ""wb"", template=sscs_bam) dcs_header = ""DCS - Singleton Correction"" ",ConsensusCruncher/DCS_maker.py,"ReplaceText(target=' is not ' @(150,40)->(150,44))","def main(): sscs_bam = pysam.AlignmentFile(args.infile, ""rb"") dcs_bam = pysam.AlignmentFile(args.outfile, ""wb"", template=sscs_bam) if re.search('dcs.sc', args.outfile) is None: sscs_singleton_bam = pysam.AlignmentFile('{}.sscs.sc.singleton.bam'.format(args.outfile.split('.dcs.sc')[0]), ""wb"", template=sscs_bam) dcs_header = ""DCS - Singleton Correction""","def main(): sscs_bam = pysam.AlignmentFile(args.infile, ""rb"") dcs_bam = pysam.AlignmentFile(args.outfile, ""wb"", template=sscs_bam) if re.search('dcs.sc', args.outfile) is not None: sscs_singleton_bam = pysam.AlignmentFile('{}.sscs.sc.singleton.bam'.format(args.outfile.split('.dcs.sc')[0]), ""wb"", template=sscs_bam) dcs_header = ""DCS - Singleton Correction""" 417,https://:@github.com/django-guardian/django-guardian.git,f60306eb93fd276879806d6e78557bdb5d1ce34f,"@@ -172,7 +172,7 @@ def get_obj_perms_model(obj, base_cls, generic_cls): for attr in fields: model = getattr(attr, 'related_model', None) if (model and issubclass(model, base_cls) and - model is not generic_cls and getattr(attr, 'enabled', True)): + model is not generic_cls and getattr(model, 'enabled', True)): # if model is generic one it would be returned anyway if not model.objects.is_generic(): # make sure that content_object's content_type is same as ",guardian/utils.py,"ReplaceText(target='model' @(175,53)->(175,57))","def get_obj_perms_model(obj, base_cls, generic_cls): for attr in fields: model = getattr(attr, 'related_model', None) if (model and issubclass(model, base_cls) and model is not generic_cls and getattr(attr, 'enabled', True)): # if model is generic one it would be returned anyway if not model.objects.is_generic(): # make sure that content_object's content_type is same as","def get_obj_perms_model(obj, base_cls, generic_cls): for attr in fields: model = getattr(attr, 'related_model', None) if (model and issubclass(model, base_cls) and model is not generic_cls and getattr(model, 'enabled', True)): # if model is generic one it would be returned anyway if not model.objects.is_generic(): # make sure that content_object's content_type is same as" 418,https://:@github.com/podhmo/magicalimport.git,293f619fee3f401ebe0daf55f001354ecf2a2124,"@@ -69,7 +69,7 @@ def import_symbol(sym, here=None, sep="":"", ns=None): sym = ""{}:{}"".format(ns, sym) module_path, fn_name = sym.rsplit(sep, 2) try: - module = import_module(sym, here=here, sep=sep) + module = import_module(module_path, here=here, sep=sep) return getattr(module, fn_name) except (ImportError, AttributeError) as e: sys.stderr.write(""could not import {!r}\n{}\n"".format(sym, e)) ",magicalimport/__init__.py,"ReplaceText(target='module_path' @(72,31)->(72,34))","def import_symbol(sym, here=None, sep="":"", ns=None): sym = ""{}:{}"".format(ns, sym) module_path, fn_name = sym.rsplit(sep, 2) try: module = import_module(sym, here=here, sep=sep) return getattr(module, fn_name) except (ImportError, AttributeError) as e: sys.stderr.write(""could not import {!r}\n{}\n"".format(sym, e))","def import_symbol(sym, here=None, sep="":"", ns=None): sym = ""{}:{}"".format(ns, sym) module_path, fn_name = sym.rsplit(sep, 2) try: module = import_module(module_path, here=here, sep=sep) return getattr(module, fn_name) except (ImportError, AttributeError) as e: sys.stderr.write(""could not import {!r}\n{}\n"".format(sym, e))" 419,https://:@github.com/sigmavirus24/betamax.git,9d84fcffbdf41133dbdd686490c993d63e0243fc,"@@ -112,7 +112,7 @@ def deserialize_response(serialized): for header_name, header_list in serialized['headers'].items(): if isinstance(header_list, list): for header_value in header_list: - header_dict.add(header_name, header_list) + header_dict.add(header_name, header_value) else: header_dict.add(header_name, header_list) r.headers = CaseInsensitiveDict(header_dict) ",betamax/cassette/util.py,"ReplaceText(target='header_value' @(115,45)->(115,56))","def deserialize_response(serialized): for header_name, header_list in serialized['headers'].items(): if isinstance(header_list, list): for header_value in header_list: header_dict.add(header_name, header_list) else: header_dict.add(header_name, header_list) r.headers = CaseInsensitiveDict(header_dict)","def deserialize_response(serialized): for header_name, header_list in serialized['headers'].items(): if isinstance(header_list, list): for header_value in header_list: header_dict.add(header_name, header_value) else: header_dict.add(header_name, header_list) r.headers = CaseInsensitiveDict(header_dict)" 420,https://:@github.com/CodyKochmann/generators.git,0c99248a9a96a675d6995855c4a9ae0efebef329,"@@ -17,7 +17,7 @@ def itemgetter(iterable, indexes): for i,x in enumerate(iterable): if i in positive_indexes: out[i]=x - negative_index_buffer.append(i) + negative_index_buffer.append(x) out.update({ni:negative_index_buffer[ni] for ni in negative_indexes}) else: # if just positive results ",generators/itemgetter.py,"ReplaceText(target='x' @(20,41)->(20,42))","def itemgetter(iterable, indexes): for i,x in enumerate(iterable): if i in positive_indexes: out[i]=x negative_index_buffer.append(i) out.update({ni:negative_index_buffer[ni] for ni in negative_indexes}) else: # if just positive results","def itemgetter(iterable, indexes): for i,x in enumerate(iterable): if i in positive_indexes: out[i]=x negative_index_buffer.append(x) out.update({ni:negative_index_buffer[ni] for ni in negative_indexes}) else: # if just positive results" 421,https://:@github.com/reiinakano/xcessiv.git,b197e370a6f8a46f6ba3e9b77fb76f150f28edd5,"@@ -146,7 +146,7 @@ def evaluate_stacked_ensemble(path, ensemble_id): ) preds = [] trues_list = [] - for train_index, test_index in cv.split(X, y): + for train_index, test_index in cv.split(secondary_features, y): X_train, X_test = secondary_features[train_index], secondary_features[test_index] y_train, y_test = y[train_index], y[test_index] est = est.fit(X_train, y_train) ",xcessiv/rqtasks.py,"ReplaceText(target='secondary_features' @(149,52)->(149,53))","def evaluate_stacked_ensemble(path, ensemble_id): ) preds = [] trues_list = [] for train_index, test_index in cv.split(X, y): X_train, X_test = secondary_features[train_index], secondary_features[test_index] y_train, y_test = y[train_index], y[test_index] est = est.fit(X_train, y_train)","def evaluate_stacked_ensemble(path, ensemble_id): ) preds = [] trues_list = [] for train_index, test_index in cv.split(secondary_features, y): X_train, X_test = secondary_features[train_index], secondary_features[test_index] y_train, y_test = y[train_index], y[test_index] est = est.fit(X_train, y_train)" 422,https://:@github.com/MosesofEgypt/mozzarilla.git,5c0f1e29111be71edbb67ef13094a0cdc83d760c,"@@ -684,7 +684,7 @@ def _compile_model_animations(self): print(error) self.update() - if messagebox.askyesno( + if not messagebox.askyesno( ""Model_animations compilation failed"", ""Errors occurred while compiling animations(check console). "" ""Do you want to save the model_animations tag anyway?"", ",mozzarilla/tools/animations_compiler_window.py,"ReplaceText(target='not ' @(687,15)->(687,15))","def _compile_model_animations(self): print(error) self.update() if messagebox.askyesno( ""Model_animations compilation failed"", ""Errors occurred while compiling animations(check console). "" ""Do you want to save the model_animations tag anyway?"",","def _compile_model_animations(self): print(error) self.update() if not messagebox.askyesno( ""Model_animations compilation failed"", ""Errors occurred while compiling animations(check console). "" ""Do you want to save the model_animations tag anyway?""," 423,https://:@github.com/HeeroYui/lutin.git,9fc593fb59a192ddf5f50a96e2a6cba76dab73b6,"@@ -23,7 +23,7 @@ class System(system.System): # no check needed ==> just add this: self.add_module_depend(['c']) self.add_export_flag('link-lib', 'X11') - if env.get_isolate_system() == False: + if env.get_isolate_system() == True: self.add_header_file([ ""/usr/include/X11/*"" ], ",lutin/z_system/lutinSystem_Linux_X11.py,"ReplaceText(target='True' @(26,33)->(26,38))","class System(system.System): # no check needed ==> just add this: self.add_module_depend(['c']) self.add_export_flag('link-lib', 'X11') if env.get_isolate_system() == False: self.add_header_file([ ""/usr/include/X11/*"" ],","class System(system.System): # no check needed ==> just add this: self.add_module_depend(['c']) self.add_export_flag('link-lib', 'X11') if env.get_isolate_system() == True: self.add_header_file([ ""/usr/include/X11/*"" ]," 424,https://:@github.com/sanger-pathogens/ariba.git,8625628cf307e533bb6e778d9b8e936e48cef727,"@@ -294,7 +294,7 @@ class ReferenceData: def sanity_check(self, outprefix): variants_only_removed = self._remove_bad_genes(self.seq_dicts['variants_only'], outprefix + '.00.check_fasta_variants_only.log') presence_absence_removed = self._remove_bad_genes(self.seq_dicts['presence_absence'], outprefix + '.00.check_fasta_presence_absence.log') - self._filter_bad_variant_data(outprefix + '.01.check_variants', variants_only_removed, presence_absence_removed) + self._filter_bad_variant_data(outprefix + '.01.check_variants', presence_absence_removed, variants_only_removed) @classmethod ",ariba/reference_data.py,"ArgSwap(idxs=1<->2 @(297,8)->(297,37))","class ReferenceData: def sanity_check(self, outprefix): variants_only_removed = self._remove_bad_genes(self.seq_dicts['variants_only'], outprefix + '.00.check_fasta_variants_only.log') presence_absence_removed = self._remove_bad_genes(self.seq_dicts['presence_absence'], outprefix + '.00.check_fasta_presence_absence.log') self._filter_bad_variant_data(outprefix + '.01.check_variants', variants_only_removed, presence_absence_removed) @classmethod","class ReferenceData: def sanity_check(self, outprefix): variants_only_removed = self._remove_bad_genes(self.seq_dicts['variants_only'], outprefix + '.00.check_fasta_variants_only.log') presence_absence_removed = self._remove_bad_genes(self.seq_dicts['presence_absence'], outprefix + '.00.check_fasta_presence_absence.log') self._filter_bad_variant_data(outprefix + '.01.check_variants', presence_absence_removed, variants_only_removed) @classmethod" 425,https://:@github.com/sanger-pathogens/ariba.git,c70bc90299a1c5a85f20127ac8c750925219316b,"@@ -192,7 +192,7 @@ class Summary: if self.show_known_het and (cluster, variant) in all_het_snps: rows[filename][cluster][key + '.%'] = 'NA' - if self.show_known_het and (ref_name, variant) in all_het_snps and key + '.%' not in rows[filename][cluster]: + if self.show_known_het and (cluster, variant) in all_het_snps and key + '.%' not in rows[filename][cluster]: rows[filename][cluster][key + '.%'] = 'NA' for key, wanted in self.cluster_columns.items(): ",ariba/summary.py,"ReplaceText(target='cluster' @(195,52)->(195,60))","class Summary: if self.show_known_het and (cluster, variant) in all_het_snps: rows[filename][cluster][key + '.%'] = 'NA' if self.show_known_het and (ref_name, variant) in all_het_snps and key + '.%' not in rows[filename][cluster]: rows[filename][cluster][key + '.%'] = 'NA' for key, wanted in self.cluster_columns.items():","class Summary: if self.show_known_het and (cluster, variant) in all_het_snps: rows[filename][cluster][key + '.%'] = 'NA' if self.show_known_het and (cluster, variant) in all_het_snps and key + '.%' not in rows[filename][cluster]: rows[filename][cluster][key + '.%'] = 'NA' for key, wanted in self.cluster_columns.items():" 426,https://:@github.com/sanger-pathogens/ariba.git,1fd2c639e7b24a69252390744ae4e1a9e49db5dd,"@@ -47,7 +47,7 @@ class MlstReporter: depths = [int(x) for x in d['smtls_nts_depth'].split(',')] depths.sort() het_pc = round(100.0 * depths[-1] / sum(depths), 2) - if results['hetmin'] == '.' or results['hetmin'] < het_pc: + if results['hetmin'] == '.' or results['hetmin'] > het_pc: results['hetmin'] = het_pc if len(het_data): results['hets'] = '.'.join(het_data) ",ariba/mlst_reporter.py,"ReplaceText(target='>' @(50,69)->(50,70))","class MlstReporter: depths = [int(x) for x in d['smtls_nts_depth'].split(',')] depths.sort() het_pc = round(100.0 * depths[-1] / sum(depths), 2) if results['hetmin'] == '.' or results['hetmin'] < het_pc: results['hetmin'] = het_pc if len(het_data): results['hets'] = '.'.join(het_data)","class MlstReporter: depths = [int(x) for x in d['smtls_nts_depth'].split(',')] depths.sort() het_pc = round(100.0 * depths[-1] / sum(depths), 2) if results['hetmin'] == '.' or results['hetmin'] > het_pc: results['hetmin'] = het_pc if len(het_data): results['hets'] = '.'.join(het_data)" 427,https://:@github.com/urschrei/pyzotero.git,cdfd191116363c947fc0a0d0b4f37849d709f9f2,"@@ -40,7 +40,7 @@ def check(): return library_version == git_version if __name__ == '__main__': - if check(): + if not check(): sys.exit(1) else: sys.exit(0) ",pre-deploy.py,"ReplaceText(target='not ' @(43,7)->(43,7))","def check(): return library_version == git_version if __name__ == '__main__': if check(): sys.exit(1) else: sys.exit(0)","def check(): return library_version == git_version if __name__ == '__main__': if not check(): sys.exit(1) else: sys.exit(0)" 428,https://:@github.com/lyft/confidant.git,5de06bb144ad392dba5ef9c75603eb9587dfcfe3,"@@ -410,7 +410,7 @@ def update_credential(id): include_credential_pairs=True, ) credential_response.permissions = permissions - return credential_response_schema.dumps(permissions) + return credential_response_schema.dumps(credential_response) @blueprint.route('/v1/credentials//', methods=['PUT']) ",confidant/routes/credentials.py,"ReplaceText(target='credential_response' @(413,44)->(413,55))","def update_credential(id): include_credential_pairs=True, ) credential_response.permissions = permissions return credential_response_schema.dumps(permissions) @blueprint.route('/v1/credentials//', methods=['PUT'])","def update_credential(id): include_credential_pairs=True, ) credential_response.permissions = permissions return credential_response_schema.dumps(credential_response) @blueprint.route('/v1/credentials//', methods=['PUT'])" 429,https://:@github.com/cloudenvy/cloudenvy.git,a19f6f84832b1dfddbf5ad7b1e84790842b22712,"@@ -35,7 +35,7 @@ class Files(cloudenvy.envy.Command): logging.info(""Copying file from '%s' to '%s'"", local_path, remote_path) - if os.path.exists(local_path): + if not os.path.exists(local_path): logging.error(""Local file '%s' not found."", local_path) dest_dir = _parse_directory(remote_path) ",cloudenvy/commands/files.py,"ReplaceText(target='not ' @(38,23)->(38,23))","class Files(cloudenvy.envy.Command): logging.info(""Copying file from '%s' to '%s'"", local_path, remote_path) if os.path.exists(local_path): logging.error(""Local file '%s' not found."", local_path) dest_dir = _parse_directory(remote_path)","class Files(cloudenvy.envy.Command): logging.info(""Copying file from '%s' to '%s'"", local_path, remote_path) if not os.path.exists(local_path): logging.error(""Local file '%s' not found."", local_path) dest_dir = _parse_directory(remote_path)" 430,https://:@github.com/WeiXuanChan/autoD.git,e163474f70ed6a02f39cd6edaa298271e5f23327,"@@ -520,7 +520,7 @@ class Imaginary(AD): class Absolute(AD): def __init__(self,func): self.func=func - self.abs=(Real(func)**2.-Imaginary(func)**2.)**0.5 + self.abs=(Real(func)**2.+Imaginary(func)**2.)**0.5 try: self.dependent=func.dependent[:] except AttributeError: ",autoD.py,"ReplaceText(target='+' @(523,32)->(523,33))","class Imaginary(AD): class Absolute(AD): def __init__(self,func): self.func=func self.abs=(Real(func)**2.-Imaginary(func)**2.)**0.5 try: self.dependent=func.dependent[:] except AttributeError:","class Imaginary(AD): class Absolute(AD): def __init__(self,func): self.func=func self.abs=(Real(func)**2.+Imaginary(func)**2.)**0.5 try: self.dependent=func.dependent[:] except AttributeError:" 431,https://:@github.com/dwavesystems/dimod.git,79979454139757bd49c1e31c67d890c1d5efeee2,"@@ -279,7 +279,7 @@ class PolyScaleComposite(ComposedPolySampler): # we need to know how much we scaled by, which we can do by looking # at the biases try: - v = next((v for v, bias in poly.items() if bias)) + v = next((v for v, bias in original.items() if bias)) except StopIteration: # nothing to scale scalar = 1 ",dimod/reference/composites/higherordercomposites.py,"ReplaceText(target='original' @(282,43)->(282,47))","class PolyScaleComposite(ComposedPolySampler): # we need to know how much we scaled by, which we can do by looking # at the biases try: v = next((v for v, bias in poly.items() if bias)) except StopIteration: # nothing to scale scalar = 1","class PolyScaleComposite(ComposedPolySampler): # we need to know how much we scaled by, which we can do by looking # at the biases try: v = next((v for v, bias in original.items() if bias)) except StopIteration: # nothing to scale scalar = 1" 432,https://:@github.com/dwavesystems/dimod.git,c21ee99ab65a519b822689361fcfcc66ffb890f2,"@@ -2146,7 +2146,7 @@ class TestSerialization(unittest.TestCase): new = dimod.BinaryQuadraticModel.from_serializable(bqm.to_serializable(use_bytes=True)) self.assertEqual(bqm, new) - self.assertEqual(bqm.info, {""tag"": 5}) + self.assertEqual(new.info, {""tag"": 5}) class TestZeroField(unittest.TestCase): ",tests/test_binary_quadratic_model.py,"ReplaceText(target='new' @(2149,25)->(2149,28))","class TestSerialization(unittest.TestCase): new = dimod.BinaryQuadraticModel.from_serializable(bqm.to_serializable(use_bytes=True)) self.assertEqual(bqm, new) self.assertEqual(bqm.info, {""tag"": 5}) class TestZeroField(unittest.TestCase):","class TestSerialization(unittest.TestCase): new = dimod.BinaryQuadraticModel.from_serializable(bqm.to_serializable(use_bytes=True)) self.assertEqual(bqm, new) self.assertEqual(new.info, {""tag"": 5}) class TestZeroField(unittest.TestCase):" 433,https://:@github.com/dwavesystems/dimod.git,ceee47e049c2c3305d459c6ae865a430dbd113e9,"@@ -197,7 +197,7 @@ def ran_r(r, graph, cls=BinaryQuadraticModel, seed=None): rvals = np.empty(2*r) rvals[0:r] = range(-r, 0) rvals[r:] = range(1, r+1) - qdata = rnd.choice(rvals, size=len(variables)) + qdata = rnd.choice(rvals, size=len(irow)) offset = 0 ",dimod/generators/random.py,"ReplaceText(target='irow' @(200,39)->(200,48))","def ran_r(r, graph, cls=BinaryQuadraticModel, seed=None): rvals = np.empty(2*r) rvals[0:r] = range(-r, 0) rvals[r:] = range(1, r+1) qdata = rnd.choice(rvals, size=len(variables)) offset = 0 ","def ran_r(r, graph, cls=BinaryQuadraticModel, seed=None): rvals = np.empty(2*r) rvals[0:r] = range(-r, 0) rvals[r:] = range(1, r+1) qdata = rnd.choice(rvals, size=len(irow)) offset = 0 " 434,https://:@github.com/dvdotsenko/jsonrpc.py.git,92ad90db194c878cb2023e97758671d72c976797,"@@ -75,7 +75,7 @@ class JSONPRCWSGIApplicationTestSuite(TestCase): response_json = responses_data[0] assert 'error' not in response_json - assert response_json['id'] == request2['id'] + assert response_json['id'] == request1['id'] assert response_json['result'] == 5 response_json = responses_data[1] ",tests/test_wsgi_application.py,"ReplaceText(target='request1' @(78,38)->(78,46))","class JSONPRCWSGIApplicationTestSuite(TestCase): response_json = responses_data[0] assert 'error' not in response_json assert response_json['id'] == request2['id'] assert response_json['result'] == 5 response_json = responses_data[1]","class JSONPRCWSGIApplicationTestSuite(TestCase): response_json = responses_data[0] assert 'error' not in response_json assert response_json['id'] == request1['id'] assert response_json['result'] == 5 response_json = responses_data[1]" 435,https://:@github.com/MarSoft/ses-mailer-2.git,8c1b6aafc09412a6b6b2b1a69337ccbd99fc43f2,"@@ -264,7 +264,7 @@ class Mail(object): for ob in optional_blocks: if ob in blocks: if ob == ""format"" and \ - mail_params[ob].lower() not in [""html"", ""text""]: + blocks[ob].lower() not in [""html"", ""text""]: continue mail_params[ob] = blocks[ob] return mail_params ",ses_mailer.py,"ReplaceText(target='blocks' @(267,24)->(267,35))","class Mail(object): for ob in optional_blocks: if ob in blocks: if ob == ""format"" and \ mail_params[ob].lower() not in [""html"", ""text""]: continue mail_params[ob] = blocks[ob] return mail_params","class Mail(object): for ob in optional_blocks: if ob in blocks: if ob == ""format"" and \ blocks[ob].lower() not in [""html"", ""text""]: continue mail_params[ob] = blocks[ob] return mail_params" 436,https://:@github.com/interpretml/interpret.git,dfae1d47394d50472e25717c53c245cbe9f8a5ad,"@@ -1067,7 +1067,7 @@ class BaseEBM(BaseEstimator): ""scores_range"": bounds, } feature_list.append(feature_dict) - density_dict.append({}) + density_list.append({}) data_dict = { ""type"": ""pairwise"", ",python/interpret/glassbox/ebm/ebm.py,"ReplaceText(target='density_list' @(1070,16)->(1070,28))","class BaseEBM(BaseEstimator): ""scores_range"": bounds, } feature_list.append(feature_dict) density_dict.append({}) data_dict = { ""type"": ""pairwise"",","class BaseEBM(BaseEstimator): ""scores_range"": bounds, } feature_list.append(feature_dict) density_list.append({}) data_dict = { ""type"": ""pairwise""," 437,https://:@gitlab.com/serial-lab/random-flavorpack.git,e69ba47e04a84e1746363a93d33bfe2ca9581cd5,"@@ -76,7 +76,7 @@ class RandomGenerator(Generator): if maximum <= minimum: raise ValueError( _(""The maximum can not be less than the minimum."")) - if start < minimum or start >= maximum: + if start < minimum or start > maximum: raise ValueError( _(""The start must be between the minimum and maximum!"")) rnrange = maximum - minimum ",random_flavorpack/generators/random.py,"ReplaceText(target='>' @(79,36)->(79,38))","class RandomGenerator(Generator): if maximum <= minimum: raise ValueError( _(""The maximum can not be less than the minimum."")) if start < minimum or start >= maximum: raise ValueError( _(""The start must be between the minimum and maximum!"")) rnrange = maximum - minimum","class RandomGenerator(Generator): if maximum <= minimum: raise ValueError( _(""The maximum can not be less than the minimum."")) if start < minimum or start > maximum: raise ValueError( _(""The start must be between the minimum and maximum!"")) rnrange = maximum - minimum" 438,https://:@github.com/Ezibenroc/PyRoaringBitMap.git,7081ceba18ccaf2ee80d3c142e6e612cf77d17d2,"@@ -779,7 +779,7 @@ class OptimizationTest(unittest.TestCase): self.assertGreater(bm2.shrink_to_fit(), 0) self.assertEqual(bm2.shrink_to_fit(), 0) bm3 = cls(bm1, optimize=True) - self.assertEqual(bm2.shrink_to_fit(), 0) + self.assertEqual(bm3.shrink_to_fit(), 0) class VersionTest(unittest.TestCase): ",test.py,"ReplaceText(target='bm3' @(782,25)->(782,28))","class OptimizationTest(unittest.TestCase): self.assertGreater(bm2.shrink_to_fit(), 0) self.assertEqual(bm2.shrink_to_fit(), 0) bm3 = cls(bm1, optimize=True) self.assertEqual(bm2.shrink_to_fit(), 0) class VersionTest(unittest.TestCase):","class OptimizationTest(unittest.TestCase): self.assertGreater(bm2.shrink_to_fit(), 0) self.assertEqual(bm2.shrink_to_fit(), 0) bm3 = cls(bm1, optimize=True) self.assertEqual(bm3.shrink_to_fit(), 0) class VersionTest(unittest.TestCase):" 439,https://:@github.com/Cavenfish/autogamess.git,09def521ebf6c9686479439d71aee114d554a5de,"@@ -136,8 +136,8 @@ def new_project(maindir, csvfile, ebasis_dir, initial_coords_dict=None, #Run Input Builder function save_dir = maindir + 'inputs/' - input_builder(csvfile, initial_coords_dict, ebasis_dir, - save_dir, title.replace('/', '\n')) + input_builder(csvfile, save_dir, ebasis_dir, + initial_coords_dict, title.replace('/', '\n')) return ",autogamess/new_project.py,"ArgSwap(idxs=1<->3 @(139,4)->(139,17))","def new_project(maindir, csvfile, ebasis_dir, initial_coords_dict=None, #Run Input Builder function save_dir = maindir + 'inputs/' input_builder(csvfile, initial_coords_dict, ebasis_dir, save_dir, title.replace('/', '\n')) return","def new_project(maindir, csvfile, ebasis_dir, initial_coords_dict=None, #Run Input Builder function save_dir = maindir + 'inputs/' input_builder(csvfile, save_dir, ebasis_dir, initial_coords_dict, title.replace('/', '\n')) return" 440,https://:@github.com/Cavenfish/autogamess.git,4dcbf5d1a0f9059f8bdbc1a346c8f9cced70f62d,"@@ -136,7 +136,7 @@ def new_project(maindir, csvfile, ebasis_dir, initial_coords_dict=None, #Run Input Builder function save_dir = maindir + 'inputs/' - input_builder(csvfile, save_dir, ebasis_dir, + input_builder(csvfile, ebasis_dir, save_dir, initial_coords_dict, title.replace('/', '\n')) ",autogamess/new_project.py,"ArgSwap(idxs=1<->2 @(139,4)->(139,17))","def new_project(maindir, csvfile, ebasis_dir, initial_coords_dict=None, #Run Input Builder function save_dir = maindir + 'inputs/' input_builder(csvfile, save_dir, ebasis_dir, initial_coords_dict, title.replace('/', '\n')) ","def new_project(maindir, csvfile, ebasis_dir, initial_coords_dict=None, #Run Input Builder function save_dir = maindir + 'inputs/' input_builder(csvfile, ebasis_dir, save_dir, initial_coords_dict, title.replace('/', '\n')) " 441,https://:@github.com/Cavenfish/autogamess.git,3890ccfd3dc7e723a37b8b5308d59a8de0b6f807,"@@ -306,6 +306,6 @@ def fill_spreadsheets(projdir=False, sorteddir=False, sheetsdir=False): if vsc in df: df[vsc].to_excel(writer, sheet_name=vsc, startrow=6) if cmp in df: - df[cmp].to_excel(writer, sheet_name=vsc, startrow=6) + df[cmp].to_excel(writer, sheet_name=cmp, startrow=6) return ",autogamess/fill_spreadsheets.py,"ReplaceText(target='cmp' @(309,52)->(309,55))","def fill_spreadsheets(projdir=False, sorteddir=False, sheetsdir=False): if vsc in df: df[vsc].to_excel(writer, sheet_name=vsc, startrow=6) if cmp in df: df[cmp].to_excel(writer, sheet_name=vsc, startrow=6) return","def fill_spreadsheets(projdir=False, sorteddir=False, sheetsdir=False): if vsc in df: df[vsc].to_excel(writer, sheet_name=vsc, startrow=6) if cmp in df: df[cmp].to_excel(writer, sheet_name=cmp, startrow=6) return" 442,https://:@github.com/EntilZha/ScalaFunctional.git,8426ff978b84cb4125052ad842ae5db64eaf42f3,"@@ -185,6 +185,6 @@ class TestStreams(unittest.TestCase): # test insert into a connection with sqlite3.connect(tmp_path) as conn: - seq(elements).to_sqlite3(tmp_path, insert_sql) + seq(elements).to_sqlite3(conn, insert_sql) result = seq.sqlite3(conn, ""SELECT id, name FROM user;"").to_list() self.assertListEqual(elements, result) ",functional/test/test_streams.py,"ReplaceText(target='conn' @(188,37)->(188,45))","class TestStreams(unittest.TestCase): # test insert into a connection with sqlite3.connect(tmp_path) as conn: seq(elements).to_sqlite3(tmp_path, insert_sql) result = seq.sqlite3(conn, ""SELECT id, name FROM user;"").to_list() self.assertListEqual(elements, result)","class TestStreams(unittest.TestCase): # test insert into a connection with sqlite3.connect(tmp_path) as conn: seq(elements).to_sqlite3(conn, insert_sql) result = seq.sqlite3(conn, ""SELECT id, name FROM user;"").to_list() self.assertListEqual(elements, result)" 443,https://:@github.com/wesselb/stheno.git,32d55bf855f88067e689684eaa5d6f9e8c7604d6,"@@ -80,7 +80,7 @@ class Kernel(Referentiable): def feat_map(x): scale = 2 * B.pi / B.cast(period, x.dtype) return B.concatenate((B.sin(x * scale), - B.cos(x * scale)), axis=0) + B.cos(x * scale)), axis=1) return Kernel(lambda x, y: self.f(feat_map(x), feat_map(y))) ",stheno/kernel.py,"ReplaceText(target='1' @(83,59)->(83,60))","class Kernel(Referentiable): def feat_map(x): scale = 2 * B.pi / B.cast(period, x.dtype) return B.concatenate((B.sin(x * scale), B.cos(x * scale)), axis=0) return Kernel(lambda x, y: self.f(feat_map(x), feat_map(y))) ","class Kernel(Referentiable): def feat_map(x): scale = 2 * B.pi / B.cast(period, x.dtype) return B.concatenate((B.sin(x * scale), B.cos(x * scale)), axis=1) return Kernel(lambda x, y: self.f(feat_map(x), feat_map(y))) " 444,https://:@github.com/djgagne/hagelslag.git,7ef4f68645a7b7146f21813f2b39a0a7208b0fdb,"@@ -19,7 +19,7 @@ class Watershed(object): self.max_intensity = max_intensity def label(self, data): - core_labels, n_labels = label(data <= self.max_intensity) + core_labels, n_labels = label(data >= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels ",hagelslag/processing/Watershed.py,"ReplaceText(target='>=' @(22,43)->(22,45))","class Watershed(object): self.max_intensity = max_intensity def label(self, data): core_labels, n_labels = label(data <= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels ","class Watershed(object): self.max_intensity = max_intensity def label(self, data): core_labels, n_labels = label(data >= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels " 445,https://:@github.com/djgagne/hagelslag.git,28dbda86b4244802a1651a808dfcfe0dbdeb62e3,"@@ -19,7 +19,7 @@ class Watershed(object): self.max_intensity = max_intensity def label(self, data): - core_labels, n_labels = label(data >= self.max_intensity) + core_labels, n_labels = label(data <= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels ",hagelslag/processing/Watershed.py,"ReplaceText(target='<=' @(22,43)->(22,45))","class Watershed(object): self.max_intensity = max_intensity def label(self, data): core_labels, n_labels = label(data >= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels ","class Watershed(object): self.max_intensity = max_intensity def label(self, data): core_labels, n_labels = label(data <= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels " 446,https://:@github.com/djgagne/hagelslag.git,be189c11c1135f782bb30529f58dff78e99f4c8e,"@@ -19,7 +19,7 @@ class Watershed(object): self.max_intensity = max_intensity def label(self, data): - core_labels, n_labels = label(data <= self.max_intensity) + core_labels, n_labels = label(data >= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels ",hagelslag/processing/Watershed.py,"ReplaceText(target='>=' @(22,43)->(22,45))","class Watershed(object): self.max_intensity = max_intensity def label(self, data): core_labels, n_labels = label(data <= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels ","class Watershed(object): self.max_intensity = max_intensity def label(self, data): core_labels, n_labels = label(data >= self.max_intensity) ws_labels = watershed(data.max() - data, markers=core_labels, mask=data >= self.min_intensity) return ws_labels " 447,https://:@github.com/ICRAR/daliuge.git,72b08c308f61bc4e9006976fc9e63f3638fad9e8,"@@ -604,7 +604,7 @@ def chiles_pg(): total_bandwidth = 480 num_obs = 8 # the same as num of data island subband_width = 60 # MHz - num_subb = total_bandwidth / subband_width + num_subb = total_bandwidth // subband_width subband_dict = collections.defaultdict(list) # for corner turning img_list = [] start_freq = 940 ",test/graphsRepository.py,"ReplaceText(target='//' @(607,31)->(607,32))","def chiles_pg(): total_bandwidth = 480 num_obs = 8 # the same as num of data island subband_width = 60 # MHz num_subb = total_bandwidth / subband_width subband_dict = collections.defaultdict(list) # for corner turning img_list = [] start_freq = 940","def chiles_pg(): total_bandwidth = 480 num_obs = 8 # the same as num of data island subband_width = 60 # MHz num_subb = total_bandwidth // subband_width subband_dict = collections.defaultdict(list) # for corner turning img_list = [] start_freq = 940" 448,https://:@github.com/ICRAR/daliuge.git,00eb7a92f6679df09650e2e8054e9163f0089785,"@@ -115,7 +115,7 @@ class TestDM(unittest.TestCase): a.setCompleted() for dm, drop in (dm1,a), (dm2,b), (dm2,c): - self.assertEqual(DROPStates.COMPLETED, dm.get_drop_property(sessionId, 'status', drop.uid)) + self.assertEqual(DROPStates.COMPLETED, dm.get_drop_property(sessionId, drop.uid, 'status')) self.assertEqual(a.checksum, int(droputils.allDropContents(c))) for dropProxy in a,b,c: ",test/manager/test_dm.py,"ArgSwap(idxs=1<->2 @(118,51)->(118,71))","class TestDM(unittest.TestCase): a.setCompleted() for dm, drop in (dm1,a), (dm2,b), (dm2,c): self.assertEqual(DROPStates.COMPLETED, dm.get_drop_property(sessionId, 'status', drop.uid)) self.assertEqual(a.checksum, int(droputils.allDropContents(c))) for dropProxy in a,b,c:","class TestDM(unittest.TestCase): a.setCompleted() for dm, drop in (dm1,a), (dm2,b), (dm2,c): self.assertEqual(DROPStates.COMPLETED, dm.get_drop_property(sessionId, drop.uid, 'status')) self.assertEqual(a.checksum, int(droputils.allDropContents(c))) for dropProxy in a,b,c:" 449,https://:@github.com/ICRAR/daliuge.git,a45bf6f0b7e2fa2627b7e4faa18324aa1087d8f5,"@@ -167,7 +167,7 @@ class DockerTests(unittest.TestCase): c = FileDROP('c', 'c') b.addInput(a) b.addOutput(c) - with DROPWaiterCtx(self, b, 100): + with DROPWaiterCtx(self, c, 100): a.setCompleted() self.assertEqual(six.b(a.dataURL), droputils.allDropContents(c)) ",test/apps/test_docker.py,"ReplaceText(target='c' @(170,33)->(170,34))","class DockerTests(unittest.TestCase): c = FileDROP('c', 'c') b.addInput(a) b.addOutput(c) with DROPWaiterCtx(self, b, 100): a.setCompleted() self.assertEqual(six.b(a.dataURL), droputils.allDropContents(c)) ","class DockerTests(unittest.TestCase): c = FileDROP('c', 'c') b.addInput(a) b.addOutput(c) with DROPWaiterCtx(self, c, 100): a.setCompleted() self.assertEqual(six.b(a.dataURL), droputils.allDropContents(c)) " 450,https://:@github.com/ICRAR/daliuge.git,882b2feb9672662c5347bf0b11ce06b0e7529be8,"@@ -512,7 +512,7 @@ class LogParser(object): for dim_log_f in possible_logs: if (os.path.exists(dim_log_f)): self._dim_log_f = [dim_log_f] - if (dim_log_f == possible_logs[1]): + if (dim_log_f == possible_logs[0]): cluster_log = os.path.join(log_dir, '0', 'start_dlg_cluster.log') if (os.path.exists(cluster_log)): self._dim_log_f.append(cluster_log) ",dlg/deploy/pawsey/scale_test.py,"ReplaceText(target='0' @(515,47)->(515,48))","class LogParser(object): for dim_log_f in possible_logs: if (os.path.exists(dim_log_f)): self._dim_log_f = [dim_log_f] if (dim_log_f == possible_logs[1]): cluster_log = os.path.join(log_dir, '0', 'start_dlg_cluster.log') if (os.path.exists(cluster_log)): self._dim_log_f.append(cluster_log)","class LogParser(object): for dim_log_f in possible_logs: if (os.path.exists(dim_log_f)): self._dim_log_f = [dim_log_f] if (dim_log_f == possible_logs[0]): cluster_log = os.path.join(log_dir, '0', 'start_dlg_cluster.log') if (os.path.exists(cluster_log)): self._dim_log_f.append(cluster_log)" 451,https://:@github.com/ICRAR/daliuge.git,f1204971537d6fa5e972cd96c963f907166dd291,"@@ -952,7 +952,7 @@ class KFamilyPartition(Partition): kwargs['weight'] = self_global_dag.node[u].get('weight', 5) self._dag.add_node(u, **kwargs) for k in self._w_attr: - self._tmp_max_dop[_w_attr] = get_max_weighted_antichain(self._dag, w_attr=k)[0] + self._tmp_max_dop[k] = get_max_weighted_antichain(self._dag, w_attr=k)[0] self._max_dop = self._tmp_max_dop def can_merge(self, that, u, v): ",dlg/dropmake/scheduler.py,"ReplaceText(target='k' @(955,30)->(955,37))","class KFamilyPartition(Partition): kwargs['weight'] = self_global_dag.node[u].get('weight', 5) self._dag.add_node(u, **kwargs) for k in self._w_attr: self._tmp_max_dop[_w_attr] = get_max_weighted_antichain(self._dag, w_attr=k)[0] self._max_dop = self._tmp_max_dop def can_merge(self, that, u, v):","class KFamilyPartition(Partition): kwargs['weight'] = self_global_dag.node[u].get('weight', 5) self._dag.add_node(u, **kwargs) for k in self._w_attr: self._tmp_max_dop[k] = get_max_weighted_antichain(self._dag, w_attr=k)[0] self._max_dop = self._tmp_max_dop def can_merge(self, that, u, v):" 452,https://:@github.com/ICRAR/daliuge.git,6a91d4338a9a90bc2413e4e78c9ed8ca02264ae4,"@@ -2225,7 +2225,7 @@ def partition(pgt, algo, num_partitions=1, num_islands=1, elif algo == ALGO_MIN_NUM_PARTS: time_greedy = 1 - time_greedy / 100.0 # assuming between 1 to 100 - pgt = MinNumPartsPGTP(pgt, deadline, num_partitions, partition_label, max_dop, merge_parts=could_merge, optimistic_factor=time_greedy) + pgt = MinNumPartsPGTP(pgt, deadline, num_partitions, partition_label, max_cpu, merge_parts=could_merge, optimistic_factor=time_greedy) elif algo == ALGO_PSO: pgt = PSOPGTP(pgt, partition_label, max_dop, deadline=deadline, topk=topk, swarm_size=swarm_size, merge_parts=could_merge) ",dlg/dropmake/pg_generator.py,"ReplaceText(target='max_cpu' @(2228,79)->(2228,86))","def partition(pgt, algo, num_partitions=1, num_islands=1, elif algo == ALGO_MIN_NUM_PARTS: time_greedy = 1 - time_greedy / 100.0 # assuming between 1 to 100 pgt = MinNumPartsPGTP(pgt, deadline, num_partitions, partition_label, max_dop, merge_parts=could_merge, optimistic_factor=time_greedy) elif algo == ALGO_PSO: pgt = PSOPGTP(pgt, partition_label, max_dop, deadline=deadline, topk=topk, swarm_size=swarm_size, merge_parts=could_merge)","def partition(pgt, algo, num_partitions=1, num_islands=1, elif algo == ALGO_MIN_NUM_PARTS: time_greedy = 1 - time_greedy / 100.0 # assuming between 1 to 100 pgt = MinNumPartsPGTP(pgt, deadline, num_partitions, partition_label, max_cpu, merge_parts=could_merge, optimistic_factor=time_greedy) elif algo == ALGO_PSO: pgt = PSOPGTP(pgt, partition_label, max_dop, deadline=deadline, topk=topk, swarm_size=swarm_size, merge_parts=could_merge)" 453,https://:@github.com/ICRAR/daliuge.git,885ea31e59129d694329161da7acf7e8f2654348,"@@ -96,7 +96,7 @@ def check_hosts(ips, port, timeout=None, check_with_session=False, retry=1): logger.info(""Host %s:%d is running"", ip, port) return ip logger.warning(""Failed to contact host %s:%d"", ip, port) - ntries -= 0 + ntries -= 1 return None # Don't return None values ",dlg/deploy/pawsey/start_dfms_cluster.py,"ReplaceText(target='1' @(99,22)->(99,23))","def check_hosts(ips, port, timeout=None, check_with_session=False, retry=1): logger.info(""Host %s:%d is running"", ip, port) return ip logger.warning(""Failed to contact host %s:%d"", ip, port) ntries -= 0 return None # Don't return None values","def check_hosts(ips, port, timeout=None, check_with_session=False, retry=1): logger.info(""Host %s:%d is running"", ip, port) return ip logger.warning(""Failed to contact host %s:%d"", ip, port) ntries -= 1 return None # Don't return None values" 454,https://:@github.com/ICRAR/daliuge.git,ca615527deef8c147aaad3c64755b5f3d89b65b8,"@@ -56,7 +56,7 @@ def timed_import(module_name): """"""Imports `module_name` and log how long it took to import it"""""" start = time.time() module = importlib.import_module(module_name) - logger.info('Imported %s in %.3f seconds', module, time.time() - start) + logger.info('Imported %s in %.3f seconds', module_name, time.time() - start) return module ",dlg/utils.py,"ReplaceText(target='module_name' @(59,47)->(59,53))","def timed_import(module_name): """"""Imports `module_name` and log how long it took to import it"""""" start = time.time() module = importlib.import_module(module_name) logger.info('Imported %s in %.3f seconds', module, time.time() - start) return module ","def timed_import(module_name): """"""Imports `module_name` and log how long it took to import it"""""" start = time.time() module = importlib.import_module(module_name) logger.info('Imported %s in %.3f seconds', module_name, time.time() - start) return module " 455,https://:@github.com/JRCSTU/co2mpas-ta.git,8e8557c3590acc6942bcabc7167de3767681e48b,"@@ -419,7 +419,7 @@ def define_alternator_status_model( if soc < dn_soc or (prev_status == 1 and soc < up_soc): status = 1 - elif has_energy_recuperation and gear_box_power_in >= 0: + elif has_energy_recuperation and gear_box_power_in < 0: status = 2 return status ",co2mpas/functions/physical/electrics/__init__.py,"ReplaceText(target='<' @(422,63)->(422,65))","def define_alternator_status_model( if soc < dn_soc or (prev_status == 1 and soc < up_soc): status = 1 elif has_energy_recuperation and gear_box_power_in >= 0: status = 2 return status","def define_alternator_status_model( if soc < dn_soc or (prev_status == 1 and soc < up_soc): status = 1 elif has_energy_recuperation and gear_box_power_in < 0: status = 2 return status" 456,https://:@github.com/JRCSTU/co2mpas-ta.git,b155780da4cd2489da6c06da12e0c4df41534ab5,"@@ -2766,8 +2766,8 @@ class Dispatcher(object): elif node_id in dists: # The node w already estimated. if dist < dists[node_id]: # Error for negative paths. - raise DispatcherError('Contradictory paths found: ' - 'negative weights?', self) + raise DispatcherError(self, 'Contradictory paths found: ' + 'negative weights?') elif node_id not in seen or dist < seen[node_id]: # Check min dist. seen[node_id] = dist # Update dist. ",co2mpas/dispatcher/__init__.py,"ArgSwap(idxs=0<->1 @(2769,22)->(2769,37))","class Dispatcher(object): elif node_id in dists: # The node w already estimated. if dist < dists[node_id]: # Error for negative paths. raise DispatcherError('Contradictory paths found: ' 'negative weights?', self) elif node_id not in seen or dist < seen[node_id]: # Check min dist. seen[node_id] = dist # Update dist. ","class Dispatcher(object): elif node_id in dists: # The node w already estimated. if dist < dists[node_id]: # Error for negative paths. raise DispatcherError(self, 'Contradictory paths found: ' 'negative weights?') elif node_id not in seen or dist < seen[node_id]: # Check min dist. seen[node_id] = dist # Update dist. " 457,https://:@github.com/JRCSTU/co2mpas-ta.git,46830a3edd1490d499b8f0e788ce87efe873d264,"@@ -225,7 +225,7 @@ def _predict_electrics( alternator_current = calculate_alternator_current( alternator_status, on_engine, gear_box_power_in, alternator_current_model, engine_start_current, - prev_battery_current, acceleration) + battery_state_of_charge, acceleration) battery_current = calculate_battery_current( electric_load, alternator_current, alternator_nominal_voltage, ",co2mpas/functions/co2mpas_model/physical/electrics/electrics_prediction.py,"ReplaceText(target='battery_state_of_charge' @(228,8)->(228,28))","def _predict_electrics( alternator_current = calculate_alternator_current( alternator_status, on_engine, gear_box_power_in, alternator_current_model, engine_start_current, prev_battery_current, acceleration) battery_current = calculate_battery_current( electric_load, alternator_current, alternator_nominal_voltage,","def _predict_electrics( alternator_current = calculate_alternator_current( alternator_status, on_engine, gear_box_power_in, alternator_current_model, engine_start_current, battery_state_of_charge, acceleration) battery_current = calculate_battery_current( electric_load, alternator_current, alternator_nominal_voltage," 458,https://:@github.com/JRCSTU/co2mpas-ta.git,45e4f0782888c84b9c99842db88457353b45efb3,"@@ -240,7 +240,7 @@ def define_data_schema(read=True): 'f0_uncorrected': positive, 'f2': positive, 'f0': positive, - 'correct_f0': positive, + 'correct_f0': _bool, 'co2_emission_low': positive, 'co2_emission_medium': positive, ",co2mpas/functions/io/schema.py,"ReplaceText(target='_bool' @(243,22)->(243,30))","def define_data_schema(read=True): 'f0_uncorrected': positive, 'f2': positive, 'f0': positive, 'correct_f0': positive, 'co2_emission_low': positive, 'co2_emission_medium': positive,","def define_data_schema(read=True): 'f0_uncorrected': positive, 'f2': positive, 'f0': positive, 'correct_f0': _bool, 'co2_emission_low': positive, 'co2_emission_medium': positive," 459,https://:@github.com/JRCSTU/co2mpas-ta.git,3fcd6ce4395980ea879bde8f1270e390e750a8ee,"@@ -3020,7 +3020,7 @@ class Dispatcher(object): self._meet[dsp_id] = initial_dist # Set view distance. # Check if inputs are satisfied. - if self.check_wait_in(node['wait_inputs'], node_id): + if self.check_wait_in(node['wait_inputs'], dsp_id): return False # Pass the node if dsp_id not in distances: ",co2mpas/dispatcher/__init__.py,"ReplaceText(target='dsp_id' @(3023,51)->(3023,58))","class Dispatcher(object): self._meet[dsp_id] = initial_dist # Set view distance. # Check if inputs are satisfied. if self.check_wait_in(node['wait_inputs'], node_id): return False # Pass the node if dsp_id not in distances:","class Dispatcher(object): self._meet[dsp_id] = initial_dist # Set view distance. # Check if inputs are satisfied. if self.check_wait_in(node['wait_inputs'], dsp_id): return False # Pass the node if dsp_id not in distances:" 460,https://:@github.com/JRCSTU/co2mpas-ta.git,e3346285e51b0bba0d909746146e0be70c3090eb,"@@ -87,7 +87,7 @@ def calculate_full_load(full_load_speeds, full_load_powers, idle_engine_speed): """""" pn = np.array((full_load_speeds, full_load_powers)) - max_speed_at_max_power, max_power = pn[:, np.argmax(pn[0])] + max_speed_at_max_power, max_power = pn[:, np.argmax(pn[1])] pn[1] /= max_power idle = idle_engine_speed[0] pn[0] = (pn[0] - idle) / (max_speed_at_max_power - idle) ",co2mpas/model/physical/engine/__init__.py,"ReplaceText(target='1' @(90,59)->(90,60))","def calculate_full_load(full_load_speeds, full_load_powers, idle_engine_speed): """""" pn = np.array((full_load_speeds, full_load_powers)) max_speed_at_max_power, max_power = pn[:, np.argmax(pn[0])] pn[1] /= max_power idle = idle_engine_speed[0] pn[0] = (pn[0] - idle) / (max_speed_at_max_power - idle)","def calculate_full_load(full_load_speeds, full_load_powers, idle_engine_speed): """""" pn = np.array((full_load_speeds, full_load_powers)) max_speed_at_max_power, max_power = pn[:, np.argmax(pn[1])] pn[1] /= max_power idle = idle_engine_speed[0] pn[0] = (pn[0] - idle) / (max_speed_at_max_power - idle)" 461,https://:@github.com/JRCSTU/co2mpas-ta.git,4154efcd8980a1790f2675afa14803991b4da76e,"@@ -1223,7 +1223,7 @@ def calibrate_co2_params( p = restrict_bounds(p) - p, s = calibrate_model_params(co2_error_function_on_phases, p) + p, s = calibrate_model_params(co2_error_function_on_emissions, p) success.append((s, copy.deepcopy(p))) _set_attr(p, vary) ",co2mpas/model/physical/engine/co2_emission.py,"ReplaceText(target='co2_error_function_on_emissions' @(1226,34)->(1226,62))","def calibrate_co2_params( p = restrict_bounds(p) p, s = calibrate_model_params(co2_error_function_on_phases, p) success.append((s, copy.deepcopy(p))) _set_attr(p, vary) ","def calibrate_co2_params( p = restrict_bounds(p) p, s = calibrate_model_params(co2_error_function_on_emissions, p) success.append((s, copy.deepcopy(p))) _set_attr(p, vary) " 462,https://:@github.com/JRCSTU/co2mpas-ta.git,4c077512de9127f377b3802d2c82fe8ebd56f5c2,"@@ -703,7 +703,7 @@ def define_data_schema(read=True): 'alternator_powers_demand': np_array, 'alternator_statuses': np_array_int, 'auxiliaries_power_losses': np_array, - 'auxiliaries_torque_loss': positive, + 'auxiliaries_torque_loss': tuplefloat, 'auxiliaries_torque_losses': np_array, 'battery_currents': np_array, 'clutch_tc_powers': np_array, ",co2mpas/io/schema.py,"ReplaceText(target='tuplefloat' @(706,35)->(706,43))","def define_data_schema(read=True): 'alternator_powers_demand': np_array, 'alternator_statuses': np_array_int, 'auxiliaries_power_losses': np_array, 'auxiliaries_torque_loss': positive, 'auxiliaries_torque_losses': np_array, 'battery_currents': np_array, 'clutch_tc_powers': np_array,","def define_data_schema(read=True): 'alternator_powers_demand': np_array, 'alternator_statuses': np_array_int, 'auxiliaries_power_losses': np_array, 'auxiliaries_torque_loss': tuplefloat, 'auxiliaries_torque_losses': np_array, 'battery_currents': np_array, 'clutch_tc_powers': np_array," 463,https://:@github.com/JRCSTU/co2mpas-ta.git,274f898a173aa42185fa5ef138035b4cb5994d28,"@@ -74,7 +74,7 @@ class TestGearBox(unittest.TestCase): def test_calculate_torque_out(self): wp, es, gbs = self.wp, self.es, self.ws self.assertEquals( - list(calculate_gear_box_torques(wp, es, gbs, 10)), list(self.tgb) + list(calculate_gear_box_torques(wp, gbs, es, 10)), list(self.tgb) ) @unittest.skip(""to be reviewed"") ",tests/functions/test_gear_box.py,"ArgSwap(idxs=1<->2 @(77,17)->(77,43))","class TestGearBox(unittest.TestCase): def test_calculate_torque_out(self): wp, es, gbs = self.wp, self.es, self.ws self.assertEquals( list(calculate_gear_box_torques(wp, es, gbs, 10)), list(self.tgb) ) @unittest.skip(""to be reviewed"")","class TestGearBox(unittest.TestCase): def test_calculate_torque_out(self): wp, es, gbs = self.wp, self.es, self.ws self.assertEquals( list(calculate_gear_box_torques(wp, gbs, es, 10)), list(self.tgb) ) @unittest.skip(""to be reviewed"")" 464,https://:@github.com/JRCSTU/co2mpas-ta.git,739964622f68661a4dc35b8a60a30db5cb8475b2,"@@ -2608,7 +2608,7 @@ class Co2guiCmd(cmdlets.Cmd): progr_bar.grid(column=1, row=1, sticky='nswe') if step is not None: - if step < 0: + if step <= 0: progr_var.set(-step) else: progr_var.set(progr_var.get() + step) ",co2mpas/co2gui/__init__.py,"ReplaceText(target='<=' @(2611,20)->(2611,21))","class Co2guiCmd(cmdlets.Cmd): progr_bar.grid(column=1, row=1, sticky='nswe') if step is not None: if step < 0: progr_var.set(-step) else: progr_var.set(progr_var.get() + step)","class Co2guiCmd(cmdlets.Cmd): progr_bar.grid(column=1, row=1, sticky='nswe') if step is not None: if step <= 0: progr_var.set(-step) else: progr_var.set(progr_var.get() + step)" 465,https://:@github.com/JRCSTU/co2mpas-ta.git,18af1fede3536121930c99ea0a2c94e8ffeb3bf7,"@@ -450,6 +450,6 @@ def calculate_drive_battery_currents_v2( n_p, n_s = drive_battery_n_parallel_cells, drive_battery_n_series_cells p = drive_battery_electric_powers r0, ocv = drive_battery_r0, drive_battery_ocv - x = ocv + np.nan_to_num(np.sqrt(ocv ** 2 - (4e3 * r0 / (n_s * n_p)) * p)) + x = ocv - np.nan_to_num(np.sqrt(ocv ** 2 - (4e3 * r0 / (n_s * n_p)) * p)) x *= n_p / (2 * r0) return x ",co2mpas/core/model/physical/electrics/batteries/drive.py,"ReplaceText(target='-' @(453,12)->(453,13))","def calculate_drive_battery_currents_v2( n_p, n_s = drive_battery_n_parallel_cells, drive_battery_n_series_cells p = drive_battery_electric_powers r0, ocv = drive_battery_r0, drive_battery_ocv x = ocv + np.nan_to_num(np.sqrt(ocv ** 2 - (4e3 * r0 / (n_s * n_p)) * p)) x *= n_p / (2 * r0) return x","def calculate_drive_battery_currents_v2( n_p, n_s = drive_battery_n_parallel_cells, drive_battery_n_series_cells p = drive_battery_electric_powers r0, ocv = drive_battery_r0, drive_battery_ocv x = ocv - np.nan_to_num(np.sqrt(ocv ** 2 - (4e3 * r0 / (n_s * n_p)) * p)) x *= n_p / (2 * r0) return x" 466,https://:@github.com/JRCSTU/co2mpas-ta.git,8f4cfb4afa97fc43a95b62b497f182fd72b0e379,"@@ -263,7 +263,7 @@ def calculate_service_battery_loads( Service battery load vector [kW]. :rtype: numpy.array """""" - p = service_battery_electric_powers - service_battery_electric_powers_supply + p = service_battery_electric_powers + service_battery_electric_powers_supply return p ",co2mpas/core/model/physical/electrics/batteries/service/__init__.py,"ReplaceText(target='+' @(266,40)->(266,41))","def calculate_service_battery_loads( Service battery load vector [kW]. :rtype: numpy.array """""" p = service_battery_electric_powers - service_battery_electric_powers_supply return p ","def calculate_service_battery_loads( Service battery load vector [kW]. :rtype: numpy.array """""" p = service_battery_electric_powers + service_battery_electric_powers_supply return p " 467,https://:@github.com/JRCSTU/co2mpas-ta.git,52695d79acea053f5ff38a8a5d223f1907d33fb8,"@@ -46,7 +46,7 @@ def calculate_final_drive_ratios(final_drive_ratio, n_gears=1): # noinspection PyUnusedLocal,PyMissingOrEmptyDocstring def is_not_manual_or_automatic(gear_box_type, *args): - return gear_box_type in ('manual', 'automatic') + return gear_box_type not in ('manual', 'automatic') dsp.add_function( ",co2mpas/core/model/physical/final_drive.py,"ReplaceText(target=' not in ' @(49,24)->(49,28))","def calculate_final_drive_ratios(final_drive_ratio, n_gears=1): # noinspection PyUnusedLocal,PyMissingOrEmptyDocstring def is_not_manual_or_automatic(gear_box_type, *args): return gear_box_type in ('manual', 'automatic') dsp.add_function(","def calculate_final_drive_ratios(final_drive_ratio, n_gears=1): # noinspection PyUnusedLocal,PyMissingOrEmptyDocstring def is_not_manual_or_automatic(gear_box_type, *args): return gear_box_type not in ('manual', 'automatic') dsp.add_function(" 468,https://:@github.com/JRCSTU/co2mpas-ta.git,401ec07523c5b34dacab9e73cf9a417dada880cb,"@@ -429,7 +429,7 @@ class CorrectGear: # 3.2 j = i + np.searchsorted(times[i:], times[i] + 1) - if not gear and up_clip(velocities, j + 1) >= up_clip(velocities, j): + if not gear and up_clip(velocities, j + 1) > up_clip(velocities, j): gear = self.min_gear return gear ",co2mpas/core/model/physical/gear_box/at_gear/__init__.py,"ReplaceText(target='>' @(432,51)->(432,53))","class CorrectGear: # 3.2 j = i + np.searchsorted(times[i:], times[i] + 1) if not gear and up_clip(velocities, j + 1) >= up_clip(velocities, j): gear = self.min_gear return gear","class CorrectGear: # 3.2 j = i + np.searchsorted(times[i:], times[i] + 1) if not gear and up_clip(velocities, j + 1) > up_clip(velocities, j): gear = self.min_gear return gear" 469,https://:@github.com/JRCSTU/co2mpas-ta.git,745c3623fffca5cf7f84358f8fff87287a35525c,"@@ -125,7 +125,7 @@ def define_tau_function(after_treatment_temperature_threshold): f = sci_sta.lognorm(max(s, dfl.EPS), 0, temp_mean).cdf def _tau_function(t0, t1, temp): - return t0 - (t1 - t0) * f(temp + 273) + return t0 + (t1 - t0) * f(temp + 273) return _tau_function ",co2mpas/core/model/physical/engine/fc.py,"ReplaceText(target='+' @(128,18)->(128,19))","def define_tau_function(after_treatment_temperature_threshold): f = sci_sta.lognorm(max(s, dfl.EPS), 0, temp_mean).cdf def _tau_function(t0, t1, temp): return t0 - (t1 - t0) * f(temp + 273) return _tau_function ","def define_tau_function(after_treatment_temperature_threshold): f = sci_sta.lognorm(max(s, dfl.EPS), 0, temp_mean).cdf def _tau_function(t0, t1, temp): return t0 + (t1 - t0) * f(temp + 273) return _tau_function " 470,https://:@github.com/RasaHQ/rasa.git,57d15923475ec8b5361cd6f84f327d864253746a,"@@ -33,7 +33,7 @@ def run_train(_config): def load_interpreter_for_model(nlp, config, persisted_path): metadata = DataRouter.read_model_metadata(persisted_path, config) - return DataRouter.create_interpreter(nlp, metadata) + return DataRouter.create_interpreter(metadata, nlp) class ResponseTest(object): ",_pytest/utilities.py,"ArgSwap(idxs=0<->1 @(36,11)->(36,40))","def run_train(_config): def load_interpreter_for_model(nlp, config, persisted_path): metadata = DataRouter.read_model_metadata(persisted_path, config) return DataRouter.create_interpreter(nlp, metadata) class ResponseTest(object):","def run_train(_config): def load_interpreter_for_model(nlp, config, persisted_path): metadata = DataRouter.read_model_metadata(persisted_path, config) return DataRouter.create_interpreter(metadata, nlp) class ResponseTest(object):" 471,https://:@github.com/RasaHQ/rasa.git,bb0b24e56a97affbfa3db91be71782f293e9e5c2,"@@ -29,7 +29,7 @@ def test_luis_data_without_tokenizer(): def test_wit_data(): td = load_data('data/examples/wit/demo-flights.json', ""en"") assert td.entity_examples != [] - assert td.intent_examples != [] + assert td.intent_examples == [] assert td.entity_synonyms == {} ",_pytest/test_training_data.py,"ReplaceText(target='==' @(32,30)->(32,32))","def test_luis_data_without_tokenizer(): def test_wit_data(): td = load_data('data/examples/wit/demo-flights.json', ""en"") assert td.entity_examples != [] assert td.intent_examples != [] assert td.entity_synonyms == {} ","def test_luis_data_without_tokenizer(): def test_wit_data(): td = load_data('data/examples/wit/demo-flights.json', ""en"") assert td.entity_examples != [] assert td.intent_examples == [] assert td.entity_synonyms == {} " 472,https://:@github.com/RasaHQ/rasa.git,12484270fb8c3c271d74c5b3269f287eaf2d7cfb,"@@ -84,7 +84,7 @@ class SklearnIntentClassifier(Component): # dirty str fix because sklearn is expecting str not instance of basestr... tuned_parameters = [{'C': [1, 2, 5, 10, 20, 100], 'kernel': [str('linear')]}] - cv_splits = max(2, min(MAX_CV_FOLDS, np.min(np.bincount(y)) / 5)) # aim for at least 5 examples in each fold + cv_splits = max(2, min(MAX_CV_FOLDS, np.min(np.bincount(y)) // 5)) # aim for at least 5 examples in each fold self.clf = GridSearchCV(SVC(C=1, probability=True), param_grid=tuned_parameters, n_jobs=num_threads, ",rasa_nlu/classifiers/sklearn_intent_classifier.py,"ReplaceText(target='//' @(87,68)->(87,69))","class SklearnIntentClassifier(Component): # dirty str fix because sklearn is expecting str not instance of basestr... tuned_parameters = [{'C': [1, 2, 5, 10, 20, 100], 'kernel': [str('linear')]}] cv_splits = max(2, min(MAX_CV_FOLDS, np.min(np.bincount(y)) / 5)) # aim for at least 5 examples in each fold self.clf = GridSearchCV(SVC(C=1, probability=True), param_grid=tuned_parameters, n_jobs=num_threads,","class SklearnIntentClassifier(Component): # dirty str fix because sklearn is expecting str not instance of basestr... tuned_parameters = [{'C': [1, 2, 5, 10, 20, 100], 'kernel': [str('linear')]}] cv_splits = max(2, min(MAX_CV_FOLDS, np.min(np.bincount(y)) // 5)) # aim for at least 5 examples in each fold self.clf = GridSearchCV(SVC(C=1, probability=True), param_grid=tuned_parameters, n_jobs=num_threads," 473,https://:@github.com/RasaHQ/rasa.git,b5f9b6ad06ff52d75522b49c745f3e83c32ee7cd,"@@ -135,7 +135,7 @@ class TrainingData(object): logger.info(""Training data stats: \n"" + ""\t- intent examples: {} ({} distinct intents)\n"".format( self.num_intent_examples, len(different_intents)) + - ""\t- found intents: {}\n"".format(list_to_str(different_entities)) + + ""\t- found intents: {}\n"".format(list_to_str(different_intents)) + ""\t- entity examples: {} ({} distinct entities)\n"".format( self.num_entity_examples, len(different_entities)) + ""\t- found entities: {}\n"".format(list_to_str(different_entities))) ",rasa_nlu/training_data.py,"ReplaceText(target='different_intents' @(138,65)->(138,83))","class TrainingData(object): logger.info(""Training data stats: \n"" + ""\t- intent examples: {} ({} distinct intents)\n"".format( self.num_intent_examples, len(different_intents)) + ""\t- found intents: {}\n"".format(list_to_str(different_entities)) + ""\t- entity examples: {} ({} distinct entities)\n"".format( self.num_entity_examples, len(different_entities)) + ""\t- found entities: {}\n"".format(list_to_str(different_entities)))","class TrainingData(object): logger.info(""Training data stats: \n"" + ""\t- intent examples: {} ({} distinct intents)\n"".format( self.num_intent_examples, len(different_intents)) + ""\t- found intents: {}\n"".format(list_to_str(different_intents)) + ""\t- entity examples: {} ({} distinct entities)\n"".format( self.num_entity_examples, len(different_entities)) + ""\t- found entities: {}\n"".format(list_to_str(different_entities)))" 474,https://:@github.com/RasaHQ/rasa.git,c5e10bd1c504146064183b6b87cfdf80d8617a4d,"@@ -28,7 +28,7 @@ class MarkdownToRasa: entities = [] utter = example_in_md for regex in [ent_regex, ent_regex_with_value]: - utter = re.sub(regex, r""\1"", example_in_md) # [text](entity) -> text + utter = re.sub(regex, r""\1"", utter) # [text](entity) -> text ent_matches = re.finditer(regex, example_in_md) for matchNum, match in enumerate(ent_matches): if 'synonym' in match.groupdict(): ",rasa_nlu/utils/md_to_rasa.py,"ReplaceText(target='utter' @(31,41)->(31,54))","class MarkdownToRasa: entities = [] utter = example_in_md for regex in [ent_regex, ent_regex_with_value]: utter = re.sub(regex, r""\1"", example_in_md) # [text](entity) -> text ent_matches = re.finditer(regex, example_in_md) for matchNum, match in enumerate(ent_matches): if 'synonym' in match.groupdict():","class MarkdownToRasa: entities = [] utter = example_in_md for regex in [ent_regex, ent_regex_with_value]: utter = re.sub(regex, r""\1"", utter) # [text](entity) -> text ent_matches = re.finditer(regex, example_in_md) for matchNum, match in enumerate(ent_matches): if 'synonym' in match.groupdict():" 475,https://:@github.com/RasaHQ/rasa.git,571c59bc9fccca87aa1c29b56ddf874fce9b111a,"@@ -87,9 +87,9 @@ class Metadata(object): return [] def for_component(self, name, defaults=None): - return config.component_config_from_pipeline(self.get('pipeline', []), - name, - defaults) + return config.component_config_from_pipeline(name, + self.get('pipeline', []), + defaults) @property def language(self): ",rasa_nlu/model.py,"ArgSwap(idxs=0<->1 @(90,15)->(90,52))","class Metadata(object): return [] def for_component(self, name, defaults=None): return config.component_config_from_pipeline(self.get('pipeline', []), name, defaults) @property def language(self):","class Metadata(object): return [] def for_component(self, name, defaults=None): return config.component_config_from_pipeline(name, self.get('pipeline', []), defaults) @property def language(self):" 476,https://:@github.com/RasaHQ/rasa.git,9a06d81201ca84812540bc4128111c55e22ffca7,"@@ -156,7 +156,7 @@ class RasaNLUModelConfig(object): return json_to_string(self.__dict__, indent=4) def for_component(self, name, defaults=None): - return component_config_from_pipeline(self.pipeline, name, defaults) + return component_config_from_pipeline(name, self.pipeline, defaults) @property def component_names(self): ",rasa_nlu/config.py,"ArgSwap(idxs=0<->1 @(159,15)->(159,45))","class RasaNLUModelConfig(object): return json_to_string(self.__dict__, indent=4) def for_component(self, name, defaults=None): return component_config_from_pipeline(self.pipeline, name, defaults) @property def component_names(self):","class RasaNLUModelConfig(object): return json_to_string(self.__dict__, indent=4) def for_component(self, name, defaults=None): return component_config_from_pipeline(name, self.pipeline, defaults) @property def component_names(self):" 477,https://:@github.com/RasaHQ/rasa.git,2d92ef4002144ec4b3d66bd911c26642e5ab698f,"@@ -42,7 +42,7 @@ def create_argument_parser(): description='evaluates a dialogue model') parent_parser = argparse.ArgumentParser(add_help=False) add_args_to_parser(parent_parser) - cli.arguments.add_model_and_story_group(parser, + cli.arguments.add_model_and_story_group(parent_parser, allow_pretrained_model=False) utils.add_logging_option_arguments(parent_parser) subparsers = parser.add_subparsers(help='mode', dest='mode') ",rasa_core/evaluate.py,"ReplaceText(target='parent_parser' @(45,44)->(45,50))","def create_argument_parser(): description='evaluates a dialogue model') parent_parser = argparse.ArgumentParser(add_help=False) add_args_to_parser(parent_parser) cli.arguments.add_model_and_story_group(parser, allow_pretrained_model=False) utils.add_logging_option_arguments(parent_parser) subparsers = parser.add_subparsers(help='mode', dest='mode')","def create_argument_parser(): description='evaluates a dialogue model') parent_parser = argparse.ArgumentParser(add_help=False) add_args_to_parser(parent_parser) cli.arguments.add_model_and_story_group(parent_parser, allow_pretrained_model=False) utils.add_logging_option_arguments(parent_parser) subparsers = parser.add_subparsers(help='mode', dest='mode')" 478,https://:@github.com/RasaHQ/rasa.git,665cf94ee30f44aac85e8ac3c5ed8b2b0694354a,"@@ -49,7 +49,7 @@ def create_argument_parser(): description='evaluates a dialogue model') parent_parser = argparse.ArgumentParser(add_help=False) add_args_to_parser(parent_parser) - cli.arguments.add_model_and_story_group(parser, + cli.arguments.add_model_and_story_group(parent_parser, allow_pretrained_model=False) utils.add_logging_option_arguments(parent_parser) subparsers = parser.add_subparsers(help='mode', dest='mode') ",rasa_core/evaluate.py,"ReplaceText(target='parent_parser' @(52,44)->(52,50))","def create_argument_parser(): description='evaluates a dialogue model') parent_parser = argparse.ArgumentParser(add_help=False) add_args_to_parser(parent_parser) cli.arguments.add_model_and_story_group(parser, allow_pretrained_model=False) utils.add_logging_option_arguments(parent_parser) subparsers = parser.add_subparsers(help='mode', dest='mode')","def create_argument_parser(): description='evaluates a dialogue model') parent_parser = argparse.ArgumentParser(add_help=False) add_args_to_parser(parent_parser) cli.arguments.add_model_and_story_group(parent_parser, allow_pretrained_model=False) utils.add_logging_option_arguments(parent_parser) subparsers = parser.add_subparsers(help='mode', dest='mode')" 479,https://:@github.com/RasaHQ/rasa.git,37f446c8246c78339727f7b09bd2021906ec8d60,"@@ -174,7 +174,7 @@ def test_generate_training_data_original_and_augmented_trackers( hasattr(t, 'is_augmented') or not t.is_augmented ] assert len(original_trackers) == 3 - assert len(original_trackers) <= 33 + assert len(training_trackers) <= 33 def test_visualize_training_data_graph(tmpdir, default_domain): ",tests/test_dsl.py,"ReplaceText(target='training_trackers' @(177,15)->(177,32))","def test_generate_training_data_original_and_augmented_trackers( hasattr(t, 'is_augmented') or not t.is_augmented ] assert len(original_trackers) == 3 assert len(original_trackers) <= 33 def test_visualize_training_data_graph(tmpdir, default_domain):","def test_generate_training_data_original_and_augmented_trackers( hasattr(t, 'is_augmented') or not t.is_augmented ] assert len(original_trackers) == 3 assert len(training_trackers) <= 33 def test_visualize_training_data_graph(tmpdir, default_domain):" 480,https://:@github.com/RasaHQ/rasa.git,31ab3bb5d10a09f8957455909311257b257f44dc,"@@ -218,7 +218,7 @@ class TestMemoizationPolicy(PolicyTestCollection): assert recalled == default_domain.index_for_action(actions[0]) for tracker, states, actions \ - in zip(trackers, all_states_augmented, all_actions_augmented): + in zip(augmented_trackers, all_states_augmented, all_actions_augmented): recalled = trained_policy.recall(states, tracker, default_domain) assert recalled == 0 ",tests/test_policies.py,"ReplaceText(target='augmented_trackers' @(221,23)->(221,31))","class TestMemoizationPolicy(PolicyTestCollection): assert recalled == default_domain.index_for_action(actions[0]) for tracker, states, actions \ in zip(trackers, all_states_augmented, all_actions_augmented): recalled = trained_policy.recall(states, tracker, default_domain) assert recalled == 0 ","class TestMemoizationPolicy(PolicyTestCollection): assert recalled == default_domain.index_for_action(actions[0]) for tracker, states, actions \ in zip(augmented_trackers, all_states_augmented, all_actions_augmented): recalled = trained_policy.recall(states, tracker, default_domain) assert recalled == 0 " 481,https://:@github.com/RasaHQ/rasa.git,90a98e954b209a05a168e86e78d4ad90e12d8869,"@@ -31,7 +31,7 @@ def run(model: Text, endpoints: Text, connector: Text = None, from rasa_core.utils import AvailableEndpoints model_path = get_model(model) - core_path, nlu_path = get_model_subdirectories(model) + core_path, nlu_path = get_model_subdirectories(model_path) _endpoints = AvailableEndpoints.read_endpoints(endpoints) if not connector and not credentials: ",rasa/run.py,"ReplaceText(target='model_path' @(34,51)->(34,56))","def run(model: Text, endpoints: Text, connector: Text = None, from rasa_core.utils import AvailableEndpoints model_path = get_model(model) core_path, nlu_path = get_model_subdirectories(model) _endpoints = AvailableEndpoints.read_endpoints(endpoints) if not connector and not credentials:","def run(model: Text, endpoints: Text, connector: Text = None, from rasa_core.utils import AvailableEndpoints model_path = get_model(model) core_path, nlu_path = get_model_subdirectories(model_path) _endpoints = AvailableEndpoints.read_endpoints(endpoints) if not connector and not credentials:" 482,https://:@github.com/RasaHQ/rasa.git,e43636652c80d0e9d81dc01f6a83ebfc5444ee12,"@@ -69,8 +69,8 @@ def test_core( if os.path.exists(core_path) and os.path.exists(nlu_path): _interpreter = NaturalLanguageInterpreter.create(nlu_path, _endpoints.nlu) - _agent = Agent.load(core_path, interpreter=_interpreter) - + _agent = Agent.load(model_path, interpreter=_interpreter) + kwargs = minimal_kwargs(kwargs, rasa.core.test, [""stories"", ""agent""]) loop.run_until_complete( ",rasa/test.py,"ReplaceText(target='model_path' @(72,28)->(72,37))","def test_core( if os.path.exists(core_path) and os.path.exists(nlu_path): _interpreter = NaturalLanguageInterpreter.create(nlu_path, _endpoints.nlu) _agent = Agent.load(core_path, interpreter=_interpreter) kwargs = minimal_kwargs(kwargs, rasa.core.test, [""stories"", ""agent""]) loop.run_until_complete(","def test_core( if os.path.exists(core_path) and os.path.exists(nlu_path): _interpreter = NaturalLanguageInterpreter.create(nlu_path, _endpoints.nlu) _agent = Agent.load(model_path, interpreter=_interpreter) kwargs = minimal_kwargs(kwargs, rasa.core.test, [""stories"", ""agent""]) loop.run_until_complete(" 483,https://:@github.com/RasaHQ/rasa.git,2d74a8355b63f587c6e1a7d69027a84982fe237d,"@@ -118,7 +118,7 @@ async def train_comparison_models( file_importer, train_path, policy_config=policy_config, - exclusion_percentage=current_run, + exclusion_percentage=percentage, kwargs=kwargs, dump_stories=dump_stories, ) ",rasa/core/train.py,"ReplaceText(target='percentage' @(121,45)->(121,56))","async def train_comparison_models( file_importer, train_path, policy_config=policy_config, exclusion_percentage=current_run, kwargs=kwargs, dump_stories=dump_stories, )","async def train_comparison_models( file_importer, train_path, policy_config=policy_config, exclusion_percentage=percentage, kwargs=kwargs, dump_stories=dump_stories, )" 484,https://:@github.com/RasaHQ/rasa.git,3b51563dc49830f4e5f9a09ebd823c5f7eb563ef,"@@ -29,7 +29,7 @@ class Tokenizer(Component): if ""use_cls_token"" in self.component_config: self.use_cls_token = self.component_config[""use_cls_token""] else: - self.use_cls_token = False + self.use_cls_token = True def add_cls_token( self, tokens: List[Token], attribute: Text = MESSAGE_TEXT_ATTRIBUTE ",rasa/nlu/tokenizers/tokenizer.py,"ReplaceText(target='True' @(32,33)->(32,38))","class Tokenizer(Component): if ""use_cls_token"" in self.component_config: self.use_cls_token = self.component_config[""use_cls_token""] else: self.use_cls_token = False def add_cls_token( self, tokens: List[Token], attribute: Text = MESSAGE_TEXT_ATTRIBUTE","class Tokenizer(Component): if ""use_cls_token"" in self.component_config: self.use_cls_token = self.component_config[""use_cls_token""] else: self.use_cls_token = True def add_cls_token( self, tokens: List[Token], attribute: Text = MESSAGE_TEXT_ATTRIBUTE" 485,https://:@github.com/RasaHQ/rasa.git,f96eb791fb2236695a98fd5a4f935c3c5d316fe3,"@@ -376,7 +376,7 @@ def test_intent_evaluation_report_large(tmpdir_factory): assert len(report.keys()) == 8 assert report[""A""] == a_results - assert result[""E""] == e_results + assert report[""E""] == e_results def test_response_evaluation_report(tmpdir_factory): ",tests/nlu/base/test_evaluation.py,"ReplaceText(target='report' @(379,11)->(379,17))","def test_intent_evaluation_report_large(tmpdir_factory): assert len(report.keys()) == 8 assert report[""A""] == a_results assert result[""E""] == e_results def test_response_evaluation_report(tmpdir_factory):","def test_intent_evaluation_report_large(tmpdir_factory): assert len(report.keys()) == 8 assert report[""A""] == a_results assert report[""E""] == e_results def test_response_evaluation_report(tmpdir_factory):" 486,https://:@github.com/RasaHQ/rasa.git,ff9bb32d79e484cd2cfd7cde0acfa9d0006e14f8,"@@ -527,7 +527,7 @@ class DotProductLoss(tf.keras.layers.Layer): tiled = tf.tile(tf.expand_dims(x, 0), (batch_size, 1, 1)) - return tf.gather(tiled, idxs, batch_dims=-1) + return tf.gather(tiled, idxs, batch_dims=1) def _get_bad_mask( self, labels: ""tf.Tensor"", target_labels: ""tf.Tensor"", idxs: ""tf.Tensor"" ",rasa/utils/tf_layers.py,"ReplaceText(target='1' @(530,49)->(530,51))","class DotProductLoss(tf.keras.layers.Layer): tiled = tf.tile(tf.expand_dims(x, 0), (batch_size, 1, 1)) return tf.gather(tiled, idxs, batch_dims=-1) def _get_bad_mask( self, labels: ""tf.Tensor"", target_labels: ""tf.Tensor"", idxs: ""tf.Tensor""","class DotProductLoss(tf.keras.layers.Layer): tiled = tf.tile(tf.expand_dims(x, 0), (batch_size, 1, 1)) return tf.gather(tiled, idxs, batch_dims=1) def _get_bad_mask( self, labels: ""tf.Tensor"", target_labels: ""tf.Tensor"", idxs: ""tf.Tensor""" 487,https://:@github.com/RasaHQ/rasa.git,75e04b5ec3cb1ac6925152f491db074a391a9378,"@@ -67,7 +67,7 @@ class SpacyFeaturizer(Featurizer): non_zero_features = np.array([f for f in features if f.any()]) if self.pooling_operation == ""mean"": - return np.mean(features, axis=0, keepdims=True) + return np.mean(non_zero_features, axis=0, keepdims=True) elif self.pooling_operation == ""max"": return np.max(features, axis=0, keepdims=True) else: ",rasa/nlu/featurizers/dense_featurizer/spacy_featurizer.py,"ReplaceText(target='non_zero_features' @(70,27)->(70,35))","class SpacyFeaturizer(Featurizer): non_zero_features = np.array([f for f in features if f.any()]) if self.pooling_operation == ""mean"": return np.mean(features, axis=0, keepdims=True) elif self.pooling_operation == ""max"": return np.max(features, axis=0, keepdims=True) else:","class SpacyFeaturizer(Featurizer): non_zero_features = np.array([f for f in features if f.any()]) if self.pooling_operation == ""mean"": return np.mean(non_zero_features, axis=0, keepdims=True) elif self.pooling_operation == ""max"": return np.max(features, axis=0, keepdims=True) else:" 488,https://:@github.com/RasaHQ/rasa.git,ba4b8f70ffbb7bb4d3429c3b6aaa1f9fbcc3f632,"@@ -69,7 +69,7 @@ class SpacyFeaturizer(Featurizer): if self.pooling_operation == ""mean"": return np.mean(non_zero_features, axis=0, keepdims=True) elif self.pooling_operation == ""max"": - return np.max(features, axis=0, keepdims=True) + return np.max(non_zero_features, axis=0, keepdims=True) else: raise ValueError( f""Invalid pooling operation specified. Available operations are "" ",rasa/nlu/featurizers/dense_featurizer/spacy_featurizer.py,"ReplaceText(target='non_zero_features' @(72,26)->(72,34))","class SpacyFeaturizer(Featurizer): if self.pooling_operation == ""mean"": return np.mean(non_zero_features, axis=0, keepdims=True) elif self.pooling_operation == ""max"": return np.max(features, axis=0, keepdims=True) else: raise ValueError( f""Invalid pooling operation specified. Available operations are ""","class SpacyFeaturizer(Featurizer): if self.pooling_operation == ""mean"": return np.mean(non_zero_features, axis=0, keepdims=True) elif self.pooling_operation == ""max"": return np.max(non_zero_features, axis=0, keepdims=True) else: raise ValueError( f""Invalid pooling operation specified. Available operations are """ 489,https://:@github.com/RasaHQ/rasa.git,a2552e73fc8e4a656f43796101121ff8963bc0da,"@@ -50,7 +50,7 @@ class EntityExtractor(Component): # get indices of entity labels that belong to one word for idx in range(1, len(entities)): if entities[idx][""start""] == entities[idx - 1][""end""]: - if entity_indices and entity_indices[-1][1] == idx - 1: + if entity_indices and entity_indices[-1][-1] == idx - 1: entity_indices[-1].append(idx) else: entity_indices.append([idx - 1, idx]) ",rasa/nlu/extractors/extractor.py,"ReplaceText(target='-1' @(53,57)->(53,58))","class EntityExtractor(Component): # get indices of entity labels that belong to one word for idx in range(1, len(entities)): if entities[idx][""start""] == entities[idx - 1][""end""]: if entity_indices and entity_indices[-1][1] == idx - 1: entity_indices[-1].append(idx) else: entity_indices.append([idx - 1, idx])","class EntityExtractor(Component): # get indices of entity labels that belong to one word for idx in range(1, len(entities)): if entities[idx][""start""] == entities[idx - 1][""end""]: if entity_indices and entity_indices[-1][-1] == idx - 1: entity_indices[-1].append(idx) else: entity_indices.append([idx - 1, idx])" 490,https://:@github.com/RasaHQ/rasa.git,16ac7259b842e188c5c012bcaf6303e4bf4a4602,"@@ -223,7 +223,7 @@ class RasaModel(tf.keras.models.Model): self.save(self.best_model_file, overwrite=True) if best_model_epoch >= 0: - logger.info(f'The model of epoch {epoch} (out of {epochs} in total) will be stored!') + logger.info(f'The model of epoch {best_model_epoch} (out of {epochs} in total) will be stored!') if self.model_summary_file is not None: self._write_model_summary() ",rasa/utils/tensorflow/models.py,"ReplaceText(target='best_model_epoch' @(226,46)->(226,51))","class RasaModel(tf.keras.models.Model): self.save(self.best_model_file, overwrite=True) if best_model_epoch >= 0: logger.info(f'The model of epoch {epoch} (out of {epochs} in total) will be stored!') if self.model_summary_file is not None: self._write_model_summary() ","class RasaModel(tf.keras.models.Model): self.save(self.best_model_file, overwrite=True) if best_model_epoch >= 0: logger.info(f'The model of epoch {best_model_epoch} (out of {epochs} in total) will be stored!') if self.model_summary_file is not None: self._write_model_summary() " 491,https://:@github.com/RasaHQ/rasa.git,194820a60d61607fc480a95d981cb570e9ec3d4f,"@@ -254,7 +254,7 @@ class RasaModel(tf.keras.models.Model): val_results = self._get_metric_results(prefix=""val_"") if self._does_model_improve(val_results): logger.debug(f""Creating model checkpoint after training..."") - best_model_epoch = epoch + best_model_epoch = epochs self.save(self.best_model_file, overwrite=True) if best_model_epoch >= 0: ",rasa/utils/tensorflow/models.py,"ReplaceText(target='epochs' @(257,35)->(257,40))","class RasaModel(tf.keras.models.Model): val_results = self._get_metric_results(prefix=""val_"") if self._does_model_improve(val_results): logger.debug(f""Creating model checkpoint after training..."") best_model_epoch = epoch self.save(self.best_model_file, overwrite=True) if best_model_epoch >= 0:","class RasaModel(tf.keras.models.Model): val_results = self._get_metric_results(prefix=""val_"") if self._does_model_improve(val_results): logger.debug(f""Creating model checkpoint after training..."") best_model_epoch = epochs self.save(self.best_model_file, overwrite=True) if best_model_epoch >= 0:" 492,https://:@github.com/gbrammer/grizli.git,a14c6aef2fb7790a5418ac882e332cbddf3771d9,"@@ -87,7 +87,7 @@ def run_all(id, t0=None, t1=None, fwhm=1200, zr=[0.65, 1.6], dz=[0.004, 0.0002], if scale_photometry: scl = mb.scale_to_photometry(z=fit.meta['z_map'][0], method='lm', templates=t0, order=scale_photometry*1) - if scl.status == 0: + if scl.status > 0: mb.pscale = scl.x st.pscale = scl.x ",grizli/fitting.py,"ReplaceText(target='>' @(90,22)->(90,24))","def run_all(id, t0=None, t1=None, fwhm=1200, zr=[0.65, 1.6], dz=[0.004, 0.0002], if scale_photometry: scl = mb.scale_to_photometry(z=fit.meta['z_map'][0], method='lm', templates=t0, order=scale_photometry*1) if scl.status == 0: mb.pscale = scl.x st.pscale = scl.x ","def run_all(id, t0=None, t1=None, fwhm=1200, zr=[0.65, 1.6], dz=[0.004, 0.0002], if scale_photometry: scl = mb.scale_to_photometry(z=fit.meta['z_map'][0], method='lm', templates=t0, order=scale_photometry*1) if scl.status > 0: mb.pscale = scl.x st.pscale = scl.x " 493,https://:@github.com/gbrammer/grizli.git,06b2bb1a51cc4090eb57f37798a4b6cb6b24b2c2,"@@ -2291,7 +2291,7 @@ For example, # Pixel area map pam = os.path.join(os.getenv('iref'), 'ir_wfc3_map.fits') print('Pixel area map: {0}'.format(pam)) - if not os.path.exists(badpix): + if not os.path.exists(pam): os.system('curl -o {0} http://www.stsci.edu/hst/wfc3/pam/ir_wfc3_map.fits'.format(pam)) def fetch_config_files(ACS=False): ",grizli/utils.py,"ReplaceText(target='pam' @(2294,26)->(2294,32))","For example, # Pixel area map pam = os.path.join(os.getenv('iref'), 'ir_wfc3_map.fits') print('Pixel area map: {0}'.format(pam)) if not os.path.exists(badpix): os.system('curl -o {0} http://www.stsci.edu/hst/wfc3/pam/ir_wfc3_map.fits'.format(pam)) def fetch_config_files(ACS=False):","For example, # Pixel area map pam = os.path.join(os.getenv('iref'), 'ir_wfc3_map.fits') print('Pixel area map: {0}'.format(pam)) if not os.path.exists(pam): os.system('curl -o {0} http://www.stsci.edu/hst/wfc3/pam/ir_wfc3_map.fits'.format(pam)) def fetch_config_files(ACS=False):" 494,https://:@github.com/gbrammer/grizli.git,60c15addafcb4ac4a0e55bc697b4bb18d6463736,"@@ -229,7 +229,7 @@ def go(root='j010311+131615', maglim=[17,26], HOME_PATH='/Volumes/Pegasus/Grizli ir_ref = None auto_script.drizzle_overlaps(root, filters=optical_filters, - make_combined=(ir_ref is not None), ref_image=ir_ref) + make_combined=(ir_ref is None), ref_image=ir_ref) if ir_ref is None: # Need ",grizli/pipeline/auto_script.py,"ReplaceText(target=' is ' @(232,33)->(232,41))","def go(root='j010311+131615', maglim=[17,26], HOME_PATH='/Volumes/Pegasus/Grizli ir_ref = None auto_script.drizzle_overlaps(root, filters=optical_filters, make_combined=(ir_ref is not None), ref_image=ir_ref) if ir_ref is None: # Need ","def go(root='j010311+131615', maglim=[17,26], HOME_PATH='/Volumes/Pegasus/Grizli ir_ref = None auto_script.drizzle_overlaps(root, filters=optical_filters, make_combined=(ir_ref is None), ref_image=ir_ref) if ir_ref is None: # Need " 495,https://:@github.com/gbrammer/grizli.git,e32899e470d02fa98365ca1ab1bfc70d6b64077b,"@@ -3420,7 +3420,7 @@ def field_rgb(root='j010514+021532', xsize=6, output_dpi=None, HOME_PATH='./', s PATH_TO = '{0}/{1}/Prep'.format(HOME_PATH, root) else: PATH_TO = './' - sci_files = glob.glob('./{1}-f*sci.fits'.format(HOME_PATH, root)) + sci_files = glob.glob('./{1}-f*sci.fits'.format(PATH_TO, root)) if filters is None: filters = [file.split('_')[-3].split('-')[-1] for file in sci_files] ",grizli/pipeline/auto_script.py,"ReplaceText(target='PATH_TO' @(3423,56)->(3423,65))","def field_rgb(root='j010514+021532', xsize=6, output_dpi=None, HOME_PATH='./', s PATH_TO = '{0}/{1}/Prep'.format(HOME_PATH, root) else: PATH_TO = './' sci_files = glob.glob('./{1}-f*sci.fits'.format(HOME_PATH, root)) if filters is None: filters = [file.split('_')[-3].split('-')[-1] for file in sci_files]","def field_rgb(root='j010514+021532', xsize=6, output_dpi=None, HOME_PATH='./', s PATH_TO = '{0}/{1}/Prep'.format(HOME_PATH, root) else: PATH_TO = './' sci_files = glob.glob('./{1}-f*sci.fits'.format(PATH_TO, root)) if filters is None: filters = [file.split('_')[-3].split('-')[-1] for file in sci_files]" 496,https://:@github.com/gbrammer/grizli.git,27974fdbe2c948dee6777f6c6d333b46e1456a80,"@@ -575,7 +575,7 @@ class GroupFLT(): is_cgs=False): """"""TBD """""" - if cpu_count == 0: + if cpu_count <= 0: cpu_count = mp.cpu_count() if fit_info is None: ",grizli/multifit.py,"ReplaceText(target='<=' @(578,21)->(578,23))","class GroupFLT(): is_cgs=False): """"""TBD """""" if cpu_count == 0: cpu_count = mp.cpu_count() if fit_info is None:","class GroupFLT(): is_cgs=False): """"""TBD """""" if cpu_count <= 0: cpu_count = mp.cpu_count() if fit_info is None:" 497,https://:@github.com/gbrammer/grizli.git,73b7211978b46ce1f7bcc1de111237c047fbe00e,"@@ -959,7 +959,7 @@ def parse_visits(field_root='', HOME_PATH='./', use_visit=True, combine_same_pa= elif (combine_minexp > 0) & (not has_grism): combined = [] for visit in visits: - if len(visit['files']) > combine_minexp*1: + if len(visit['files']) >= combine_minexp*1: combined.append(copy.deepcopy(visit)) else: filter_pa = '-'.join(visit['product'].split('-')[-2:]) ",grizli/pipeline/auto_script.py,"ReplaceText(target='>=' @(962,35)->(962,36))","def parse_visits(field_root='', HOME_PATH='./', use_visit=True, combine_same_pa= elif (combine_minexp > 0) & (not has_grism): combined = [] for visit in visits: if len(visit['files']) > combine_minexp*1: combined.append(copy.deepcopy(visit)) else: filter_pa = '-'.join(visit['product'].split('-')[-2:])","def parse_visits(field_root='', HOME_PATH='./', use_visit=True, combine_same_pa= elif (combine_minexp > 0) & (not has_grism): combined = [] for visit in visits: if len(visit['files']) >= combine_minexp*1: combined.append(copy.deepcopy(visit)) else: filter_pa = '-'.join(visit['product'].split('-')[-2:])" 498,https://:@github.com/gbrammer/grizli.git,54178395a55d79f53bf11d651b53bb6bc3448eb6,"@@ -3386,7 +3386,7 @@ def make_filter_combinations(root, weight_fnu=True, filter_combinations=FILTER_C # UVIS if filt_i.startswith('f') & filt_i.endswith('u'): - filt_i = filt_i[:1] + filt_i = filt_i[:-1] band = None for f in filter_combinations: ",grizli/pipeline/auto_script.py,"ReplaceText(target='-1' @(3389,29)->(3389,30))","def make_filter_combinations(root, weight_fnu=True, filter_combinations=FILTER_C # UVIS if filt_i.startswith('f') & filt_i.endswith('u'): filt_i = filt_i[:1] band = None for f in filter_combinations:","def make_filter_combinations(root, weight_fnu=True, filter_combinations=FILTER_C # UVIS if filt_i.startswith('f') & filt_i.endswith('u'): filt_i = filt_i[:-1] band = None for f in filter_combinations:" 499,https://:@github.com/PmagPy/PmagPy.git,153e127b39023f35ad6724b0e89609849ec48689,"@@ -33,7 +33,7 @@ def main(): try: fh_last = open(last_path, 'r+') last_checked = pickle.load(fh_last) - if last_checked > time.time() - 24*60*60: + if last_checked < time.time() - 24*60*60: return # stop here because it's been less than 24 hours else: pickle.dump(time.time(), fh_last) ",check_updates.py,"ReplaceText(target='<' @(36,24)->(36,25))","def main(): try: fh_last = open(last_path, 'r+') last_checked = pickle.load(fh_last) if last_checked > time.time() - 24*60*60: return # stop here because it's been less than 24 hours else: pickle.dump(time.time(), fh_last)","def main(): try: fh_last = open(last_path, 'r+') last_checked = pickle.load(fh_last) if last_checked < time.time() - 24*60*60: return # stop here because it's been less than 24 hours else: pickle.dump(time.time(), fh_last)" 500,https://:@github.com/PmagPy/PmagPy.git,1c9dfb436532fcefcdf85913462eca89c4a05886,"@@ -3363,7 +3363,7 @@ def upload_magic3(concat=0, dir_path='.', dmodel=None, vocab="""", contribution=No # otherwise create a new Contribution in dir_path con = Contribution(dir_path, vocabulary=vocab) - dir_path = contribution.directory + dir_path = con.directory # take out any extra added columns con.remove_non_magic_cols() # begin the upload process ",pmagpy/ipmag.py,"ReplaceText(target='con' @(3366,15)->(3366,27))","def upload_magic3(concat=0, dir_path='.', dmodel=None, vocab="""", contribution=No # otherwise create a new Contribution in dir_path con = Contribution(dir_path, vocabulary=vocab) dir_path = contribution.directory # take out any extra added columns con.remove_non_magic_cols() # begin the upload process","def upload_magic3(concat=0, dir_path='.', dmodel=None, vocab="""", contribution=No # otherwise create a new Contribution in dir_path con = Contribution(dir_path, vocabulary=vocab) dir_path = con.directory # take out any extra added columns con.remove_non_magic_cols() # begin the upload process" 501,https://:@github.com/PmagPy/PmagPy.git,8fd06aa1272e4a82082fc0a0b5641242e2f18154,"@@ -72,7 +72,7 @@ def main(): pastTime=startTime if d < commandLength: pastTime=startTime-commandLength - printout=""Due to long processing time the look-back time has been extended to "" +str(pastTime.total_seconds()) + "" seconds"" + ""\n"" + printout=""Due to long processing time the look-back time has been extended to "" +str(commandLength.total_seconds()) + "" seconds"" + ""\n"" f.write(printout) else: pastTime=startTime-d ",programs/createNewPlots.py,"ReplaceText(target='commandLength' @(75,97)->(75,105))","def main(): pastTime=startTime if d < commandLength: pastTime=startTime-commandLength printout=""Due to long processing time the look-back time has been extended to "" +str(pastTime.total_seconds()) + "" seconds"" + ""\n"" f.write(printout) else: pastTime=startTime-d","def main(): pastTime=startTime if d < commandLength: pastTime=startTime-commandLength printout=""Due to long processing time the look-back time has been extended to "" +str(commandLength.total_seconds()) + "" seconds"" + ""\n"" f.write(printout) else: pastTime=startTime-d" 502,https://:@github.com/PmagPy/PmagPy.git,de14e55e58558ac9d6980bdaf309fe17496a8f44,"@@ -3524,7 +3524,7 @@ def iodp_kly4s_lore(kly4s_file, meas_out='measurements.txt', tau3=in_df['Kmin susceptibility (SI)']/3 v3_dec=in_df['Kmin dec (deg)'] v3_inc=in_df['Kmin inc (deg)'] - specimens_df['aniso_v3']=tau1.astype('str')+"":""+v3_dec.astype('str')+"":""+v3_inc.astype('str') + specimens_df['aniso_v3']=tau3.astype('str')+"":""+v3_dec.astype('str')+"":""+v3_inc.astype('str') # output data files ",pmagpy/convert_2_magic.py,"ReplaceText(target='tau3' @(3527,29)->(3527,33))","def iodp_kly4s_lore(kly4s_file, meas_out='measurements.txt', tau3=in_df['Kmin susceptibility (SI)']/3 v3_dec=in_df['Kmin dec (deg)'] v3_inc=in_df['Kmin inc (deg)'] specimens_df['aniso_v3']=tau1.astype('str')+"":""+v3_dec.astype('str')+"":""+v3_inc.astype('str') # output data files","def iodp_kly4s_lore(kly4s_file, meas_out='measurements.txt', tau3=in_df['Kmin susceptibility (SI)']/3 v3_dec=in_df['Kmin dec (deg)'] v3_inc=in_df['Kmin inc (deg)'] specimens_df['aniso_v3']=tau3.astype('str')+"":""+v3_dec.astype('str')+"":""+v3_inc.astype('str') # output data files" 503,https://:@github.com/efficios/pytsdl.git,1b6d994aa14340af28ed903692ff0fde598ebaeb,"@@ -1671,7 +1671,7 @@ class _DocCreatorVisitor: # assign tag to copy now variant_copy.tag = self._decode_unary(t.tag.value) - return variant + return variant_copy def _type_to_obj(self, t): return self._type_to_obj_map[type(t)](t) ",pytsdl/parser.py,"ReplaceText(target='variant_copy' @(1674,15)->(1674,22))","class _DocCreatorVisitor: # assign tag to copy now variant_copy.tag = self._decode_unary(t.tag.value) return variant def _type_to_obj(self, t): return self._type_to_obj_map[type(t)](t)","class _DocCreatorVisitor: # assign tag to copy now variant_copy.tag = self._decode_unary(t.tag.value) return variant_copy def _type_to_obj(self, t): return self._type_to_obj_map[type(t)](t)" 504,https://:@github.com/mabrownnyu/youtube-data-api.git,07d71d5668d1dbeec28d84ce1cf8982fbd71be36,"@@ -585,7 +585,7 @@ class YoutubeDataApi: else: captions = [] for v_id in video_id: - captions.append(_get_captions(video_id, lang_code=lang_code, parser=parser, **kwargs)) + captions.append(_get_captions(v_id, lang_code=lang_code, parser=parser, **kwargs)) return captions ",youtube_api/youtube_api.py,"ReplaceText(target='v_id' @(588,46)->(588,54))","class YoutubeDataApi: else: captions = [] for v_id in video_id: captions.append(_get_captions(video_id, lang_code=lang_code, parser=parser, **kwargs)) return captions ","class YoutubeDataApi: else: captions = [] for v_id in video_id: captions.append(_get_captions(v_id, lang_code=lang_code, parser=parser, **kwargs)) return captions " 505,https://:@github.com/xhochy/conda-mirror-ng.git,e0b34555d779f9b440512f850da39aa5a0e29ece,"@@ -85,5 +85,5 @@ def test_handling_bad_package(tmpdir, repodata): with bz2.BZ2File(bad_pkg_path, 'wb') as f: f.write(""This is a fake package"".encode()) assert bad_pkg_name in os.listdir(bad_pkg_root) - conda_mirror._validate_packages(repodata, local_repo_root) + conda_mirror._validate_packages(repodata, bad_pkg_root) assert bad_pkg_name not in os.listdir(bad_pkg_root) \ No newline at end of file ",test/test_conda_mirror.py,"ReplaceText(target='bad_pkg_root' @(88,46)->(88,61))","def test_handling_bad_package(tmpdir, repodata): with bz2.BZ2File(bad_pkg_path, 'wb') as f: f.write(""This is a fake package"".encode()) assert bad_pkg_name in os.listdir(bad_pkg_root) conda_mirror._validate_packages(repodata, local_repo_root) assert bad_pkg_name not in os.listdir(bad_pkg_root) \ No newline at end of file","def test_handling_bad_package(tmpdir, repodata): with bz2.BZ2File(bad_pkg_path, 'wb') as f: f.write(""This is a fake package"".encode()) assert bad_pkg_name in os.listdir(bad_pkg_root) conda_mirror._validate_packages(repodata, bad_pkg_root) assert bad_pkg_name not in os.listdir(bad_pkg_root) \ No newline at end of file" 506,https://:@github.com/kelsoncm/sc4.git,8c4e8ac8358668aaa6c32b73af44178e6e9db3ab,"@@ -45,6 +45,6 @@ def others_months(): def daterange(start, end, step=datetime.timedelta(1)): curr = start - while curr < end: + while curr <= end: yield curr curr += step ",sc4py/sc4py/datetime.py,"ReplaceText(target='<=' @(48,15)->(48,16))","def others_months(): def daterange(start, end, step=datetime.timedelta(1)): curr = start while curr < end: yield curr curr += step","def others_months(): def daterange(start, end, step=datetime.timedelta(1)): curr = start while curr <= end: yield curr curr += step" 507,https://:@github.com/makingspace/pubsubpy.git,bd6903e8ea6e7069712d7cf17cb725aa7f821d1a,"@@ -5,7 +5,7 @@ MODEL_EXCHANGE = 'model_exchange' __REQUIRED_INIT_KWARGS = {AMQP_URL, MODEL_EXCHANGE} __OPTIONAL_INIT_KWARGS = set() -__ALLOWED_INIT_KWARGS = __REQUIRED_INIT_KWARGS & __OPTIONAL_INIT_KWARGS +__ALLOWED_INIT_KWARGS = __REQUIRED_INIT_KWARGS | __OPTIONAL_INIT_KWARGS def init(**kwargs): ",pubsub/__init__.py,"ReplaceText(target='|' @(8,47)->(8,48))","MODEL_EXCHANGE = 'model_exchange' __REQUIRED_INIT_KWARGS = {AMQP_URL, MODEL_EXCHANGE} __OPTIONAL_INIT_KWARGS = set() __ALLOWED_INIT_KWARGS = __REQUIRED_INIT_KWARGS & __OPTIONAL_INIT_KWARGS def init(**kwargs):","MODEL_EXCHANGE = 'model_exchange' __REQUIRED_INIT_KWARGS = {AMQP_URL, MODEL_EXCHANGE} __OPTIONAL_INIT_KWARGS = set() __ALLOWED_INIT_KWARGS = __REQUIRED_INIT_KWARGS | __OPTIONAL_INIT_KWARGS def init(**kwargs):" 508,https://:@github.com/moff4/kframe.git,01c644e825136b2b86d9b6f7dd6a34e4997c128c,"@@ -310,7 +310,7 @@ class Parent: kwargs (dict) - dict of arg that will be passed to init() as **kwargs (plugins only) """""" from kframe.base.plugin import Plugin - if issubclass(target, Plugin): + if not issubclass(target, Plugin): raise ValueError('target ({}) bust be isinstance of kframe.Plugin'.format(str(target))) self.plugin_t[kw.get('key', target.name)] = { 'target': target, ",kframe/base/parent.py,"ReplaceText(target='not ' @(313,11)->(313,11))","class Parent: kwargs (dict) - dict of arg that will be passed to init() as **kwargs (plugins only) """""" from kframe.base.plugin import Plugin if issubclass(target, Plugin): raise ValueError('target ({}) bust be isinstance of kframe.Plugin'.format(str(target))) self.plugin_t[kw.get('key', target.name)] = { 'target': target,","class Parent: kwargs (dict) - dict of arg that will be passed to init() as **kwargs (plugins only) """""" from kframe.base.plugin import Plugin if not issubclass(target, Plugin): raise ValueError('target ({}) bust be isinstance of kframe.Plugin'.format(str(target))) self.plugin_t[kw.get('key', target.name)] = { 'target': target," 509,https://:@github.com/moff4/kframe.git,85c41d1f13cb2c7d79787bbe35de661aa6c6b824,"@@ -329,7 +329,7 @@ class Task: cfg.update(kwargs) if 'shedule' in cfg: cfg['shedule'] = self._convert_shedule(cfg['shedule']) - self.cfg.update(kwargs) + self.cfg.update(cfg) def ready_for_run(self, t, tm): """""" ",kframe/plugins/planner/task.py,"ReplaceText(target='cfg' @(332,24)->(332,30))","class Task: cfg.update(kwargs) if 'shedule' in cfg: cfg['shedule'] = self._convert_shedule(cfg['shedule']) self.cfg.update(kwargs) def ready_for_run(self, t, tm): """"""","class Task: cfg.update(kwargs) if 'shedule' in cfg: cfg['shedule'] = self._convert_shedule(cfg['shedule']) self.cfg.update(cfg) def ready_for_run(self, t, tm): """"""" 510,https://:@github.com/qaviton/qaviton_package_manager.git,0498c2b71479109db949e369a0b7189d75dded65,"@@ -63,7 +63,7 @@ class Build(Prep): def update_version(self, version): version = self.versioning(version) content = self.get_pkg_init() - if b'\n__version__' not in content or not content.startswith(b'__version__'): + if b'\n__version__' not in content and not content.startswith(b'__version__'): raise IOError(""missing __version__ in the package __init__.py file"") lines = content.splitlines() for i, line in enumerate(lines): ",qaviton_package_manager/manager_methods/distribute_to_git.py,"ReplaceText(target='and' @(66,43)->(66,45))","class Build(Prep): def update_version(self, version): version = self.versioning(version) content = self.get_pkg_init() if b'\n__version__' not in content or not content.startswith(b'__version__'): raise IOError(""missing __version__ in the package __init__.py file"") lines = content.splitlines() for i, line in enumerate(lines):","class Build(Prep): def update_version(self, version): version = self.versioning(version) content = self.get_pkg_init() if b'\n__version__' not in content and not content.startswith(b'__version__'): raise IOError(""missing __version__ in the package __init__.py file"") lines = content.splitlines() for i, line in enumerate(lines):" 511,https://:@github.com/morganthrapp/pyACH.git,516f347fa832237e2868544c078f86f80c7c2a1c,"@@ -256,7 +256,7 @@ class BatchHeader: def _get_effective_entry_date(effective_entry_date): _date = datetime.datetime.today() _date += datetime.timedelta(days=effective_entry_date) - while _date.isoweekday() not in WEEKEND: + while _date.isoweekday() in WEEKEND: _date += datetime.timedelta(days=1) return _date.strftime(day_format_string) ",pyach/ACHRecordTypes.py,"ReplaceText(target=' in ' @(259,32)->(259,40))","class BatchHeader: def _get_effective_entry_date(effective_entry_date): _date = datetime.datetime.today() _date += datetime.timedelta(days=effective_entry_date) while _date.isoweekday() not in WEEKEND: _date += datetime.timedelta(days=1) return _date.strftime(day_format_string) ","class BatchHeader: def _get_effective_entry_date(effective_entry_date): _date = datetime.datetime.today() _date += datetime.timedelta(days=effective_entry_date) while _date.isoweekday() in WEEKEND: _date += datetime.timedelta(days=1) return _date.strftime(day_format_string) " 512,https://:@github.com/eldarion/agon-ratings.git,99a317f1ead850e948cf08123fef8ea60b30060e,"@@ -72,7 +72,7 @@ class Rating(models.Model): rating_obj = None if rating_obj and rating == 0: - return rating.clear() + return rating_obj.clear() if rating_obj is None: rating_obj = cls.objects.create( ",pinax/ratings/models.py,"ReplaceText(target='rating_obj' @(75,19)->(75,25))","class Rating(models.Model): rating_obj = None if rating_obj and rating == 0: return rating.clear() if rating_obj is None: rating_obj = cls.objects.create(","class Rating(models.Model): rating_obj = None if rating_obj and rating == 0: return rating_obj.clear() if rating_obj is None: rating_obj = cls.objects.create(" 513,https://:@github.com/sraashis/ature.git,caee2ab19dc6b73ab1916156ad80c5732957803f,"@@ -94,7 +94,7 @@ class PatchesGenerator(Dataset): img_tensor = self.transform(img_tensor) if self.segment_mode: - return self.data[ID], img_tensor, self.labels[index] + return self.data[index], img_tensor, self.labels[index] return img_tensor, self.labels[index] ",neuralnet/utils/datasets.py,"ReplaceText(target='index' @(97,29)->(97,31))","class PatchesGenerator(Dataset): img_tensor = self.transform(img_tensor) if self.segment_mode: return self.data[ID], img_tensor, self.labels[index] return img_tensor, self.labels[index] ","class PatchesGenerator(Dataset): img_tensor = self.transform(img_tensor) if self.segment_mode: return self.data[index], img_tensor, self.labels[index] return img_tensor, self.labels[index] " 514,https://:@github.com/sraashis/ature.git,e192de63324d8472c331bd06ab36ea710ee93d2a,"@@ -96,7 +96,7 @@ class ThrnetTrainer(NNTrainer): img_loss += current_loss thr = thr_map[..., None][..., None] - segmented = (prob_map >= thr.byte()) + segmented = (prob_map > thr.byte()) # batch_score = ScoreAccumulator().add_tensor(segmented, truth) print('Loss: ', current_loss, end='\r') ",neuralnet/thrnet/thrnet_trainer.py,"ReplaceText(target='>' @(99,42)->(99,44))","class ThrnetTrainer(NNTrainer): img_loss += current_loss thr = thr_map[..., None][..., None] segmented = (prob_map >= thr.byte()) # batch_score = ScoreAccumulator().add_tensor(segmented, truth) print('Loss: ', current_loss, end='\r')","class ThrnetTrainer(NNTrainer): img_loss += current_loss thr = thr_map[..., None][..., None] segmented = (prob_map > thr.byte()) # batch_score = ScoreAccumulator().add_tensor(segmented, truth) print('Loss: ', current_loss, end='\r')" 515,https://:@github.com/sraashis/ature.git,934f9ff3b34b487614e4f2653c153cd78d716b57,"@@ -50,7 +50,7 @@ class ThrnetTrainer(NNTrainer): if gen_images: img = segmented_img.clone().cpu().numpy() - img_score.add_array(img_obj.ground_truth, img) + img_score.add_array(img, img_obj.ground_truth) # img = iu.remove_connected_comp(np.array(segmented_img, dtype=np.uint8), # connected_comp_diam_limit=10) IMG.fromarray(np.array(img, dtype=np.uint8)).save( ",neuralnet/mapnet/mapnet_trainer.py,"ArgSwap(idxs=0<->1 @(53,20)->(53,39))","class ThrnetTrainer(NNTrainer): if gen_images: img = segmented_img.clone().cpu().numpy() img_score.add_array(img_obj.ground_truth, img) # img = iu.remove_connected_comp(np.array(segmented_img, dtype=np.uint8), # connected_comp_diam_limit=10) IMG.fromarray(np.array(img, dtype=np.uint8)).save(","class ThrnetTrainer(NNTrainer): if gen_images: img = segmented_img.clone().cpu().numpy() img_score.add_array(img, img_obj.ground_truth) # img = iu.remove_connected_comp(np.array(segmented_img, dtype=np.uint8), # connected_comp_diam_limit=10) IMG.fromarray(np.array(img, dtype=np.uint8)).save(" 516,https://:@github.com/sraashis/ature.git,934f9ff3b34b487614e4f2653c153cd78d716b57,"@@ -59,7 +59,7 @@ class UNetNNTrainer(NNTrainer): if gen_images: map_img = map_img.cpu().numpy() predicted_img = predicted_img.cpu().numpy() - img_score.add_array(img_obj.ground_truth, predicted_img) + img_score.add_array(predicted_img, img_obj.ground_truth) IMG.fromarray(np.array(predicted_img, dtype=np.uint8)).save( os.path.join(self.log_dir, 'pred_' + img_obj.file_name.split('.')[0] + '.png')) IMG.fromarray(np.array(map_img, dtype=np.uint8)).save( ",neuralnet/unet/unet_trainer.py,"ArgSwap(idxs=0<->1 @(62,20)->(62,39))","class UNetNNTrainer(NNTrainer): if gen_images: map_img = map_img.cpu().numpy() predicted_img = predicted_img.cpu().numpy() img_score.add_array(img_obj.ground_truth, predicted_img) IMG.fromarray(np.array(predicted_img, dtype=np.uint8)).save( os.path.join(self.log_dir, 'pred_' + img_obj.file_name.split('.')[0] + '.png')) IMG.fromarray(np.array(map_img, dtype=np.uint8)).save(","class UNetNNTrainer(NNTrainer): if gen_images: map_img = map_img.cpu().numpy() predicted_img = predicted_img.cpu().numpy() img_score.add_array(predicted_img, img_obj.ground_truth) IMG.fromarray(np.array(predicted_img, dtype=np.uint8)).save( os.path.join(self.log_dir, 'pred_' + img_obj.file_name.split('.')[0] + '.png')) IMG.fromarray(np.array(map_img, dtype=np.uint8)).save(" 517,https://:@github.com/tessgi/ticgen.git,9350670fed545226d33c16432802990b6ddd7274,"@@ -144,7 +144,7 @@ class Star(object): E * self.Tmag**4 + F * self.Tmag**5) def get_oneSigmaNoise(self): - return (np.exp(self.get_oneHourNoiseLnsigma()) * + return (np.exp(self.get_oneHourNoiseLnsigma()) / np.sqrt(self.integration / 60.)) def TESS_Mag_VJKs(self): ",ticgen/ticgen.py,"ReplaceText(target='/' @(147,55)->(147,56))","class Star(object): E * self.Tmag**4 + F * self.Tmag**5) def get_oneSigmaNoise(self): return (np.exp(self.get_oneHourNoiseLnsigma()) * np.sqrt(self.integration / 60.)) def TESS_Mag_VJKs(self):","class Star(object): E * self.Tmag**4 + F * self.Tmag**5) def get_oneSigmaNoise(self): return (np.exp(self.get_oneHourNoiseLnsigma()) / np.sqrt(self.integration / 60.)) def TESS_Mag_VJKs(self):" 518,https://:@github.com/aki-nishimura/bayes-bridge.git,728164889880a793dd156bafeeaaec2da93c4706,"@@ -94,7 +94,7 @@ class SparseRegressionCoefficientSampler(): )) precond_hessian_matvec = lambda beta: \ precond_prior_prec * beta \ - + precond_scale * loglik_hessian_matvec(precond_scale * beta) + - precond_scale * loglik_hessian_matvec(precond_scale * beta) precond_hessian_op = sp.sparse.linalg.LinearOperator( (X.shape[1], X.shape[1]), precond_hessian_matvec ) ",bayesbridge/reg_coef_sampler/reg_coef_sampler.py,"ReplaceText(target='-' @(97,12)->(97,13))","class SparseRegressionCoefficientSampler(): )) precond_hessian_matvec = lambda beta: \ precond_prior_prec * beta \ + precond_scale * loglik_hessian_matvec(precond_scale * beta) precond_hessian_op = sp.sparse.linalg.LinearOperator( (X.shape[1], X.shape[1]), precond_hessian_matvec )","class SparseRegressionCoefficientSampler(): )) precond_hessian_matvec = lambda beta: \ precond_prior_prec * beta \ - precond_scale * loglik_hessian_matvec(precond_scale * beta) precond_hessian_op = sp.sparse.linalg.LinearOperator( (X.shape[1], X.shape[1]), precond_hessian_matvec )" 519,https://:@github.com/aki-nishimura/bayes-bridge.git,8558d665b0d07e1565d88b4d477a67c576c7ffbd,"@@ -70,7 +70,7 @@ class BayesBridge(): self.model = LinearModel(outcome, X) elif model == 'logit': n_success, n_trial = outcome - self.model = LogisticModel(n_success, X, n_trial) + self.model = LogisticModel(n_success, n_trial, X) elif model == 'cox': self.model = CoxModel(event_time, censoring_time, X) else: ",bayesbridge/bayesbridge.py,"ArgSwap(idxs=1<->2 @(73,25)->(73,38))","class BayesBridge(): self.model = LinearModel(outcome, X) elif model == 'logit': n_success, n_trial = outcome self.model = LogisticModel(n_success, X, n_trial) elif model == 'cox': self.model = CoxModel(event_time, censoring_time, X) else:","class BayesBridge(): self.model = LinearModel(outcome, X) elif model == 'logit': n_success, n_trial = outcome self.model = LogisticModel(n_success, n_trial, X) elif model == 'cox': self.model = CoxModel(event_time, censoring_time, X) else:" 520,https://:@github.com/BTrDB/btrdb4-python.git,68f67274b6c2a6bb4a9206cfb00e7c3747cab1fa,"@@ -36,7 +36,7 @@ from btrdb4.endpoint import Endpoint from btrdb4.utils import * MIN_TIME = -(16 << 56) -MAX_TIME = 48 >> 56 +MAX_TIME = 48 << 56 MAX_POINTWIDTH = 63 class Connection(object): ",btrdb4/__init__.py,"ReplaceText(target='<<' @(39,14)->(39,16))","from btrdb4.endpoint import Endpoint from btrdb4.utils import * MIN_TIME = -(16 << 56) MAX_TIME = 48 >> 56 MAX_POINTWIDTH = 63 class Connection(object):","from btrdb4.endpoint import Endpoint from btrdb4.utils import * MIN_TIME = -(16 << 56) MAX_TIME = 48 << 56 MAX_POINTWIDTH = 63 class Connection(object):" 521,https://:@github.com/mahaoyang/newspaper.git,ac1d4c7346ddd0e035f9c7968e7e712340723934,"@@ -62,7 +62,7 @@ def prepare_url(url, source_url=None): """"""operations that purify a url, removes arguments, redirects, and merges relatives with absolutes"""""" - if source_url is None: + if source_url is not None: source_domain = urlparse(source_url).netloc proper_url = urljoin(source_url, url) proper_url = redirect_back(proper_url, source_domain) ",newspaper/urls.py,"ReplaceText(target=' is not ' @(65,17)->(65,21))","def prepare_url(url, source_url=None): """"""operations that purify a url, removes arguments, redirects, and merges relatives with absolutes"""""" if source_url is None: source_domain = urlparse(source_url).netloc proper_url = urljoin(source_url, url) proper_url = redirect_back(proper_url, source_domain)","def prepare_url(url, source_url=None): """"""operations that purify a url, removes arguments, redirects, and merges relatives with absolutes"""""" if source_url is not None: source_domain = urlparse(source_url).netloc proper_url = urljoin(source_url, url) proper_url = redirect_back(proper_url, source_domain)" 522,https://:@github.com/tmconsulting/onelya-railway-sdk.git,059265060ae8f9828ae6f5d7a143988cd9c5da4c,"@@ -28,7 +28,7 @@ class Session(object): if 'Code' in response: raise OnelyaAPIError(method, response, data) - return data + return response def __send_api_request(self, method, data): url = '{}{}'.format(Session.API_URL, method) ",onelya_railway_sdk/session.py,"ReplaceText(target='response' @(31,15)->(31,19))","class Session(object): if 'Code' in response: raise OnelyaAPIError(method, response, data) return data def __send_api_request(self, method, data): url = '{}{}'.format(Session.API_URL, method)","class Session(object): if 'Code' in response: raise OnelyaAPIError(method, response, data) return response def __send_api_request(self, method, data): url = '{}{}'.format(Session.API_URL, method)" 523,https://:@github.com/rafalp/misago-social-app-django.git,d1d23e7e3cf4364c0d35289290b27787b84f5211,"@@ -50,7 +50,7 @@ def sanitize_redirect(host, redirect_to): """""" # Quick sanity check. if not redirect_to or \ - not isinstance(redirect_to, six.string_types) and \ + not isinstance(redirect_to, six.string_types) or \ getattr(redirect_to, 'decode', None) and \ not isinstance(redirect_to.decode(), six.string_types): return None ",social/utils.py,"ReplaceText(target='or' @(53,53)->(53,56))","def sanitize_redirect(host, redirect_to): """""" # Quick sanity check. if not redirect_to or \ not isinstance(redirect_to, six.string_types) and \ getattr(redirect_to, 'decode', None) and \ not isinstance(redirect_to.decode(), six.string_types): return None","def sanitize_redirect(host, redirect_to): """""" # Quick sanity check. if not redirect_to or \ not isinstance(redirect_to, six.string_types) or \ getattr(redirect_to, 'decode', None) and \ not isinstance(redirect_to.decode(), six.string_types): return None" 524,https://:@github.com/rafalp/misago-social-app-django.git,7d0628e7a756526b50449435eb02b2806e815755,"@@ -132,7 +132,7 @@ def partial_pipeline_data(strategy, user, *args, **kwargs): kwargs.setdefault('user', user) kwargs.setdefault('request', strategy.request) kwargs.update(xkwargs) - return idx, backend, xargs, xkwargs + return idx, backend, xargs, kwargs def build_absolute_uri(host_url, path=None): ",social/utils.py,"ReplaceText(target='kwargs' @(135,36)->(135,43))","def partial_pipeline_data(strategy, user, *args, **kwargs): kwargs.setdefault('user', user) kwargs.setdefault('request', strategy.request) kwargs.update(xkwargs) return idx, backend, xargs, xkwargs def build_absolute_uri(host_url, path=None):","def partial_pipeline_data(strategy, user, *args, **kwargs): kwargs.setdefault('user', user) kwargs.setdefault('request', strategy.request) kwargs.update(xkwargs) return idx, backend, xargs, kwargs def build_absolute_uri(host_url, path=None):" 525,https://:@github.com/rafalp/misago-social-app-django.git,d53529b57f0a4992889ad490e5314a2244155afa,"@@ -27,7 +27,7 @@ class SocialAuthExceptionMiddleware(object): return if isinstance(exception, SocialAuthBaseException): - backend_name = strategy.backend.name + backend_name = request.backend.name message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) try: ",social/apps/django_app/middleware.py,"ReplaceText(target='request' @(30,27)->(30,35))","class SocialAuthExceptionMiddleware(object): return if isinstance(exception, SocialAuthBaseException): backend_name = strategy.backend.name message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) try:","class SocialAuthExceptionMiddleware(object): return if isinstance(exception, SocialAuthBaseException): backend_name = request.backend.name message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) try:" 526,https://:@github.com/c137digital/unv_app.git,d217fa0d780bc6f2acbbf4ea307630c78a695653,"@@ -34,7 +34,7 @@ class ComponentSettings: """"""Create app settings, overrided by env."""""" settings = settings or {} if base_settings: - settings = update_dict_recur(settings, base_settings) + settings = update_dict_recur(base_settings, settings) for key, value in os.environ.items(): if 'SETTINGS_' not in key: continue ",src/unv/app/settings.py,"ArgSwap(idxs=0<->1 @(37,23)->(37,40))","class ComponentSettings: """"""Create app settings, overrided by env."""""" settings = settings or {} if base_settings: settings = update_dict_recur(settings, base_settings) for key, value in os.environ.items(): if 'SETTINGS_' not in key: continue","class ComponentSettings: """"""Create app settings, overrided by env."""""" settings = settings or {} if base_settings: settings = update_dict_recur(base_settings, settings) for key, value in os.environ.items(): if 'SETTINGS_' not in key: continue" 527,https://:@github.com/timothycrosley/blox.git,fdc21c5be25dd5452075748e4027e067bfb28e1e,"@@ -141,7 +141,7 @@ class TagAttributes(type): full_attribute_map = dict(parents[0].attribute_map) full_attribute_map.update(attribute_map) attribute_map = full_attribute_map - class_dict['attribute_map'] = full_attributes + class_dict['attribute_map'] = attribute_map class_dict['attribute_descriptors'] = attributes attribute_signals = (attribute.signal for attribute in attributes.values() if getattr(attribute, 'signal')) ",blox/base.py,"ReplaceText(target='attribute_map' @(144,46)->(144,61))","class TagAttributes(type): full_attribute_map = dict(parents[0].attribute_map) full_attribute_map.update(attribute_map) attribute_map = full_attribute_map class_dict['attribute_map'] = full_attributes class_dict['attribute_descriptors'] = attributes attribute_signals = (attribute.signal for attribute in attributes.values() if getattr(attribute, 'signal'))","class TagAttributes(type): full_attribute_map = dict(parents[0].attribute_map) full_attribute_map.update(attribute_map) attribute_map = full_attribute_map class_dict['attribute_map'] = attribute_map class_dict['attribute_descriptors'] = attributes attribute_signals = (attribute.signal for attribute in attributes.values() if getattr(attribute, 'signal'))" 528,https://:@github.com/Vizzuality/LMIPy.git,abd7e5a3a0d4e6f5fdaf2798647adb88c490cd6b,"@@ -557,5 +557,5 @@ class Layer: # confirm update # update other layer - target_layer.update(update_params=payload, token=token) + target_layer.update(update_params=filtered_payload, token=token) ",LMIPy/layer.py,"ReplaceText(target='filtered_payload' @(560,42)->(560,49))","class Layer: # confirm update # update other layer target_layer.update(update_params=payload, token=token) ","class Layer: # confirm update # update other layer target_layer.update(update_params=filtered_payload, token=token) " 529,https://:@github.com/collective/mr.cabot.git,9c955abc239fcdff9bd12db236142387bce61f21,"@@ -7,7 +7,7 @@ def html_snippet(obj): else: lat, lon = loc content = IListing(obj).summary - if lat < 0: + if lat > 0: hemi = ""west"" else: hemi = ""east"" ",src/mr/cabot/html.py,"ReplaceText(target='>' @(10,11)->(10,12))","def html_snippet(obj): else: lat, lon = loc content = IListing(obj).summary if lat < 0: hemi = ""west"" else: hemi = ""east""","def html_snippet(obj): else: lat, lon = loc content = IListing(obj).summary if lat > 0: hemi = ""west"" else: hemi = ""east""" 530,https://:@github.com/TeamSpen210/srctools.git,079e1c394836a6daecc3e4c996514286937a98dc,"@@ -392,7 +392,7 @@ class ModelManager: with open(qc.ref_smd, 'rb') as fb: child_ref = Mesh.parse_smd(fb) - if prop.skin != 0 and prop.skin <= len(mdl.skins): + if prop.skin != 0 and prop.skin < len(mdl.skins): # We need to rename the materials to match the skin. swap_skins = dict(zip( mdl.skins[0], ",srctools/compiler/propcombine.py,"ReplaceText(target='<' @(395,48)->(395,50))","class ModelManager: with open(qc.ref_smd, 'rb') as fb: child_ref = Mesh.parse_smd(fb) if prop.skin != 0 and prop.skin <= len(mdl.skins): # We need to rename the materials to match the skin. swap_skins = dict(zip( mdl.skins[0],","class ModelManager: with open(qc.ref_smd, 'rb') as fb: child_ref = Mesh.parse_smd(fb) if prop.skin != 0 and prop.skin < len(mdl.skins): # We need to rename the materials to match the skin. swap_skins = dict(zip( mdl.skins[0]," 531,https://:@github.com/TeamSpen210/srctools.git,ef4510d1517525251ae2f62f8be714b068e4d909,"@@ -1799,7 +1799,7 @@ class Entity: base_name = orig_name.rstrip('0123456789') - if self.map.by_target[orig_name]: + if self.map.by_target[base_name]: # Check every index in order. for i in itertools.count(start=1): name = base_name + str(i) ",srctools/vmf.py,"ReplaceText(target='base_name' @(1802,30)->(1802,39))","class Entity: base_name = orig_name.rstrip('0123456789') if self.map.by_target[orig_name]: # Check every index in order. for i in itertools.count(start=1): name = base_name + str(i)","class Entity: base_name = orig_name.rstrip('0123456789') if self.map.by_target[base_name]: # Check every index in order. for i in itertools.count(start=1): name = base_name + str(i)" 532,https://:@github.com/TeamSpen210/srctools.git,3954c99aa7922609c5c90a40b239ef57d747c5cc,"@@ -88,7 +88,7 @@ def main(argv: List[str]) -> None: LOGGER.warning('No studiomdl path provided.') studiomdl_loc = None - run_transformations(vmf, fsys, packlist, path, game_info, studiomdl_loc) + run_transformations(vmf, fsys, packlist, bsp_file, game_info, studiomdl_loc) if studiomdl_loc is not None and args.propcombine: LOGGER.info('Combining props...') ",srctools/scripts/postcompiler.py,"ReplaceText(target='bsp_file' @(91,45)->(91,49))","def main(argv: List[str]) -> None: LOGGER.warning('No studiomdl path provided.') studiomdl_loc = None run_transformations(vmf, fsys, packlist, path, game_info, studiomdl_loc) if studiomdl_loc is not None and args.propcombine: LOGGER.info('Combining props...')","def main(argv: List[str]) -> None: LOGGER.warning('No studiomdl path provided.') studiomdl_loc = None run_transformations(vmf, fsys, packlist, bsp_file, game_info, studiomdl_loc) if studiomdl_loc is not None and args.propcombine: LOGGER.info('Combining props...')" 533,https://:@github.com/garicchi/pyassistant.git,46494b523af213c34a755bfee77fdc0ff00525b1,"@@ -31,4 +31,4 @@ class Assistant(): with open(self.setting_file, 'w') as f: json.dump(self.setting,f) - return True \ No newline at end of file + return False \ No newline at end of file ",assistant/util/assistant.py,"ReplaceText(target='False' @(34,15)->(34,19))","class Assistant(): with open(self.setting_file, 'w') as f: json.dump(self.setting,f) return True \ No newline at end of file \ No newline at end of file","class Assistant(): with open(self.setting_file, 'w') as f: json.dump(self.setting,f) \ No newline at end of file return False \ No newline at end of file" 534,https://:@github.com/u0078867/PyBiomech.git,b817b7617d9d57c39c72d8288d8cdb5748b9755c,"@@ -272,7 +272,7 @@ def evalPolynomialDerivative(poly, u, der=1): tck, dummy = interpolate.splprep([x.tolist(),x.tolist()], s=0, k=1) xU = np.array(interpolate.splev(u, tck)[1]) out = f2(xU) - p = np.array([np.ones((x.shape[0],)), out]).T + p = np.array([np.ones((xU.shape[0],)), out]).T return p ",src/PyBiomech/vtkh.py,"ReplaceText(target='xU' @(275,27)->(275,28))","def evalPolynomialDerivative(poly, u, der=1): tck, dummy = interpolate.splprep([x.tolist(),x.tolist()], s=0, k=1) xU = np.array(interpolate.splev(u, tck)[1]) out = f2(xU) p = np.array([np.ones((x.shape[0],)), out]).T return p ","def evalPolynomialDerivative(poly, u, der=1): tck, dummy = interpolate.splprep([x.tolist(),x.tolist()], s=0, k=1) xU = np.array(interpolate.splev(u, tck)[1]) out = f2(xU) p = np.array([np.ones((xU.shape[0],)), out]).T return p " 535,https://:@github.com/mardix/gokku.git,c44093fc8d160748f4c6902e590ecd2193fdeb90,"@@ -509,7 +509,7 @@ def deploy_node(app, deltas={}): first_time = False if not exists(virtualenv_path): echo(""-----> Creating virtualenv_path for '{}'"".format(app), fg='green') - makedirs(node_path) + makedirs(virtualenv_path) first_time = True if not exists(node_path): echo(""-----> Creating node_modules for '{}'"".format(app), fg='green') ",gokku.py,"ReplaceText(target='virtualenv_path' @(512,17)->(512,26))","def deploy_node(app, deltas={}): first_time = False if not exists(virtualenv_path): echo(""-----> Creating virtualenv_path for '{}'"".format(app), fg='green') makedirs(node_path) first_time = True if not exists(node_path): echo(""-----> Creating node_modules for '{}'"".format(app), fg='green')","def deploy_node(app, deltas={}): first_time = False if not exists(virtualenv_path): echo(""-----> Creating virtualenv_path for '{}'"".format(app), fg='green') makedirs(virtualenv_path) first_time = True if not exists(node_path): echo(""-----> Creating node_modules for '{}'"".format(app), fg='green')" 536,https://:@github.com/sophacles/pyCLiFF.git,35bf4ff2714329a786c093d7e24a63e6fc1555b9,"@@ -16,7 +16,7 @@ def handle_opts(opts): def datahandler(line): global n - if n > clmax: + if n >= clmax: raise StopIteration n += 1 ",examples/head.py,"ReplaceText(target='>=' @(19,9)->(19,10))","def handle_opts(opts): def datahandler(line): global n if n > clmax: raise StopIteration n += 1","def handle_opts(opts): def datahandler(line): global n if n >= clmax: raise StopIteration n += 1" 537,https://:@github.com/pilt/flask-versioned.git,2dd47374531a9426845a2b3b10fa5f2dc2418bf2,"@@ -45,7 +45,7 @@ class FileChangedDriver(Driver): mods = time.strftime('%Y%m%dT%H%M%S', modt) return self.format % { 'version': mods, - 'path': path, + 'path': stream, } ",flaskext/versioned/__init__.py,"ReplaceText(target='stream' @(48,20)->(48,24))","class FileChangedDriver(Driver): mods = time.strftime('%Y%m%dT%H%M%S', modt) return self.format % { 'version': mods, 'path': path, } ","class FileChangedDriver(Driver): mods = time.strftime('%Y%m%dT%H%M%S', modt) return self.format % { 'version': mods, 'path': stream, } " 538,https://:@github.com/lantunes/netomaton.git,7d73976ac295f05911b9b67e495bd54021f97644,"@@ -7,7 +7,7 @@ if __name__ == '__main__': initial_conditions = [0] * 100 + [1] + [0] * 99 - activities, connectivities = evolve(adjacencies, initial_conditions, timesteps=100, + activities, connectivities = evolve(initial_conditions, adjacencies, timesteps=100, activity_rule=lambda n, c, t: ActivityRule.nks_ca_rule(n, c, 30)) plot_grid(activities) ",demos/elementary_ca/elementary_ca_demo.py,"ArgSwap(idxs=0<->1 @(10,33)->(10,39))","if __name__ == '__main__': initial_conditions = [0] * 100 + [1] + [0] * 99 activities, connectivities = evolve(adjacencies, initial_conditions, timesteps=100, activity_rule=lambda n, c, t: ActivityRule.nks_ca_rule(n, c, 30)) plot_grid(activities)","if __name__ == '__main__': initial_conditions = [0] * 100 + [1] + [0] * 99 activities, connectivities = evolve(initial_conditions, adjacencies, timesteps=100, activity_rule=lambda n, c, t: ActivityRule.nks_ca_rule(n, c, 30)) plot_grid(activities)" 539,https://:@github.com/lantunes/netomaton.git,7d73976ac295f05911b9b67e495bd54021f97644,"@@ -61,7 +61,7 @@ if __name__ == '__main__': initial_conditions = half_two - activities, connectivities = evolve(hopfield_net.adjacency_matrix, initial_conditions, timesteps=155, + activities, connectivities = evolve(initial_conditions, hopfield_net.adjacency_matrix, timesteps=155, activity_rule=hopfield_net.activity_rule) # view the weights, stored in the adjacency matrix ",demos/hopfield_net/hopfield_net_demo.py,"ArgSwap(idxs=0<->1 @(64,33)->(64,39))","if __name__ == '__main__': initial_conditions = half_two activities, connectivities = evolve(hopfield_net.adjacency_matrix, initial_conditions, timesteps=155, activity_rule=hopfield_net.activity_rule) # view the weights, stored in the adjacency matrix","if __name__ == '__main__': initial_conditions = half_two activities, connectivities = evolve(initial_conditions, hopfield_net.adjacency_matrix, timesteps=155, activity_rule=hopfield_net.activity_rule) # view the weights, stored in the adjacency matrix" 540,https://:@github.com/orionw/tuningDEAP.git,7e7a40a386832fd386dfb8f67ff10e27ade0421e,"@@ -96,7 +96,7 @@ class TestConfigMapping(unittest.TestCase): assert value == bool(new_value) and type(value) == bool, ""did not set the correct value from the map, expected {} but got {} (which is not the original {})"".format(""bool"", bool(new_value), type(value), value) set_by_path(test_config, path, new_value, is_bool=False) int_value = get_by_path(test_config, path) - assert new_value == int_value and type(int_value) == int, ""did not set the correct value from the map, expected type {} = {} but got type {} = {})"".format(""int"", int_value, type(int_value), new_value) + assert value == int_value and type(int_value) == int, ""did not set the correct value from the map, expected type {} = {} but got type {} = {})"".format(""int"", int_value, type(int_value), new_value) def test_set_from_map_invalid(self): test_value = ""three_levels"" ",test/test_config_mapping.py,"ReplaceText(target='value' @(99,15)->(99,24))","class TestConfigMapping(unittest.TestCase): assert value == bool(new_value) and type(value) == bool, ""did not set the correct value from the map, expected {} but got {} (which is not the original {})"".format(""bool"", bool(new_value), type(value), value) set_by_path(test_config, path, new_value, is_bool=False) int_value = get_by_path(test_config, path) assert new_value == int_value and type(int_value) == int, ""did not set the correct value from the map, expected type {} = {} but got type {} = {})"".format(""int"", int_value, type(int_value), new_value) def test_set_from_map_invalid(self): test_value = ""three_levels""","class TestConfigMapping(unittest.TestCase): assert value == bool(new_value) and type(value) == bool, ""did not set the correct value from the map, expected {} but got {} (which is not the original {})"".format(""bool"", bool(new_value), type(value), value) set_by_path(test_config, path, new_value, is_bool=False) int_value = get_by_path(test_config, path) assert value == int_value and type(int_value) == int, ""did not set the correct value from the map, expected type {} = {} but got type {} = {})"".format(""int"", int_value, type(int_value), new_value) def test_set_from_map_invalid(self): test_value = ""three_levels""" 541,https://:@github.com/benjamincrom/scrabble.git,59d26971b75475d0a66aeb03902fda6bfa57a048,"@@ -188,7 +188,7 @@ def move_does_not_stack_tiles(letter_list, location_set): # return False def move_is_rack_size_or_less(location_set): - return len(location_set) > config.PLAYER_RACK_SIZE + return len(location_set) <= config.PLAYER_RACK_SIZE # print('Move places greater than seven tiles.') # return False # else: ",scrabble_game.py,"ReplaceText(target='<=' @(191,29)->(191,30))","def move_does_not_stack_tiles(letter_list, location_set): # return False def move_is_rack_size_or_less(location_set): return len(location_set) > config.PLAYER_RACK_SIZE # print('Move places greater than seven tiles.') # return False # else:","def move_does_not_stack_tiles(letter_list, location_set): # return False def move_is_rack_size_or_less(location_set): return len(location_set) <= config.PLAYER_RACK_SIZE # print('Move places greater than seven tiles.') # return False # else:" 542,https://:@bitbucket.org/norok2/pytk.git,934113ff8273afe9c2737a1bdee6f5f298217986,"@@ -179,7 +179,7 @@ def center(target, reference=None): geometry = reference.winfo_geometry() else: geometry = reference - if isinstance(reference, str): + if isinstance(geometry, str): geometry = Geometry(geometry) target_geometry = Geometry(target.winfo_geometry()) target.geometry(str(target_geometry.set_to_center(geometry))) ",pytk/util.py,"ReplaceText(target='geometry' @(182,18)->(182,27))","def center(target, reference=None): geometry = reference.winfo_geometry() else: geometry = reference if isinstance(reference, str): geometry = Geometry(geometry) target_geometry = Geometry(target.winfo_geometry()) target.geometry(str(target_geometry.set_to_center(geometry)))","def center(target, reference=None): geometry = reference.winfo_geometry() else: geometry = reference if isinstance(geometry, str): geometry = Geometry(geometry) target_geometry = Geometry(target.winfo_geometry()) target.geometry(str(target_geometry.set_to_center(geometry)))" 543,https://:@github.com/ds4dm/ecole.git,90d17acf7796734b64299619474a60519b19db59,"@@ -13,7 +13,7 @@ def test_IsDone(state): def test_NLPIterations(state): reward_func = R.NLPIterations() reward_func.reset(state) - assert reward_func.get(state) >= 0 + assert reward_func.get(state) <= 0 assert reward_func.get(state, done=True) == 0 ",python/tests/test_reward.py,"ReplaceText(target='<=' @(16,34)->(16,36))","def test_IsDone(state): def test_NLPIterations(state): reward_func = R.NLPIterations() reward_func.reset(state) assert reward_func.get(state) >= 0 assert reward_func.get(state, done=True) == 0 ","def test_IsDone(state): def test_NLPIterations(state): reward_func = R.NLPIterations() reward_func.reset(state) assert reward_func.get(state) <= 0 assert reward_func.get(state, done=True) == 0 " 544,https://:@github.com/ds4dm/ecole.git,6bc408253cbea5c8cb6740412601d13eb6772039,"@@ -101,4 +101,4 @@ def test_LpIterations(model): def test_NNodes(model): reward_func = R.NNodes() reward_func.reset(model) - assert reward_func.obtain_reward(model) <= 0 + assert reward_func.obtain_reward(model) >= 0 ",python/tests/test_reward.py,"ReplaceText(target='>=' @(104,44)->(104,46))","def test_LpIterations(model): def test_NNodes(model): reward_func = R.NNodes() reward_func.reset(model) assert reward_func.obtain_reward(model) <= 0","def test_LpIterations(model): def test_NNodes(model): reward_func = R.NNodes() reward_func.reset(model) assert reward_func.obtain_reward(model) >= 0" 545,https://:@github.com/nodedge/nodedge.git,b610ea8a12132e143aafe2824a83a9c032a973f7,"@@ -313,7 +313,7 @@ class GraphicsView(QGraphicsView): event.localPos(), event.screenPos(), Qt.LeftButton, - event.buttons() & -Qt.LeftButton, + event.buttons() | -Qt.LeftButton, event.modifiers(), ) super().mouseReleaseEvent(fake_event) ",nodedge/graphics_view.py,"ReplaceText(target='|' @(316,28)->(316,29))","class GraphicsView(QGraphicsView): event.localPos(), event.screenPos(), Qt.LeftButton, event.buttons() & -Qt.LeftButton, event.modifiers(), ) super().mouseReleaseEvent(fake_event)","class GraphicsView(QGraphicsView): event.localPos(), event.screenPos(), Qt.LeftButton, event.buttons() | -Qt.LeftButton, event.modifiers(), ) super().mouseReleaseEvent(fake_event)" 546,https://:@github.com/ovnicraft/suds2.git,b5d1aa94c6c825f717bf41f687ca687241aeae43,"@@ -130,7 +130,7 @@ class UMBase: return content.data lang = attributes.lang() if not len(node.children) and content.text is None: - if self.nillable(content.data) and content.node.isnil(): + if self.nillable(content.data) or content.node.isnil(): return None else: return xlstr.string('', lang) ",suds/bindings/unmarshaller.py,"ReplaceText(target='or' @(133,43)->(133,46))","class UMBase: return content.data lang = attributes.lang() if not len(node.children) and content.text is None: if self.nillable(content.data) and content.node.isnil(): return None else: return xlstr.string('', lang)","class UMBase: return content.data lang = attributes.lang() if not len(node.children) and content.text is None: if self.nillable(content.data) or content.node.isnil(): return None else: return xlstr.string('', lang)" 547,https://:@github.com/ovnicraft/suds2.git,e54498f49a9973bc9a385885b5a220026503f22b,"@@ -113,6 +113,6 @@ class Options(Skin): Definition('retxml', bool, False), Definition('autoblend', bool, False), Definition('cachingpolicy', int, 0), - Definition('plugins', [], (list, tuple)), + Definition('plugins', (list, tuple), []), ] Skin.__init__(self, domain, definitions, kwargs) ",suds/options.py,"ArgSwap(idxs=1<->2 @(116,12)->(116,22))","class Options(Skin): Definition('retxml', bool, False), Definition('autoblend', bool, False), Definition('cachingpolicy', int, 0), Definition('plugins', [], (list, tuple)), ] Skin.__init__(self, domain, definitions, kwargs)","class Options(Skin): Definition('retxml', bool, False), Definition('autoblend', bool, False), Definition('cachingpolicy', int, 0), Definition('plugins', (list, tuple), []), ] Skin.__init__(self, domain, definitions, kwargs)" 548,https://:@github.com/lukegb/ticketml.git,99c13a8e34a4397470564a355d639a4fbd5c72c4,"@@ -122,7 +122,7 @@ class BaseBackend(object): self._serial.write(h2b('1d21' + hex)) def get_characters_per_line(self, font_width): - return self.BASE_CHARS_PER_LINE / font_width + return self.BASE_CHARS_PER_LINE // font_width class Ibm4610Backend(BaseBackend): BARCODE_MAP = { ",ticketml/ticketml.py,"ReplaceText(target='//' @(125,40)->(125,41))","class BaseBackend(object): self._serial.write(h2b('1d21' + hex)) def get_characters_per_line(self, font_width): return self.BASE_CHARS_PER_LINE / font_width class Ibm4610Backend(BaseBackend): BARCODE_MAP = {","class BaseBackend(object): self._serial.write(h2b('1d21' + hex)) def get_characters_per_line(self, font_width): return self.BASE_CHARS_PER_LINE // font_width class Ibm4610Backend(BaseBackend): BARCODE_MAP = {" 549,https://:@github.com/EmanuelGoncalves/crispy.git,2a029a350d328a65b32b5434a6b555dcc94a562c,"@@ -60,7 +60,7 @@ def iterate_correction(crispr_file, crispr_lib_file, cnv_file, output_folder, bs assert len(overlap_genes) > 0, 'No genes (rows) overlap between CRISPR and Copy-number matrices' # run correction for each cell line - for sample in overlap_genes: + for sample in overlap_samples: if bsub_flag: print('[{}] Crispy: bsub {}'.format(dt.now().strftime('%Y-%m-%d %H:%M:%S'), sample)) ",scripts/crispy/processing/correct_cnv_bias.py,"ReplaceText(target='overlap_samples' @(63,18)->(63,31))","def iterate_correction(crispr_file, crispr_lib_file, cnv_file, output_folder, bs assert len(overlap_genes) > 0, 'No genes (rows) overlap between CRISPR and Copy-number matrices' # run correction for each cell line for sample in overlap_genes: if bsub_flag: print('[{}] Crispy: bsub {}'.format(dt.now().strftime('%Y-%m-%d %H:%M:%S'), sample)) ","def iterate_correction(crispr_file, crispr_lib_file, cnv_file, output_folder, bs assert len(overlap_genes) > 0, 'No genes (rows) overlap between CRISPR and Copy-number matrices' # run correction for each cell line for sample in overlap_samples: if bsub_flag: print('[{}] Crispy: bsub {}'.format(dt.now().strftime('%Y-%m-%d %H:%M:%S'), sample)) " 550,https://:@github.com/ninapavlich/sitecomber-article-tests.git,a053bd33aa15bf1c6e4a2dded9e5e1a71511e9bc,"@@ -159,4 +159,4 @@ def check_spelling(page, settings): message = ""No misspellings found"" if not found_misspellings else u'Found %s misspelling(s): ""%s""' % (len(misspelled), '"", ""'.join(misspelled)) return found_misspellings, message - return True, 'No article found' + return False, 'No article found' ",sitecomber_article_tests/utils.py,"ReplaceText(target='False' @(162,11)->(162,15))","def check_spelling(page, settings): message = ""No misspellings found"" if not found_misspellings else u'Found %s misspelling(s): ""%s""' % (len(misspelled), '"", ""'.join(misspelled)) return found_misspellings, message return True, 'No article found'","def check_spelling(page, settings): message = ""No misspellings found"" if not found_misspellings else u'Found %s misspelling(s): ""%s""' % (len(misspelled), '"", ""'.join(misspelled)) return found_misspellings, message return False, 'No article found'" 551,https://:@github.com/salpreh/tablat.git,fef6e07276bced6e885653ef760884a0ee5e0606,"@@ -132,7 +132,7 @@ class Table(object): end = row_lenght filt_data = [] - while end < len(self._table_data): + while end <= len(self._table_data): filt_data.extend(self._filter_list(self._table_data[start:end], mask)) start = end end += row_lenght ",tablat/Table.py,"ReplaceText(target='<=' @(135,18)->(135,19))","class Table(object): end = row_lenght filt_data = [] while end < len(self._table_data): filt_data.extend(self._filter_list(self._table_data[start:end], mask)) start = end end += row_lenght","class Table(object): end = row_lenght filt_data = [] while end <= len(self._table_data): filt_data.extend(self._filter_list(self._table_data[start:end], mask)) start = end end += row_lenght" 552,https://:@github.com/cloudshare/cloudshare-py-sdk.git,1363279f77267f5e18ec26f2d1bd345b3adea08e,"@@ -156,7 +156,7 @@ def request(method, path, queryParams=None, content=None): path=path, queryParams=queryParams, content=content) - if res.status / 100 != 2: + if res.status // 100 != 2: raise Exception('{} {}'.format(res.status, res.content['message'])) return res.content ",example.py,"ReplaceText(target='//' @(159,18)->(159,19))","def request(method, path, queryParams=None, content=None): path=path, queryParams=queryParams, content=content) if res.status / 100 != 2: raise Exception('{} {}'.format(res.status, res.content['message'])) return res.content ","def request(method, path, queryParams=None, content=None): path=path, queryParams=queryParams, content=content) if res.status // 100 != 2: raise Exception('{} {}'.format(res.status, res.content['message'])) return res.content " 553,https://:@github.com/Oslandia/deeposlandia.git,529dd916303d712ea3c51bb8454349812537e506,"@@ -111,7 +111,7 @@ if __name__ == '__main__': testing_dataset.load(testing_filename, args.nb_testing_image) else: input_image_dir = os.path.join(input_repo, ""testing"") - testing_dataset.populate(input_image_dir, preprocessed_testing_path, + testing_dataset.populate(preprocessed_testing_path, input_image_dir, nb_images=args.nb_testing_image, labelling=False) testing_dataset.save(testing_filename) ",sources/test.py,"ArgSwap(idxs=0<->1 @(114,8)->(114,32))","if __name__ == '__main__': testing_dataset.load(testing_filename, args.nb_testing_image) else: input_image_dir = os.path.join(input_repo, ""testing"") testing_dataset.populate(input_image_dir, preprocessed_testing_path, nb_images=args.nb_testing_image, labelling=False) testing_dataset.save(testing_filename) ","if __name__ == '__main__': testing_dataset.load(testing_filename, args.nb_testing_image) else: input_image_dir = os.path.join(input_repo, ""testing"") testing_dataset.populate(preprocessed_testing_path, input_image_dir, nb_images=args.nb_testing_image, labelling=False) testing_dataset.save(testing_filename) " 554,https://:@github.com/Oslandia/deeposlandia.git,2bc626291e2f069c68e4a5a43e6ef5bfc3059d6a,"@@ -158,7 +158,7 @@ class SemanticSegmentationModel(ConvolutionalNeuralNetwork): name=dataset_type+""_images"") label_filepaths = [dataset.image_info[i][""label_filename""] for i in range(dataset.get_nb_images())] - label_tensors = ops.convert_to_tensor(image_filepaths, dtype=tf.string, + label_tensors = ops.convert_to_tensor(label_filepaths, dtype=tf.string, name=dataset_type+""_labels"") input_queue = tf.train.slice_input_producer([image_tensors, label_tensors], ",sources/semantic_segmentation.py,"ReplaceText(target='label_filepaths' @(161,50)->(161,65))","class SemanticSegmentationModel(ConvolutionalNeuralNetwork): name=dataset_type+""_images"") label_filepaths = [dataset.image_info[i][""label_filename""] for i in range(dataset.get_nb_images())] label_tensors = ops.convert_to_tensor(image_filepaths, dtype=tf.string, name=dataset_type+""_labels"") input_queue = tf.train.slice_input_producer([image_tensors, label_tensors],","class SemanticSegmentationModel(ConvolutionalNeuralNetwork): name=dataset_type+""_images"") label_filepaths = [dataset.image_info[i][""label_filename""] for i in range(dataset.get_nb_images())] label_tensors = ops.convert_to_tensor(label_filepaths, dtype=tf.string, name=dataset_type+""_labels"") input_queue = tf.train.slice_input_producer([image_tensors, label_tensors]," 555,https://:@github.com/Oslandia/deeposlandia.git,09e5206460eae73b533e9007ca5241bd5baee7f6,"@@ -449,7 +449,7 @@ def main(args): ""semseg"", ""predicted_geometries"", ) - os.makedirs(predicted_label_folder, exist_ok=True) + os.makedirs(predicted_geom_folder, exist_ok=True) predicted_geom_file = os.path.join( predicted_geom_folder, args.image_basename + ""_"" + str(args.image_size) + "".geojson"", ",deeposlandia/postprocess.py,"ReplaceText(target='predicted_geom_folder' @(452,16)->(452,38))","def main(args): ""semseg"", ""predicted_geometries"", ) os.makedirs(predicted_label_folder, exist_ok=True) predicted_geom_file = os.path.join( predicted_geom_folder, args.image_basename + ""_"" + str(args.image_size) + "".geojson"",","def main(args): ""semseg"", ""predicted_geometries"", ) os.makedirs(predicted_geom_folder, exist_ok=True) predicted_geom_file = os.path.join( predicted_geom_folder, args.image_basename + ""_"" + str(args.image_size) + "".geojson""," 556,https://:@github.com/metal3d/keras-video-generators.git,7313aa497a80147714dda3581ce34d4821130ae1,"@@ -72,7 +72,7 @@ class VideoFrameGenerator(Sequence): # split factor should be a propoer value if split is not None: - assert 0.0 > split < 1.0 + assert 0.0 < split < 1.0 # be sure that classes are well ordered classes.sort() ",src/keras_video/generator.py,"ReplaceText(target='<' @(75,23)->(75,24))","class VideoFrameGenerator(Sequence): # split factor should be a propoer value if split is not None: assert 0.0 > split < 1.0 # be sure that classes are well ordered classes.sort()","class VideoFrameGenerator(Sequence): # split factor should be a propoer value if split is not None: assert 0.0 < split < 1.0 # be sure that classes are well ordered classes.sort()" 557,https://:@github.com/yongzhuo/Macropodus.git,11789503e9122303464bf6f02df1122397c0ca97,"@@ -142,7 +142,7 @@ class RandomEmbedding(BaseEmbedding): else: raise RuntimeError(""your input level_type is wrong, it must be 'word', 'char', 'ngram'"") for text_one in text: - if term_one not in token2idx: + if text_one not in token2idx: token2idx[text_one] = len(token2idx) else: raise RuntimeError(""your input corpus_path is wrong, it must be 'dict' or 'corpus'"") ",macropodus/network/base/embedding.py,"ReplaceText(target='text_one' @(145,27)->(145,35))","class RandomEmbedding(BaseEmbedding): else: raise RuntimeError(""your input level_type is wrong, it must be 'word', 'char', 'ngram'"") for text_one in text: if term_one not in token2idx: token2idx[text_one] = len(token2idx) else: raise RuntimeError(""your input corpus_path is wrong, it must be 'dict' or 'corpus'"")","class RandomEmbedding(BaseEmbedding): else: raise RuntimeError(""your input level_type is wrong, it must be 'word', 'char', 'ngram'"") for text_one in text: if text_one not in token2idx: token2idx[text_one] = len(token2idx) else: raise RuntimeError(""your input corpus_path is wrong, it must be 'dict' or 'corpus'"")" 558,https://:@github.com/foxkit-us/PyIRC.git,c0bcbffa66f6fe1ddb7f3002e85fa38bfaafa103,"@@ -156,7 +156,7 @@ class IRCString(UserString): def convert(self, case): """"""Convert string into another caseform"""""" - return IRCString(self, case) + return IRCString(case, self) def ascii_lower(self): """"""Return a copy of the string S converted to lowercase, using ASCII ",PyIRC/casemapping.py,"ArgSwap(idxs=0<->1 @(159,15)->(159,24))","class IRCString(UserString): def convert(self, case): """"""Convert string into another caseform"""""" return IRCString(self, case) def ascii_lower(self): """"""Return a copy of the string S converted to lowercase, using ASCII","class IRCString(UserString): def convert(self, case): """"""Convert string into another caseform"""""" return IRCString(case, self) def ascii_lower(self): """"""Return a copy of the string S converted to lowercase, using ASCII" 559,https://:@github.com/foxkit-us/PyIRC.git,b262e84b066a39cd911a37c5f3ab517413ed707f,"@@ -332,7 +332,7 @@ class UserTrack(BaseExtension): basicrfc = self.get_extension(""BasicRFC"") - if self.casecmp(user.nick, basicrfc.nick): + if self.casecmp(target.nick, basicrfc.nick): # It's us! isupport = self.get_extension(""ISupport"") ",PyIRC/extensions/usertrack.py,"ReplaceText(target='target' @(335,24)->(335,28))","class UserTrack(BaseExtension): basicrfc = self.get_extension(""BasicRFC"") if self.casecmp(user.nick, basicrfc.nick): # It's us! isupport = self.get_extension(""ISupport"") ","class UserTrack(BaseExtension): basicrfc = self.get_extension(""BasicRFC"") if self.casecmp(target.nick, basicrfc.nick): # It's us! isupport = self.get_extension(""ISupport"") " 560,https://:@github.com/foxkit-us/PyIRC.git,71fa54a10227f629b88a2345a1da19b7db02b862,"@@ -48,7 +48,7 @@ class NullSocket(IRCBase): def inject_line(self, line): """"""Inject a Line into the recvq for the client."""""" - assert isinstance(Line, line) + assert isinstance(line, Line) self.recvq.put(line) def loop(self): ",PyIRC/io/null.py,"ArgSwap(idxs=0<->1 @(51,15)->(51,25))","class NullSocket(IRCBase): def inject_line(self, line): """"""Inject a Line into the recvq for the client."""""" assert isinstance(Line, line) self.recvq.put(line) def loop(self):","class NullSocket(IRCBase): def inject_line(self, line): """"""Inject a Line into the recvq for the client."""""" assert isinstance(line, Line) self.recvq.put(line) def loop(self):" 561,https://:@github.com/foxkit-us/PyIRC.git,bf102eab33bde57ba3ae1b240a84ee2d161103f0,"@@ -362,7 +362,7 @@ class XTerm16ColourFormatter(ANSIFormatter): if self.background is not None: bgc = ColoursANSI[self.background.name].value - ret.append(str(fgc.background_16)) + ret.append(str(bgc.background_16)) else: # Reset background just in case ret.append(self.fmt_resetbackground) ",PyIRC/formatting/formatters.py,"ReplaceText(target='bgc' @(365,31)->(365,34))","class XTerm16ColourFormatter(ANSIFormatter): if self.background is not None: bgc = ColoursANSI[self.background.name].value ret.append(str(fgc.background_16)) else: # Reset background just in case ret.append(self.fmt_resetbackground)","class XTerm16ColourFormatter(ANSIFormatter): if self.background is not None: bgc = ColoursANSI[self.background.name].value ret.append(str(bgc.background_16)) else: # Reset background just in case ret.append(self.fmt_resetbackground)" 562,https://:@bitbucket.org/pixelforest/pixelforest_drf.git,71155a01605838be2123eae28b650ceae32d7c2c,"@@ -14,7 +14,7 @@ from ..permissions import FullDjangoModelPermissions User = get_user_model() -if User is PFUser: +if User is not PFUser: raise ImproperlyConfigured(""Pf User is not the User model"") ",pixelforest_drf/rest/users/api_views.py,"ReplaceText(target=' is not ' @(17,7)->(17,11))","from ..permissions import FullDjangoModelPermissions User = get_user_model() if User is PFUser: raise ImproperlyConfigured(""Pf User is not the User model"") ","from ..permissions import FullDjangoModelPermissions User = get_user_model() if User is not PFUser: raise ImproperlyConfigured(""Pf User is not the User model"") " 563,https://:@github.com/sphemakh/meerkathi.git,b6220f225f989604f184d10863e5012f215ed639,"@@ -65,7 +65,7 @@ class worker_administrator(object): else: worker = name + '_worker' - self.workers.append((name, worker, order)) + self.workers.append((name, worker, i)) self.workers = sorted(self.workers, key=lambda a: a[2]) ",meerkathi/workers/worker_administrator.py,"ReplaceText(target='i' @(68,47)->(68,52))","class worker_administrator(object): else: worker = name + '_worker' self.workers.append((name, worker, order)) self.workers = sorted(self.workers, key=lambda a: a[2]) ","class worker_administrator(object): else: worker = name + '_worker' self.workers.append((name, worker, i)) self.workers = sorted(self.workers, key=lambda a: a[2]) " 564,https://:@github.com/sphemakh/meerkathi.git,8bb75b04fe481c06cf0e7987e0072ed58fea1bc3,"@@ -528,7 +528,7 @@ found in our database or in the CASA NRAO database'.format(field)) step = 'plot_fluxscale_{0:d}'.format(i) table = prefix+"".F0"" fieldtoplot = [] - fieldtoplot.append(utils.get_field_id(msinfo, ref)[0]) + fieldtoplot.append(utils.get_field_id(msinfo, trans)[0]) recipe.add('cab/ragavi', step, { ""table"" : '{0:s}/{1:s}:{2:s}'.format(get_dir_path(pipeline.caltables, pipeline), table, 'output'), ",meerkathi/workers/cross_cal_worker.py,"ReplaceText(target='trans' @(531,62)->(531,65))","found in our database or in the CASA NRAO database'.format(field)) step = 'plot_fluxscale_{0:d}'.format(i) table = prefix+"".F0"" fieldtoplot = [] fieldtoplot.append(utils.get_field_id(msinfo, ref)[0]) recipe.add('cab/ragavi', step, { ""table"" : '{0:s}/{1:s}:{2:s}'.format(get_dir_path(pipeline.caltables, pipeline), table, 'output'),","found in our database or in the CASA NRAO database'.format(field)) step = 'plot_fluxscale_{0:d}'.format(i) table = prefix+"".F0"" fieldtoplot = [] fieldtoplot.append(utils.get_field_id(msinfo, trans)[0]) recipe.add('cab/ragavi', step, { ""table"" : '{0:s}/{1:s}:{2:s}'.format(get_dir_path(pipeline.caltables, pipeline), table, 'output')," 565,https://:@github.com/sphemakh/meerkathi.git,67485769492da55875da1fea491a7a32ce82d16a,"@@ -176,7 +176,7 @@ def worker(pipeline, recipe, config): substep = 'delete_flag_versions_after_{0:s}_ms{1:d}'.format(version, target_iter) manflags.delete_cflags(pipeline, recipe, available_flagversions[available_flagversions.index(version)+1], - msname, cab_name=substep) + fms, cab_name=substep) flagv = tms+'.flagversions' ",caracal/workers/transform_worker.py,"ReplaceText(target='fms' @(179,24)->(179,30))","def worker(pipeline, recipe, config): substep = 'delete_flag_versions_after_{0:s}_ms{1:d}'.format(version, target_iter) manflags.delete_cflags(pipeline, recipe, available_flagversions[available_flagversions.index(version)+1], msname, cab_name=substep) flagv = tms+'.flagversions' ","def worker(pipeline, recipe, config): substep = 'delete_flag_versions_after_{0:s}_ms{1:d}'.format(version, target_iter) manflags.delete_cflags(pipeline, recipe, available_flagversions[available_flagversions.index(version)+1], fms, cab_name=substep) flagv = tms+'.flagversions' " 566,https://:@gitlab.com/nekokatt/hikari.git,0b4d26aa20ddbf580ad84581bc5eeea34c687896,"@@ -48,4 +48,4 @@ class TestReaction: assert re.count == 420 assert re.me is True - test_state.parse_emoji.assert_called_with(None, emoji_dict) + test_state.parse_emoji.assert_called_with(emoji_dict, None) ",tests/hikari/core/model/test_reaction.py,"ArgSwap(idxs=0<->1 @(51,8)->(51,49))","class TestReaction: assert re.count == 420 assert re.me is True test_state.parse_emoji.assert_called_with(None, emoji_dict)","class TestReaction: assert re.count == 420 assert re.me is True test_state.parse_emoji.assert_called_with(emoji_dict, None)" 567,https://:@gitlab.com/nekokatt/hikari.git,b40bd61096cbd597d0f2863351ebddebf571867d,"@@ -286,7 +286,7 @@ class DispatchingEventAdapterImpl(dispatching_event_adapter.DispatchingEventAdap for role_id in role_ids: role_obj = self.fabric.state_registry.get_role_by_id(guild_id, role_id) - if role_objs is not None: + if role_obj is not None: role_objs.append(role_obj) else: self.logger.warning( ",hikari/orm/dispatching_event_adapter_impl.py,"ReplaceText(target='role_obj' @(289,19)->(289,28))","class DispatchingEventAdapterImpl(dispatching_event_adapter.DispatchingEventAdap for role_id in role_ids: role_obj = self.fabric.state_registry.get_role_by_id(guild_id, role_id) if role_objs is not None: role_objs.append(role_obj) else: self.logger.warning(","class DispatchingEventAdapterImpl(dispatching_event_adapter.DispatchingEventAdap for role_id in role_ids: role_obj = self.fabric.state_registry.get_role_by_id(guild_id, role_id) if role_obj is not None: role_objs.append(role_obj) else: self.logger.warning(" 568,https://:@gitlab.com/nekokatt/hikari.git,89f2070c7a2135162e4852a8b778490b4695bc78,"@@ -699,7 +699,7 @@ class BotAppImpl(bot.IBotApp): if plat == ""win32"": supports_color |= os.getenv(""TERM_PROGRAM"", None) == ""mintty"" supports_color |= ""ANSICON"" in os.environ - supports_color |= is_a_tty + supports_color &= is_a_tty else: supports_color = is_a_tty ",hikari/impl/bot.py,"ReplaceText(target='&=' @(702,31)->(702,33))","class BotAppImpl(bot.IBotApp): if plat == ""win32"": supports_color |= os.getenv(""TERM_PROGRAM"", None) == ""mintty"" supports_color |= ""ANSICON"" in os.environ supports_color |= is_a_tty else: supports_color = is_a_tty ","class BotAppImpl(bot.IBotApp): if plat == ""win32"": supports_color |= os.getenv(""TERM_PROGRAM"", None) == ""mintty"" supports_color |= ""ANSICON"" in os.environ supports_color &= is_a_tty else: supports_color = is_a_tty " 569,https://:@github.com/matthewhanson/boto3-utils.git,23390e1f08fda449451266dc7136a89914e00b4e,"@@ -33,7 +33,7 @@ class s3(object): _url = deepcopy(url) if url[0:5] == 'https': _url = cls.https_to_s3(url) - if url[0:5] != 's3://': + if _url[0:5] != 's3://': raise Exception('Invalid S3 url %s' % _url) url_obj = _url.replace('s3://', '').split('/') ",boto3utils/s3.py,"ReplaceText(target='_url' @(36,11)->(36,14))","class s3(object): _url = deepcopy(url) if url[0:5] == 'https': _url = cls.https_to_s3(url) if url[0:5] != 's3://': raise Exception('Invalid S3 url %s' % _url) url_obj = _url.replace('s3://', '').split('/')","class s3(object): _url = deepcopy(url) if url[0:5] == 'https': _url = cls.https_to_s3(url) if _url[0:5] != 's3://': raise Exception('Invalid S3 url %s' % _url) url_obj = _url.replace('s3://', '').split('/')" 570,https://:@github.com/spex-xray/pyspextools.git,c68beb5206e3525010e0265f2c18f8f5fc4bebc3,"@@ -131,7 +131,7 @@ class OGIPRegion(Region): if isinstance(corr, Pha): self.corr = corr self.input_corr = True - elif back is None: + elif corr is None: self.input_corr = False else: self.input_corr = False ",pyspextools/io/ogip.py,"ReplaceText(target='corr' @(134,13)->(134,17))","class OGIPRegion(Region): if isinstance(corr, Pha): self.corr = corr self.input_corr = True elif back is None: self.input_corr = False else: self.input_corr = False","class OGIPRegion(Region): if isinstance(corr, Pha): self.corr = corr self.input_corr = True elif corr is None: self.input_corr = False else: self.input_corr = False" 571,https://:@github.com/djerbic/xlrd-ignore-writeaccess-corruption.git,8ce449208ac3a8a1f4ec9c72954c11afcd40d3a8,"@@ -1975,7 +1975,7 @@ class Sheet(BaseObject): nchars = data2_len - 1 if nb: assert nchars % 2 == 0 - nchars /= 2 + nchars //= 2 utext, endpos = unpack_unicode_update_pos(data2, 0, known_len=nchars) assert endpos == data2_len o.text += utext ",xlrd/sheet.py,"ReplaceText(target='//=' @(1978,23)->(1978,25))","class Sheet(BaseObject): nchars = data2_len - 1 if nb: assert nchars % 2 == 0 nchars /= 2 utext, endpos = unpack_unicode_update_pos(data2, 0, known_len=nchars) assert endpos == data2_len o.text += utext","class Sheet(BaseObject): nchars = data2_len - 1 if nb: assert nchars % 2 == 0 nchars //= 2 utext, endpos = unpack_unicode_update_pos(data2, 0, known_len=nchars) assert endpos == data2_len o.text += utext" 572,https://:@github.com/ijiraq/daomop.git,2b9c4af87e1b899b7589cfb04aa272540d2e8a04,"@@ -61,7 +61,7 @@ class GeneralModelTest(FileReadingTestCase, DirectoryCleaningTestCase): # Put a real fits image on the first source, first observation apcor_str = ""4 15 0.19 0.01"" with open(self.get_abs_path(path), ""rb"") as fh: - self.first_image = DownloadedFitsImage(fh.read(), apcor_str, Mock(), in_memory=True) + self.first_image = DownloadedFitsImage(fh.read(), Mock(), apcor_str, in_memory=True) first_reading = self.model.get_current_workunit().get_sources()[0].get_readings()[0] self.model._on_image_loaded(first_reading, self.first_image) ",src/ossos-pipeline/tests/test_integration/test_models.py,"ArgSwap(idxs=1<->2 @(64,31)->(64,50))","class GeneralModelTest(FileReadingTestCase, DirectoryCleaningTestCase): # Put a real fits image on the first source, first observation apcor_str = ""4 15 0.19 0.01"" with open(self.get_abs_path(path), ""rb"") as fh: self.first_image = DownloadedFitsImage(fh.read(), apcor_str, Mock(), in_memory=True) first_reading = self.model.get_current_workunit().get_sources()[0].get_readings()[0] self.model._on_image_loaded(first_reading, self.first_image) ","class GeneralModelTest(FileReadingTestCase, DirectoryCleaningTestCase): # Put a real fits image on the first source, first observation apcor_str = ""4 15 0.19 0.01"" with open(self.get_abs_path(path), ""rb"") as fh: self.first_image = DownloadedFitsImage(fh.read(), Mock(), apcor_str, in_memory=True) first_reading = self.model.get_current_workunit().get_sources()[0].get_readings()[0] self.model._on_image_loaded(first_reading, self.first_image) " 573,https://:@github.com/iamsteadman/bambu-buffer.git,5704abdda5297d6cde2ccac7f91ded4108e1f616,"@@ -12,7 +12,7 @@ def post_save_receiver(sender, instance, **kwargs): name = m.pop(0) app, model = name.lower().split('.') - if app != instance._meta.app_label and model != instance._meta.module_name: + if app != instance._meta.app_label or model != instance._meta.module_name: continue if any(m): ",bambu_buffer/receivers.py,"ReplaceText(target='or' @(15,43)->(15,46))","def post_save_receiver(sender, instance, **kwargs): name = m.pop(0) app, model = name.lower().split('.') if app != instance._meta.app_label and model != instance._meta.module_name: continue if any(m):","def post_save_receiver(sender, instance, **kwargs): name = m.pop(0) app, model = name.lower().split('.') if app != instance._meta.app_label or model != instance._meta.module_name: continue if any(m):" 574,https://:@github.com/khllkcm/templot.git,d4b329d16f94e3808e54b05116a8545e987a5e7b,"@@ -95,7 +95,7 @@ def plot_aggregated_map( if aggregation_method not in aggregates: raise ValueError( - f""{group} is not a valid aggregation method. Possible values are: {', '.join([k for k in aggregates])}"" + f""{aggregation_method} is not a valid aggregation method. Possible values are: {', '.join([k for k in aggregates])}"" ) map_data = aggregates[aggregation_method][variables] ",templot/plot_aggregated_map.py,"ReplaceText(target='aggregation_method' @(98,15)->(98,20))","def plot_aggregated_map( if aggregation_method not in aggregates: raise ValueError( f""{group} is not a valid aggregation method. Possible values are: {', '.join([k for k in aggregates])}"" ) map_data = aggregates[aggregation_method][variables]","def plot_aggregated_map( if aggregation_method not in aggregates: raise ValueError( f""{aggregation_method} is not a valid aggregation method. Possible values are: {', '.join([k for k in aggregates])}"" ) map_data = aggregates[aggregation_method][variables]" 575,https://:@github.com/cjneely10/BioMetaDB.git,71352d2e75c038af886007c7b82591896aa23e1c,"@@ -146,4 +146,4 @@ def create_database(db_name, table_name, directory_name, data_file, alias, silen if not silent: _initialization_display_message_epilogue() if not integrity_cancel: - integrity_check(directory_name, table_name, ""None"", silent) + integrity_check(db_name, table_name, ""None"", silent) ",BioMetaDB/DBOperations/create_database.py,"ReplaceText(target='db_name' @(149,24)->(149,38))","def create_database(db_name, table_name, directory_name, data_file, alias, silen if not silent: _initialization_display_message_epilogue() if not integrity_cancel: integrity_check(directory_name, table_name, ""None"", silent)","def create_database(db_name, table_name, directory_name, data_file, alias, silen if not silent: _initialization_display_message_epilogue() if not integrity_cancel: integrity_check(db_name, table_name, ""None"", silent)" 576,https://:@github.com/lsst-sqre/kubespawner.git,5f0ca5f9734552b4c40563828899316d2b69156c,"@@ -361,7 +361,7 @@ class KubeSpawner(Spawner): # shut down to complete while True: data = yield self.get_pod_info(self.pod_name) - if data is not None: + if data is None: break time.sleep(5) ",kubespawner/spawner.py,"ReplaceText(target=' is ' @(364,23)->(364,31))","class KubeSpawner(Spawner): # shut down to complete while True: data = yield self.get_pod_info(self.pod_name) if data is not None: break time.sleep(5) ","class KubeSpawner(Spawner): # shut down to complete while True: data = yield self.get_pod_info(self.pod_name) if data is None: break time.sleep(5) " 577,https://:@github.com/lsst-sqre/kubespawner.git,df9936a785e34c898ffd065f17697a0035cf310c,"@@ -404,7 +404,7 @@ class KubeSpawner(Spawner): @gen.coroutine def start(self): pvc_data = get_pvc_info(self.pvc_name) - if pvc_data is not None: + if pvc_data is None: pvc_manifest = self.get_pvc_manifest() yield self.httpclient.fetch(self.request( url=k8s_url(self.namespace, 'persistentvolumeclaims'), ",kubespawner/spawner.py,"ReplaceText(target=' is ' @(407,19)->(407,27))","class KubeSpawner(Spawner): @gen.coroutine def start(self): pvc_data = get_pvc_info(self.pvc_name) if pvc_data is not None: pvc_manifest = self.get_pvc_manifest() yield self.httpclient.fetch(self.request( url=k8s_url(self.namespace, 'persistentvolumeclaims'),","class KubeSpawner(Spawner): @gen.coroutine def start(self): pvc_data = get_pvc_info(self.pvc_name) if pvc_data is None: pvc_manifest = self.get_pvc_manifest() yield self.httpclient.fetch(self.request( url=k8s_url(self.namespace, 'persistentvolumeclaims')," 578,https://:@github.com/d-meiser/cold-atoms.git,8235e3bc1d9cc9b1bbfe27948d24adc48db33f06,"@@ -48,5 +48,5 @@ def bend_kick(dt, Bz, ensemble, forces, reference_impl=False): f = np.zeros_like(ensemble.v) for force in forces: force.force(dt, ensemble, f) - ensemble.v *= f / m + ensemble.v += f / m updater(0.5 * dt, omegaB, ensemble.x, ensemble.v) ",src/coldatoms/bend_kick.py,"ReplaceText(target='+=' @(51,19)->(51,21))","def bend_kick(dt, Bz, ensemble, forces, reference_impl=False): f = np.zeros_like(ensemble.v) for force in forces: force.force(dt, ensemble, f) ensemble.v *= f / m updater(0.5 * dt, omegaB, ensemble.x, ensemble.v)","def bend_kick(dt, Bz, ensemble, forces, reference_impl=False): f = np.zeros_like(ensemble.v) for force in forces: force.force(dt, ensemble, f) ensemble.v += f / m updater(0.5 * dt, omegaB, ensemble.x, ensemble.v)" 579,https://:@github.com/silvacms/silva.pas.base.git,d0e1b5196420a6a1359fc5f45d220d172f7a1e01,"@@ -41,7 +41,7 @@ class SilvaCascadingPASPlugin(SearchPrincipalsPlugin): for authenticator_id, auth in authenticators: try: info = auth.authenticateCredentials(credentials) - if info is not None and info[0] is None: + if info is not None and info[0] is not None: # Failed login can be None OR (None, None) return info except _SWALLOWABLE_PLUGIN_EXCEPTIONS: ",src/silva/pas/base/plugins/cascading.py,"ReplaceText(target=' is not ' @(44,47)->(44,51))","class SilvaCascadingPASPlugin(SearchPrincipalsPlugin): for authenticator_id, auth in authenticators: try: info = auth.authenticateCredentials(credentials) if info is not None and info[0] is None: # Failed login can be None OR (None, None) return info except _SWALLOWABLE_PLUGIN_EXCEPTIONS:","class SilvaCascadingPASPlugin(SearchPrincipalsPlugin): for authenticator_id, auth in authenticators: try: info = auth.authenticateCredentials(credentials) if info is not None and info[0] is not None: # Failed login can be None OR (None, None) return info except _SWALLOWABLE_PLUGIN_EXCEPTIONS:" 580,https://:@github.com/jgolob/maliampi.git,dd0a5bf78106e083005db0e7bd21f1122e63f162,"@@ -239,7 +239,7 @@ class Workflow_Placement(sl.WorkflowTask): lpca = self.new_task( 'calculate_lpca', Jplace_PCA, - containerinfo=long_containerinfo, + containerinfo=highmem_containerinfo, path=os.path.join( self.destination_dir, 'placement', ",maliampi/subcommands/placement.py,"ReplaceText(target='highmem_containerinfo' @(242,26)->(242,44))","class Workflow_Placement(sl.WorkflowTask): lpca = self.new_task( 'calculate_lpca', Jplace_PCA, containerinfo=long_containerinfo, path=os.path.join( self.destination_dir, 'placement',","class Workflow_Placement(sl.WorkflowTask): lpca = self.new_task( 'calculate_lpca', Jplace_PCA, containerinfo=highmem_containerinfo, path=os.path.join( self.destination_dir, 'placement'," 581,https://:@github.com/jgolob/maliampi.git,cdea28dbb12093af0165e983149da396b69fe33a,"@@ -115,7 +115,7 @@ class Workflow_DADA2(sl.WorkflowTask): batch_errModels[batch] = self.new_task( 'dada2_learn_error_batch_{}'.format(batch), DADA2_LearnError, - containerinfo=heavy_containerinfo, + containerinfo=midcpu_containerinfo, batch=batch, tar_reads=False, path=os.path.join( ",maliampi/subcommands/sv_dada2.py,"ReplaceText(target='midcpu_containerinfo' @(118,30)->(118,49))","class Workflow_DADA2(sl.WorkflowTask): batch_errModels[batch] = self.new_task( 'dada2_learn_error_batch_{}'.format(batch), DADA2_LearnError, containerinfo=heavy_containerinfo, batch=batch, tar_reads=False, path=os.path.join(","class Workflow_DADA2(sl.WorkflowTask): batch_errModels[batch] = self.new_task( 'dada2_learn_error_batch_{}'.format(batch), DADA2_LearnError, containerinfo=midcpu_containerinfo, batch=batch, tar_reads=False, path=os.path.join(" 582,https://:@github.com/jgolob/maliampi.git,3cde81cdd2b908b7edd44a000986744301092fae,"@@ -203,7 +203,7 @@ class Workflow_Classify(sl.WorkflowTask): placement_db_classified = self.new_task( 'classify_into_placement_db', PlacementDB_Classify_SV, - containerinfo=heavy_containerinfo, + containerinfo=midcpu_containerinfo, ) placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz ",maliampi/subcommands/classify.py,"ReplaceText(target='midcpu_containerinfo' @(206,26)->(206,45))","class Workflow_Classify(sl.WorkflowTask): placement_db_classified = self.new_task( 'classify_into_placement_db', PlacementDB_Classify_SV, containerinfo=heavy_containerinfo, ) placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz","class Workflow_Classify(sl.WorkflowTask): placement_db_classified = self.new_task( 'classify_into_placement_db', PlacementDB_Classify_SV, containerinfo=midcpu_containerinfo, ) placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz" 583,https://:@github.com/jgolob/maliampi.git,f50cfcea1e390ae5eb05de0c116c2251a09f4864,"@@ -203,7 +203,7 @@ class Workflow_Classify(sl.WorkflowTask): placement_db_classified = self.new_task( 'classify_into_placement_db', PlacementDB_Classify_SV, - containerinfo=midcpu_containerinfo, + containerinfo=highmem_containerinfo, ) placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz ",maliampi/subcommands/classify.py,"ReplaceText(target='highmem_containerinfo' @(206,26)->(206,46))","class Workflow_Classify(sl.WorkflowTask): placement_db_classified = self.new_task( 'classify_into_placement_db', PlacementDB_Classify_SV, containerinfo=midcpu_containerinfo, ) placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz","class Workflow_Classify(sl.WorkflowTask): placement_db_classified = self.new_task( 'classify_into_placement_db', PlacementDB_Classify_SV, containerinfo=highmem_containerinfo, ) placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz" 584,https://:@github.com/d3rp/clima.git,92eced31f43fd49f87e6af8582066a25fc0ba726,"@@ -46,7 +46,7 @@ def SeparateFlagArgs(args: list): Returns: A tuple with the Fire args (a list), followed by the Flag args (a list). """""" - if len(args) > 1 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args: + if len(args) > 0 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args: args.pop() args.append('--') args.append('-h') ",clima/fire/parser.py,"ReplaceText(target='0' @(49,17)->(49,18))","def SeparateFlagArgs(args: list): Returns: A tuple with the Fire args (a list), followed by the Flag args (a list). """""" if len(args) > 1 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args: args.pop() args.append('--') args.append('-h')","def SeparateFlagArgs(args: list): Returns: A tuple with the Fire args (a list), followed by the Flag args (a list). """""" if len(args) > 0 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args: args.pop() args.append('--') args.append('-h')" 585,https://:@github.com/jeffkinnison/pyrameter.git,306c95b1e0643fc47e0206281cd12c714849782d,"@@ -47,7 +47,7 @@ def backend_factory(path, *args, **kwargs): if os.path.isfile(path) or os.path.isdir(path): from pyrameter.db.local import JsonStorage return JsonStorage(path, *args, **kwargs) - elif path.find('mongodb://') >= 0: + elif path.find('mongodb://') == 0: from pyrameter.db.mongo import MongoStorage return MongoStorage(path, *args, **kwargs) else: ",pyrameter/db/backend_factory.py,"ReplaceText(target='==' @(50,33)->(50,35))","def backend_factory(path, *args, **kwargs): if os.path.isfile(path) or os.path.isdir(path): from pyrameter.db.local import JsonStorage return JsonStorage(path, *args, **kwargs) elif path.find('mongodb://') >= 0: from pyrameter.db.mongo import MongoStorage return MongoStorage(path, *args, **kwargs) else:","def backend_factory(path, *args, **kwargs): if os.path.isfile(path) or os.path.isdir(path): from pyrameter.db.local import JsonStorage return JsonStorage(path, *args, **kwargs) elif path.find('mongodb://') == 0: from pyrameter.db.mongo import MongoStorage return MongoStorage(path, *args, **kwargs) else:" 586,https://:@github.com/RADAR-base/pyRADAR-processing.git,2c6ea694e1d40b9c16d6a10e10c0af9afd5a3d0d,"@@ -115,7 +115,7 @@ class Project(RadarObject): self.ptcs_update_info(info) labels = kwargs.get('labels', False) - if info: + if labels: for ptc in labels: if ptc not in self.participants: self.add_participant(ptc) ",radar/wrappers.py,"ReplaceText(target='labels' @(118,11)->(118,15))","class Project(RadarObject): self.ptcs_update_info(info) labels = kwargs.get('labels', False) if info: for ptc in labels: if ptc not in self.participants: self.add_participant(ptc)","class Project(RadarObject): self.ptcs_update_info(info) labels = kwargs.get('labels', False) if labels: for ptc in labels: if ptc not in self.participants: self.add_participant(ptc)" 587,https://:@github.com/marshallward/ropes.git,b8fd70b68d2ec157c7f2397aab3931e50c5a16ae,"@@ -145,7 +145,7 @@ class Rope(object): else: if start is None: offset = index.step + (head.length - 1) % (-index.step) - elif start > 0: + elif start >= 0: offset = index.step + min(start, head.length - 1) % (-index.step) else: offset = index.step + (start + head.length) % (-index.step) ",ropes.py,"ReplaceText(target='>=' @(148,35)->(148,36))","class Rope(object): else: if start is None: offset = index.step + (head.length - 1) % (-index.step) elif start > 0: offset = index.step + min(start, head.length - 1) % (-index.step) else: offset = index.step + (start + head.length) % (-index.step)","class Rope(object): else: if start is None: offset = index.step + (head.length - 1) % (-index.step) elif start >= 0: offset = index.step + min(start, head.length - 1) % (-index.step) else: offset = index.step + (start + head.length) % (-index.step)" 588,https://:@github.com/pkgw/bibtools.git,2273ff1a94f4f6952026c5ab1d3ddffa042f2158,"@@ -204,7 +204,7 @@ class Dump (multitool.Command): help_if_no_args = False def invoke (self, args, app=None, **kwargs): - if len (args) != 1: + if len (args) != 0: raise multitool.UsageError ('expected no arguments') app.export_all (sys.stdout, 72) ",bibtools/cli.py,"ReplaceText(target='0' @(207,25)->(207,26))","class Dump (multitool.Command): help_if_no_args = False def invoke (self, args, app=None, **kwargs): if len (args) != 1: raise multitool.UsageError ('expected no arguments') app.export_all (sys.stdout, 72)","class Dump (multitool.Command): help_if_no_args = False def invoke (self, args, app=None, **kwargs): if len (args) != 0: raise multitool.UsageError ('expected no arguments') app.export_all (sys.stdout, 72)" 589,https://:@github.com/cooper-software/hammock.git,ed682f4d33be53d7d2f2b21b384a36a2770c6cf5,"@@ -20,7 +20,7 @@ class Hammock(object): entities = set() self.collections_by_class_name = {} - for collection_cls in collections: + for collection_cls in collection_classes: entities.add(collection_cls.entity) collection = collection_cls(storage) self.collections_by_class_name[collection_cls.__name__] = collection ",hammock/__init__.py,"ReplaceText(target='collection_classes' @(23,24)->(23,35))","class Hammock(object): entities = set() self.collections_by_class_name = {} for collection_cls in collections: entities.add(collection_cls.entity) collection = collection_cls(storage) self.collections_by_class_name[collection_cls.__name__] = collection","class Hammock(object): entities = set() self.collections_by_class_name = {} for collection_cls in collection_classes: entities.add(collection_cls.entity) collection = collection_cls(storage) self.collections_by_class_name[collection_cls.__name__] = collection" 590,https://:@github.com/bempp/bempp-cl.git,7ab5546ce89b626e146cb29433ed1113a3c72c9c,"@@ -97,7 +97,7 @@ def visualize_with_jupyter_notebook(obj, mode=""element"", transformation=None): for element in grid.entity_iterator(0): index = element.index local_values = np.real( - transformation(obj.evaluate(element, local_coordinates)) + transformation(obj.evaluate(index, local_coordinates)) ) values[index] = local_values.flatten() ",bempp/api/external/viewers.py,"ReplaceText(target='index' @(100,44)->(100,51))","def visualize_with_jupyter_notebook(obj, mode=""element"", transformation=None): for element in grid.entity_iterator(0): index = element.index local_values = np.real( transformation(obj.evaluate(element, local_coordinates)) ) values[index] = local_values.flatten() ","def visualize_with_jupyter_notebook(obj, mode=""element"", transformation=None): for element in grid.entity_iterator(0): index = element.index local_values = np.real( transformation(obj.evaluate(index, local_coordinates)) ) values[index] = local_values.flatten() " 591,https://:@github.com/bempp/bempp-cl.git,094eb06f36e837f3a17d2abe23f4bb78d1a32dc0,"@@ -91,7 +91,7 @@ def assemble_dense( cols = domain.global_dof_count nshape_test = dual_to_range.number_of_shape_functions - nshape_trial = dual_to_range.number_of_shape_functions + nshape_trial = domain.number_of_shape_functions precision = operator_descriptor.precision ",bempp/core/numba/dense_assembler.py,"ReplaceText(target='domain' @(94,19)->(94,32))","def assemble_dense( cols = domain.global_dof_count nshape_test = dual_to_range.number_of_shape_functions nshape_trial = dual_to_range.number_of_shape_functions precision = operator_descriptor.precision ","def assemble_dense( cols = domain.global_dof_count nshape_test = dual_to_range.number_of_shape_functions nshape_trial = domain.number_of_shape_functions precision = operator_descriptor.precision " 592,https://:@github.com/bempp/bempp-cl.git,242da1c08304423e6ef6ead60e691928426dab1b,"@@ -1035,9 +1035,9 @@ def helmholtz_hypersingular_regular( ] * ( curl_product[test_fun_index, trial_fun_index] - wavenumber - * wavenumber + * wavenumber * local_test_fun_values[ - 0, test_fun_index, quad_point_index + 0, test_fun_index, test_point_index ] * local_trial_fun_values[ 0, trial_fun_index, quad_point_index ",bempp/core/numba/kernels.py,"ReplaceText(target='test_point_index' @(1040,55)->(1040,71))","def helmholtz_hypersingular_regular( ] * ( curl_product[test_fun_index, trial_fun_index] - wavenumber * wavenumber * local_test_fun_values[ 0, test_fun_index, quad_point_index ] * local_trial_fun_values[ 0, trial_fun_index, quad_point_index","def helmholtz_hypersingular_regular( ] * ( curl_product[test_fun_index, trial_fun_index] - wavenumber * wavenumber * local_test_fun_values[ 0, test_fun_index, test_point_index ] * local_trial_fun_values[ 0, trial_fun_index, quad_point_index" 593,https://:@github.com/bempp/bempp-cl.git,1bb4a1c097e4e3e87ed328f37cde5abd9c0c24b9,"@@ -33,7 +33,7 @@ class DensePotentialAssembler(object): x_transformed = self.space.map_to_full_grid @ ( self.space.dof_transformation @ x ) - result = implementation(x) + result = implementation(x_transformed) return result.reshape([kernel_dimension, -1], order=""F"") self._evaluator = potential_evaluator ",bempp/core/dense_potential_assembler.py,"ReplaceText(target='x_transformed' @(36,36)->(36,37))","class DensePotentialAssembler(object): x_transformed = self.space.map_to_full_grid @ ( self.space.dof_transformation @ x ) result = implementation(x) return result.reshape([kernel_dimension, -1], order=""F"") self._evaluator = potential_evaluator","class DensePotentialAssembler(object): x_transformed = self.space.map_to_full_grid @ ( self.space.dof_transformation @ x ) result = implementation(x_transformed) return result.reshape([kernel_dimension, -1], order=""F"") self._evaluator = potential_evaluator" 594,https://:@bitbucket.org/agaveapi/agaveflask.git,17f24e257b275fe1bf64afcf6a5b09d87ab05b79,"@@ -34,7 +34,7 @@ def read_config(conf_file='service.conf'): raise RuntimeError('No config file found.') if not parser.parser.read(place): raise RuntimeError(""couldn't read config file from {0}"" - .format(', '.join(place))) + .format(', '.join(places))) return parser Config = read_config() \ No newline at end of file ",agaveflask/config.py,"ReplaceText(target='places' @(37,45)->(37,50))","def read_config(conf_file='service.conf'): raise RuntimeError('No config file found.') if not parser.parser.read(place): raise RuntimeError(""couldn't read config file from {0}"" .format(', '.join(place))) return parser Config = read_config() \ No newline at end of file","def read_config(conf_file='service.conf'): raise RuntimeError('No config file found.') if not parser.parser.read(place): raise RuntimeError(""couldn't read config file from {0}"" .format(', '.join(places))) return parser Config = read_config() \ No newline at end of file" 595,https://:@github.com/llazzaro/jarvispatrick.git,05457d04a6982a47c39d5109b6e91efa6441bd93,"@@ -27,7 +27,7 @@ class JarvisPatrick(object): def __call__(self, number_of_neighbors, number_of_common_neighbors): """""" """""" - if number_of_common_neighbors >= number_of_neighbors: + if number_of_common_neighbors > number_of_neighbors: raise ValueError('Asked for more common neighbors than number of neighbors') neighbors_list = {} for element in self.dataset_elements: ",jarvispatrick/__init__.py,"ReplaceText(target='>' @(30,38)->(30,40))","class JarvisPatrick(object): def __call__(self, number_of_neighbors, number_of_common_neighbors): """""" """""" if number_of_common_neighbors >= number_of_neighbors: raise ValueError('Asked for more common neighbors than number of neighbors') neighbors_list = {} for element in self.dataset_elements:","class JarvisPatrick(object): def __call__(self, number_of_neighbors, number_of_common_neighbors): """""" """""" if number_of_common_neighbors > number_of_neighbors: raise ValueError('Asked for more common neighbors than number of neighbors') neighbors_list = {} for element in self.dataset_elements:" 596,https://:@github.com/kennydo/oauthlib.git,1f292e6923aa9419d28e3700e22102dffd447886,"@@ -112,7 +112,7 @@ def collect_parameters(uri_query='', body='', headers=None, if isinstance(k, str): k = k.decode('utf-8') if isinstance(v, str): - if v.startswith('oauth_'): + if k.startswith('oauth_'): v = utils.unescape(v) else: v = v.decode('utf-8') ",oauthlib/oauth1/rfc5849/signature.py,"ReplaceText(target='k' @(115,15)->(115,16))","def collect_parameters(uri_query='', body='', headers=None, if isinstance(k, str): k = k.decode('utf-8') if isinstance(v, str): if v.startswith('oauth_'): v = utils.unescape(v) else: v = v.decode('utf-8')","def collect_parameters(uri_query='', body='', headers=None, if isinstance(k, str): k = k.decode('utf-8') if isinstance(v, str): if k.startswith('oauth_'): v = utils.unescape(v) else: v = v.decode('utf-8')" 597,https://:@github.com/kennydo/oauthlib.git,8f57459fbbab1f317d5475f31f90b1a75016a2a8,"@@ -281,7 +281,7 @@ def add_params_to_uri(uri, params, fragment=False): """"""Add a list of two-tuples to the uri query components."""""" sch, net, path, par, query, fra = urlparse.urlparse(uri) if fragment: - fra = add_params_to_qs(query, params) + fra = add_params_to_qs(fra, params) else: query = add_params_to_qs(query, params) return urlparse.urlunparse((sch, net, path, par, query, fra)) ",oauthlib/common.py,"ReplaceText(target='fra' @(284,31)->(284,36))","def add_params_to_uri(uri, params, fragment=False): """"""Add a list of two-tuples to the uri query components."""""" sch, net, path, par, query, fra = urlparse.urlparse(uri) if fragment: fra = add_params_to_qs(query, params) else: query = add_params_to_qs(query, params) return urlparse.urlunparse((sch, net, path, par, query, fra))","def add_params_to_uri(uri, params, fragment=False): """"""Add a list of two-tuples to the uri query components."""""" sch, net, path, par, query, fra = urlparse.urlparse(uri) if fragment: fra = add_params_to_qs(fra, params) else: query = add_params_to_qs(query, params) return urlparse.urlunparse((sch, net, path, par, query, fra))" 598,https://:@github.com/jakobrunge/tigramite.git,2011867b0f0cc4c3ca6bb3317b2a3a37d828116b,"@@ -236,7 +236,7 @@ def time_bin_with_mask(data, time_bin_length, sample_selector=None): sample_selector.shape = (T, 1) bindata = numpy.zeros( - (T / time_bin_length,) + data.shape[1:], dtype=""float32"") + (T // time_bin_length,) + data.shape[1:], dtype=""float32"") for index, i in enumerate(range(0, T - time_bin_length + 1, time_bin_length)): # print weighted_avg_and_std(fulldata[i:i+time_bin_length], axis=0, ",tigramite/data_processing.py,"ReplaceText(target='//' @(239,11)->(239,12))","def time_bin_with_mask(data, time_bin_length, sample_selector=None): sample_selector.shape = (T, 1) bindata = numpy.zeros( (T / time_bin_length,) + data.shape[1:], dtype=""float32"") for index, i in enumerate(range(0, T - time_bin_length + 1, time_bin_length)): # print weighted_avg_and_std(fulldata[i:i+time_bin_length], axis=0,","def time_bin_with_mask(data, time_bin_length, sample_selector=None): sample_selector.shape = (T, 1) bindata = numpy.zeros( (T // time_bin_length,) + data.shape[1:], dtype=""float32"") for index, i in enumerate(range(0, T - time_bin_length + 1, time_bin_length)): # print weighted_avg_and_std(fulldata[i:i+time_bin_length], axis=0," 599,https://:@github.com/jakobrunge/tigramite.git,2011867b0f0cc4c3ca6bb3317b2a3a37d828116b,"@@ -528,7 +528,7 @@ class LinearMediation(Models): def tsg_to_net(self, node, max_lag): """"""Helper function to translate from time series graph to network."""""" - row = node / max_lag + row = node // max_lag lag = node % max_lag return (row, -lag) ",tigramite/models.py,"ReplaceText(target='//' @(531,19)->(531,20))","class LinearMediation(Models): def tsg_to_net(self, node, max_lag): """"""Helper function to translate from time series graph to network."""""" row = node / max_lag lag = node % max_lag return (row, -lag) ","class LinearMediation(Models): def tsg_to_net(self, node, max_lag): """"""Helper function to translate from time series graph to network."""""" row = node // max_lag lag = node % max_lag return (row, -lag) " 600,https://:@github.com/jakobrunge/tigramite.git,ebf5ae6ad58a416f2097bc7453df96b6ff584b17,"@@ -2577,7 +2577,7 @@ class CMIsymb(CondIndTest): dim, T = symb_array.shape # Needed because np.bincount cannot process longs - if isinstance(self.n_symbs ** dim, int): + if not isinstance(self.n_symbs ** dim, int): raise ValueError(""Too many n_symbs and/or dimensions, "" ""numpy.bincount cannot process longs"") if self.n_symbs ** dim * 16. / 8. / 1024. ** 3 > 3.: ",tigramite/independence_tests.py,"ReplaceText(target='not ' @(2580,11)->(2580,11))","class CMIsymb(CondIndTest): dim, T = symb_array.shape # Needed because np.bincount cannot process longs if isinstance(self.n_symbs ** dim, int): raise ValueError(""Too many n_symbs and/or dimensions, "" ""numpy.bincount cannot process longs"") if self.n_symbs ** dim * 16. / 8. / 1024. ** 3 > 3.:","class CMIsymb(CondIndTest): dim, T = symb_array.shape # Needed because np.bincount cannot process longs if not isinstance(self.n_symbs ** dim, int): raise ValueError(""Too many n_symbs and/or dimensions, "" ""numpy.bincount cannot process longs"") if self.n_symbs ** dim * 16. / 8. / 1024. ** 3 > 3.:" 601,https://:@github.com/ontio/neo-boa.git,07ac051d44eb38ac612effd14b57af0a5b65c90e,"@@ -8,7 +8,7 @@ class SCTest(FunctionCode): @staticmethod def Main(a, b): - if a > b: + if a == b: return True ",tests/src/CompareTest2.py,"ReplaceText(target='==' @(11,13)->(11,14))","class SCTest(FunctionCode): @staticmethod def Main(a, b): if a > b: return True ","class SCTest(FunctionCode): @staticmethod def Main(a, b): if a == b: return True " 602,https://:@github.com/ggventurini/python-deltasigma.git,3dd6127dc022234c4433d4e4a018942927fa417f,"@@ -59,7 +59,7 @@ def cancelPZ(arg1, tol=1e-6): z = copy.copy(arg1.zeros) p = copy.copy(arg1.poles) k = arg1.gain - for i in range(max(z.shape) - 1, 0, -1): + for i in range(max(z.shape) - 1, -1, -1): d = z[i] - p cancel = np.nonzero(np.abs(d) < tol)[0] if cancel.size: ",deltasigma/_cancelPZ.py,"ReplaceText(target='-1' @(62,37)->(62,38))","def cancelPZ(arg1, tol=1e-6): z = copy.copy(arg1.zeros) p = copy.copy(arg1.poles) k = arg1.gain for i in range(max(z.shape) - 1, 0, -1): d = z[i] - p cancel = np.nonzero(np.abs(d) < tol)[0] if cancel.size:","def cancelPZ(arg1, tol=1e-6): z = copy.copy(arg1.zeros) p = copy.copy(arg1.poles) k = arg1.gain for i in range(max(z.shape) - 1, -1, -1): d = z[i] - p cancel = np.nonzero(np.abs(d) < tol)[0] if cancel.size:" 603,https://:@github.com/jordens/rayopt.git,3bc56650b966e2c34d25d47af76d3b7f63110c4f,"@@ -199,7 +199,7 @@ class Analysis(object): axp, axm, axsm, axss, axo = axi axp.add_patch(mpl.patches.Circle((0, 0), r, edgecolor=""black"", facecolor=""none"")) - axp.text(-.1, .5, ""OY=%s"" % hi, rotation=""vertical"", + axo.text(-.1, .5, ""OY=%s"" % hi, rotation=""vertical"", transform=axp.transAxes, verticalalignment=""center"") for i, (wi, ci) in enumerate(zip(wavelengths, colors)): ",rayopt/analysis.py,"ReplaceText(target='axo' @(202,12)->(202,15))","class Analysis(object): axp, axm, axsm, axss, axo = axi axp.add_patch(mpl.patches.Circle((0, 0), r, edgecolor=""black"", facecolor=""none"")) axp.text(-.1, .5, ""OY=%s"" % hi, rotation=""vertical"", transform=axp.transAxes, verticalalignment=""center"") for i, (wi, ci) in enumerate(zip(wavelengths, colors)):","class Analysis(object): axp, axm, axsm, axss, axo = axi axp.add_patch(mpl.patches.Circle((0, 0), r, edgecolor=""black"", facecolor=""none"")) axo.text(-.1, .5, ""OY=%s"" % hi, rotation=""vertical"", transform=axp.transAxes, verticalalignment=""center"") for i, (wi, ci) in enumerate(zip(wavelengths, colors)):" 604,https://:@github.com/jordens/rayopt.git,0d5689d0c36fa3aec836c7869e169f4bc4b1a72f,"@@ -333,7 +333,7 @@ class System(list): c = getattr(el, ""curvature"", 0) if pending is not None: r = max(el.radius, pending.radius) - if c < 0: + if c <= 0: el.radius = r if c0 > 0: pending.radius = r ",rayopt/system.py,"ReplaceText(target='<=' @(336,21)->(336,22))","class System(list): c = getattr(el, ""curvature"", 0) if pending is not None: r = max(el.radius, pending.radius) if c < 0: el.radius = r if c0 > 0: pending.radius = r","class System(list): c = getattr(el, ""curvature"", 0) if pending is not None: r = max(el.radius, pending.radius) if c <= 0: el.radius = r if c0 > 0: pending.radius = r" 605,https://:@github.com/pantherlab/v2d-cli.git,fe2f6fe46f14778cfcb74852d817d1876d171352,"@@ -92,7 +92,7 @@ def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: - print_diff(d, args.domain) + print_diff(args.domain, d) if write: f.write(d + ""\n"") if (args.check): ",v2d/main.py,"ArgSwap(idxs=0<->1 @(95,16)->(95,26))","def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: print_diff(d, args.domain) if write: f.write(d + ""\n"") if (args.check):","def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: print_diff(args.domain, d) if write: f.write(d + ""\n"") if (args.check):" 606,https://:@github.com/xtimon/inipgdump.git,47c9bf35a256ee9c6caa0aeb6913a5e80cc15d23,"@@ -92,7 +92,7 @@ def main(): if not os.path.isdir(dump_dir): print('Folder \'%s\' not found' % dump_dir) sys.exit(1) - if keep_count <= 0: + if keep_count < 0: print('keep_count must be greater than 0') sys.exit(1) make_dump(conf_file, dump_dir, keep_count) ",inipgdump/core.py,"ReplaceText(target='<' @(95,18)->(95,20))","def main(): if not os.path.isdir(dump_dir): print('Folder \'%s\' not found' % dump_dir) sys.exit(1) if keep_count <= 0: print('keep_count must be greater than 0') sys.exit(1) make_dump(conf_file, dump_dir, keep_count)","def main(): if not os.path.isdir(dump_dir): print('Folder \'%s\' not found' % dump_dir) sys.exit(1) if keep_count < 0: print('keep_count must be greater than 0') sys.exit(1) make_dump(conf_file, dump_dir, keep_count)" 607,https://:@github.com/dogebuild/dogebuild.git,5fbc92cbf6aceb4a99374e5e19208b3889c36628,"@@ -14,7 +14,7 @@ class Doge: plugin_full_name = self.contrib_name + '-' + plugin_name plugin_package = self.contrib_name + '_' + plugin_name - if not self.check_plugin_installed(plugin_full_name): + if not self.check_plugin_installed(plugin_package): self.pip.install(plugin_full_name) # ??? file, path, desc = self.find_dotted_module(plugin_package + '.loader') ",dogebuild/Doge.py,"ReplaceText(target='plugin_package' @(17,43)->(17,59))","class Doge: plugin_full_name = self.contrib_name + '-' + plugin_name plugin_package = self.contrib_name + '_' + plugin_name if not self.check_plugin_installed(plugin_full_name): self.pip.install(plugin_full_name) # ??? file, path, desc = self.find_dotted_module(plugin_package + '.loader')","class Doge: plugin_full_name = self.contrib_name + '-' + plugin_name plugin_package = self.contrib_name + '_' + plugin_name if not self.check_plugin_installed(plugin_package): self.pip.install(plugin_full_name) # ??? file, path, desc = self.find_dotted_module(plugin_package + '.loader')" 608,https://:@github.com/jiosue/qubovert.git,11782cc691038742a250ee53b863c413f28b6455,"@@ -329,7 +329,7 @@ class DictArithmetic(dict): for k, v in other.items(): self[k] -= v else: - self[()] -= v + self[()] -= other return self def __mul__(self, other): ",qubovert/utils/_dict_arithmetic.py,"ReplaceText(target='other' @(332,24)->(332,25))","class DictArithmetic(dict): for k, v in other.items(): self[k] -= v else: self[()] -= v return self def __mul__(self, other):","class DictArithmetic(dict): for k, v in other.items(): self[k] -= v else: self[()] -= other return self def __mul__(self, other):" 609,https://:@github.com/jiosue/qubovert.git,ad39ad11cea1cd2ca8f82a23b21990cd0e758915,"@@ -323,7 +323,7 @@ class SpinSimulation: # the change in energy from flipping variable i is equal to # -2 * (the energy of the subgraph depending on i) dE = -2 * puso_value(self._state, self._subgraphs[i]) - if dE < 0 or (T and random.random() < exp(-dE / T)): + if dE <= 0 or (T and random.random() < exp(-dE / T)): self._flip_bit(i) ",qubovert/sim/_simulations.py,"ReplaceText(target='<=' @(326,22)->(326,23))","class SpinSimulation: # the change in energy from flipping variable i is equal to # -2 * (the energy of the subgraph depending on i) dE = -2 * puso_value(self._state, self._subgraphs[i]) if dE < 0 or (T and random.random() < exp(-dE / T)): self._flip_bit(i) ","class SpinSimulation: # the change in energy from flipping variable i is equal to # -2 * (the energy of the subgraph depending on i) dE = -2 * puso_value(self._state, self._subgraphs[i]) if dE <= 0 or (T and random.random() < exp(-dE / T)): self._flip_bit(i) " 610,https://:@github.com/gjo/colander_jsonschema.git,14d7446b85b8faf56705047146a62f10981c0bf7,"@@ -124,7 +124,7 @@ class ValidatorConversionDispatcher(object): if isinstance(validator, colander.All): converted = {} for v in validator.validators: - ret = self(schema_node, validator) + ret = self(schema_node, v) converted.update(ret) return converted ",colander_jsonschema/__init__.py,"ReplaceText(target='v' @(127,40)->(127,49))","class ValidatorConversionDispatcher(object): if isinstance(validator, colander.All): converted = {} for v in validator.validators: ret = self(schema_node, validator) converted.update(ret) return converted ","class ValidatorConversionDispatcher(object): if isinstance(validator, colander.All): converted = {} for v in validator.validators: ret = self(schema_node, v) converted.update(ret) return converted " 611,https://:@github.com/ucl-exoplanets/TauREx3_public.git,fdfa8c4e1d29dc715c7f42d55c21c0d911390a83,"@@ -127,7 +127,7 @@ def main(): wlgrid = np.log10(10000/bindown_wngrid) if args.plot: - if get_rank()==0 and nprocs()==1: + if get_rank()==0 and nprocs()<=1: import matplotlib.pyplot as plt if args.contrib: for name,value in contrib: ",taurex/taurex.py,"ReplaceText(target='<=' @(130,38)->(130,40))","def main(): wlgrid = np.log10(10000/bindown_wngrid) if args.plot: if get_rank()==0 and nprocs()==1: import matplotlib.pyplot as plt if args.contrib: for name,value in contrib:","def main(): wlgrid = np.log10(10000/bindown_wngrid) if args.plot: if get_rank()==0 and nprocs()<=1: import matplotlib.pyplot as plt if args.contrib: for name,value in contrib:" 612,https://:@github.com/ucl-exoplanets/TauREx3_public.git,b159dcc22b3e753aaea101031b3c8df14e5affdc,"@@ -135,7 +135,7 @@ def main(): priors = {} priors['Profiles'] = profiles priors['Spectra'] = spectrum - out.store_dictionary(solution,group_name='Priors') + out.store_dictionary(priors,group_name='Priors') else: out.store_dictionary(profiles,group_name='Profiles') out.store_dictionary(spectrum,group_name='Spectra') ",taurex/taurex.py,"ReplaceText(target='priors' @(138,37)->(138,45))","def main(): priors = {} priors['Profiles'] = profiles priors['Spectra'] = spectrum out.store_dictionary(solution,group_name='Priors') else: out.store_dictionary(profiles,group_name='Profiles') out.store_dictionary(spectrum,group_name='Spectra')","def main(): priors = {} priors['Profiles'] = profiles priors['Spectra'] = spectrum out.store_dictionary(priors,group_name='Priors') else: out.store_dictionary(profiles,group_name='Profiles') out.store_dictionary(spectrum,group_name='Spectra')" 613,https://:@github.com/ucl-exoplanets/TauREx3_public.git,1aa67f68d7086afcf2390add80728193d7a9024e,"@@ -13,7 +13,7 @@ def nprocs(): try: from mpi4py import MPI except ImportError: - return 0 + return 1 comm = MPI.COMM_WORLD ",taurex/mpi.py,"ReplaceText(target='1' @(16,15)->(16,16))","def nprocs(): try: from mpi4py import MPI except ImportError: return 0 comm = MPI.COMM_WORLD ","def nprocs(): try: from mpi4py import MPI except ImportError: return 1 comm = MPI.COMM_WORLD " 614,https://:@github.com/sjoerdk/yeahyeah.git,11a1a12a02c9fea724f0dc4072b5e86e688e33fd,"@@ -66,7 +66,7 @@ def add(context: ClockifyPluginContext, message, project, time): project_obj = None log_start = time - click.echo(f""Adding {message} at {as_local(log_start)} to project {project}"") + click.echo(f""Adding {message} at {as_local(log_start)} to project {project_obj}"") context.session.add_time_entry( start_time=time, description=message, project=project_obj ) ",plugins/clockify_plugin/cli.py,"ReplaceText(target='project_obj' @(69,71)->(69,78))","def add(context: ClockifyPluginContext, message, project, time): project_obj = None log_start = time click.echo(f""Adding {message} at {as_local(log_start)} to project {project}"") context.session.add_time_entry( start_time=time, description=message, project=project_obj )","def add(context: ClockifyPluginContext, message, project, time): project_obj = None log_start = time click.echo(f""Adding {message} at {as_local(log_start)} to project {project_obj}"") context.session.add_time_entry( start_time=time, description=message, project=project_obj )" 615,https://:@bitbucket.org/synerty/peek-plugin-graphdb.git,c47b1c7df8ba01b9a47a9afda0f1c1f829517990,"@@ -58,7 +58,7 @@ class PackedSegmentTupleProvider(TuplesProviderABC): # Create the new object foundDocuments.append(GraphDbPackedSegmentTuple( - key=key, + key=subKey, packedJson=segmentsByKey[subKey] )) ",peek_plugin_graphdb/_private/client/tuple_providers/PackedSegmentTupleProvider.py,"ReplaceText(target='subKey' @(61,24)->(61,27))","class PackedSegmentTupleProvider(TuplesProviderABC): # Create the new object foundDocuments.append(GraphDbPackedSegmentTuple( key=key, packedJson=segmentsByKey[subKey] )) ","class PackedSegmentTupleProvider(TuplesProviderABC): # Create the new object foundDocuments.append(GraphDbPackedSegmentTuple( key=subKey, packedJson=segmentsByKey[subKey] )) " 616,https://:@github.com/ihgazni2/ematmap.git,d6f160d8c7b85fdca2d552ca6de1c1c3c75b3245,"@@ -50,7 +50,7 @@ def get_matsize(m): size = 0 depth = len(m) for i in range(depth): - layer = m[depth] + layer = m[i] lngth = len(layer) for j in range(lngth): size = size + 1 ",ematmap/utils.py,"ReplaceText(target='i' @(53,18)->(53,23))","def get_matsize(m): size = 0 depth = len(m) for i in range(depth): layer = m[depth] lngth = len(layer) for j in range(lngth): size = size + 1","def get_matsize(m): size = 0 depth = len(m) for i in range(depth): layer = m[i] lngth = len(layer) for j in range(lngth): size = size + 1" 617,https://:@github.com/ndawe/goodruns.git,fa5a7a24b6ebaa80141a0fd5b887e61eeb60d0d0,"@@ -258,7 +258,7 @@ class GRL(object): version = root.find('NamedLumiRange/Version') if version is not None: self.version = version.text - self.metadata = root.findall('NamedLumiRange/Metadata') + self.metadata += root.findall('NamedLumiRange/Metadata') lbcols = root.findall( 'NamedLumiRange/LumiBlockCollection') for lbcol in lbcols: ",goodruns/grl.py,"ReplaceText(target='+=' @(261,22)->(261,23))","class GRL(object): version = root.find('NamedLumiRange/Version') if version is not None: self.version = version.text self.metadata = root.findall('NamedLumiRange/Metadata') lbcols = root.findall( 'NamedLumiRange/LumiBlockCollection') for lbcol in lbcols:","class GRL(object): version = root.find('NamedLumiRange/Version') if version is not None: self.version = version.text self.metadata += root.findall('NamedLumiRange/Metadata') lbcols = root.findall( 'NamedLumiRange/LumiBlockCollection') for lbcol in lbcols:" 618,https://:@github.com/churchill-lab/scBASE.git,456bacc4227fd3ccb5a901a205b0add65f9d8dfc,"@@ -37,7 +37,7 @@ except NameError: def select(loomfile, min_read_count, min_cell_count, layer): with loompy.connect(loomfile) as ds: - gsurv = (ds.sparse(layer=layer) >= min_read_count).sum(axis=1) > min_cell_count + gsurv = (ds.sparse(layer=layer) >= min_read_count).sum(axis=1) >= min_cell_count ds.ra.Selected = np.squeeze(np.asarray(gsurv)) LOG.info('Total %d genes selected' % gsurv.sum()) # totals = ds.map([np.sum], axis=1)[0] # Select based upon cell size? ",scbase/scbase.py,"ReplaceText(target='>=' @(40,71)->(40,72))","except NameError: def select(loomfile, min_read_count, min_cell_count, layer): with loompy.connect(loomfile) as ds: gsurv = (ds.sparse(layer=layer) >= min_read_count).sum(axis=1) > min_cell_count ds.ra.Selected = np.squeeze(np.asarray(gsurv)) LOG.info('Total %d genes selected' % gsurv.sum()) # totals = ds.map([np.sum], axis=1)[0] # Select based upon cell size?","except NameError: def select(loomfile, min_read_count, min_cell_count, layer): with loompy.connect(loomfile) as ds: gsurv = (ds.sparse(layer=layer) >= min_read_count).sum(axis=1) >= min_cell_count ds.ra.Selected = np.squeeze(np.asarray(gsurv)) LOG.info('Total %d genes selected' % gsurv.sum()) # totals = ds.map([np.sum], axis=1)[0] # Select based upon cell size?" 619,https://:@github.com/glottolog/treedb.git,af327b021d5aa5ee8c593903f663f5653181217d,"@@ -48,7 +48,7 @@ def iterrecords(bind=ENGINE, windowsize=WINDOWSIZE, skip_unknown=True): with bind.connect() as conn: select_files.bind = conn select_values.bind = conn - for in_slice in window_slices(File.id, size=windowsize, bind=bind): + for in_slice in window_slices(File.id, size=windowsize, bind=conn): if log.level <= logging.DEBUG: where = literal_compile(in_slice(File.id)) log.debug('fetch rows %r', where.string) ",treedb/raw/records.py,"ReplaceText(target='conn' @(51,69)->(51,73))","def iterrecords(bind=ENGINE, windowsize=WINDOWSIZE, skip_unknown=True): with bind.connect() as conn: select_files.bind = conn select_values.bind = conn for in_slice in window_slices(File.id, size=windowsize, bind=bind): if log.level <= logging.DEBUG: where = literal_compile(in_slice(File.id)) log.debug('fetch rows %r', where.string)","def iterrecords(bind=ENGINE, windowsize=WINDOWSIZE, skip_unknown=True): with bind.connect() as conn: select_files.bind = conn select_values.bind = conn for in_slice in window_slices(File.id, size=windowsize, bind=conn): if log.level <= logging.DEBUG: where = literal_compile(in_slice(File.id)) log.debug('fetch rows %r', where.string)" 620,https://:@github.com/funkybob/django-rated.git,4c68393abfdbb42030e0211c8c99ac8f2fa251d0,"@@ -14,7 +14,7 @@ class RatedMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): # Try to determine the realm for this view try: - realm = request._rated_realm + realm = view_func._rated_realm except AttributeError: try: realm = settings.REALM_MAP[request.resolver_match.url_name] ",rated/middleware.py,"ReplaceText(target='view_func' @(17,20)->(17,27))","class RatedMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): # Try to determine the realm for this view try: realm = request._rated_realm except AttributeError: try: realm = settings.REALM_MAP[request.resolver_match.url_name]","class RatedMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): # Try to determine the realm for this view try: realm = view_func._rated_realm except AttributeError: try: realm = settings.REALM_MAP[request.resolver_match.url_name]" 621,https://:@github.com/StevenGolovkine/FDApy.git,f1768ccf93593162be890f8685027b9d9a1d3ad2,"@@ -25,7 +25,7 @@ def _check_argvals(argvals): ------ argvals : list of numpy.ndarray """""" - if isinstance(argvals, (np.ndarray, list)): + if not isinstance(argvals, (np.ndarray, list)): raise ValueError( 'argvals has to be a list of numpy.ndarray or a numpy.ndarray!') # TODO: Modify the condition to accept multidimensional irregular ",FDApy/irregular_functional.py,"ReplaceText(target='not ' @(28,7)->(28,7))","def _check_argvals(argvals): ------ argvals : list of numpy.ndarray """""" if isinstance(argvals, (np.ndarray, list)): raise ValueError( 'argvals has to be a list of numpy.ndarray or a numpy.ndarray!') # TODO: Modify the condition to accept multidimensional irregular","def _check_argvals(argvals): ------ argvals : list of numpy.ndarray """""" if not isinstance(argvals, (np.ndarray, list)): raise ValueError( 'argvals has to be a list of numpy.ndarray or a numpy.ndarray!') # TODO: Modify the condition to accept multidimensional irregular" 622,https://:@github.com/StevenGolovkine/FDApy.git,f1768ccf93593162be890f8685027b9d9a1d3ad2,"@@ -30,7 +30,7 @@ def _check_argvals(argvals): ------ argvals : list of numpy.ndarray """""" - if isinstance(argvals, (np.ndarray, list)): + if not isinstance(argvals, (np.ndarray, list)): raise ValueError( 'argvals has to be a list of numpy.ndarray or a numpy.ndarray!') if isinstance(argvals, list) and \ ",FDApy/univariate_functional.py,"ReplaceText(target='not ' @(33,7)->(33,7))","def _check_argvals(argvals): ------ argvals : list of numpy.ndarray """""" if isinstance(argvals, (np.ndarray, list)): raise ValueError( 'argvals has to be a list of numpy.ndarray or a numpy.ndarray!') if isinstance(argvals, list) and \","def _check_argvals(argvals): ------ argvals : list of numpy.ndarray """""" if not isinstance(argvals, (np.ndarray, list)): raise ValueError( 'argvals has to be a list of numpy.ndarray or a numpy.ndarray!') if isinstance(argvals, list) and \" 623,https://:@github.com/StevenGolovkine/FDApy.git,4fbe69f439588f469d858b25c3d063e02b45ed97,"@@ -24,9 +24,9 @@ def _check_data(data): ------ data : list of UnivariateFunctionalData ot IrregularFunctionalData """""" - if isinstance(data, (list, - UnivariateFunctionalData, - IrregularFunctionalData)): + if not isinstance(data, (list, + UnivariateFunctionalData, + IrregularFunctionalData)): raise ValueError( """"""Data has to be a list or elements of UnivariateFunctionalData or IrregularFunctionalData!"""""") ",FDApy/multivariate_functional.py,"ReplaceText(target='not ' @(27,7)->(27,7))","def _check_data(data): ------ data : list of UnivariateFunctionalData ot IrregularFunctionalData """""" if isinstance(data, (list, UnivariateFunctionalData, IrregularFunctionalData)): raise ValueError( """"""Data has to be a list or elements of UnivariateFunctionalData or IrregularFunctionalData!"""""")","def _check_data(data): ------ data : list of UnivariateFunctionalData ot IrregularFunctionalData """""" if not isinstance(data, (list, UnivariateFunctionalData, IrregularFunctionalData)): raise ValueError( """"""Data has to be a list or elements of UnivariateFunctionalData or IrregularFunctionalData!"""""")" 624,https://:@github.com/StevenGolovkine/FDApy.git,a671e9da96d43a8cd21778b535374dce8942e7da,"@@ -1075,7 +1075,7 @@ class IrregularFunctionalData(FunctionalData): bandwidth=b, degree=degree) pred = lp.fit_predict(arg, val, points_estim) - smooth_argvals[i] = arg + smooth_argvals[i] = points_estim smooth_values[i] = pred return IrregularFunctionalData({'input_dim_0': smooth_argvals}, smooth_values) ",FDApy/representation/functional_data.py,"ReplaceText(target='points_estim' @(1078,32)->(1078,35))","class IrregularFunctionalData(FunctionalData): bandwidth=b, degree=degree) pred = lp.fit_predict(arg, val, points_estim) smooth_argvals[i] = arg smooth_values[i] = pred return IrregularFunctionalData({'input_dim_0': smooth_argvals}, smooth_values)","class IrregularFunctionalData(FunctionalData): bandwidth=b, degree=degree) pred = lp.fit_predict(arg, val, points_estim) smooth_argvals[i] = points_estim smooth_values[i] = pred return IrregularFunctionalData({'input_dim_0': smooth_argvals}, smooth_values)" 625,https://:@github.com/Flowminder/pytest-airflow.git,47c128f0affa875e4baed2f7223fcd0747f3bb55,"@@ -138,7 +138,7 @@ def _task_gen(item, **kwds): provide_context=True, dag=dag, ) - dag.set_dependency(task_id, ""__pytest_branch"") + dag.set_dependency(""__pytest_branch"", task_id) return task ",pytest_airflow/plugin.py,"ArgSwap(idxs=0<->1 @(141,4)->(141,22))","def _task_gen(item, **kwds): provide_context=True, dag=dag, ) dag.set_dependency(task_id, ""__pytest_branch"") return task ","def _task_gen(item, **kwds): provide_context=True, dag=dag, ) dag.set_dependency(""__pytest_branch"", task_id) return task " 626,https://:@github.com/datadrivencontrol/pyvrft.git,d21df29ac62c08e4de3bfbcc1c01a6943cfe78fe,"@@ -77,7 +77,7 @@ def design(u,y,y_iv,Td,C,L): y_iv=y_iv[0:N,:] # virtual error ebar=rv-y - ebar_iv=rv-y_iv + ebar_iv=rv_iv-y_iv # remove the last samples of the input (to match the dimension of the virtual error) uf=uf[0:N,:] ",vrft/control.py,"ReplaceText(target='rv_iv' @(80,16)->(80,18))","def design(u,y,y_iv,Td,C,L): y_iv=y_iv[0:N,:] # virtual error ebar=rv-y ebar_iv=rv-y_iv # remove the last samples of the input (to match the dimension of the virtual error) uf=uf[0:N,:] ","def design(u,y,y_iv,Td,C,L): y_iv=y_iv[0:N,:] # virtual error ebar=rv-y ebar_iv=rv_iv-y_iv # remove the last samples of the input (to match the dimension of the virtual error) uf=uf[0:N,:] " 627,https://:@github.com/onecommons/unfurl.git,c7b04c15dc919919696f6d20fef4465c25fda6d3,"@@ -67,7 +67,7 @@ class Resource(object): @property def root(self): - return self.ancestors[0] + return self.ancestors[-1] def __getitem__(self, name): if not name: ",giterop/resource.py,"ReplaceText(target='-1' @(70,26)->(70,27))","class Resource(object): @property def root(self): return self.ancestors[0] def __getitem__(self, name): if not name:","class Resource(object): @property def root(self): return self.ancestors[-1] def __getitem__(self, name): if not name:" 628,https://:@github.com/onecommons/unfurl.git,7b9fe40414b2646ba7ee98e1f7ab770feed1c80a,"@@ -336,7 +336,7 @@ Returns: if not configSpec: raise UnfurlError( 'unable to find an implementation to ""%s"" ""%s"" on """"%s"": %s' - % (action, resource.template.name, resource.template.name, reason) + % (action, resource.template.name, resource.template.name, notfoundmsg) ) logger.debug( ""creating configuration %s with %s to run for %s: %s"", ",unfurl/plan.py,"ReplaceText(target='notfoundmsg' @(339,75)->(339,81))","Returns: if not configSpec: raise UnfurlError( 'unable to find an implementation to ""%s"" ""%s"" on """"%s"": %s' % (action, resource.template.name, resource.template.name, reason) ) logger.debug( ""creating configuration %s with %s to run for %s: %s"",","Returns: if not configSpec: raise UnfurlError( 'unable to find an implementation to ""%s"" ""%s"" on """"%s"": %s' % (action, resource.template.name, resource.template.name, notfoundmsg) ) logger.debug( ""creating configuration %s with %s to run for %s: %s""," 629,https://:@github.com/heartexlabs/label-studio-evalme.git,9b7f13ab32802d5ef602d1c4f9399e949b9f3df8,"@@ -35,7 +35,7 @@ class HTMLTagsEvalItem(EvalItem): def _as_html_tags_eval_item(item): - if not isinstance(HTMLTagsEvalItem, item): + if not isinstance(item, HTMLTagsEvalItem): return HTMLTagsEvalItem(item) return item ",evalme/text/text.py,"ArgSwap(idxs=0<->1 @(38,11)->(38,21))","class HTMLTagsEvalItem(EvalItem): def _as_html_tags_eval_item(item): if not isinstance(HTMLTagsEvalItem, item): return HTMLTagsEvalItem(item) return item ","class HTMLTagsEvalItem(EvalItem): def _as_html_tags_eval_item(item): if not isinstance(item, HTMLTagsEvalItem): return HTMLTagsEvalItem(item) return item " 630,https://:@github.com/parlance/ctcdecode.git,1a35bb5fc07eee0c9939fdf824fa8158ec52499a,"@@ -20,7 +20,7 @@ class CTCBeamDecoder(object): def decode(self, probs, seq_lens): # We expect batch x seq x label_size probs = probs.cpu().float() - seq_lens = probs.cpu().int() + seq_lens = seq_lens.cpu().int() batch_size, max_seq_len = probs.size(0), probs.size(1) output = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int() timesteps = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int() ",ctcdecode/__init__.py,"ReplaceText(target='seq_lens' @(23,19)->(23,24))","class CTCBeamDecoder(object): def decode(self, probs, seq_lens): # We expect batch x seq x label_size probs = probs.cpu().float() seq_lens = probs.cpu().int() batch_size, max_seq_len = probs.size(0), probs.size(1) output = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int() timesteps = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int()","class CTCBeamDecoder(object): def decode(self, probs, seq_lens): # We expect batch x seq x label_size probs = probs.cpu().float() seq_lens = seq_lens.cpu().int() batch_size, max_seq_len = probs.size(0), probs.size(1) output = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int() timesteps = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int()" 631,https://:@github.com/benmaier/binpacking.git,6ada2c62c319d56cd0f5918a2f01ff61d0e45348,"@@ -107,7 +107,7 @@ def to_constant_bin_number(d,N_bin,weight_pos=None,lower_bound=None,upper_bound= while not found_bin: #if this weight fits in the bin - if new_weight_sum < V_bin_max: + if new_weight_sum <= V_bin_max: #...put it in if isdict: ",binpacking/to_constant_bin_number.py,"ReplaceText(target='<=' @(110,30)->(110,31))","def to_constant_bin_number(d,N_bin,weight_pos=None,lower_bound=None,upper_bound= while not found_bin: #if this weight fits in the bin if new_weight_sum < V_bin_max: #...put it in if isdict:","def to_constant_bin_number(d,N_bin,weight_pos=None,lower_bound=None,upper_bound= while not found_bin: #if this weight fits in the bin if new_weight_sum <= V_bin_max: #...put it in if isdict:" 632,https://:@github.com/amatino-code/nozomi.git,dc608f09a68fc8972f563e2b9974692581d40efc,"@@ -257,7 +257,7 @@ integers'.format( min_value=min_value )) - return values + return validated def optionally_parse_bool( self, ",nozomi/http/parseable_data.py,"ReplaceText(target='validated' @(260,15)->(260,21))","integers'.format( min_value=min_value )) return values def optionally_parse_bool( self,","integers'.format( min_value=min_value )) return validated def optionally_parse_bool( self," 633,https://:@github.com/amatino-code/nozomi.git,b486a1109ac83dcabb4022d071644cadc4734769,"@@ -70,7 +70,7 @@ class Resource: if not candidate.grants_read_to(unauthorised_agent): raise NotAuthorised continue - return broadcast_candidate + return unauthorised_agent if not broadcast_candidate.grants_read_to(unauthorised_agent): raise NotAuthorised ",nozomi/resources/resource.py,"ReplaceText(target='unauthorised_agent' @(73,19)->(73,38))","class Resource: if not candidate.grants_read_to(unauthorised_agent): raise NotAuthorised continue return broadcast_candidate if not broadcast_candidate.grants_read_to(unauthorised_agent): raise NotAuthorised","class Resource: if not candidate.grants_read_to(unauthorised_agent): raise NotAuthorised continue return unauthorised_agent if not broadcast_candidate.grants_read_to(unauthorised_agent): raise NotAuthorised" 634,https://:@github.com/Puumanamana/CoCoNet.git,5e966cbf19199b62e265f1320a5e60a0cdb2e26e,"@@ -54,7 +54,7 @@ def make_positive_pairs(label, frag_steps, contig_frags, fppc, encoding_len=128) if k < fppc: # print(""WARNING: cannot make {} unique pairs with genome of {} fragments"".format(fppc, contig_frags), end='\r') pairs.sp = np.tile(label, [fppc, 2]) - pairs.start = np.random.choice(frag_steps, [fppc, 2]) + pairs.start = np.random.choice(contig_frags, [fppc, 2]) pairs.end = pairs.start + frag_steps return pairs ",coconet/fragmentation.py,"ReplaceText(target='contig_frags' @(57,39)->(57,49))","def make_positive_pairs(label, frag_steps, contig_frags, fppc, encoding_len=128) if k < fppc: # print(""WARNING: cannot make {} unique pairs with genome of {} fragments"".format(fppc, contig_frags), end='\r') pairs.sp = np.tile(label, [fppc, 2]) pairs.start = np.random.choice(frag_steps, [fppc, 2]) pairs.end = pairs.start + frag_steps return pairs","def make_positive_pairs(label, frag_steps, contig_frags, fppc, encoding_len=128) if k < fppc: # print(""WARNING: cannot make {} unique pairs with genome of {} fragments"".format(fppc, contig_frags), end='\r') pairs.sp = np.tile(label, [fppc, 2]) pairs.start = np.random.choice(contig_frags, [fppc, 2]) pairs.end = pairs.start + frag_steps return pairs" 635,https://:@github.com/struts2spring/sql-editor.git,92d594a22fc8cf532f18a445961615037bfa2685,"@@ -305,7 +305,7 @@ class FileBrowser(FileTree): fileName=os.path.split(path)[-1] - stc.SetText(FileOperations().readFile(filePath=fname)) + stc.SetText(FileOperations().readFile(filePath=path)) centerPaneTab.window.addTab(name='openFileLoad'+fileName, worksheetPanel=stc) # win = wx.GetApp().GetActiveWindow() ",src/view/views/file/explorer/FileBrowserPanel.py,"ReplaceText(target='path' @(308,67)->(308,72))","class FileBrowser(FileTree): fileName=os.path.split(path)[-1] stc.SetText(FileOperations().readFile(filePath=fname)) centerPaneTab.window.addTab(name='openFileLoad'+fileName, worksheetPanel=stc) # win = wx.GetApp().GetActiveWindow()","class FileBrowser(FileTree): fileName=os.path.split(path)[-1] stc.SetText(FileOperations().readFile(filePath=path)) centerPaneTab.window.addTab(name='openFileLoad'+fileName, worksheetPanel=stc) # win = wx.GetApp().GetActiveWindow()" 636,https://:@github.com/struts2spring/sql-editor.git,3b18738cabd125bf7e4faeb0170edcc888f22c0b,"@@ -2306,7 +2306,7 @@ class ScrolledThumbnail(wx.ScrolledWindow): logger.error(e, exc_info=True) logger.error('selectedBookIndex: %s, len: %s', selectedBookIndex, len(self._items)) # logger.debug(.0deleteBooks) - if len(deleteBooks) > 0: + if len(deleteBooks) >= 0: self.updateStatusBar(text=f'{len(deleteBooks)} books deleted') self.GetParent().GetParent().loadingBook() self.GetParent().GetParent().updatePangnation() ",src/view/views/calibre/book/browser/BookThumbCrtl.py,"ReplaceText(target='>=' @(2309,28)->(2309,29))","class ScrolledThumbnail(wx.ScrolledWindow): logger.error(e, exc_info=True) logger.error('selectedBookIndex: %s, len: %s', selectedBookIndex, len(self._items)) # logger.debug(.0deleteBooks) if len(deleteBooks) > 0: self.updateStatusBar(text=f'{len(deleteBooks)} books deleted') self.GetParent().GetParent().loadingBook() self.GetParent().GetParent().updatePangnation()","class ScrolledThumbnail(wx.ScrolledWindow): logger.error(e, exc_info=True) logger.error('selectedBookIndex: %s, len: %s', selectedBookIndex, len(self._items)) # logger.debug(.0deleteBooks) if len(deleteBooks) >= 0: self.updateStatusBar(text=f'{len(deleteBooks)} books deleted') self.GetParent().GetParent().loadingBook() self.GetParent().GetParent().updatePangnation()" 637,https://:@github.com/khaledghobashy/uraeus.git,d0011bf8d00b0212dd67ce4cd64b21719fbed709,"@@ -186,7 +186,7 @@ class internal_force(generic_force): defflection = self.LF - distance velocity = unit_vector.T*self.joint.dijd - self.Fi = unit_vector*(self.Fs(defflection) + self.Fd(velocity)) + self.Fi = unit_vector*(self.Fs(defflection) - self.Fd(velocity)) Ti_e = 2*G(self.Pi).T*(self.Ti + Skew(self.ui).T*self.Fi) force_vector = sm.BlockMatrix([[self.Fi], [Ti_e]]) ",source/symbolic_classes/forces.py,"ReplaceText(target='-' @(189,52)->(189,53))","class internal_force(generic_force): defflection = self.LF - distance velocity = unit_vector.T*self.joint.dijd self.Fi = unit_vector*(self.Fs(defflection) + self.Fd(velocity)) Ti_e = 2*G(self.Pi).T*(self.Ti + Skew(self.ui).T*self.Fi) force_vector = sm.BlockMatrix([[self.Fi], [Ti_e]])","class internal_force(generic_force): defflection = self.LF - distance velocity = unit_vector.T*self.joint.dijd self.Fi = unit_vector*(self.Fs(defflection) - self.Fd(velocity)) Ti_e = 2*G(self.Pi).T*(self.Ti + Skew(self.ui).T*self.Fi) force_vector = sm.BlockMatrix([[self.Fi], [Ti_e]])" 638,https://:@github.com/naglis/odd-bunch.git,6e9e55c327eaa6bccd5a54a1da850db418fa3a3a,"@@ -74,7 +74,7 @@ class FieldAttrStringRedundant(Plugin): f'for field ""{field.name}"". The same value will be computed ' f""by Odoo automatically."", addon, - locations=[Location(path, [column_index_1(string_kwarg.start_pos)])], + locations=[Location(path, [column_index_1(field.start_pos)])], confidence=Confidence.LOW, categories=[""redundancy""], sources=sources, ",odd_bunch/plugin/field_attr_string_redundant.py,"ReplaceText(target='field' @(77,58)->(77,70))","class FieldAttrStringRedundant(Plugin): f'for field ""{field.name}"". The same value will be computed ' f""by Odoo automatically."", addon, locations=[Location(path, [column_index_1(string_kwarg.start_pos)])], confidence=Confidence.LOW, categories=[""redundancy""], sources=sources,","class FieldAttrStringRedundant(Plugin): f'for field ""{field.name}"". The same value will be computed ' f""by Odoo automatically."", addon, locations=[Location(path, [column_index_1(field.start_pos)])], confidence=Confidence.LOW, categories=[""redundancy""], sources=sources," 639,https://:@github.com/naglis/odd-bunch.git,6e9e55c327eaa6bccd5a54a1da850db418fa3a3a,"@@ -23,7 +23,7 @@ class TrackVisibilityAlways(Plugin): ""deprecated since version 12.0"", addon, locations=[ - Location(field.model.path, [column_index_1(kwarg.start_pos)]) + Location(field.model.path, [column_index_1(field.start_pos)]) ], categories=[""deprecated""], sources=[ ",odd_bunch/plugin/track_visibility_always.py,"ReplaceText(target='field' @(26,67)->(26,72))","class TrackVisibilityAlways(Plugin): ""deprecated since version 12.0"", addon, locations=[ Location(field.model.path, [column_index_1(kwarg.start_pos)]) ], categories=[""deprecated""], sources=[","class TrackVisibilityAlways(Plugin): ""deprecated since version 12.0"", addon, locations=[ Location(field.model.path, [column_index_1(field.start_pos)]) ], categories=[""deprecated""], sources=[" 640,https://:@github.com/haipdev/config.git,c81fb07972b62e9c51d47b7306ad0cb39b90025d,"@@ -115,7 +115,7 @@ def get(*paths, **options): elif value is not MANDATORY: result[key] = value else: - path = '/'.join(path) + path = '/'.join(paths) raise HaipConfigException(f'option ""{key}"" not found in section ""{path}""') return result ",haip/config.py,"ReplaceText(target='paths' @(118,28)->(118,32))","def get(*paths, **options): elif value is not MANDATORY: result[key] = value else: path = '/'.join(path) raise HaipConfigException(f'option ""{key}"" not found in section ""{path}""') return result ","def get(*paths, **options): elif value is not MANDATORY: result[key] = value else: path = '/'.join(paths) raise HaipConfigException(f'option ""{key}"" not found in section ""{path}""') return result " 641,https://:@github.com/woblers/rightmove_webscraper.py.git,75bc8dc28e5a998582ddf86ae43a3160b5729a90,"@@ -37,7 +37,7 @@ class rightmove_data(object): There are 24 results on each results page, but note that the rightmove website limits results pages to a maximum of 42 pages."""""" - page_count = self.results_count() / 24 + page_count = self.results_count() // 24 if self.results_count() % 24 > 0: page_count += 1 ",rightmove_webscraper.py,"ReplaceText(target='//' @(40,42)->(40,43))","class rightmove_data(object): There are 24 results on each results page, but note that the rightmove website limits results pages to a maximum of 42 pages."""""" page_count = self.results_count() / 24 if self.results_count() % 24 > 0: page_count += 1 ","class rightmove_data(object): There are 24 results on each results page, but note that the rightmove website limits results pages to a maximum of 42 pages."""""" page_count = self.results_count() // 24 if self.results_count() % 24 > 0: page_count += 1 " 642,https://:@github.com/DomBennett/MassPhylogenyEstimation.git,e72cb1554f059c77b45c8c74af96bd0b2fb140b9,"@@ -39,7 +39,7 @@ with open(os.path.join(working_dir, ""data"", ""test_alignment.p""), # MOCK def dummy_blast(query, subj, minoverlap): # should return bools and positions - bools = [True for e in subj] + bools = [True for e in query] positions = [0 for e in subj] max_positions = [len(e) for e in subj] positions.extend(max_positions) ",tests/test_tools_alignment.py,"ReplaceText(target='query' @(42,27)->(42,31))","with open(os.path.join(working_dir, ""data"", ""test_alignment.p""), # MOCK def dummy_blast(query, subj, minoverlap): # should return bools and positions bools = [True for e in subj] positions = [0 for e in subj] max_positions = [len(e) for e in subj] positions.extend(max_positions)","with open(os.path.join(working_dir, ""data"", ""test_alignment.p""), # MOCK def dummy_blast(query, subj, minoverlap): # should return bools and positions bools = [True for e in query] positions = [0 for e in subj] max_positions = [len(e) for e in subj] positions.extend(max_positions)" 643,https://:@github.com/DomBennett/MassPhylogenyEstimation.git,832e9df9733c4e266c0583d4e1a329b5f72d4f4c,"@@ -159,7 +159,7 @@ class Stager(object): @classmethod def run_all(klass, wd, stages): for s in stages: - if check(stage=s, directory=wd): + if not check(stage=s, directory=wd): Stager(wd, s).run() ",pglt/tools/system_tools.py,"ReplaceText(target='not ' @(162,15)->(162,15))","class Stager(object): @classmethod def run_all(klass, wd, stages): for s in stages: if check(stage=s, directory=wd): Stager(wd, s).run() ","class Stager(object): @classmethod def run_all(klass, wd, stages): for s in stages: if not check(stage=s, directory=wd): Stager(wd, s).run() " 644,https://:@bitbucket.org/bowaggonerpublic/bomail.git,383fe87f4b5a54ce110d33850ce10f19e088a001,"@@ -62,7 +62,7 @@ def main(): exit(0) if sys.argv[1] == ""help"": - if len(sys.argv) < 2: + if len(sys.argv) <= 2: print(usage_str) elif sys.argv[2] == ""datestr"": print(bomail.util.datestr.datestr_str) ",bomail/bomail.py,"ReplaceText(target='<=' @(65,21)->(65,22))","def main(): exit(0) if sys.argv[1] == ""help"": if len(sys.argv) < 2: print(usage_str) elif sys.argv[2] == ""datestr"": print(bomail.util.datestr.datestr_str)","def main(): exit(0) if sys.argv[1] == ""help"": if len(sys.argv) <= 2: print(usage_str) elif sys.argv[2] == ""datestr"": print(bomail.util.datestr.datestr_str)" 645,https://:@bitbucket.org/bowaggonerpublic/bomail.git,6769b3f3dc022b9674b2f26d2ff842f74703da7e,"@@ -73,7 +73,7 @@ class TabNoThread: new_fileset = set(new_filenames) self.remove_files([t[0] for t in self.file_data if t[0] not in new_fileset], old_disp_info) # assume, worst-case, that all matching files have changed/added - self.update_for_change(new_fileset, old_disp_info) + self.update_for_change(new_filenames, old_disp_info) # lazily load display data and return disp_data, is_unread, is_marked ",bomail/guistuff/tabnothread.py,"ReplaceText(target='new_filenames' @(76,27)->(76,38))","class TabNoThread: new_fileset = set(new_filenames) self.remove_files([t[0] for t in self.file_data if t[0] not in new_fileset], old_disp_info) # assume, worst-case, that all matching files have changed/added self.update_for_change(new_fileset, old_disp_info) # lazily load display data and return disp_data, is_unread, is_marked","class TabNoThread: new_fileset = set(new_filenames) self.remove_files([t[0] for t in self.file_data if t[0] not in new_fileset], old_disp_info) # assume, worst-case, that all matching files have changed/added self.update_for_change(new_filenames, old_disp_info) # lazily load display data and return disp_data, is_unread, is_marked" 646,https://:@github.com/GainCompliance/gain-requests-futures.git,2779819b9b7554d787280d5889878237ba1937b5,"@@ -69,7 +69,7 @@ class FuturesSession(Session): func = super(FuturesSession, self).send if isinstance(self.executor, ProcessPoolExecutor): try: - dumps(request) + dumps(func) except (TypeError, PickleError): raise RuntimeError(PICKLE_ERROR) return self.executor.submit(func, request, **kwargs) ",requests_futures/sessions.py,"ReplaceText(target='func' @(72,22)->(72,29))","class FuturesSession(Session): func = super(FuturesSession, self).send if isinstance(self.executor, ProcessPoolExecutor): try: dumps(request) except (TypeError, PickleError): raise RuntimeError(PICKLE_ERROR) return self.executor.submit(func, request, **kwargs)","class FuturesSession(Session): func = super(FuturesSession, self).send if isinstance(self.executor, ProcessPoolExecutor): try: dumps(func) except (TypeError, PickleError): raise RuntimeError(PICKLE_ERROR) return self.executor.submit(func, request, **kwargs)" 647,https://:@github.com/praekelt/casepropods.family_connect_subscription.git,9f04ceacb29a64763e11de6c8fd3008faf9eddb2,"@@ -95,7 +95,7 @@ class SubscriptionPod(Pod): 'subscription_ids': active_sub_ids } }) - if len(active_sub_ids) > 0: + if len(active_sub_ids) > 1: actions.append(self.get_cancel_action(active_sub_ids)) content['actions'] = actions ",casepropods/family_connect_subscription/plugin.py,"ReplaceText(target='1' @(98,33)->(98,34))","class SubscriptionPod(Pod): 'subscription_ids': active_sub_ids } }) if len(active_sub_ids) > 0: actions.append(self.get_cancel_action(active_sub_ids)) content['actions'] = actions","class SubscriptionPod(Pod): 'subscription_ids': active_sub_ids } }) if len(active_sub_ids) > 1: actions.append(self.get_cancel_action(active_sub_ids)) content['actions'] = actions" 648,https://:@github.com/fmilthaler/FinQuant.git,075430f74799040aa1d46c722e16a52a82637c63,"@@ -783,7 +783,7 @@ def _yfinance_request(names, start_date=None, end_date=None): try: import datetime if isinstance(start_date, str): - start_date = datetime.datetime.strptime(end_date, ""%Y-%m-%d"") + start_date = datetime.datetime.strptime(start_date, ""%Y-%m-%d"") if isinstance(end_date, str): end_date = datetime.datetime.strptime(end_date, ""%Y-%m-%d"") except ImportError: ",finquant/portfolio.py,"ReplaceText(target='start_date' @(786,52)->(786,60))","def _yfinance_request(names, start_date=None, end_date=None): try: import datetime if isinstance(start_date, str): start_date = datetime.datetime.strptime(end_date, ""%Y-%m-%d"") if isinstance(end_date, str): end_date = datetime.datetime.strptime(end_date, ""%Y-%m-%d"") except ImportError:","def _yfinance_request(names, start_date=None, end_date=None): try: import datetime if isinstance(start_date, str): start_date = datetime.datetime.strptime(start_date, ""%Y-%m-%d"") if isinstance(end_date, str): end_date = datetime.datetime.strptime(end_date, ""%Y-%m-%d"") except ImportError:" 649,https://:@github.com/MrTango/click.git,a6af25df9c2e82e94c3aa15d579f9347881e5efb,"@@ -1173,7 +1173,7 @@ class Argument(Parameter): if attrs.get('default') is not None: required = False else: - required = attrs.get('nargs', 0) > 0 + required = attrs.get('nargs', 1) > 0 Parameter.__init__(self, param_decls, required=required, **attrs) def make_metavar(self): ",click/core.py,"ReplaceText(target='1' @(1176,46)->(1176,47))","class Argument(Parameter): if attrs.get('default') is not None: required = False else: required = attrs.get('nargs', 0) > 0 Parameter.__init__(self, param_decls, required=required, **attrs) def make_metavar(self):","class Argument(Parameter): if attrs.get('default') is not None: required = False else: required = attrs.get('nargs', 1) > 0 Parameter.__init__(self, param_decls, required=required, **attrs) def make_metavar(self):" 650,https://:@github.com/MrTango/click.git,336e5e08acf98a4033e5aa4c6fcef118d4f469ec,"@@ -224,7 +224,7 @@ def version_option(version=None, *param_decls, **attrs): message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): - if value or ctx.resilient_parsing: + if not value or ctx.resilient_parsing: return prog = prog_name if prog is None: ",click/decorators.py,"ReplaceText(target='not ' @(227,15)->(227,15))","def version_option(version=None, *param_decls, **attrs): message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if value or ctx.resilient_parsing: return prog = prog_name if prog is None:","def version_option(version=None, *param_decls, **attrs): message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if not value or ctx.resilient_parsing: return prog = prog_name if prog is None:" 651,https://:@github.com/MrTango/click.git,598c6d76fbc036fb3219d9f09948a682cda66601,"@@ -213,7 +213,7 @@ class CliRunner(object): old_env = {} try: for key, value in iteritems(env): - old_env[key] = os.environ.get(value) + old_env[key] = os.environ.get(key) if value is None: try: del os.environ[key] ",click/testing.py,"ReplaceText(target='key' @(216,46)->(216,51))","class CliRunner(object): old_env = {} try: for key, value in iteritems(env): old_env[key] = os.environ.get(value) if value is None: try: del os.environ[key]","class CliRunner(object): old_env = {} try: for key, value in iteritems(env): old_env[key] = os.environ.get(key) if value is None: try: del os.environ[key]" 652,https://:@github.com/epeios-q37/atlas-python.git,c310fd7273b7ec139c0eca6be43506cb611d5bfc,"@@ -69,7 +69,7 @@ class Chatroom: def displayMessages(this, dom): global messages - if len(messages) >= this.lastMessage: + if len(messages) > this.lastMessage: id = dom.createElement(""span"") dom.setLayoutXSL(id, this.buildXML(), ""Messages.xsl"") dom.insertChild(id, ""Board"") ",Chatroom/main.py,"ReplaceText(target='>' @(72,19)->(72,21))","class Chatroom: def displayMessages(this, dom): global messages if len(messages) >= this.lastMessage: id = dom.createElement(""span"") dom.setLayoutXSL(id, this.buildXML(), ""Messages.xsl"") dom.insertChild(id, ""Board"")","class Chatroom: def displayMessages(this, dom): global messages if len(messages) > this.lastMessage: id = dom.createElement(""span"") dom.setLayoutXSL(id, this.buildXML(), ""Messages.xsl"") dom.insertChild(id, ""Board"")" 653,https://:@github.com/herrersystem/apize.git,3f4ce76b32fdc1cddc66cde54f0d7552b2ab2101,"@@ -15,7 +15,7 @@ def send_request(url, method, """""" ## Parse url args for p in args: - url = url.replace(':'+p, str(params[p])) + url = url.replace(':' + p, str(args[p])) try: if data: ",apize/decorators.py,"ReplaceText(target='args' @(18,31)->(18,37))","def send_request(url, method, """""" ## Parse url args for p in args: url = url.replace(':'+p, str(params[p])) try: if data:","def send_request(url, method, """""" ## Parse url args for p in args: url = url.replace(':' + p, str(args[p])) try: if data:" 654,https://:@github.com/silvacms/silva.core.services.git,a674128c54bb10f2abdda32808285fabc985e363,"@@ -39,7 +39,7 @@ class SecretService(SilvaService): assert len(args) > 1, u'Too few arguments' challenge = hmac.new(self.__key, str(args[0]), hashlib.sha1) for arg in args[1:]: - challenge.update(str(args)) + challenge.update(str(arg)) return challenge.hexdigest() InitializeClass(SecretService) ",src/silva/core/services/secret.py,"ReplaceText(target='arg' @(42,33)->(42,37))","class SecretService(SilvaService): assert len(args) > 1, u'Too few arguments' challenge = hmac.new(self.__key, str(args[0]), hashlib.sha1) for arg in args[1:]: challenge.update(str(args)) return challenge.hexdigest() InitializeClass(SecretService)","class SecretService(SilvaService): assert len(args) > 1, u'Too few arguments' challenge = hmac.new(self.__key, str(args[0]), hashlib.sha1) for arg in args[1:]: challenge.update(str(arg)) return challenge.hexdigest() InitializeClass(SecretService)" 655,https://:@github.com/SatelliteApplicationsCatapult/sedas_pyapi.git,db1d3308de5180dd9a26e8bc73b82c97d2f07507,"@@ -225,7 +225,7 @@ class SeDASAPI: req = Request(url, headers=self.headers) try: decoded = json.load(urlopen(req)) - if len(decoded) > 1 and 'downloadUrl' in decoded[0]: + if len(decoded) >= 1 and 'downloadUrl' in decoded[0]: return decoded[0]['downloadUrl'] return None except HTTPError as e: ",getthestuff/sedas_api.py,"ReplaceText(target='>=' @(228,28)->(228,29))","class SeDASAPI: req = Request(url, headers=self.headers) try: decoded = json.load(urlopen(req)) if len(decoded) > 1 and 'downloadUrl' in decoded[0]: return decoded[0]['downloadUrl'] return None except HTTPError as e:","class SeDASAPI: req = Request(url, headers=self.headers) try: decoded = json.load(urlopen(req)) if len(decoded) >= 1 and 'downloadUrl' in decoded[0]: return decoded[0]['downloadUrl'] return None except HTTPError as e:" 656,https://:@github.com/gigaquads/pybiz.git,9431e28a54c7a64f4fabcd861239a9651a75dde5,"@@ -91,7 +91,7 @@ class YamlDao(Dao): cur_data = self.fetch(_id) new_data = DictUtils.merge(cur_data, data) Yaml.to_file(file_path=file_path, data=new_data) - return data + return new_data def delete(self, _id) -> None: """""" ",pybiz/dao/yaml_dao.py,"ReplaceText(target='new_data' @(94,15)->(94,19))","class YamlDao(Dao): cur_data = self.fetch(_id) new_data = DictUtils.merge(cur_data, data) Yaml.to_file(file_path=file_path, data=new_data) return data def delete(self, _id) -> None: """"""","class YamlDao(Dao): cur_data = self.fetch(_id) new_data = DictUtils.merge(cur_data, data) Yaml.to_file(file_path=file_path, data=new_data) return new_data def delete(self, _id) -> None: """"""" 657,https://:@github.com/gigaquads/pybiz.git,cc4bc8499bdffbf4bef4704afb722fa55c7ccc1d,"@@ -790,7 +790,7 @@ class BizObject( related_bizobj_list.append(obj) else: related_bizobj_list.append( - rel.target(related_data) + rel.target(obj) ) self._related_bizobjs[rel.name] = related_bizobj_list ",pybiz/biz.py,"ReplaceText(target='obj' @(793,39)->(793,51))","class BizObject( related_bizobj_list.append(obj) else: related_bizobj_list.append( rel.target(related_data) ) self._related_bizobjs[rel.name] = related_bizobj_list","class BizObject( related_bizobj_list.append(obj) else: related_bizobj_list.append( rel.target(obj) ) self._related_bizobjs[rel.name] = related_bizobj_list" 658,https://:@github.com/gigaquads/pybiz.git,4bfdaf78df6eec9213f65df0656d346cfd4a45f2,"@@ -79,6 +79,6 @@ class BreadthFirstSaver(Saver): v_type = v.__class__ if v._id is None: to_create[v_type].append(v) - elif x.dirty: + elif v.dirty: to_update[v_type].append(x) self._aggregate_related(v, to_create, to_update) ",pybiz/biz/internal/save.py,"ReplaceText(target='v' @(82,21)->(82,22))","class BreadthFirstSaver(Saver): v_type = v.__class__ if v._id is None: to_create[v_type].append(v) elif x.dirty: to_update[v_type].append(x) self._aggregate_related(v, to_create, to_update)","class BreadthFirstSaver(Saver): v_type = v.__class__ if v._id is None: to_create[v_type].append(v) elif v.dirty: to_update[v_type].append(x) self._aggregate_related(v, to_create, to_update)" 659,https://:@github.com/gigaquads/pybiz.git,9ccaa42fdf4677090e93c27b2326c5d935d568f9,"@@ -80,5 +80,5 @@ class BreadthFirstSaver(Saver): if v._id is None: to_create[v_type].append(v) elif v.dirty: - to_update[v_type].append(x) + to_update[v_type].append(v) self._aggregate_related(v, to_create, to_update) ",pybiz/biz/internal/save.py,"ReplaceText(target='v' @(83,45)->(83,46))","class BreadthFirstSaver(Saver): if v._id is None: to_create[v_type].append(v) elif v.dirty: to_update[v_type].append(x) self._aggregate_related(v, to_create, to_update)","class BreadthFirstSaver(Saver): if v._id is None: to_create[v_type].append(v) elif v.dirty: to_update[v_type].append(v) self._aggregate_related(v, to_create, to_update)" 660,https://:@github.com/gigaquads/pybiz.git,c042a85234732c1ff96c0240b378595d24631fbe,"@@ -116,7 +116,7 @@ class CompositeGuard(Guard): if rhs_exc is not None and lhs_exc is not None: return CompositeGuardException(lhs_exc, rhs_exc) elif self._op == OP_CODE.NOT: - if lhs_exc is not None: + if lhs_exc is None: return lhs_exc else: return ValueError(f'op not recognized, ""{self._op}""') ",pybiz/api/middleware/guard_middleware/guard.py,"ReplaceText(target=' is ' @(119,22)->(119,30))","class CompositeGuard(Guard): if rhs_exc is not None and lhs_exc is not None: return CompositeGuardException(lhs_exc, rhs_exc) elif self._op == OP_CODE.NOT: if lhs_exc is not None: return lhs_exc else: return ValueError(f'op not recognized, ""{self._op}""')","class CompositeGuard(Guard): if rhs_exc is not None and lhs_exc is not None: return CompositeGuardException(lhs_exc, rhs_exc) elif self._op == OP_CODE.NOT: if lhs_exc is None: return lhs_exc else: return ValueError(f'op not recognized, ""{self._op}""')" 661,https://:@github.com/gigaquads/pybiz.git,30e14e8c946edb447a76ea243a271c6a03895def,"@@ -43,7 +43,7 @@ class ActionDecorator(object): else: func = obj action = self.setup_action(func, False) - return action + return func def setup_action(self, func, overwrite): action = self.app.action_type(func, self) ",ravel/app/base/action_decorator.py,"ReplaceText(target='func' @(46,19)->(46,25))","class ActionDecorator(object): else: func = obj action = self.setup_action(func, False) return action def setup_action(self, func, overwrite): action = self.app.action_type(func, self)","class ActionDecorator(object): else: func = obj action = self.setup_action(func, False) return func def setup_action(self, func, overwrite): action = self.app.action_type(func, self)" 662,https://:@github.com/a1phat0ny/noteboard.git,82eea493ff696d09af702a1cfd0c645f5f61b86e,"@@ -429,7 +429,7 @@ def display_board(date=False, sort=False, im=False): (Fore.LIGHTBLACK_EX + ""(due: {})"".format(color + str(duedate) + Fore.LIGHTBLACK_EX)) if item[""due""] else """", Fore.LIGHTBLACK_EX + str(item[""date""])) else: - p(star, Fore.LIGHTMAGENTA_EX + str(item[""id""]).rjust(2), mark, text_color + item[""text""], tag_text, due_text, day_text) + p(star, Fore.LIGHTMAGENTA_EX + str(item[""id""]).rjust(2), mark, text_color + item[""text""], tag_text, day_text, due_text) print() print_footer() print_total() ",noteboard/cli.py,"ArgSwap(idxs=5<->6 @(432,16)->(432,17))","def display_board(date=False, sort=False, im=False): (Fore.LIGHTBLACK_EX + ""(due: {})"".format(color + str(duedate) + Fore.LIGHTBLACK_EX)) if item[""due""] else """", Fore.LIGHTBLACK_EX + str(item[""date""])) else: p(star, Fore.LIGHTMAGENTA_EX + str(item[""id""]).rjust(2), mark, text_color + item[""text""], tag_text, due_text, day_text) print() print_footer() print_total()","def display_board(date=False, sort=False, im=False): (Fore.LIGHTBLACK_EX + ""(due: {})"".format(color + str(duedate) + Fore.LIGHTBLACK_EX)) if item[""due""] else """", Fore.LIGHTBLACK_EX + str(item[""date""])) else: p(star, Fore.LIGHTMAGENTA_EX + str(item[""id""]).rjust(2), mark, text_color + item[""text""], tag_text, day_text, due_text) print() print_footer() print_total()" 663,https://:@github.com/tlevine/sheetmusic.git,5c919c8d4c6be39cd42847e44942305521c7fa52,"@@ -54,7 +54,7 @@ def _next_note(first_note, second_note_name): If the second note name is less than the first (""G"" is greater than ""C""), return a note of the second name in the octave above the first. ''' - if second_note_name > first_note.name: + if second_note_name >= first_note.name: second_note_octave = first_note.octave else: second_note_octave = first_note.octave + 1 ",libsheetmusic/music.py,"ReplaceText(target='>=' @(57,24)->(57,25))","def _next_note(first_note, second_note_name): If the second note name is less than the first (""G"" is greater than ""C""), return a note of the second name in the octave above the first. ''' if second_note_name > first_note.name: second_note_octave = first_note.octave else: second_note_octave = first_note.octave + 1","def _next_note(first_note, second_note_name): If the second note name is less than the first (""G"" is greater than ""C""), return a note of the second name in the octave above the first. ''' if second_note_name >= first_note.name: second_note_octave = first_note.octave else: second_note_octave = first_note.octave + 1" 664,https://:@github.com/tlevine/sheetmusic.git,62a714388992483a00824d0ce16af7a7c8b9ee7e,"@@ -80,4 +80,4 @@ def util_functions(): def functions(): callables = reduce(u.merge, [scale_functions(), chord_functions(), progression_functions(), interval_functions(), util_functions()]) - return {k:u.to_function(v, k) for k,v in callables.items()} + return {k:u.to_function(k, v) for k,v in callables.items()} ",libsheetmusic/main.py,"ArgSwap(idxs=0<->1 @(83,14)->(83,27))","def util_functions(): def functions(): callables = reduce(u.merge, [scale_functions(), chord_functions(), progression_functions(), interval_functions(), util_functions()]) return {k:u.to_function(v, k) for k,v in callables.items()}","def util_functions(): def functions(): callables = reduce(u.merge, [scale_functions(), chord_functions(), progression_functions(), interval_functions(), util_functions()]) return {k:u.to_function(k, v) for k,v in callables.items()}" 665,https://:@gitlab.com/ebenhoeh/modelbase.git,dcc3cdf01cf74859ff59f4a641a9caf0faa21069,"@@ -207,7 +207,7 @@ class Model(core.ParameterModel): raise TypeError(""Rate name must be str"") if not callable(rate_function): raise TypeError(""Rate function must be a function"") - if variables is not None: + if variables is None: variables = [] if not isinstance(variables, list): raise TypeError(""Variables must be a list"") ",modelbase/ode/model.py,"ReplaceText(target=' is ' @(210,20)->(210,28))","class Model(core.ParameterModel): raise TypeError(""Rate name must be str"") if not callable(rate_function): raise TypeError(""Rate function must be a function"") if variables is not None: variables = [] if not isinstance(variables, list): raise TypeError(""Variables must be a list"")","class Model(core.ParameterModel): raise TypeError(""Rate name must be str"") if not callable(rate_function): raise TypeError(""Rate function must be a function"") if variables is None: variables = [] if not isinstance(variables, list): raise TypeError(""Variables must be a list"")" 666,https://:@gitlab.com/ebenhoeh/modelbase.git,34fc0fc7c745eef34ae0edf0377347d83b733890,"@@ -281,7 +281,7 @@ class Model(core.ParameterModel): def get_rate_indexes(self, rate_name=None): v, k = zip(*enumerate(self.get_rate_names())) rate_idx = dict(zip(k, v)) - if rate_name is not None: + if rate_name is None: return rate_idx return rate_idx[rate_name] ",modelbase/ode/model.py,"ReplaceText(target=' is ' @(284,20)->(284,28))","class Model(core.ParameterModel): def get_rate_indexes(self, rate_name=None): v, k = zip(*enumerate(self.get_rate_names())) rate_idx = dict(zip(k, v)) if rate_name is not None: return rate_idx return rate_idx[rate_name] ","class Model(core.ParameterModel): def get_rate_indexes(self, rate_name=None): v, k = zip(*enumerate(self.get_rate_names())) rate_idx = dict(zip(k, v)) if rate_name is None: return rate_idx return rate_idx[rate_name] " 667,https://:@github.com/kalombos/pynetsnmp.git,812b5789589ca0d99f6e6d2339fee7e4254e9c01,"@@ -637,7 +637,7 @@ class Session(object): MAXFD = 1024 -fdset = c_int32 * (MAXFD/32) +fdset = c_int32 * (MAXFD//32) class timeval(Structure): _fields_ = [ ",pynetsnmp/netsnmp.py,"ReplaceText(target='//' @(640,24)->(640,25))","class Session(object): MAXFD = 1024 fdset = c_int32 * (MAXFD/32) class timeval(Structure): _fields_ = [","class Session(object): MAXFD = 1024 fdset = c_int32 * (MAXFD//32) class timeval(Structure): _fields_ = [" 668,https://:@github.com/kalombos/pynetsnmp.git,f2883247d0b1df1804aa12653b06dce1d2137697,"@@ -312,7 +312,7 @@ def strToOid(oidStr): return mkoid(tuple([int(x) for x in oidStr.strip('.').split('.')])) def decodeOid(pdu): - return tuple([pdu.val.objid[i] for i in range(pdu.val_len / sizeof(u_long))]) + return tuple([pdu.val.objid[i] for i in range(pdu.val_len // sizeof(u_long))]) def decodeIp(pdu): return '.'.join(map(str, pdu.val.bitstring[:4])) ",pynetsnmp/netsnmp.py,"ReplaceText(target='//' @(315,62)->(315,63))","def strToOid(oidStr): return mkoid(tuple([int(x) for x in oidStr.strip('.').split('.')])) def decodeOid(pdu): return tuple([pdu.val.objid[i] for i in range(pdu.val_len / sizeof(u_long))]) def decodeIp(pdu): return '.'.join(map(str, pdu.val.bitstring[:4]))","def strToOid(oidStr): return mkoid(tuple([int(x) for x in oidStr.strip('.').split('.')])) def decodeOid(pdu): return tuple([pdu.val.objid[i] for i in range(pdu.val_len // sizeof(u_long))]) def decodeIp(pdu): return '.'.join(map(str, pdu.val.bitstring[:4]))" 669,https://:@github.com/Swiftea/Crawler.git,fb03cfc257939d5b86fe00037ab6b00fd54c9afa,"@@ -14,7 +14,7 @@ def stats(dir_stats=DIR_STATS): stat_links = ('Average links in webpage: ' + str(average(content))) if len(content) > 10000: compress_stats(dir_stats + 'stat_links') - result += stat_links + '\n' + result = stat_links + '\n' try: with open(dir_stats + 'stat_webpages', 'r') as myfile: content = myfile.read().split() ",crawler/stats.py,"ReplaceText(target='=' @(17,8)->(17,10))","def stats(dir_stats=DIR_STATS): stat_links = ('Average links in webpage: ' + str(average(content))) if len(content) > 10000: compress_stats(dir_stats + 'stat_links') result += stat_links + '\n' try: with open(dir_stats + 'stat_webpages', 'r') as myfile: content = myfile.read().split()","def stats(dir_stats=DIR_STATS): stat_links = ('Average links in webpage: ' + str(average(content))) if len(content) > 10000: compress_stats(dir_stats + 'stat_links') result = stat_links + '\n' try: with open(dir_stats + 'stat_webpages', 'r') as myfile: content = myfile.read().split()" 670,https://:@bitbucket.org/mikhail-makovenko/save-to-db.git,0b152880bfce8af5f211bfbb3d5677f283823bdc,"@@ -187,7 +187,7 @@ class AdapterBase(object): :returns: Item list and corresponding ORM models as a list of lists (in case one item updates multiple models). """""" - return db_persist(cls, item, adapter_settings) + return db_persist(item, cls, adapter_settings) @classmethod ",save_to_db/adapters/utils/adapter_base.py,"ArgSwap(idxs=0<->1 @(190,15)->(190,25))","class AdapterBase(object): :returns: Item list and corresponding ORM models as a list of lists (in case one item updates multiple models). """""" return db_persist(cls, item, adapter_settings) @classmethod","class AdapterBase(object): :returns: Item list and corresponding ORM models as a list of lists (in case one item updates multiple models). """""" return db_persist(item, cls, adapter_settings) @classmethod" 671,https://:@github.com/itu-algorithms/itu.algs4.git,8a06e126f13f6d54802e342b1ad7c44ec792ffc3,"@@ -64,7 +64,7 @@ class Queue: if __name__ == '__main__': queue = Queue() - if len(sys.argv) > 0: + if len(sys.argv) > 1: sys.stdin = open(sys.argv[1]) while not stdio.isEmpty(): input_item = stdio.readString() ",fundamentals/queue.py,"ReplaceText(target='1' @(67,23)->(67,24))","class Queue: if __name__ == '__main__': queue = Queue() if len(sys.argv) > 0: sys.stdin = open(sys.argv[1]) while not stdio.isEmpty(): input_item = stdio.readString()","class Queue: if __name__ == '__main__': queue = Queue() if len(sys.argv) > 1: sys.stdin = open(sys.argv[1]) while not stdio.isEmpty(): input_item = stdio.readString()" 672,https://:@github.com/itu-algorithms/itu.algs4.git,2282d1fa58d8c525d83890def4dc5b4d1902a0dd,"@@ -9,6 +9,6 @@ class ThreeSumFast: count = 0 for i in range(n): for j in range(i+1, n): - if binary_search.index_of(a, -a[i]-a[j]) > i: + if binary_search.index_of(a, -a[i]-a[j]) > j: count += 1 return count ",algs4/fundamentals/three_sum_fast.py,"ReplaceText(target='j' @(12,59)->(12,60))","class ThreeSumFast: count = 0 for i in range(n): for j in range(i+1, n): if binary_search.index_of(a, -a[i]-a[j]) > i: count += 1 return count","class ThreeSumFast: count = 0 for i in range(n): for j in range(i+1, n): if binary_search.index_of(a, -a[i]-a[j]) > j: count += 1 return count" 673,https://:@github.com/itu-algorithms/itu.algs4.git,62cc19d6f09e3f24abbe1551d69d67474518a7cb,"@@ -183,7 +183,7 @@ class BinarySearchST: while j < self._n-1: self._keys[j] = self._keys[j+1] self._vals[j] = self._vals[j+1] - j = 1 + j += 1 self._n -= 1 n = self._n ",itu/algs4/searching/binary_search_st.py,"ReplaceText(target='+=' @(186,14)->(186,15))","class BinarySearchST: while j < self._n-1: self._keys[j] = self._keys[j+1] self._vals[j] = self._vals[j+1] j = 1 self._n -= 1 n = self._n","class BinarySearchST: while j < self._n-1: self._keys[j] = self._keys[j+1] self._vals[j] = self._vals[j+1] j += 1 self._n -= 1 n = self._n" 674,https://:@github.com/itu-algorithms/itu.algs4.git,616a6dd32cf80578bfae1ce36dbede8eb2e241cc,"@@ -481,7 +481,7 @@ class RedBlackBST(Generic[Key, Val]): return if lo < x.key: self._keys(x.left, queue, lo, hi) - if not x.key < lo and x.key < hi: + if not x.key < lo and x.key <= hi: queue.enqueue(x.key) if hi > x.key: self._keys(x.right, queue, lo, hi) ",itu/algs4/searching/red_black_bst.py,"ReplaceText(target='<=' @(484,37)->(484,38))","class RedBlackBST(Generic[Key, Val]): return if lo < x.key: self._keys(x.left, queue, lo, hi) if not x.key < lo and x.key < hi: queue.enqueue(x.key) if hi > x.key: self._keys(x.right, queue, lo, hi)","class RedBlackBST(Generic[Key, Val]): return if lo < x.key: self._keys(x.left, queue, lo, hi) if not x.key < lo and x.key <= hi: queue.enqueue(x.key) if hi > x.key: self._keys(x.right, queue, lo, hi)" 675,https://:@github.com/kbytesys/django-recaptcha3.git,69219ca34dc834fede05f4e7f107ba17156f8f45,"@@ -15,7 +15,7 @@ logger = logging.getLogger(__name__) class ReCaptchaField(forms.CharField): def __init__(self, attrs=None, *args, **kwargs): - if os.environ.get('RECAPTCHA_DISABLE', None) is not None: + if os.environ.get('RECAPTCHA_DISABLE', None) is None: self._private_key = kwargs.pop('private_key', settings.RECAPTCHA_PRIVATE_KEY) self._score_threshold = kwargs.pop('score_threshold', settings.RECAPTCHA_SCORE_THRESHOLD) ",snowpenguin/django/recaptcha3/fields.py,"ReplaceText(target=' is ' @(18,52)->(18,60))","logger = logging.getLogger(__name__) class ReCaptchaField(forms.CharField): def __init__(self, attrs=None, *args, **kwargs): if os.environ.get('RECAPTCHA_DISABLE', None) is not None: self._private_key = kwargs.pop('private_key', settings.RECAPTCHA_PRIVATE_KEY) self._score_threshold = kwargs.pop('score_threshold', settings.RECAPTCHA_SCORE_THRESHOLD) ","logger = logging.getLogger(__name__) class ReCaptchaField(forms.CharField): def __init__(self, attrs=None, *args, **kwargs): if os.environ.get('RECAPTCHA_DISABLE', None) is None: self._private_key = kwargs.pop('private_key', settings.RECAPTCHA_PRIVATE_KEY) self._score_threshold = kwargs.pop('score_threshold', settings.RECAPTCHA_SCORE_THRESHOLD) " 676,https://:@github.com/MonetDBSolutions/mal_analytics.git,0b7cd6d9394adc932e19a29eda69bb11e5a3fb19,"@@ -375,7 +375,7 @@ class ProfilerObjectParser: except json.JSONDecodeError as json_error: LOGGER.warning(""W001: Cannot parse object"") LOGGER.warning(json_string) - LOGGER.warning(""Decoder reports %s"", json_string) + LOGGER.warning(""Decoder reports %s"", json_error) return dispatcher = { ",mal_profiler/profiler_parser.py,"ReplaceText(target='json_error' @(378,49)->(378,60))","class ProfilerObjectParser: except json.JSONDecodeError as json_error: LOGGER.warning(""W001: Cannot parse object"") LOGGER.warning(json_string) LOGGER.warning(""Decoder reports %s"", json_string) return dispatcher = {","class ProfilerObjectParser: except json.JSONDecodeError as json_error: LOGGER.warning(""W001: Cannot parse object"") LOGGER.warning(json_string) LOGGER.warning(""Decoder reports %s"", json_error) return dispatcher = {" 677,https://:@github.com/MonetDBSolutions/mal_analytics.git,a4e4a3d115ffc81721248d71176d8205c1866d98,"@@ -148,7 +148,7 @@ class DatabaseManager(object, metaclass=Singleton): stmt = list() for ln in sql_in: cline = ln.strip() - if ln.startswith('--') or len(cline) == 0: + if cline.startswith('--') or len(cline) == 0: continue stmt.append(cline) ",mal_analytics/db_manager.py,"ReplaceText(target='cline' @(151,15)->(151,17))","class DatabaseManager(object, metaclass=Singleton): stmt = list() for ln in sql_in: cline = ln.strip() if ln.startswith('--') or len(cline) == 0: continue stmt.append(cline)","class DatabaseManager(object, metaclass=Singleton): stmt = list() for ln in sql_in: cline = ln.strip() if cline.startswith('--') or len(cline) == 0: continue stmt.append(cline)" 678,https://:@github.com/codepost-io/codePost-api-python.git,00320258dd53e987c66c9af2d021fb93b38ac20c,"@@ -812,7 +812,7 @@ def remove_comments(api_key, submission_id=None, file_id=None): headers=auth_headers ) - if r.status_code != 204: + if r.status_code == 204: comments_to_delete += r.json().get(""comments"", list()) deleted_comments += 1 except: ",codePost_api/helpers.py,"ReplaceText(target='==' @(815,29)->(815,31))","def remove_comments(api_key, submission_id=None, file_id=None): headers=auth_headers ) if r.status_code != 204: comments_to_delete += r.json().get(""comments"", list()) deleted_comments += 1 except:","def remove_comments(api_key, submission_id=None, file_id=None): headers=auth_headers ) if r.status_code == 204: comments_to_delete += r.json().get(""comments"", list()) deleted_comments += 1 except:" 679,https://:@github.com/optimatorlab/veroviz.git,0c34d475219e023bbc77e96bbcf8c7bd2ec09fde,"@@ -527,7 +527,7 @@ def geoAreaOfPolygon(poly): polyArea = 0 # Use polygon triangulation to cut the bounding region into a list of triangles, calculate the area of each triangle - lstTriangle = tripy.earclip(poly) + lstTriangle = tripy.earclip(cleanPoly) lstArea = [] for i in range(len(lstTriangle)): lstArea.append(geoAreaOfTriangle(lstTriangle[i][0], lstTriangle[i][1], lstTriangle[i][2])) ",veroviz/_geometry.py,"ReplaceText(target='cleanPoly' @(530,29)->(530,33))","def geoAreaOfPolygon(poly): polyArea = 0 # Use polygon triangulation to cut the bounding region into a list of triangles, calculate the area of each triangle lstTriangle = tripy.earclip(poly) lstArea = [] for i in range(len(lstTriangle)): lstArea.append(geoAreaOfTriangle(lstTriangle[i][0], lstTriangle[i][1], lstTriangle[i][2]))","def geoAreaOfPolygon(poly): polyArea = 0 # Use polygon triangulation to cut the bounding region into a list of triangles, calculate the area of each triangle lstTriangle = tripy.earclip(cleanPoly) lstArea = [] for i in range(len(lstTriangle)): lstArea.append(geoAreaOfTriangle(lstTriangle[i][0], lstTriangle[i][1], lstTriangle[i][2]))" 680,https://:@github.com/slipguru/adenine.git,0ea659ee40e7d0eff55de0da241e5e2566de4a48,"@@ -380,7 +380,7 @@ def analysis_worker(elem, root, y, feat_names, class_names, lock): model=voronoi_mdl_obj) elif hasattr(mdl_obj, 'n_leaves_'): plotting.tree(root=rootname, data_in=step_in, - labels=step_out, model=mdl_obj) + labels=y, model=mdl_obj) plotting.dendrogram(root=rootname, data_in=step_in, labels=y, model=mdl_obj) ",adenine/core/analyze_results.py,"ReplaceText(target='y' @(383,37)->(383,45))","def analysis_worker(elem, root, y, feat_names, class_names, lock): model=voronoi_mdl_obj) elif hasattr(mdl_obj, 'n_leaves_'): plotting.tree(root=rootname, data_in=step_in, labels=step_out, model=mdl_obj) plotting.dendrogram(root=rootname, data_in=step_in, labels=y, model=mdl_obj) ","def analysis_worker(elem, root, y, feat_names, class_names, lock): model=voronoi_mdl_obj) elif hasattr(mdl_obj, 'n_leaves_'): plotting.tree(root=rootname, data_in=step_in, labels=y, model=mdl_obj) plotting.dendrogram(root=rootname, data_in=step_in, labels=y, model=mdl_obj) " 681,https://:@github.com/Tenchi2xh/Almonds.git,79cd9da8e404df197cbe23586aeacec156080722,"@@ -135,7 +135,7 @@ class Cursebox(object): return EVENT_RIGHT elif ch == 3: return EVENT_CTRL_C - elif 0 >= ch < 256: + elif 0 <= ch < 256: return chr(ch) else: return EVENT_UNHANDLED ",almonds/cursebox/cursebox.py,"ReplaceText(target='<=' @(138,15)->(138,17))","class Cursebox(object): return EVENT_RIGHT elif ch == 3: return EVENT_CTRL_C elif 0 >= ch < 256: return chr(ch) else: return EVENT_UNHANDLED","class Cursebox(object): return EVENT_RIGHT elif ch == 3: return EVENT_CTRL_C elif 0 <= ch < 256: return chr(ch) else: return EVENT_UNHANDLED" 682,https://:@github.com/abrahamrhoffman/anaxdb.git,0ff2588e2af89bb06d04834ad6bef887ed5ebb14,"@@ -263,7 +263,7 @@ class Database(object): try: tableFile = (self._path + ""/"" + aTableName + "".pq"") tableFileEnc = (self._path + ""/"" + aTableName + "".enc"") - self._decrypt(tableFileEnc) + self._decrypt(tableFile) dataframe = pq.read_table(tableFile).to_pandas() os.remove(tableFile) return dataframe ",anaxdb/anaxdb.py,"ReplaceText(target='tableFile' @(266,30)->(266,42))","class Database(object): try: tableFile = (self._path + ""/"" + aTableName + "".pq"") tableFileEnc = (self._path + ""/"" + aTableName + "".enc"") self._decrypt(tableFileEnc) dataframe = pq.read_table(tableFile).to_pandas() os.remove(tableFile) return dataframe","class Database(object): try: tableFile = (self._path + ""/"" + aTableName + "".pq"") tableFileEnc = (self._path + ""/"" + aTableName + "".enc"") self._decrypt(tableFile) dataframe = pq.read_table(tableFile).to_pandas() os.remove(tableFile) return dataframe" 683,https://:@github.com/badmetacoder/calculator.git,531135ec2a5b354165ad6e6e6b8d2e4d84b8ee38,"@@ -96,7 +96,7 @@ class SimpleCalculator(): elif self.op == '+': self.r1 = self.r1 + self.r2 elif self.op == '-': - self.r1 = self.r1 + self.r2 + self.r1 = self.r1 - self.r2 elif self.op == '*': self.r1 = self.r1 * self.r2 elif self.op == '/': ",calculator/simple.py,"ReplaceText(target='-' @(99,34)->(99,35))","class SimpleCalculator(): elif self.op == '+': self.r1 = self.r1 + self.r2 elif self.op == '-': self.r1 = self.r1 + self.r2 elif self.op == '*': self.r1 = self.r1 * self.r2 elif self.op == '/':","class SimpleCalculator(): elif self.op == '+': self.r1 = self.r1 + self.r2 elif self.op == '-': self.r1 = self.r1 - self.r2 elif self.op == '*': self.r1 = self.r1 * self.r2 elif self.op == '/':" 684,https://:@github.com/mhantke/h5writer.git,b70deaa06e1b8043aa658410e6ffe2310f796c35,"@@ -150,7 +150,7 @@ class H5WriterMPI(AbstractH5Writer): def _write_solocache_group_to_file(self, data_dict, group_prefix=""/""): if self._is_master() and group_prefix != ""/"": - if group_prefix in self._f: + if group_prefix not in self._f: self._f.create_group(group_prefix) keys = data_dict.keys() keys.sort() ",src/h5writer_mpi.py,"ReplaceText(target=' not in ' @(153,27)->(153,31))","class H5WriterMPI(AbstractH5Writer): def _write_solocache_group_to_file(self, data_dict, group_prefix=""/""): if self._is_master() and group_prefix != ""/"": if group_prefix in self._f: self._f.create_group(group_prefix) keys = data_dict.keys() keys.sort()","class H5WriterMPI(AbstractH5Writer): def _write_solocache_group_to_file(self, data_dict, group_prefix=""/""): if self._is_master() and group_prefix != ""/"": if group_prefix not in self._f: self._f.create_group(group_prefix) keys = data_dict.keys() keys.sort()" 685,https://:@github.com/MushroomRL/mushroom-rl.git,21a7d99f2c2f28a1de150b3464c7b649b096d757,"@@ -6,7 +6,7 @@ class EpsGreedy(object): self._epsilon = epsilon def __call__(self): - if np.random.uniform() > self._epsilon: + if np.random.uniform() < self._epsilon: return False return True ",PyPi/policy/policy.py,"ReplaceText(target='<' @(9,31)->(9,32))","class EpsGreedy(object): self._epsilon = epsilon def __call__(self): if np.random.uniform() > self._epsilon: return False return True ","class EpsGreedy(object): self._epsilon = epsilon def __call__(self): if np.random.uniform() < self._epsilon: return False return True " 686,https://:@github.com/MushroomRL/mushroom-rl.git,86fae8d69f4906e0e395163d1b2fa43371d28deb,"@@ -103,7 +103,7 @@ class Algorithm(object): if render: self.mdp._render() - last = 0 if n_steps < self.mdp.horizon or not absorbing else 1 + last = 0 if n_steps < self.mdp.horizon and not absorbing else 1 sample = self.state.ravel().tolist() + action.ravel().tolist() + \ [reward] + next_state.ravel().tolist() + \ [absorbing, last] ",PyPi/algorithms/algorithm.py,"ReplaceText(target='and' @(106,51)->(106,53))","class Algorithm(object): if render: self.mdp._render() last = 0 if n_steps < self.mdp.horizon or not absorbing else 1 sample = self.state.ravel().tolist() + action.ravel().tolist() + \ [reward] + next_state.ravel().tolist() + \ [absorbing, last]","class Algorithm(object): if render: self.mdp._render() last = 0 if n_steps < self.mdp.horizon and not absorbing else 1 sample = self.state.ravel().tolist() + action.ravel().tolist() + \ [reward] + next_state.ravel().tolist() + \ [absorbing, last]" 687,https://:@github.com/MushroomRL/mushroom-rl.git,2f134a73ac9cdab98206afeab6cd39bb02b6a6fc,"@@ -113,7 +113,7 @@ class Core(object): action_idx = self.agent.draw_action(self.state, self.agent.approximator) action_value = self.mdp.action_space.get_value(action_idx) - next_state, reward, absorbing, _ = self.mdp.step(action_idx) + next_state, reward, absorbing, _ = self.mdp.step(action_value) J += self.mdp.gamma ** n_steps * reward n_steps += 1 ",PyPi/core/core.py,"ReplaceText(target='action_value' @(116,61)->(116,71))","class Core(object): action_idx = self.agent.draw_action(self.state, self.agent.approximator) action_value = self.mdp.action_space.get_value(action_idx) next_state, reward, absorbing, _ = self.mdp.step(action_idx) J += self.mdp.gamma ** n_steps * reward n_steps += 1 ","class Core(object): action_idx = self.agent.draw_action(self.state, self.agent.approximator) action_value = self.mdp.action_space.get_value(action_idx) next_state, reward, absorbing, _ = self.mdp.step(action_value) J += self.mdp.gamma ** n_steps * reward n_steps += 1 " 688,https://:@github.com/MushroomRL/mushroom-rl.git,a38031ed8b004f73983b53919acfd4c36e1f2bf1,"@@ -75,4 +75,4 @@ class Binarizer(Preprocessor): The binarized input data array. """""" - return (x > self._threshold).astype(np.float) + return (x >= self._threshold).astype(np.float) ",mushroom/utils/preprocessor.py,"ReplaceText(target='>=' @(78,18)->(78,19))","class Binarizer(Preprocessor): The binarized input data array. """""" return (x > self._threshold).astype(np.float)","class Binarizer(Preprocessor): The binarized input data array. """""" return (x >= self._threshold).astype(np.float)" 689,https://:@github.com/MushroomRL/mushroom-rl.git,bcf82aaeed185c53d3f512491f80ec793e264bab,"@@ -237,7 +237,7 @@ class RDQN(DQN): state, action, _, _, absorbing, _ =\ self._replay_memory.get_idxs(idxs) - no_abs_idxs = idxs[np.argwhere(absorbing != 0).ravel()] + no_abs_idxs = idxs[np.argwhere(absorbing == 0).ravel()] state, action, _, _, absorbing, _ =\ self._replay_memory.get_idxs(no_abs_idxs) next_state, next_action, next_reward, _, next_absorbing, _ =\ ",mushroom/algorithms/dqn.py,"ReplaceText(target='==' @(240,53)->(240,55))","class RDQN(DQN): state, action, _, _, absorbing, _ =\ self._replay_memory.get_idxs(idxs) no_abs_idxs = idxs[np.argwhere(absorbing != 0).ravel()] state, action, _, _, absorbing, _ =\ self._replay_memory.get_idxs(no_abs_idxs) next_state, next_action, next_reward, _, next_absorbing, _ =\","class RDQN(DQN): state, action, _, _, absorbing, _ =\ self._replay_memory.get_idxs(idxs) no_abs_idxs = idxs[np.argwhere(absorbing == 0).ravel()] state, action, _, _, absorbing, _ =\ self._replay_memory.get_idxs(no_abs_idxs) next_state, next_action, next_reward, _, next_absorbing, _ =\" 690,https://:@github.com/MushroomRL/mushroom-rl.git,d4ec7569d1f7409b05754abe8a11a69f016efd01,"@@ -258,7 +258,7 @@ class SARSALambdaDiscrete(TD): for s in self.mdp_info.observation_space.values: for a in self.mdp_info.action_space.values: self.Q[s, a] += self.alpha(s, a) * delta * self.e[s, a] - self.e[s, a] = self.mdp_info.gamma * self._lambda + self.e[s, a] *= self.mdp_info.gamma * self._lambda class SARSALambdaContinuous(TD): ",mushroom/algorithms/value/td.py,"ReplaceText(target='*=' @(261,29)->(261,30))","class SARSALambdaDiscrete(TD): for s in self.mdp_info.observation_space.values: for a in self.mdp_info.action_space.values: self.Q[s, a] += self.alpha(s, a) * delta * self.e[s, a] self.e[s, a] = self.mdp_info.gamma * self._lambda class SARSALambdaContinuous(TD):","class SARSALambdaDiscrete(TD): for s in self.mdp_info.observation_space.values: for a in self.mdp_info.action_space.values: self.Q[s, a] += self.alpha(s, a) * delta * self.e[s, a] self.e[s, a] *= self.mdp_info.gamma * self._lambda class SARSALambdaContinuous(TD):" 691,https://:@github.com/MushroomRL/mushroom-rl.git,809c24e9b50202c6c06fbe6fc7e4b067894230c4,"@@ -161,7 +161,7 @@ class DoubleFQI(FQI): next_state = list() absorbing = list() - half = len(x) / 2 + half = len(x) // 2 for i in range(2): s, a, r, ss, ab, _ = parse_dataset(x[i * half:(i + 1) * half]) state.append(s) ",mushroom/algorithms/value/batch_td.py,"ReplaceText(target='//' @(164,22)->(164,23))","class DoubleFQI(FQI): next_state = list() absorbing = list() half = len(x) / 2 for i in range(2): s, a, r, ss, ab, _ = parse_dataset(x[i * half:(i + 1) * half]) state.append(s)","class DoubleFQI(FQI): next_state = list() absorbing = list() half = len(x) // 2 for i in range(2): s, a, r, ss, ab, _ = parse_dataset(x[i * half:(i + 1) * half]) state.append(s)" 692,https://:@github.com/MushroomRL/mushroom-rl.git,809c24e9b50202c6c06fbe6fc7e4b067894230c4,"@@ -186,7 +186,7 @@ class AveragedDQN(DQN): assert isinstance(self.target_approximator.model, Ensemble) def _update_target(self): - idx = self._n_updates / self._target_update_frequency\ + idx = self._n_updates // self._target_update_frequency\ % self._n_approximators self.target_approximator.model[idx].set_weights( self.approximator.model.get_weights()) ",mushroom/algorithms/value/dqn.py,"ReplaceText(target='//' @(189,30)->(189,31))","class AveragedDQN(DQN): assert isinstance(self.target_approximator.model, Ensemble) def _update_target(self): idx = self._n_updates / self._target_update_frequency\ % self._n_approximators self.target_approximator.model[idx].set_weights( self.approximator.model.get_weights())","class AveragedDQN(DQN): assert isinstance(self.target_approximator.model, Ensemble) def _update_target(self): idx = self._n_updates // self._target_update_frequency\ % self._n_approximators self.target_approximator.model[idx].set_weights( self.approximator.model.get_weights())" 693,https://:@github.com/MushroomRL/mushroom-rl.git,809c24e9b50202c6c06fbe6fc7e4b067894230c4,"@@ -108,7 +108,7 @@ def compute_probabilities(grid_map, cell_list, passenger_list, prob): passenger_states = cartesian([[0, 1]] * len(passenger_list)) for i in range(n_states): - idx = i / len(cell_list) + idx = i // len(cell_list) collected_passengers = np.array( passenger_list)[np.argwhere(passenger_states[idx] == 1).ravel()] state = c[i % len(cell_list)] ",mushroom/environments/generators/taxi.py,"ReplaceText(target='//' @(111,16)->(111,17))","def compute_probabilities(grid_map, cell_list, passenger_list, prob): passenger_states = cartesian([[0, 1]] * len(passenger_list)) for i in range(n_states): idx = i / len(cell_list) collected_passengers = np.array( passenger_list)[np.argwhere(passenger_states[idx] == 1).ravel()] state = c[i % len(cell_list)]","def compute_probabilities(grid_map, cell_list, passenger_list, prob): passenger_states = cartesian([[0, 1]] * len(passenger_list)) for i in range(n_states): idx = i // len(cell_list) collected_passengers = np.array( passenger_list)[np.argwhere(passenger_states[idx] == 1).ravel()] state = c[i % len(cell_list)]" 694,https://:@github.com/MushroomRL/mushroom-rl.git,809c24e9b50202c6c06fbe6fc7e4b067894230c4,"@@ -54,7 +54,7 @@ class AbstractGridWorld(Environment): @staticmethod def convert_to_grid(state, width): - return np.array([state[0] / width, state[0] % width]) + return np.array([state[0] // width, state[0] % width]) @staticmethod def convert_to_int(state, width): ",mushroom/environments/grid_world.py,"ReplaceText(target='//' @(57,34)->(57,35))","class AbstractGridWorld(Environment): @staticmethod def convert_to_grid(state, width): return np.array([state[0] / width, state[0] % width]) @staticmethod def convert_to_int(state, width):","class AbstractGridWorld(Environment): @staticmethod def convert_to_grid(state, width): return np.array([state[0] // width, state[0] % width]) @staticmethod def convert_to_int(state, width):" 695,https://:@github.com/MushroomRL/mushroom-rl.git,809c24e9b50202c6c06fbe6fc7e4b067894230c4,"@@ -90,7 +90,7 @@ def experiment(alg): # evaluate initial policy pi.set_epsilon(epsilon_test) mdp.set_episode_end(ends_at_life=False) - for n_epoch in range(1, max_steps / evaluation_frequency + 1): + for n_epoch in range(1, max_steps // evaluation_frequency + 1): # learning step pi.set_epsilon(epsilon) mdp.set_episode_end(ends_at_life=True) ",tests/atari_dqn/atari_dqn.py,"ReplaceText(target='//' @(93,38)->(93,39))","def experiment(alg): # evaluate initial policy pi.set_epsilon(epsilon_test) mdp.set_episode_end(ends_at_life=False) for n_epoch in range(1, max_steps / evaluation_frequency + 1): # learning step pi.set_epsilon(epsilon) mdp.set_episode_end(ends_at_life=True)","def experiment(alg): # evaluate initial policy pi.set_epsilon(epsilon_test) mdp.set_episode_end(ends_at_life=False) for n_epoch in range(1, max_steps // evaluation_frequency + 1): # learning step pi.set_epsilon(epsilon) mdp.set_episode_end(ends_at_life=True)" 696,https://:@github.com/MushroomRL/mushroom-rl.git,a3695d7feb30d5fbb277fb1e8a7e3711d84545a2,"@@ -294,7 +294,7 @@ def experiment(): agent.policy.set_q(agent.approximator) np.save(folder_name + '/scores.npy', scores) - for n_epoch in range(1, max_steps / evaluation_frequency + 1): + for n_epoch in range(1, max_steps // evaluation_frequency + 1): print_epoch(n_epoch) print('- Learning:') # learning step ",examples/atari_dqn/atari_dqn.py,"ReplaceText(target='//' @(297,42)->(297,43))","def experiment(): agent.policy.set_q(agent.approximator) np.save(folder_name + '/scores.npy', scores) for n_epoch in range(1, max_steps / evaluation_frequency + 1): print_epoch(n_epoch) print('- Learning:') # learning step","def experiment(): agent.policy.set_q(agent.approximator) np.save(folder_name + '/scores.npy', scores) for n_epoch in range(1, max_steps // evaluation_frequency + 1): print_epoch(n_epoch) print('- Learning:') # learning step" 697,https://:@github.com/MushroomRL/mushroom-rl.git,238a6a652a8ce6c7fb23eba48dd52a2bce343b92,"@@ -51,7 +51,7 @@ class DQN(Agent): self._batch_size = batch_size self._n_approximators = n_approximators self._clip_reward = clip_reward - self._target_update_frequency = target_update_frequency / train_frequency + self._target_update_frequency = target_update_frequency // train_frequency self._max_no_op_actions = max_no_op_actions self._no_op_action_value = no_op_action_value ",mushroom/algorithms/value/dqn.py,"ReplaceText(target='//' @(54,64)->(54,65))","class DQN(Agent): self._batch_size = batch_size self._n_approximators = n_approximators self._clip_reward = clip_reward self._target_update_frequency = target_update_frequency / train_frequency self._max_no_op_actions = max_no_op_actions self._no_op_action_value = no_op_action_value ","class DQN(Agent): self._batch_size = batch_size self._n_approximators = n_approximators self._clip_reward = clip_reward self._target_update_frequency = target_update_frequency // train_frequency self._max_no_op_actions = max_no_op_actions self._no_op_action_value = no_op_action_value " 698,https://:@github.com/MushroomRL/mushroom-rl.git,bdd275227ed4e37833414e33176bbe0585f02a8b,"@@ -180,7 +180,7 @@ class InvertedPendulumDiscrete(Environment): u = 0. else: u = self._max_u - action += np.random.uniform(-self._noise_u, self._noise_u) + u += np.random.uniform(-self._noise_u, self._noise_u) new_state = odeint(self._dynamics, self._state, [0, self._dt], (u,)) ",mushroom/environments/inverted_pendulum.py,"ReplaceText(target='u' @(183,8)->(183,14))","class InvertedPendulumDiscrete(Environment): u = 0. else: u = self._max_u action += np.random.uniform(-self._noise_u, self._noise_u) new_state = odeint(self._dynamics, self._state, [0, self._dt], (u,)) ","class InvertedPendulumDiscrete(Environment): u = 0. else: u = self._max_u u += np.random.uniform(-self._noise_u, self._noise_u) new_state = odeint(self._dynamics, self._state, [0, self._dt], (u,)) " 699,https://:@github.com/MushroomRL/mushroom-rl.git,590aabe042c74f6d6be4b1b821ad35d9ae1a47f7,"@@ -232,7 +232,7 @@ class ReplayMemory(object): allows it to be used. """""" - return self.size > self._initial_size + return self.size >= self._initial_size @property def size(self): ",mushroom/utils/replay_memory.py,"ReplaceText(target='>=' @(235,25)->(235,26))","class ReplayMemory(object): allows it to be used. """""" return self.size > self._initial_size @property def size(self):","class ReplayMemory(object): allows it to be used. """""" return self.size >= self._initial_size @property def size(self):" 700,https://:@github.com/MushroomRL/mushroom-rl.git,00f820f10d492257264eb0587aac92193ba65650,"@@ -78,7 +78,7 @@ def experiment(n_epochs, n_steps, n_steps_test): n_actions=mdp.info.action_space.n) # Agent - agent = DQN(TorchApproximator, pi, mdp.info, + agent = DQN(mdp.info, pi, TorchApproximator, approximator_params=approximator_params, batch_size=batch_size, n_approximators=1, initial_replay_size=initial_replay_size, max_replay_size=max_replay_size, ",examples/acrobot_dqn.py,"ArgSwap(idxs=0<->2 @(81,12)->(81,15))","def experiment(n_epochs, n_steps, n_steps_test): n_actions=mdp.info.action_space.n) # Agent agent = DQN(TorchApproximator, pi, mdp.info, approximator_params=approximator_params, batch_size=batch_size, n_approximators=1, initial_replay_size=initial_replay_size, max_replay_size=max_replay_size,","def experiment(n_epochs, n_steps, n_steps_test): n_actions=mdp.info.action_space.n) # Agent agent = DQN(mdp.info, pi, TorchApproximator, approximator_params=approximator_params, batch_size=batch_size, n_approximators=1, initial_replay_size=initial_replay_size, max_replay_size=max_replay_size," 701,https://:@github.com/MushroomRL/mushroom-rl.git,00f820f10d492257264eb0587aac92193ba65650,"@@ -37,7 +37,7 @@ def experiment(): # Agent algorithm_params = dict(n_iterations=20) - agent = FQI(approximator, pi, mdp.info, + agent = FQI(mdp.info, pi, approximator, approximator_params=approximator_params, **algorithm_params) # Algorithm ",examples/car_on_hill_fqi.py,"ArgSwap(idxs=0<->2 @(40,12)->(40,15))","def experiment(): # Agent algorithm_params = dict(n_iterations=20) agent = FQI(approximator, pi, mdp.info, approximator_params=approximator_params, **algorithm_params) # Algorithm","def experiment(): # Agent algorithm_params = dict(n_iterations=20) agent = FQI(mdp.info, pi, approximator, approximator_params=approximator_params, **algorithm_params) # Algorithm" 702,https://:@github.com/MushroomRL/mushroom-rl.git,00f820f10d492257264eb0587aac92193ba65650,"@@ -33,7 +33,7 @@ def experiment(algorithm_class, exp): # Agent learning_rate = ExponentialParameter(value=1., exp=exp, size=mdp.info.size) algorithm_params = dict(learning_rate=learning_rate) - agent = algorithm_class(pi, mdp.info, **algorithm_params) + agent = algorithm_class(mdp.info, pi, **algorithm_params) # Algorithm collect_Q = CollectQ(agent.approximator) ",examples/double_chain_q_learning/double_chain.py,"ArgSwap(idxs=0<->1 @(36,12)->(36,27))","def experiment(algorithm_class, exp): # Agent learning_rate = ExponentialParameter(value=1., exp=exp, size=mdp.info.size) algorithm_params = dict(learning_rate=learning_rate) agent = algorithm_class(pi, mdp.info, **algorithm_params) # Algorithm collect_Q = CollectQ(agent.approximator)","def experiment(algorithm_class, exp): # Agent learning_rate = ExponentialParameter(value=1., exp=exp, size=mdp.info.size) algorithm_params = dict(learning_rate=learning_rate) agent = algorithm_class(mdp.info, pi, **algorithm_params) # Algorithm collect_Q = CollectQ(agent.approximator)" 703,https://:@github.com/MushroomRL/mushroom-rl.git,00f820f10d492257264eb0587aac92193ba65650,"@@ -38,7 +38,7 @@ def experiment(algorithm_class, exp): # Agent learning_rate = ExponentialParameter(value=1, exp=exp, size=mdp.info.size) algorithm_params = dict(learning_rate=learning_rate) - agent = algorithm_class(pi, mdp.info, **algorithm_params) + agent = algorithm_class(mdp.info, pi, **algorithm_params) # Algorithm start = mdp.convert_to_int(mdp._start, mdp._width) ",examples/grid_world_td.py,"ArgSwap(idxs=0<->1 @(41,12)->(41,27))","def experiment(algorithm_class, exp): # Agent learning_rate = ExponentialParameter(value=1, exp=exp, size=mdp.info.size) algorithm_params = dict(learning_rate=learning_rate) agent = algorithm_class(pi, mdp.info, **algorithm_params) # Algorithm start = mdp.convert_to_int(mdp._start, mdp._width)","def experiment(algorithm_class, exp): # Agent learning_rate = ExponentialParameter(value=1, exp=exp, size=mdp.info.size) algorithm_params = dict(learning_rate=learning_rate) agent = algorithm_class(mdp.info, pi, **algorithm_params) # Algorithm start = mdp.convert_to_int(mdp._start, mdp._width)" 704,https://:@github.com/MushroomRL/mushroom-rl.git,3644c74bf5069331dfd80f1b65e281460fefab21,"@@ -191,7 +191,7 @@ class TRPO(Agent): new_loss = self._compute_loss(obs, act, adv, old_log_prob) kl = self._compute_kl(obs, old_pol_dist) improve = new_loss - prev_loss - if kl <= self._max_kl * 1.5 or improve >= 0: + if kl <= self._max_kl * 1.5 and improve >= 0: violation = False break stepsize *= .5 ",mushroom_rl/algorithms/actor_critic/deep_actor_critic/trpo.py,"ReplaceText(target='and' @(194,40)->(194,42))","class TRPO(Agent): new_loss = self._compute_loss(obs, act, adv, old_log_prob) kl = self._compute_kl(obs, old_pol_dist) improve = new_loss - prev_loss if kl <= self._max_kl * 1.5 or improve >= 0: violation = False break stepsize *= .5","class TRPO(Agent): new_loss = self._compute_loss(obs, act, adv, old_log_prob) kl = self._compute_kl(obs, old_pol_dist) improve = new_loss - prev_loss if kl <= self._max_kl * 1.5 and improve >= 0: violation = False break stepsize *= .5" 705,https://:@github.com/ska-sa/katsdpimager.git,9606d1eefd02b2fe7039fe09e6bf7647d0b6c30b,"@@ -20,7 +20,7 @@ def parse_quantity(str_value): """"""Parse a string into an astropy Quantity. Rather than trying to guess where the split occurs, we try every position from the back until we succeed."""""" - for i in range(len(str_value), -1, 0): + for i in range(len(str_value), 0, -1): try: value = float(str_value[:i]) unit = units.Unit(str_value[i:]) ",scripts/imager.py,"ArgSwap(idxs=1<->2 @(23,13)->(23,18))","def parse_quantity(str_value): """"""Parse a string into an astropy Quantity. Rather than trying to guess where the split occurs, we try every position from the back until we succeed."""""" for i in range(len(str_value), -1, 0): try: value = float(str_value[:i]) unit = units.Unit(str_value[i:])","def parse_quantity(str_value): """"""Parse a string into an astropy Quantity. Rather than trying to guess where the split occurs, we try every position from the back until we succeed."""""" for i in range(len(str_value), 0, -1): try: value = float(str_value[:i]) unit = units.Unit(str_value[i:])" 706,https://:@github.com/ska-sa/katsdpimager.git,87edf0d372e8b40702cc72cc96c07ddb62fe19cc,"@@ -479,7 +479,7 @@ class Weights(accel.OperationSequence): self.ensure_all_bound() # If self._fill is set, it is not necessary to clear first because # finalize will set all relevant values. - if self._fill is not None: + if self._fill is None: self.buffer('grid').zero(self.command_queue) def grid(self, uv, weights): ",katsdpimager/weight.py,"ReplaceText(target=' is ' @(482,21)->(482,29))","class Weights(accel.OperationSequence): self.ensure_all_bound() # If self._fill is set, it is not necessary to clear first because # finalize will set all relevant values. if self._fill is not None: self.buffer('grid').zero(self.command_queue) def grid(self, uv, weights):","class Weights(accel.OperationSequence): self.ensure_all_bound() # If self._fill is set, it is not necessary to clear first because # finalize will set all relevant values. if self._fill is None: self.buffer('grid').zero(self.command_queue) def grid(self, uv, weights):" 707,https://:@github.com/ska-sa/katsdpimager.git,c1790fa1bf597a5fb592ee05ff7205b17fbcc85e,"@@ -134,7 +134,7 @@ class Image(object): # TODO: should use the WCS transformation slices[i - 3] = 'IQUV'.find(stokes) elif axis_type == 'VOPT': - slices[i - 3] = channel + slices[i - 3] = rel_channel self._render_thumb(output_dir, filename, slices, mode, stokes, channel) self._render_full(output_dir, filename, slices, mode, stokes, channel) ",tests/images_report.py,"ReplaceText(target='rel_channel' @(137,36)->(137,43))","class Image(object): # TODO: should use the WCS transformation slices[i - 3] = 'IQUV'.find(stokes) elif axis_type == 'VOPT': slices[i - 3] = channel self._render_thumb(output_dir, filename, slices, mode, stokes, channel) self._render_full(output_dir, filename, slices, mode, stokes, channel) ","class Image(object): # TODO: should use the WCS transformation slices[i - 3] = 'IQUV'.find(stokes) elif axis_type == 'VOPT': slices[i - 3] = rel_channel self._render_thumb(output_dir, filename, slices, mode, stokes, channel) self._render_full(output_dir, filename, slices, mode, stokes, channel) " 708,https://:@github.com/gdoumenc/coworks.git,4a24754388adcf2fb8b878fb6a97cce8bf443e55,"@@ -53,7 +53,7 @@ def invoke(initial, ctx): handler = get_handler(project_dir, module, service) cmd = project_config.get_command(handler, module, service, workspace) if not cmd: - raise CwsClientError(f""Undefined command {cmd}.\n"") + raise CwsClientError(f""Undefined command {cmd_name}.\n"") # Defines the proxy command with all user options def call_execute(**command_options): ",coworks/cws/client.py,"ReplaceText(target='cmd_name' @(56,58)->(56,61))","def invoke(initial, ctx): handler = get_handler(project_dir, module, service) cmd = project_config.get_command(handler, module, service, workspace) if not cmd: raise CwsClientError(f""Undefined command {cmd}.\n"") # Defines the proxy command with all user options def call_execute(**command_options):","def invoke(initial, ctx): handler = get_handler(project_dir, module, service) cmd = project_config.get_command(handler, module, service, workspace) if not cmd: raise CwsClientError(f""Undefined command {cmd_name}.\n"") # Defines the proxy command with all user options def call_execute(**command_options):" 709,https://:@github.com/geokrety/geokrety-api.git,402a0659cc311fcb296865db0a8303130cb85f92,"@@ -9,5 +9,5 @@ def dasherize(text): def require_relationship(resource_list, data): for resource in resource_list: if resource not in data: - raise UnprocessableEntity({'pointer': '/data/relationships/{}'.format(resource)}, - ""A valid relationship with {} resource is required"".format(resource)) + raise UnprocessableEntity(""A valid relationship with {} resource is required"".format(resource), + {'pointer': '/data/relationships/{}'.format(resource)}) ",app/api/helpers/utilities.py,"ArgSwap(idxs=0<->1 @(12,18)->(12,37))","def dasherize(text): def require_relationship(resource_list, data): for resource in resource_list: if resource not in data: raise UnprocessableEntity({'pointer': '/data/relationships/{}'.format(resource)}, ""A valid relationship with {} resource is required"".format(resource))","def dasherize(text): def require_relationship(resource_list, data): for resource in resource_list: if resource not in data: raise UnprocessableEntity(""A valid relationship with {} resource is required"".format(resource), {'pointer': '/data/relationships/{}'.format(resource)})" 710,https://:@github.com/troylar/mike-brady.git,51ac87ab42555fcea332280f21425fd0398ad22a,"@@ -43,7 +43,7 @@ def render_templates(target_path, replace_values, file_types): template = env.get_template(f) rendered = template.render(replace_values) with open(full_path, ""w"") as fh: - print('Writing {}'.format(f)) + print('Writing {}'.format(full_path)) fh.write(rendered) ",src/main.py,"ReplaceText(target='full_path' @(46,42)->(46,43))","def render_templates(target_path, replace_values, file_types): template = env.get_template(f) rendered = template.render(replace_values) with open(full_path, ""w"") as fh: print('Writing {}'.format(f)) fh.write(rendered) ","def render_templates(target_path, replace_values, file_types): template = env.get_template(f) rendered = template.render(replace_values) with open(full_path, ""w"") as fh: print('Writing {}'.format(full_path)) fh.write(rendered) " 711,https://:@github.com/timwhite/greg.git,0a729af52a7ca3d66cefa89513f97fb5cd932b8e,"@@ -756,7 +756,7 @@ def sync(args): feed.fix_linkdate(entry) # Sort entries_to_download, but only if you want to download as # many as there are - if stop < len(entries_to_download): + if stop >= len(entries_to_download): entries_to_download.sort(key=operator.attrgetter(""linkdate""), reverse=False) for entry in entries_to_download: ",greg/greg.py,"ReplaceText(target='>=' @(759,20)->(759,21))","def sync(args): feed.fix_linkdate(entry) # Sort entries_to_download, but only if you want to download as # many as there are if stop < len(entries_to_download): entries_to_download.sort(key=operator.attrgetter(""linkdate""), reverse=False) for entry in entries_to_download:","def sync(args): feed.fix_linkdate(entry) # Sort entries_to_download, but only if you want to download as # many as there are if stop >= len(entries_to_download): entries_to_download.sort(key=operator.attrgetter(""linkdate""), reverse=False) for entry in entries_to_download:" 712,https://:@github.com/yeago/question-stack.git,71958e8a2745787aacd5bf8b07867a4710b2bb4b,"@@ -61,7 +61,7 @@ def accepted_answer(request,slug,comment): if not instance == comment.content_object: raise Http404 - if not request.user.has_perm('stack.change_question') or not request.user == instance.comment.user: + if not request.user.has_perm('stack.change_question') and not request.user == instance.comment.user: raise Http404 if instance.accepted_answer: ",views.py,"ReplaceText(target='and' @(64,55)->(64,57))","def accepted_answer(request,slug,comment): if not instance == comment.content_object: raise Http404 if not request.user.has_perm('stack.change_question') or not request.user == instance.comment.user: raise Http404 if instance.accepted_answer:","def accepted_answer(request,slug,comment): if not instance == comment.content_object: raise Http404 if not request.user.has_perm('stack.change_question') and not request.user == instance.comment.user: raise Http404 if instance.accepted_answer:" 713,https://:@github.com/jtbish/piecewise.git,5f227f50d16d04d756045804b21ca5bd18c83597,"@@ -14,7 +14,7 @@ class FuzzyXCSFLinearPredictionCreditAssignment: ] total_matching_degrees = sum(matching_degrees) assert total_matching_degrees > 0.0 - for (classifier, matching_degree) in zip(matching_degrees, action_set): + for (classifier, matching_degree) in zip(action_set, matching_degrees): credit_weight = (matching_degree / total_matching_degrees) self._update_experience(classifier, credit_weight) payoff_diff = payoff - classifier.get_prediction(situation) ",piecewise/fuzzy/credit_assignment.py,"ArgSwap(idxs=0<->1 @(17,45)->(17,48))","class FuzzyXCSFLinearPredictionCreditAssignment: ] total_matching_degrees = sum(matching_degrees) assert total_matching_degrees > 0.0 for (classifier, matching_degree) in zip(matching_degrees, action_set): credit_weight = (matching_degree / total_matching_degrees) self._update_experience(classifier, credit_weight) payoff_diff = payoff - classifier.get_prediction(situation)","class FuzzyXCSFLinearPredictionCreditAssignment: ] total_matching_degrees = sum(matching_degrees) assert total_matching_degrees > 0.0 for (classifier, matching_degree) in zip(action_set, matching_degrees): credit_weight = (matching_degree / total_matching_degrees) self._update_experience(classifier, credit_weight) payoff_diff = payoff - classifier.get_prediction(situation)" 714,https://:@github.com/Clinical-Genomics/cg.git,f65fa404f3761f726a5bd32e3794e3c3d6771a26,"@@ -110,7 +110,7 @@ def update(context, answered_out, case_id): if delivery_date is None: log.warn(""sample not delivered: %s"", hk_sample.lims_id) context.abort() - delivery_dates.append(delivery_dates) + delivery_dates.append(delivery_date) latest_date = sorted(delivery_dates)[-1] log.debug(""fillin answered out date in HK"") hk_run.answeredout_at = datetime.combine(latest_date, datetime.min.time()) ",cg/commands.py,"ReplaceText(target='delivery_date' @(113,34)->(113,48))","def update(context, answered_out, case_id): if delivery_date is None: log.warn(""sample not delivered: %s"", hk_sample.lims_id) context.abort() delivery_dates.append(delivery_dates) latest_date = sorted(delivery_dates)[-1] log.debug(""fillin answered out date in HK"") hk_run.answeredout_at = datetime.combine(latest_date, datetime.min.time())","def update(context, answered_out, case_id): if delivery_date is None: log.warn(""sample not delivered: %s"", hk_sample.lims_id) context.abort() delivery_dates.append(delivery_date) latest_date = sorted(delivery_dates)[-1] log.debug(""fillin answered out date in HK"") hk_run.answeredout_at = datetime.combine(latest_date, datetime.min.time())" 715,https://:@github.com/Clinical-Genomics/cg.git,a9c45156e08953c30b15eccd7431e76ce0809ac3,"@@ -174,7 +174,7 @@ def start(lims_api, customer_id, family_name): log.debug(""%s has status %s"", sample.sample_id, sample_status) statuses.add(sample_status) - if len(is_externals) == 0: + if len(is_externals) == 1: data = dict(is_external=is_externals.pop()) else: # mix of internal and external samples ",cg/apps/lims.py,"ReplaceText(target='1' @(177,28)->(177,29))","def start(lims_api, customer_id, family_name): log.debug(""%s has status %s"", sample.sample_id, sample_status) statuses.add(sample_status) if len(is_externals) == 0: data = dict(is_external=is_externals.pop()) else: # mix of internal and external samples","def start(lims_api, customer_id, family_name): log.debug(""%s has status %s"", sample.sample_id, sample_status) statuses.add(sample_status) if len(is_externals) == 1: data = dict(is_external=is_externals.pop()) else: # mix of internal and external samples" 716,https://:@github.com/Clinical-Genomics/cg.git,ea94c447cec22ba9e9a5febcf78f1816f0b2de5d,"@@ -90,7 +90,7 @@ def family(context: click.Context, customer: str, name: bool, samples: bool, families.append(family_obj) for family_obj in families: - LOG.debug(f""{family_id.internal_id}: get info about family"") + LOG.debug(f""{family_obj.internal_id}: get info about family"") row = [ family_obj.internal_id, family_obj.name, ",cg/cli/get.py,"ReplaceText(target='family_obj' @(93,21)->(93,30))","def family(context: click.Context, customer: str, name: bool, samples: bool, families.append(family_obj) for family_obj in families: LOG.debug(f""{family_id.internal_id}: get info about family"") row = [ family_obj.internal_id, family_obj.name,","def family(context: click.Context, customer: str, name: bool, samples: bool, families.append(family_obj) for family_obj in families: LOG.debug(f""{family_obj.internal_id}: get info about family"") row = [ family_obj.internal_id, family_obj.name," 717,https://:@github.com/Clinical-Genomics/cg.git,097837f7aeded32f7792fd77ede05c006732e06b,"@@ -18,7 +18,7 @@ class BackupApi(): """"""Check if there's too many flowcells already ""ondisk""."""""" ondisk_flowcells = self.status.flowcells(status='ondisk').count() LOG.debug(f""ondisk flowcells: {ondisk_flowcells}"") - return ondisk_flowcells < max_flowcells + return ondisk_flowcells > max_flowcells def check_processing(self, max_flowcells: int=3) -> bool: """"""Check if the processing queue for flowcells is not full."""""" ",cg/meta/backup.py,"ReplaceText(target='>' @(21,32)->(21,33))","class BackupApi(): """"""Check if there's too many flowcells already ""ondisk""."""""" ondisk_flowcells = self.status.flowcells(status='ondisk').count() LOG.debug(f""ondisk flowcells: {ondisk_flowcells}"") return ondisk_flowcells < max_flowcells def check_processing(self, max_flowcells: int=3) -> bool: """"""Check if the processing queue for flowcells is not full.""""""","class BackupApi(): """"""Check if there's too many flowcells already ""ondisk""."""""" ondisk_flowcells = self.status.flowcells(status='ondisk').count() LOG.debug(f""ondisk flowcells: {ondisk_flowcells}"") return ondisk_flowcells > max_flowcells def check_processing(self, max_flowcells: int=3) -> bool: """"""Check if the processing queue for flowcells is not full.""""""" 718,https://:@github.com/codesyntax/Products.Bitakora.git,c9af30f2114b45151a57d527b6d87150d17ec226,"@@ -23,7 +23,7 @@ __version__ = ""$Revision$"" def manage_addComment(self, author, body, url='', email='', date=None, bitakora_cpt='', random_cpt='', captcha_zz=0, REQUEST=None): """""" Called from HTML form when commenting """""" from utils import checkCaptchaValue, isCommentSpam - if not captcha_zz: + if captcha_zz: if not checkCaptchaValue(random_cpt, bitakora_cpt): if REQUEST is not None: return REQUEST.RESPONSE.redirect(self.absolute_url()+u'?msg=%s&body=%s&comment_author=%s&comment_email=%s&comment_url=%s#bitakora_cpt_control' % (self.gettext('Are you a bot? Please try again...'), url_quote(body.encode('utf-8')), url_quote(author.encode('utf-8')), url_quote(email.encode('utf-8')), url_quote(url.encode('utf-8')))) ",Comment.py,"ReplaceText(target='' @(26,7)->(26,11))","__version__ = ""$Revision$"" def manage_addComment(self, author, body, url='', email='', date=None, bitakora_cpt='', random_cpt='', captcha_zz=0, REQUEST=None): """""" Called from HTML form when commenting """""" from utils import checkCaptchaValue, isCommentSpam if not captcha_zz: if not checkCaptchaValue(random_cpt, bitakora_cpt): if REQUEST is not None: return REQUEST.RESPONSE.redirect(self.absolute_url()+u'?msg=%s&body=%s&comment_author=%s&comment_email=%s&comment_url=%s#bitakora_cpt_control' % (self.gettext('Are you a bot? Please try again...'), url_quote(body.encode('utf-8')), url_quote(author.encode('utf-8')), url_quote(email.encode('utf-8')), url_quote(url.encode('utf-8'))))","__version__ = ""$Revision$"" def manage_addComment(self, author, body, url='', email='', date=None, bitakora_cpt='', random_cpt='', captcha_zz=0, REQUEST=None): """""" Called from HTML form when commenting """""" from utils import checkCaptchaValue, isCommentSpam if captcha_zz: if not checkCaptchaValue(random_cpt, bitakora_cpt): if REQUEST is not None: return REQUEST.RESPONSE.redirect(self.absolute_url()+u'?msg=%s&body=%s&comment_author=%s&comment_email=%s&comment_url=%s#bitakora_cpt_control' % (self.gettext('Are you a bot? Please try again...'), url_quote(body.encode('utf-8')), url_quote(author.encode('utf-8')), url_quote(email.encode('utf-8')), url_quote(url.encode('utf-8'))))" 719,https://:@gitlab.com/saltspiro/spiro-deploy.git,660c01a080bb7c82a593146ca85c3d04f237881a,"@@ -112,7 +112,7 @@ def main(argv=sys.argv[1:]): print(event, pprint.pformat(data), flush=True) if event == 'highstate-start': - minions += set(data['minions']) + minions |= set(data['minions']) elif event == 'highstate': minions.discard(data['minion']) ",spirodeploy/cli.py,"ReplaceText(target='|=' @(115,20)->(115,22))","def main(argv=sys.argv[1:]): print(event, pprint.pformat(data), flush=True) if event == 'highstate-start': minions += set(data['minions']) elif event == 'highstate': minions.discard(data['minion']) ","def main(argv=sys.argv[1:]): print(event, pprint.pformat(data), flush=True) if event == 'highstate-start': minions |= set(data['minions']) elif event == 'highstate': minions.discard(data['minion']) " 720,https://:@github.com/ymoch/preacher.git,5b49e834eb2c9ea03ba9619b9fb0cb2120ff68a7,"@@ -142,7 +142,7 @@ class Case: response_verification = self._response.verify( response, - ValueContext(origin_datetime=response.starts), + ValueContext(origin_datetime=execution.starts), ) return CaseResult( label=self._label, ",preacher/core/scenario/case.py,"ReplaceText(target='execution' @(145,41)->(145,49))","class Case: response_verification = self._response.verify( response, ValueContext(origin_datetime=response.starts), ) return CaseResult( label=self._label,","class Case: response_verification = self._response.verify( response, ValueContext(origin_datetime=execution.starts), ) return CaseResult( label=self._label," 721,https://:@gitlab.com/socco/GliderTools.git,c0a6ae0924dabda3ddd6c03947a4038554e90eb1,"@@ -468,7 +468,7 @@ def savitzky_golay(arr, window_size, order, deriv=0, rate=1, interpolate=True): # allow to interpolate for half the window size if interpolate: - ser = Series(arr).interpolate(limit=half_window) + ser = Series(arr).interpolate(limit=window_size) y = array(ser) else: y = array(arr) ",buoyancy_glider_utils/cleaning.py,"ReplaceText(target='window_size' @(471,44)->(471,55))","def savitzky_golay(arr, window_size, order, deriv=0, rate=1, interpolate=True): # allow to interpolate for half the window size if interpolate: ser = Series(arr).interpolate(limit=half_window) y = array(ser) else: y = array(arr)","def savitzky_golay(arr, window_size, order, deriv=0, rate=1, interpolate=True): # allow to interpolate for half the window size if interpolate: ser = Series(arr).interpolate(limit=window_size) y = array(ser) else: y = array(arr)" 722,https://:@github.com/hattya/scmver.git,9fc6568b7fc7814e4659e4140da9ffcfe69321ca,"@@ -95,7 +95,7 @@ def _is_wc_root(root, info): p = os.path.dirname(root) return (p == root or not os.path.isdir(os.path.join(p, '.svn')) - or _info(p).get('Repository UUID') == info['Repository UUID']) + or _info(p).get('Repository UUID') != info['Repository UUID']) return False ",scmver/subversion.py,"ReplaceText(target='!=' @(98,51)->(98,53))","def _is_wc_root(root, info): p = os.path.dirname(root) return (p == root or not os.path.isdir(os.path.join(p, '.svn')) or _info(p).get('Repository UUID') == info['Repository UUID']) return False ","def _is_wc_root(root, info): p = os.path.dirname(root) return (p == root or not os.path.isdir(os.path.join(p, '.svn')) or _info(p).get('Repository UUID') != info['Repository UUID']) return False " 723,https://:@github.com/h0m3/python-mprint.git,782bec1d992d0ee19c8f0128d83ad4b9069bee3f,"@@ -82,7 +82,7 @@ def markup(string): ) newString += string.split("">"", 1)[1] string = newString - return newString + return string # Print markup characters to screen ",mprint/mprint.py,"ReplaceText(target='string' @(85,11)->(85,20))","def markup(string): ) newString += string.split("">"", 1)[1] string = newString return newString # Print markup characters to screen","def markup(string): ) newString += string.split("">"", 1)[1] string = newString return string # Print markup characters to screen" 724,https://:@github.com/brettviren/worch.git,7941cffa22b2e9933e57139329e3c9d9cf555623,"@@ -31,7 +31,7 @@ def feature_command(tgen): cmd_dir = tgen.make_node(tgen.worch.command_dir) cmd_node = cmd_dir.make_node(tgen.worch.command_cmd) cmd_target = \ - map(cmd_dir.make_node, tgen.to_list(tgen.worch.command_target)) + map(tgen.make_node, tgen.to_list(tgen.worch.command_target)) cmd_rule = '{command_cmd_prefix}{command_cmd} {command_cmd_options} {command_cmd_postfix}' tgen.step('command', rule = tgen.worch.format(cmd_rule), ",orch/features/feature_command.py,"ReplaceText(target='tgen' @(34,12)->(34,19))","def feature_command(tgen): cmd_dir = tgen.make_node(tgen.worch.command_dir) cmd_node = cmd_dir.make_node(tgen.worch.command_cmd) cmd_target = \ map(cmd_dir.make_node, tgen.to_list(tgen.worch.command_target)) cmd_rule = '{command_cmd_prefix}{command_cmd} {command_cmd_options} {command_cmd_postfix}' tgen.step('command', rule = tgen.worch.format(cmd_rule),","def feature_command(tgen): cmd_dir = tgen.make_node(tgen.worch.command_dir) cmd_node = cmd_dir.make_node(tgen.worch.command_cmd) cmd_target = \ map(tgen.make_node, tgen.to_list(tgen.worch.command_target)) cmd_rule = '{command_cmd_prefix}{command_cmd} {command_cmd_options} {command_cmd_postfix}' tgen.step('command', rule = tgen.worch.format(cmd_rule)," 725,https://:@github.com/slipguru/icing.git,a292074640464c3c407850db151595153d28cf0f,"@@ -109,7 +109,7 @@ def sim_function(ig1, ig2, method='jaccard', model='ham', correction = correction_function(max(ig1.mut, ig2.mut)) # ss = 1 - ((1 - ss) * max(correction, 0)) # ss = 1 - ((1 - ss) * correction) - ss *= correction + ss += correction # return min(max(ss, 0), 1) return max(ss, 0) ",icing/core/cloning.py,"ReplaceText(target='+=' @(112,11)->(112,13))","def sim_function(ig1, ig2, method='jaccard', model='ham', correction = correction_function(max(ig1.mut, ig2.mut)) # ss = 1 - ((1 - ss) * max(correction, 0)) # ss = 1 - ((1 - ss) * correction) ss *= correction # return min(max(ss, 0), 1) return max(ss, 0) ","def sim_function(ig1, ig2, method='jaccard', model='ham', correction = correction_function(max(ig1.mut, ig2.mut)) # ss = 1 - ((1 - ss) * max(correction, 0)) # ss = 1 - ((1 - ss) * correction) ss += correction # return min(max(ss, 0), 1) return max(ss, 0) " 726,https://:@github.com/slipguru/icing.git,7179403bf32d1f649ef7ea63a060ecd4ffb5a9e6,"@@ -109,7 +109,7 @@ def sim_function(ig1, ig2, method='jaccard', model='ham', correction = correction_function(max(ig1.mut, ig2.mut)) # ss = 1 - ((1 - ss) * max(correction, 0)) # ss = 1 - ((1 - ss) * correction) - ss += (1. - correction) + ss *= (1. - correction) # return min(max(ss, 0), 1) return max(ss, 0) ",icing/core/cloning.py,"ReplaceText(target='*=' @(112,11)->(112,13))","def sim_function(ig1, ig2, method='jaccard', model='ham', correction = correction_function(max(ig1.mut, ig2.mut)) # ss = 1 - ((1 - ss) * max(correction, 0)) # ss = 1 - ((1 - ss) * correction) ss += (1. - correction) # return min(max(ss, 0), 1) return max(ss, 0) ","def sim_function(ig1, ig2, method='jaccard', model='ham', correction = correction_function(max(ig1.mut, ig2.mut)) # ss = 1 - ((1 - ss) * max(correction, 0)) # ss = 1 - ((1 - ss) * correction) ss *= (1. - correction) # return min(max(ss, 0), 1) return max(ss, 0) " 727,https://:@github.com/jojoduquartier/dsdbmanager.git,d074b1099d1bb9b729760d42e36aaae1944c64c7,"@@ -246,7 +246,7 @@ class DbMiddleware(object): def __init__(self, engine, connect_only, schema): self.engine = engine - if connect_only: + if not connect_only: inspection = reflection.Inspector.from_engine(self.engine) views = inspection.get_view_names(schema=schema) tables = inspection.get_table_names(schema=schema) ",dsdbmanager/dbobject.py,"ReplaceText(target='not ' @(249,11)->(249,11))","class DbMiddleware(object): def __init__(self, engine, connect_only, schema): self.engine = engine if connect_only: inspection = reflection.Inspector.from_engine(self.engine) views = inspection.get_view_names(schema=schema) tables = inspection.get_table_names(schema=schema)","class DbMiddleware(object): def __init__(self, engine, connect_only, schema): self.engine = engine if not connect_only: inspection = reflection.Inspector.from_engine(self.engine) views = inspection.get_view_names(schema=schema) tables = inspection.get_table_names(schema=schema)" 728,https://:@gitlab.com/HartkopfF/Purple.git,d8b25ebbe423fb005169913d63410713eb5a49ec,"@@ -414,7 +414,7 @@ def print_result(peps, print_peps,threshold): # prints flagged peptides in console, if print_peps == True # peptides are flagged, if they are greater than the average of all positive scores scores = list(peps.values()) - scores_in_tens = [int(round(i, -1)) if i >= threshold else -1 for i in scores] # only round positiv scores + scores_in_tens = [int(round(i, -1)) if i <= threshold else -1 for i in scores] # only round positiv scores freq_scores = {x: scores_in_tens.count(x) for x in scores_in_tens} # Dictionary Comprehension if print_peps == 1: ",src/Purple_methods.py,"ReplaceText(target='<=' @(417,45)->(417,47))","def print_result(peps, print_peps,threshold): # prints flagged peptides in console, if print_peps == True # peptides are flagged, if they are greater than the average of all positive scores scores = list(peps.values()) scores_in_tens = [int(round(i, -1)) if i >= threshold else -1 for i in scores] # only round positiv scores freq_scores = {x: scores_in_tens.count(x) for x in scores_in_tens} # Dictionary Comprehension if print_peps == 1:","def print_result(peps, print_peps,threshold): # prints flagged peptides in console, if print_peps == True # peptides are flagged, if they are greater than the average of all positive scores scores = list(peps.values()) scores_in_tens = [int(round(i, -1)) if i <= threshold else -1 for i in scores] # only round positiv scores freq_scores = {x: scores_in_tens.count(x) for x in scores_in_tens} # Dictionary Comprehension if print_peps == 1:" 729,https://:@github.com/bjoernricks/python-quilt.git,2a4e97b554669b95bb1d22f220ac2d7ba6df9012,"@@ -46,7 +46,7 @@ class Import(Command): """""" Import patch into the patch queue The patch is inserted after the current top applied patch """""" - if not new_name: + if new_name: dir_name = os.path.dirname(new_name) name = os.path.basename(new_name) dest_dir = self.quilt_patches + Directory(dir_name) ",quilt/patchimport.py,"ReplaceText(target='' @(49,11)->(49,15))","class Import(Command): """""" Import patch into the patch queue The patch is inserted after the current top applied patch """""" if not new_name: dir_name = os.path.dirname(new_name) name = os.path.basename(new_name) dest_dir = self.quilt_patches + Directory(dir_name)","class Import(Command): """""" Import patch into the patch queue The patch is inserted after the current top applied patch """""" if new_name: dir_name = os.path.dirname(new_name) name = os.path.basename(new_name) dest_dir = self.quilt_patches + Directory(dir_name)" 730,https://:@github.com/bjoernricks/python-quilt.git,1c2a80d50b73cf182574c0e1f0d7aa5b6ab91631,"@@ -93,7 +93,7 @@ class Push(Command): applied = self.db.applied_patches() for patch in applied: if patch in patches: - patches.remove(applied) + patches.remove(patch) if not patches: raise AllPatchesApplied(self.series, self.db.top_patch()) ",quilt/push.py,"ReplaceText(target='patch' @(96,31)->(96,38))","class Push(Command): applied = self.db.applied_patches() for patch in applied: if patch in patches: patches.remove(applied) if not patches: raise AllPatchesApplied(self.series, self.db.top_patch())","class Push(Command): applied = self.db.applied_patches() for patch in applied: if patch in patches: patches.remove(patch) if not patches: raise AllPatchesApplied(self.series, self.db.top_patch())" 731,https://:@github.com/HypothesisWorks/hypothesis-python.git,7d201f06333b185a25a5d77df7a01d08790655cb,"@@ -69,7 +69,7 @@ def test_a_verifier_saves_any_failing_examples_in_its_database(): def test_a_verifier_retrieves_previous_failing_examples_from_the_database(): database = ExampleDatabase() verifier = Verifier(settings=hs.Settings(database=database)) - verifier.falsify(lambda x: x != 11, int) + verifier.falsify(lambda x: x < 11, int) called = [] def save_calls(t): ",tests/test_database.py,"ReplaceText(target='<' @(72,33)->(72,35))","def test_a_verifier_saves_any_failing_examples_in_its_database(): def test_a_verifier_retrieves_previous_failing_examples_from_the_database(): database = ExampleDatabase() verifier = Verifier(settings=hs.Settings(database=database)) verifier.falsify(lambda x: x != 11, int) called = [] def save_calls(t):","def test_a_verifier_saves_any_failing_examples_in_its_database(): def test_a_verifier_retrieves_previous_failing_examples_from_the_database(): database = ExampleDatabase() verifier = Verifier(settings=hs.Settings(database=database)) verifier.falsify(lambda x: x < 11, int) called = [] def save_calls(t):" 732,https://:@github.com/HypothesisWorks/hypothesis-python.git,b5a59b2e474f1f2bcff898aeeba9cc3ca2e5d186,"@@ -89,7 +89,7 @@ class TestRunner(object): raise RunIsComplete() self.examples_considered += 1 if ( - buffer[:self.last_data.index] == + buffer[:self.last_data.index] >= self.last_data.buffer[:self.last_data.index] ): return False ",src/hypothesis/internal/conjecture/engine.py,"ReplaceText(target='>=' @(92,42)->(92,44))","class TestRunner(object): raise RunIsComplete() self.examples_considered += 1 if ( buffer[:self.last_data.index] == self.last_data.buffer[:self.last_data.index] ): return False","class TestRunner(object): raise RunIsComplete() self.examples_considered += 1 if ( buffer[:self.last_data.index] >= self.last_data.buffer[:self.last_data.index] ): return False" 733,https://:@github.com/HypothesisWorks/hypothesis-python.git,5f990a2d351ad02ac698375428c54c86b907f505,"@@ -686,7 +686,7 @@ def characters(whitelist_categories=None, blacklist_categories=None, if ( whitelist_characters is not None and blacklist_characters is not None and - set(whitelist_characters).intersection(set(whitelist_characters)) + set(blacklist_characters).intersection(set(whitelist_characters)) ): raise InvalidArgument( 'Cannot have characters in both whitelist_characters=%r, ' ",src/hypothesis/strategies.py,"ReplaceText(target='blacklist_characters' @(689,12)->(689,32))","def characters(whitelist_categories=None, blacklist_categories=None, if ( whitelist_characters is not None and blacklist_characters is not None and set(whitelist_characters).intersection(set(whitelist_characters)) ): raise InvalidArgument( 'Cannot have characters in both whitelist_characters=%r, '","def characters(whitelist_categories=None, blacklist_categories=None, if ( whitelist_characters is not None and blacklist_characters is not None and set(blacklist_characters).intersection(set(whitelist_characters)) ): raise InvalidArgument( 'Cannot have characters in both whitelist_characters=%r, '" 734,https://:@github.com/HypothesisWorks/hypothesis-python.git,5bd4086b1be92933cef2bb61f98770df1114ed7a,"@@ -691,7 +691,7 @@ def characters(whitelist_categories=None, blacklist_categories=None, raise InvalidArgument( 'Cannot have characters in both whitelist_characters=%r, ' 'and blacklist_characters=%r' % ( - whitelist_characters, blacklist_categories, + whitelist_characters, blacklist_characters, ) ) ",src/hypothesis/strategies.py,"ReplaceText(target='blacklist_characters' @(694,38)->(694,58))","def characters(whitelist_categories=None, blacklist_categories=None, raise InvalidArgument( 'Cannot have characters in both whitelist_characters=%r, ' 'and blacklist_characters=%r' % ( whitelist_characters, blacklist_categories, ) ) ","def characters(whitelist_categories=None, blacklist_categories=None, raise InvalidArgument( 'Cannot have characters in both whitelist_characters=%r, ' 'and blacklist_characters=%r' % ( whitelist_characters, blacklist_characters, ) ) " 735,https://:@github.com/HypothesisWorks/hypothesis-python.git,a10d8cf98473dbdaedf1d317c8ad2d51b38699fe,"@@ -30,7 +30,7 @@ if __name__ == '__main__': if ( os.environ['CIRCLE_BRANCH'] != 'master' and - os.environ['CI_PULL_REQUEST'] != '' + os.environ['CI_PULL_REQUEST'] == '' ): print('We only run CI builds on the master branch or in pull requests') sys.exit(0) ",scripts/run_circle.py,"ReplaceText(target='==' @(33,38)->(33,40))","if __name__ == '__main__': if ( os.environ['CIRCLE_BRANCH'] != 'master' and os.environ['CI_PULL_REQUEST'] != '' ): print('We only run CI builds on the master branch or in pull requests') sys.exit(0)","if __name__ == '__main__': if ( os.environ['CIRCLE_BRANCH'] != 'master' and os.environ['CI_PULL_REQUEST'] == '' ): print('We only run CI builds on the master branch or in pull requests') sys.exit(0)" 736,https://:@github.com/HypothesisWorks/hypothesis-python.git,8f9b8211e5c7b3d6e791bc9203e12b494eba9d64,"@@ -1119,7 +1119,7 @@ def find(specifier, condition, settings=None, random=None, database_key=None): if success: successful_examples[0] += 1 - if settings.verbosity == Verbosity.verbose: + if settings.verbosity >= Verbosity.verbose: if not successful_examples[0]: report( u'Tried non-satisfying example %s' % (nicerepr(result),)) ",hypothesis-python/src/hypothesis/core.py,"ReplaceText(target='>=' @(1122,30)->(1122,32))","def find(specifier, condition, settings=None, random=None, database_key=None): if success: successful_examples[0] += 1 if settings.verbosity == Verbosity.verbose: if not successful_examples[0]: report( u'Tried non-satisfying example %s' % (nicerepr(result),))","def find(specifier, condition, settings=None, random=None, database_key=None): if success: successful_examples[0] += 1 if settings.verbosity >= Verbosity.verbose: if not successful_examples[0]: report( u'Tried non-satisfying example %s' % (nicerepr(result),))" 737,https://:@github.com/HypothesisWorks/hypothesis-python.git,8a912d3d94dbd45ada80476bfbf11eea334ec48d,"@@ -119,7 +119,7 @@ def assert_can_release(): def has_travis_secrets(): - return os.environ.get('TRAVIS_SECURE_ENV_VARS', None) != 'true' + return os.environ.get('TRAVIS_SECURE_ENV_VARS', None) == 'true' def build_jobs(): ",tooling/src/hypothesistooling/__init__.py,"ReplaceText(target='==' @(122,58)->(122,60))","def assert_can_release(): def has_travis_secrets(): return os.environ.get('TRAVIS_SECURE_ENV_VARS', None) != 'true' def build_jobs():","def assert_can_release(): def has_travis_secrets(): return os.environ.get('TRAVIS_SECURE_ENV_VARS', None) == 'true' def build_jobs():" 738,https://:@github.com/HypothesisWorks/hypothesis-python.git,3dba57307b412696b30f86eb7d0fdb189421b5c7,"@@ -2209,7 +2209,7 @@ class Shrinker(object): u, v = self.blocks[i] b = int_from_bytes(self.shrink_target.buffer[u:v]) lowered = b - offset - if lowered <= 0: + if lowered < 0: continue attempt = bytearray(self.shrink_target.buffer) attempt[u:v] = int_to_bytes(lowered, v - u) ",hypothesis-python/src/hypothesis/internal/conjecture/engine.py,"ReplaceText(target='<' @(2212,27)->(2212,29))","class Shrinker(object): u, v = self.blocks[i] b = int_from_bytes(self.shrink_target.buffer[u:v]) lowered = b - offset if lowered <= 0: continue attempt = bytearray(self.shrink_target.buffer) attempt[u:v] = int_to_bytes(lowered, v - u)","class Shrinker(object): u, v = self.blocks[i] b = int_from_bytes(self.shrink_target.buffer[u:v]) lowered = b - offset if lowered < 0: continue attempt = bytearray(self.shrink_target.buffer) attempt[u:v] = int_to_bytes(lowered, v - u)" 739,https://:@github.com/HypothesisWorks/hypothesis-python.git,a55eeda06ec2650b446a3ef0885a4f765d0c5513,"@@ -317,7 +317,7 @@ class settings( bits = [] for name, setting in all_settings.items(): value = getattr(self, name) - if value != setting.default or not setting.hide_repr: + if value != setting.default and not setting.hide_repr: bits.append('%s=%r' % (name, value)) return 'settings(%s)' % ', '.join(sorted(bits)) ",hypothesis-python/src/hypothesis/_settings.py,"ReplaceText(target='and' @(320,40)->(320,42))","class settings( bits = [] for name, setting in all_settings.items(): value = getattr(self, name) if value != setting.default or not setting.hide_repr: bits.append('%s=%r' % (name, value)) return 'settings(%s)' % ', '.join(sorted(bits)) ","class settings( bits = [] for name, setting in all_settings.items(): value = getattr(self, name) if value != setting.default and not setting.hide_repr: bits.append('%s=%r' % (name, value)) return 'settings(%s)' % ', '.join(sorted(bits)) " 740,https://:@github.com/HypothesisWorks/hypothesis-python.git,feaa70b9ee7e4659bb31bcbd0bd6077c179516bf,"@@ -439,7 +439,7 @@ class StepCounter(RuleBasedStateMachine): self.step_count += 1 def teardown(self): - assert self.step_count == settings_step_count + assert self.step_count <= settings_step_count test_settings_decorator_applies_to_rule_based_state_machine_class = \ ",hypothesis-python/tests/cover/test_settings.py,"ReplaceText(target='<=' @(442,31)->(442,33))","class StepCounter(RuleBasedStateMachine): self.step_count += 1 def teardown(self): assert self.step_count == settings_step_count test_settings_decorator_applies_to_rule_based_state_machine_class = \","class StepCounter(RuleBasedStateMachine): self.step_count += 1 def teardown(self): assert self.step_count <= settings_step_count test_settings_decorator_applies_to_rule_based_state_machine_class = \" 741,https://:@github.com/HypothesisWorks/hypothesis-python.git,012cdca96f6f3887bc5a93f5a1efaf4f58cde27d,"@@ -656,7 +656,7 @@ def sampled_from(elements): return sets(sampled_from(values), min_size=1).map( lambda s: reduce(operator.or_, s) ) - return SampledFromStrategy(values) + return SampledFromStrategy(elements) @cacheable ",hypothesis-python/src/hypothesis/strategies/_internal/core.py,"ReplaceText(target='elements' @(659,31)->(659,37))","def sampled_from(elements): return sets(sampled_from(values), min_size=1).map( lambda s: reduce(operator.or_, s) ) return SampledFromStrategy(values) @cacheable","def sampled_from(elements): return sets(sampled_from(values), min_size=1).map( lambda s: reduce(operator.or_, s) ) return SampledFromStrategy(elements) @cacheable" 742,https://:@github.com/HypothesisWorks/hypothesis-python.git,a9c5902f94250156d80baff42da96e9d08778d26,"@@ -1842,7 +1842,7 @@ def complex_numbers( # Order of conditions carefully tuned so that for a given pair of # magnitude arguments, we always either draw or do not draw the bool # (crucial for good shrinking behaviour) but only invert when needed. - if min_magnitude != 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude: + if min_magnitude > 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude: zr = -zr return complex(zr, zi) ",hypothesis-python/src/hypothesis/strategies/_internal/core.py,"ReplaceText(target='>' @(1845,25)->(1845,27))","def complex_numbers( # Order of conditions carefully tuned so that for a given pair of # magnitude arguments, we always either draw or do not draw the bool # (crucial for good shrinking behaviour) but only invert when needed. if min_magnitude != 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude: zr = -zr return complex(zr, zi) ","def complex_numbers( # Order of conditions carefully tuned so that for a given pair of # magnitude arguments, we always either draw or do not draw the bool # (crucial for good shrinking behaviour) but only invert when needed. if min_magnitude > 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude: zr = -zr return complex(zr, zi) " 743,https://:@github.com/pyfa-org/eos.git,4a87a594d189c71e916538d04026dc470cc12313,"@@ -418,7 +418,7 @@ class InfoBuilder: # Negate condition for else clause processing # We do not need to recombine it with conditions passed to our method, # as condition being reverted is part of combined tree - self.__invertCondition(currentConditions) + self.__invertCondition(newConditions) self.__generic(elseClause, deepcopy(currentConditions)) def __makeConditionRouter(self, element): ",data/effect/builder/builder.py,"ReplaceText(target='newConditions' @(421,31)->(421,48))","class InfoBuilder: # Negate condition for else clause processing # We do not need to recombine it with conditions passed to our method, # as condition being reverted is part of combined tree self.__invertCondition(currentConditions) self.__generic(elseClause, deepcopy(currentConditions)) def __makeConditionRouter(self, element):","class InfoBuilder: # Negate condition for else clause processing # We do not need to recombine it with conditions passed to our method, # as condition being reverted is part of combined tree self.__invertCondition(newConditions) self.__generic(elseClause, deepcopy(currentConditions)) def __makeConditionRouter(self, element):" 744,https://:@github.com/pyfa-org/eos.git,23c14ff52c9ab1a52ca35887ca043680046dcaf7,"@@ -38,7 +38,7 @@ class TestSkillUniqueness(RestrictionTestCase): restrictionError1 = fit.getRestrictionError(skill1, Restriction.skillUniqueness) self.assertIsNotNone(restrictionError1) self.assertEqual(restrictionError1.skill, 56) - restrictionError2 = fit.getRestrictionError(skill1, Restriction.skillUniqueness) + restrictionError2 = fit.getRestrictionError(skill2, Restriction.skillUniqueness) self.assertIsNotNone(restrictionError2) self.assertEqual(restrictionError2.skill, 56) fit.items.remove(skill1) ",tests/restrictionTracker/restrictions/testSkillUniqueness.py,"ReplaceText(target='skill2' @(41,52)->(41,58))","class TestSkillUniqueness(RestrictionTestCase): restrictionError1 = fit.getRestrictionError(skill1, Restriction.skillUniqueness) self.assertIsNotNone(restrictionError1) self.assertEqual(restrictionError1.skill, 56) restrictionError2 = fit.getRestrictionError(skill1, Restriction.skillUniqueness) self.assertIsNotNone(restrictionError2) self.assertEqual(restrictionError2.skill, 56) fit.items.remove(skill1)","class TestSkillUniqueness(RestrictionTestCase): restrictionError1 = fit.getRestrictionError(skill1, Restriction.skillUniqueness) self.assertIsNotNone(restrictionError1) self.assertEqual(restrictionError1.skill, 56) restrictionError2 = fit.getRestrictionError(skill2, Restriction.skillUniqueness) self.assertIsNotNone(restrictionError2) self.assertEqual(restrictionError2.skill, 56) fit.items.remove(skill1)" 745,https://:@github.com/pyfa-org/eos.git,ec16898d0f6e700159a14af551196f3d7e31aa43,"@@ -52,7 +52,7 @@ class SlotIndexRegister(RestrictionRegister): def registerHolder(self, holder): # Skip items which don't have index specifier slotIndex = holder.item.attributes.get(self.__slotIndexAttr) - if slotIndex is not None: + if slotIndex is None: return self.__slottedHolders.addData(slotIndex, holder) ",fit/restrictionTracker/restriction/slotIndex.py,"ReplaceText(target=' is ' @(55,20)->(55,28))","class SlotIndexRegister(RestrictionRegister): def registerHolder(self, holder): # Skip items which don't have index specifier slotIndex = holder.item.attributes.get(self.__slotIndexAttr) if slotIndex is not None: return self.__slottedHolders.addData(slotIndex, holder) ","class SlotIndexRegister(RestrictionRegister): def registerHolder(self, holder): # Skip items which don't have index specifier slotIndex = holder.item.attributes.get(self.__slotIndexAttr) if slotIndex is None: return self.__slottedHolders.addData(slotIndex, holder) " 746,https://:@github.com/pyfa-org/eos.git,e8ea4b04ff260c186d55ece03df22dbd6aa509e9,"@@ -61,7 +61,7 @@ class ResourceRegister(RestrictionRegister): # Can be None, so fall back to 0 in this case output = stats.output or 0 # If we're not out of resource, do nothing - if totalUse > output: + if totalUse <= output: return taintedHolders = {} for holder in self.__resourceUsers: ",fit/restrictionTracker/restriction/resource.py,"ReplaceText(target='<=' @(64,20)->(64,21))","class ResourceRegister(RestrictionRegister): # Can be None, so fall back to 0 in this case output = stats.output or 0 # If we're not out of resource, do nothing if totalUse > output: return taintedHolders = {} for holder in self.__resourceUsers:","class ResourceRegister(RestrictionRegister): # Can be None, so fall back to 0 in this case output = stats.output or 0 # If we're not out of resource, do nothing if totalUse <= output: return taintedHolders = {} for holder in self.__resourceUsers:" 747,https://:@github.com/pyfa-org/eos.git,700a4414cab25efe4e306e64c9cee28250f7363a,"@@ -151,7 +151,7 @@ class MsgHelper: # Unapply effects from targets tgt_getter = getattr(item, '_get_effects_tgts', None) if tgt_getter: - effects_tgts = tgt_getter(start_ids) + effects_tgts = tgt_getter(stop_ids) for effect_id, tgt_items in effects_tgts.items(): msgs.append(EffectUnapplied(item, effect_id, tgt_items)) # Stop effects ",eos/pubsub/message/helper.py,"ReplaceText(target='stop_ids' @(154,42)->(154,51))","class MsgHelper: # Unapply effects from targets tgt_getter = getattr(item, '_get_effects_tgts', None) if tgt_getter: effects_tgts = tgt_getter(start_ids) for effect_id, tgt_items in effects_tgts.items(): msgs.append(EffectUnapplied(item, effect_id, tgt_items)) # Stop effects","class MsgHelper: # Unapply effects from targets tgt_getter = getattr(item, '_get_effects_tgts', None) if tgt_getter: effects_tgts = tgt_getter(stop_ids) for effect_id, tgt_items in effects_tgts.items(): msgs.append(EffectUnapplied(item, effect_id, tgt_items)) # Stop effects" 748,https://:@github.com/Hasenpfote/fpq.git,8220505c7830967477a5502c061d9efd91d66ae8,"@@ -58,7 +58,7 @@ def encode_fp_to_snorm(x, *, dtype=np.uint8, nbits=None): if nbits is None: nbits = max_nbits assert (0 < nbits <= max_nbits), '`nbits` value is out of range.' - mask = np.invert(dtype(np.iinfo(nbits).max) << dtype(nbits)) + mask = np.invert(dtype(np.iinfo(dtype).max) << dtype(nbits)) return dtype(np.around(x * x.dtype.type((1 << (nbits-1)) - 1))) & mask def decode_snorm_to_fp(x, *, dtype=np.float32, nbits=None): ",fpq/d3d.py,"ReplaceText(target='dtype' @(61,36)->(61,41))","def encode_fp_to_snorm(x, *, dtype=np.uint8, nbits=None): if nbits is None: nbits = max_nbits assert (0 < nbits <= max_nbits), '`nbits` value is out of range.' mask = np.invert(dtype(np.iinfo(nbits).max) << dtype(nbits)) return dtype(np.around(x * x.dtype.type((1 << (nbits-1)) - 1))) & mask def decode_snorm_to_fp(x, *, dtype=np.float32, nbits=None):","def encode_fp_to_snorm(x, *, dtype=np.uint8, nbits=None): if nbits is None: nbits = max_nbits assert (0 < nbits <= max_nbits), '`nbits` value is out of range.' mask = np.invert(dtype(np.iinfo(dtype).max) << dtype(nbits)) return dtype(np.around(x * x.dtype.type((1 << (nbits-1)) - 1))) & mask def decode_snorm_to_fp(x, *, dtype=np.float32, nbits=None):" 749,https://:@github.com/theodo/flask-restful.git,4dfe49f1de3dfd9598b4ae92b9e6b6644fa999f7,"@@ -338,7 +338,7 @@ class APITestCase(unittest.TestCase): def record(sender, exception): recorded.append(exception) - got_request_exception.connect(record, api) + got_request_exception.connect(record, app) try: with app.test_request_context(""/foo""): api.handle_error(exception) ",tests/test_api.py,"ReplaceText(target='app' @(341,46)->(341,49))","class APITestCase(unittest.TestCase): def record(sender, exception): recorded.append(exception) got_request_exception.connect(record, api) try: with app.test_request_context(""/foo""): api.handle_error(exception)","class APITestCase(unittest.TestCase): def record(sender, exception): recorded.append(exception) got_request_exception.connect(record, app) try: with app.test_request_context(""/foo""): api.handle_error(exception)" 750,https://:@github.com/askholme/django_minifiedstorage.git,0f7821618021d7fb4497a0ddd4312fbbc4e41262,"@@ -45,7 +45,7 @@ class MinifiedManifestStaticFilesStorage(ManifestStaticFilesStorage): # save gziped file as fell, we overwrite the content_file variable to save a tiny bit memory try: content = zlib_compress(content) - super(MinifiedManifestStaticFilesStorage, self)._save(""%s.gz"" % hashed_name,ContentFile(content)) + super(MinifiedManifestStaticFilesStorage, self)._save(""%s.gz"" % saved_name,ContentFile(content)) except Exception as e: raise MinifiedStorageException(""Could not gzip file %s, error: %s"" % (hashed_name,e,)) return saved_name \ No newline at end of file ",minifiedstorage/storages.py,"ReplaceText(target='saved_name' @(48,80)->(48,91))","class MinifiedManifestStaticFilesStorage(ManifestStaticFilesStorage): # save gziped file as fell, we overwrite the content_file variable to save a tiny bit memory try: content = zlib_compress(content) super(MinifiedManifestStaticFilesStorage, self)._save(""%s.gz"" % hashed_name,ContentFile(content)) except Exception as e: raise MinifiedStorageException(""Could not gzip file %s, error: %s"" % (hashed_name,e,)) return saved_name \ No newline at end of file","class MinifiedManifestStaticFilesStorage(ManifestStaticFilesStorage): # save gziped file as fell, we overwrite the content_file variable to save a tiny bit memory try: content = zlib_compress(content) super(MinifiedManifestStaticFilesStorage, self)._save(""%s.gz"" % saved_name,ContentFile(content)) except Exception as e: raise MinifiedStorageException(""Could not gzip file %s, error: %s"" % (hashed_name,e,)) return saved_name \ No newline at end of file" 751,https://:@github.com/SiLab-Bonn/pymosa.git,07741f8afef86a85bf61c13aa8733f6f211195ae,"@@ -133,7 +133,7 @@ class TluTuning(m26): # Determine best delay setting (center of working delay settings) good_indices = np.where(np.logical_and(data_array['error_rate'][:-1] == 0, np.diff(data_array['error_rate']) == 0))[0] - best_index = good_indices[good_indices.shape[0] / 2] + best_index = good_indices[good_indices.shape[0] // 2] best_delay_setting = data_array['TRIGGER_DATA_DELAY'][best_index] logging.info('The best delay setting for this setup is %d', best_delay_setting) ",pymosa/tune_tlu.py,"ReplaceText(target='//' @(136,68)->(136,69))","class TluTuning(m26): # Determine best delay setting (center of working delay settings) good_indices = np.where(np.logical_and(data_array['error_rate'][:-1] == 0, np.diff(data_array['error_rate']) == 0))[0] best_index = good_indices[good_indices.shape[0] / 2] best_delay_setting = data_array['TRIGGER_DATA_DELAY'][best_index] logging.info('The best delay setting for this setup is %d', best_delay_setting) ","class TluTuning(m26): # Determine best delay setting (center of working delay settings) good_indices = np.where(np.logical_and(data_array['error_rate'][:-1] == 0, np.diff(data_array['error_rate']) == 0))[0] best_index = good_indices[good_indices.shape[0] // 2] best_delay_setting = data_array['TRIGGER_DATA_DELAY'][best_index] logging.info('The best delay setting for this setup is %d', best_delay_setting) " 752,https://:@github.com/dripton/Slugathon.git,641fc1e43403827b046dc1fe69cb6da162d9a83c,"@@ -70,7 +70,7 @@ class Marker(object): label = str(self.height) text_width, text_height = draw.textsize(label, font=font) x = 0.65 * leng - 0.5 * text_width - y = 0.55 * leng - 0.5 * text_width + y = 0.55 * leng - 0.5 * text_height draw.rectangle(((x + 0.1 * text_width, y + 0.1 * text_height), (x + 0.9 * text_width, y + 0.9 * text_height)), fill=white) draw.text((x, y), label, fill=black, font=font) ",slugathon/Marker.py,"ReplaceText(target='text_height' @(73,32)->(73,42))","class Marker(object): label = str(self.height) text_width, text_height = draw.textsize(label, font=font) x = 0.65 * leng - 0.5 * text_width y = 0.55 * leng - 0.5 * text_width draw.rectangle(((x + 0.1 * text_width, y + 0.1 * text_height), (x + 0.9 * text_width, y + 0.9 * text_height)), fill=white) draw.text((x, y), label, fill=black, font=font)","class Marker(object): label = str(self.height) text_width, text_height = draw.textsize(label, font=font) x = 0.65 * leng - 0.5 * text_width y = 0.55 * leng - 0.5 * text_height draw.rectangle(((x + 0.1 * text_width, y + 0.1 * text_height), (x + 0.9 * text_width, y + 0.9 * text_height)), fill=white) draw.text((x, y), label, fill=black, font=font)" 753,https://:@github.com/dripton/Slugathon.git,d6957007cf4968b383c258c9894eb638fedb290a,"@@ -265,7 +265,7 @@ class Creature(object): skill1 -= 1 elif border == ""Wall"": skill1 += 1 - elif border2 == ""Slope"" and not self.is_native(border): + elif border2 == ""Slope"" and not self.is_native(border2): skill1 -= 1 elif border2 == ""Wall"": skill1 -= 1 ",slugathon/Creature.py,"ReplaceText(target='border2' @(268,59)->(268,65))","class Creature(object): skill1 -= 1 elif border == ""Wall"": skill1 += 1 elif border2 == ""Slope"" and not self.is_native(border): skill1 -= 1 elif border2 == ""Wall"": skill1 -= 1","class Creature(object): skill1 -= 1 elif border == ""Wall"": skill1 += 1 elif border2 == ""Slope"" and not self.is_native(border2): skill1 -= 1 elif border2 == ""Wall"": skill1 -= 1" 754,https://:@github.com/dripton/Slugathon.git,f2bfd2d2c6429dfaa37c5844a52e13124690df13,"@@ -238,7 +238,7 @@ class Creature(object): elif border == ""Dune"" and self.is_native(border): dice += 2 border2 = hex1.opposite_border(hexside) - if border2 == ""Dune"" and not self.is_native(border): + if border2 == ""Dune"" and not self.is_native(border2): dice -= 1 elif target in self.rangestrike_targets: dice = int(self.power / 2) ",slugathon/Creature.py,"ReplaceText(target='border2' @(241,56)->(241,62))","class Creature(object): elif border == ""Dune"" and self.is_native(border): dice += 2 border2 = hex1.opposite_border(hexside) if border2 == ""Dune"" and not self.is_native(border): dice -= 1 elif target in self.rangestrike_targets: dice = int(self.power / 2)","class Creature(object): elif border == ""Dune"" and self.is_native(border): dice += 2 border2 = hex1.opposite_border(hexside) if border2 == ""Dune"" and not self.is_native(border2): dice -= 1 elif target in self.rangestrike_targets: dice = int(self.power / 2)" 755,https://:@github.com/dripton/Slugathon.git,b971ac13adfde83f63ff75be45cc6851d769b86e,"@@ -267,7 +267,7 @@ class CleverBot(DimBot.DimBot): max_mean_hits = max(mean_hits, max_mean_hits) # Don't encourage titans to charge early. - if creature.name != ""Titan"" or game.battle_turn > 4: + if creature.name != ""Titan"" or game.battle_turn >= 4: score += HIT_BONUS * max_mean_hits score += KILL_BONUS * probable_kill score -= DAMAGE_PENALTY * total_mean_damage_taken ",slugathon/ai/CleverBot.py,"ReplaceText(target='>=' @(270,60)->(270,61))","class CleverBot(DimBot.DimBot): max_mean_hits = max(mean_hits, max_mean_hits) # Don't encourage titans to charge early. if creature.name != ""Titan"" or game.battle_turn > 4: score += HIT_BONUS * max_mean_hits score += KILL_BONUS * probable_kill score -= DAMAGE_PENALTY * total_mean_damage_taken","class CleverBot(DimBot.DimBot): max_mean_hits = max(mean_hits, max_mean_hits) # Don't encourage titans to charge early. if creature.name != ""Titan"" or game.battle_turn >= 4: score += HIT_BONUS * max_mean_hits score += KILL_BONUS * probable_kill score -= DAMAGE_PENALTY * total_mean_damage_taken" 756,https://:@github.com/dripton/Slugathon.git,13e968722e4cf18f662d5405ee3bc895929300ec,"@@ -173,7 +173,7 @@ class GUIBattleHex(object): if not os.path.exists(border_path): sliceborder.slice_border_image(image_path, border_path, hexsides) - input_surface = cairo.ImageSurface.create_from_png(image_path) + input_surface = cairo.ImageSurface.create_from_png(border_path) input_width = input_surface.get_width() input_height = input_surface.get_height() output_width = myboxsize[0] ",slugathon/gui/GUIBattleHex.py,"ReplaceText(target='border_path' @(176,67)->(176,77))","class GUIBattleHex(object): if not os.path.exists(border_path): sliceborder.slice_border_image(image_path, border_path, hexsides) input_surface = cairo.ImageSurface.create_from_png(image_path) input_width = input_surface.get_width() input_height = input_surface.get_height() output_width = myboxsize[0]","class GUIBattleHex(object): if not os.path.exists(border_path): sliceborder.slice_border_image(image_path, border_path, hexsides) input_surface = cairo.ImageSurface.create_from_png(border_path) input_width = input_surface.get_width() input_height = input_surface.get_height() output_width = myboxsize[0]" 757,https://:@bitbucket.org/fchampalimaud/pythonvideoannotator-models.git,cde08126d01f0e218cf5450cc39caa1bdeb689b6,"@@ -47,4 +47,4 @@ class Object2dIO(Object2dBase): func = getattr(self, dataset_conf['factory-function']) dataset = func() dataset.name = name - dataset.load(data, dataset_path) \ No newline at end of file + dataset.load(dataset_conf, dataset_path) \ No newline at end of file ",pythonvideoannotator_models/models/video/objects/object2d/object2d_io.py,"ReplaceText(target='dataset_conf' @(50,17)->(50,21))","class Object2dIO(Object2dBase): func = getattr(self, dataset_conf['factory-function']) dataset = func() dataset.name = name dataset.load(data, dataset_path) \ No newline at end of file \ No newline at end of file","class Object2dIO(Object2dBase): func = getattr(self, dataset_conf['factory-function']) dataset = func() dataset.name = name \ No newline at end of file dataset.load(dataset_conf, dataset_path) \ No newline at end of file" 758,https://:@bitbucket.org/fchampalimaud/pythonvideoannotator-models.git,b567c052b952ce719e2974564f8b6cefb1a1a753,"@@ -64,7 +64,7 @@ class PathBase(Dataset): def interpolate_range(self, begin, end, interpolation_mode=None): positions = [[i, self.get_position(i)] for i in range(begin, end+1) if self.get_position(i) is not None] - if len(positions)>2: + if len(positions)>=2: positions = interpolate_positions(positions, begin, end, interpolation_mode) for frame, pos in positions: self.set_position(frame, pos[0], pos[1]) self._tmp_points= [] ",pythonvideoannotator_models/models/video/objects/object2d/datasets/path/path_base.py,"ReplaceText(target='>=' @(67,19)->(67,20))","class PathBase(Dataset): def interpolate_range(self, begin, end, interpolation_mode=None): positions = [[i, self.get_position(i)] for i in range(begin, end+1) if self.get_position(i) is not None] if len(positions)>2: positions = interpolate_positions(positions, begin, end, interpolation_mode) for frame, pos in positions: self.set_position(frame, pos[0], pos[1]) self._tmp_points= []","class PathBase(Dataset): def interpolate_range(self, begin, end, interpolation_mode=None): positions = [[i, self.get_position(i)] for i in range(begin, end+1) if self.get_position(i) is not None] if len(positions)>=2: positions = interpolate_positions(positions, begin, end, interpolation_mode) for frame, pos in positions: self.set_position(frame, pos[0], pos[1]) self._tmp_points= []" 759,https://:@bitbucket.org/fchampalimaud/pythonvideoannotator-models.git,190b462c6df6128fd6ffffb055d84a093a07d381,"@@ -57,7 +57,7 @@ class VideoIO(VideoBase): dataset_conf = json.load(infile) func = getattr(self, dataset_conf['factory-function']) dataset = func() - dataset.load(data, obj_dir) + dataset.load(dataset_conf, obj_dir) dataset.name = name super(VideoIO, self).load(data, video_path) \ No newline at end of file ",pythonvideoannotator_models/models/video/video_io.py,"ReplaceText(target='dataset_conf' @(60,17)->(60,21))","class VideoIO(VideoBase): dataset_conf = json.load(infile) func = getattr(self, dataset_conf['factory-function']) dataset = func() dataset.load(data, obj_dir) dataset.name = name super(VideoIO, self).load(data, video_path) \ No newline at end of file","class VideoIO(VideoBase): dataset_conf = json.load(infile) func = getattr(self, dataset_conf['factory-function']) dataset = func() dataset.load(dataset_conf, obj_dir) dataset.name = name super(VideoIO, self).load(data, video_path) \ No newline at end of file" 760,https://:@github.com/ch3pjw/junction.git,97f897e1fe41e165333f7a5248c951f686a13a89,"@@ -4,7 +4,7 @@ import blessings class Terminal(blessings.Terminal): def draw_block(self, block, x, y): for y, line in enumerate(block, start=y): - self.stream.write(self.move(x, y)) + self.stream.write(self.move(y, x)) self.stream.write(line) _terminal = Terminal() ",junction/terminal.py,"ArgSwap(idxs=0<->1 @(7,30)->(7,39))","import blessings class Terminal(blessings.Terminal): def draw_block(self, block, x, y): for y, line in enumerate(block, start=y): self.stream.write(self.move(x, y)) self.stream.write(line) _terminal = Terminal()","import blessings class Terminal(blessings.Terminal): def draw_block(self, block, x, y): for y, line in enumerate(block, start=y): self.stream.write(self.move(y, x)) self.stream.write(line) _terminal = Terminal()" 761,https://:@gitlab.com/kamichal/renew.git,88823f6ffb58d69e34338f50893049c23739c42c,"@@ -90,7 +90,7 @@ class ArgsInspect(object): msg = ""Variadic arg has to be stored as a tuple, list or OrderedDict, got {}"" raise TypeError(msg.format(type(object_instance).__name__)) - if isinstance(object_instance, OrderedDict): + if isinstance(variadic_arg, OrderedDict): variadic_arg = variadic_arg.items() for attribute_object in variadic_arg: ",renew/_inspection.py,"ReplaceText(target='variadic_arg' @(93,26)->(93,41))","class ArgsInspect(object): msg = ""Variadic arg has to be stored as a tuple, list or OrderedDict, got {}"" raise TypeError(msg.format(type(object_instance).__name__)) if isinstance(object_instance, OrderedDict): variadic_arg = variadic_arg.items() for attribute_object in variadic_arg:","class ArgsInspect(object): msg = ""Variadic arg has to be stored as a tuple, list or OrderedDict, got {}"" raise TypeError(msg.format(type(object_instance).__name__)) if isinstance(variadic_arg, OrderedDict): variadic_arg = variadic_arg.items() for attribute_object in variadic_arg:" 762,https://:@github.com/DataIntegrationAlliance/DIRestInvoker.git,968df11afd78a42bb3294d90a0b73a2ae8777ab7,"@@ -32,7 +32,7 @@ class WindRestInvoker: ret_dic = None if ret_data.status_code != 200: - if ret_dic is None and 'error_code' in ret_dic and ret_dic['error_code'] == -4001: + if ret_dic is not None and 'error_code' in ret_dic and ret_dic['error_code'] == -4001: logger.error('%s post %s got error\n%s', self._url(path), req_data, ret_dic) return None else: ",direstinvoker/iwind.py,"ReplaceText(target=' is not ' @(35,22)->(35,26))","class WindRestInvoker: ret_dic = None if ret_data.status_code != 200: if ret_dic is None and 'error_code' in ret_dic and ret_dic['error_code'] == -4001: logger.error('%s post %s got error\n%s', self._url(path), req_data, ret_dic) return None else:","class WindRestInvoker: ret_dic = None if ret_data.status_code != 200: if ret_dic is not None and 'error_code' in ret_dic and ret_dic['error_code'] == -4001: logger.error('%s post %s got error\n%s', self._url(path), req_data, ret_dic) return None else:" 763,https://:@github.com/tlevine/blargparse.git,05ce9594f89b154fee2f25a0ece74867756a51ea,"@@ -109,7 +109,7 @@ def test_multiple_subparsers(): b = sps.add_parser('b') b.add_argument('--bbb', '-b') - a.add_aggregate('BBB', lambda args:args.bbb.upper()) + b.add_aggregate('BBB', lambda args:args.bbb.upper()) assert bp.parse_args([]) == argparse.Namespace(command = None) assert bp.parse_args(['a', '--aaa', 'tom']) == argparse.Namespace(command = None, aaa = 'tom', AAA = 'TOM') ",test_blargparse.py,"ReplaceText(target='b' @(112,4)->(112,5))","def test_multiple_subparsers(): b = sps.add_parser('b') b.add_argument('--bbb', '-b') a.add_aggregate('BBB', lambda args:args.bbb.upper()) assert bp.parse_args([]) == argparse.Namespace(command = None) assert bp.parse_args(['a', '--aaa', 'tom']) == argparse.Namespace(command = None, aaa = 'tom', AAA = 'TOM')","def test_multiple_subparsers(): b = sps.add_parser('b') b.add_argument('--bbb', '-b') b.add_aggregate('BBB', lambda args:args.bbb.upper()) assert bp.parse_args([]) == argparse.Namespace(command = None) assert bp.parse_args(['a', '--aaa', 'tom']) == argparse.Namespace(command = None, aaa = 'tom', AAA = 'TOM')" 764,https://:@gitlab.com/larsyunker/unithandler.git,db31d7adb35e6ff60a6a719dbe9f7966eee8ab07,"@@ -151,7 +151,7 @@ def interpret_unit_block(unitblock: str) -> dict: if char.isdigit(): # if a digit, increase counter num += char elif char == '-' or char == MINUS: # if a negative sign, change sign - sign = -1 + sign *= -1 elif char in [' ', DOT, '*']: # if a separator, ignore pass else: # otherwise add to unit ",unithandler/base.py,"ReplaceText(target='*=' @(154,17)->(154,18))","def interpret_unit_block(unitblock: str) -> dict: if char.isdigit(): # if a digit, increase counter num += char elif char == '-' or char == MINUS: # if a negative sign, change sign sign = -1 elif char in [' ', DOT, '*']: # if a separator, ignore pass else: # otherwise add to unit","def interpret_unit_block(unitblock: str) -> dict: if char.isdigit(): # if a digit, increase counter num += char elif char == '-' or char == MINUS: # if a negative sign, change sign sign *= -1 elif char in [' ', DOT, '*']: # if a separator, ignore pass else: # otherwise add to unit" 765,https://:@github.com/egtaonline/quiesce.git,9cfe8094d875d54dae3bddd8560e5010cd8bf6e8,"@@ -70,7 +70,7 @@ async def deviation_payoffs(sched, mix, num, *, boots=0, chunk_size=None): n = num while 0 < n: new_profs = sched.random_deviation_profiles( - min(num, chunk_size), mix).reshape((-1, mix.size)) + min(n, chunk_size), mix).reshape((-1, mix.size)) n -= chunk_size new_futures = [asyncio.ensure_future(sched.sample_payoffs(prof)) for prof in new_profs] ",egta/bootstrap.py,"ReplaceText(target='n' @(73,16)->(73,19))","async def deviation_payoffs(sched, mix, num, *, boots=0, chunk_size=None): n = num while 0 < n: new_profs = sched.random_deviation_profiles( min(num, chunk_size), mix).reshape((-1, mix.size)) n -= chunk_size new_futures = [asyncio.ensure_future(sched.sample_payoffs(prof)) for prof in new_profs]","async def deviation_payoffs(sched, mix, num, *, boots=0, chunk_size=None): n = num while 0 < n: new_profs = sched.random_deviation_profiles( min(n, chunk_size), mix).reshape((-1, mix.size)) n -= chunk_size new_futures = [asyncio.ensure_future(sched.sample_payoffs(prof)) for prof in new_profs]" 766,https://:@github.com/benlindsay/job_tree.git,fd96b394a96e1eb0aac3e2d4df91505e41a4c604,"@@ -22,7 +22,7 @@ job_file_list = ['params.input', 'sub.sh'] # Generate a flat job tree submit the jobs. # Add 'submit = False' to prevent submission. -job_tree(tier_list, job_file_list) +job_tree(job_file_list, tier_list) # Running this script should generate a directory tree that looks like this: ",samples/flat_sample/test.py,"ArgSwap(idxs=0<->1 @(25,0)->(25,8))","job_file_list = ['params.input', 'sub.sh'] # Generate a flat job tree submit the jobs. # Add 'submit = False' to prevent submission. job_tree(tier_list, job_file_list) # Running this script should generate a directory tree that looks like this: ","job_file_list = ['params.input', 'sub.sh'] # Generate a flat job tree submit the jobs. # Add 'submit = False' to prevent submission. job_tree(job_file_list, tier_list) # Running this script should generate a directory tree that looks like this: " 767,https://:@github.com/lampwins/orangengine.git,27a79be91e8fe3dd41b02ca7e943a21e2bd2b12d,"@@ -189,7 +189,7 @@ class BaseDriver(object): if len(set_list) == 0 or len(target_element) > 1: # no valid matches or more than one target element identified (meaning this will have to be a new policy) - return CandidatePolicy(target_dict=target_element) + return CandidatePolicy(target_dict=param_dict) else: # found valid matches # the intersection of all match sets is the set of all policies that the target element can to appended to ",orangengine/drivers/base.py,"ReplaceText(target='param_dict' @(192,47)->(192,61))","class BaseDriver(object): if len(set_list) == 0 or len(target_element) > 1: # no valid matches or more than one target element identified (meaning this will have to be a new policy) return CandidatePolicy(target_dict=target_element) else: # found valid matches # the intersection of all match sets is the set of all policies that the target element can to appended to","class BaseDriver(object): if len(set_list) == 0 or len(target_element) > 1: # no valid matches or more than one target element identified (meaning this will have to be a new policy) return CandidatePolicy(target_dict=param_dict) else: # found valid matches # the intersection of all match sets is the set of all policies that the target element can to appended to" 768,https://:@github.com/korijn/git-lfs-azure-transfer.git,f3d7d7992adb676929d29d12c213d5169d12ccdc,"@@ -48,7 +48,7 @@ def report_error(code, message, event=None, oid=None): } if event: payload['event'] = event - if event: + if oid: payload['oid'] = oid write(payload) ",git_lfs_azure_transfer.py,"ReplaceText(target='oid' @(51,7)->(51,12))","def report_error(code, message, event=None, oid=None): } if event: payload['event'] = event if event: payload['oid'] = oid write(payload) ","def report_error(code, message, event=None, oid=None): } if event: payload['event'] = event if oid: payload['oid'] = oid write(payload) " 769,https://:@github.com/danielfrg/datasciencebox.git,74ca80ebb2ecf33b71e1926b4c2c6094179aa893,"@@ -31,7 +31,7 @@ class Project(object): if not os.path.exists(os.path.join(dir_, 'dsbfile')): raise DSBException('""{}"" not found on """"{}"" or its parents'.format(settingsfile, path)) - return cls.from_file(filepath=os.path.join(settingsfile, dir_)) + return cls.from_file(filepath=os.path.join(dir_, settingsfile)) @classmethod def from_file(cls, filepath): ",datasciencebox/core/project.py,"ArgSwap(idxs=0<->1 @(34,38)->(34,50))","class Project(object): if not os.path.exists(os.path.join(dir_, 'dsbfile')): raise DSBException('""{}"" not found on """"{}"" or its parents'.format(settingsfile, path)) return cls.from_file(filepath=os.path.join(settingsfile, dir_)) @classmethod def from_file(cls, filepath):","class Project(object): if not os.path.exists(os.path.join(dir_, 'dsbfile')): raise DSBException('""{}"" not found on """"{}"" or its parents'.format(settingsfile, path)) return cls.from_file(filepath=os.path.join(dir_, settingsfile)) @classmethod def from_file(cls, filepath):" 770,https://:@github.com/nick-youngblut/SIPSim.git,f11ace61e1ba5fdb7afc8a9ec4409cb37e643558,"@@ -146,7 +146,7 @@ class SimFrags(object): # draw from fragment size distribution fragSize = int(self.fld(size=1)) - if fragSize < readTempSize: + if fragSize <= readTempSize: tryCnt += 1 continue ",lib/SimFrags.py,"ReplaceText(target='<=' @(149,24)->(149,25))","class SimFrags(object): # draw from fragment size distribution fragSize = int(self.fld(size=1)) if fragSize < readTempSize: tryCnt += 1 continue ","class SimFrags(object): # draw from fragment size distribution fragSize = int(self.fld(size=1)) if fragSize <= readTempSize: tryCnt += 1 continue " 771,https://:@github.com/Akuli/pythotk.git,c16149611fdeb7017bf65828c54d4c5bdf9edcc4,"@@ -132,7 +132,7 @@ class Widget: # use some_widget.to_tcl() to access the _widget_path self._widget_path = '%s.%s%d' % ( - parentpath, safe_class_name, next(counts[widgetname])) + parentpath, safe_class_name, next(counts[safe_class_name])) # TODO: some config options can only be given when the widget is # created, add support for them ",pythotk/_widgets.py,"ReplaceText(target='safe_class_name' @(135,53)->(135,63))","class Widget: # use some_widget.to_tcl() to access the _widget_path self._widget_path = '%s.%s%d' % ( parentpath, safe_class_name, next(counts[widgetname])) # TODO: some config options can only be given when the widget is # created, add support for them","class Widget: # use some_widget.to_tcl() to access the _widget_path self._widget_path = '%s.%s%d' % ( parentpath, safe_class_name, next(counts[safe_class_name])) # TODO: some config options can only be given when the widget is # created, add support for them" 772,https://:@github.com/claird/PyPDF4.git,d5738dccbca3cf4d2eaf7e307a853dc31baf4a53,"@@ -117,7 +117,7 @@ class FlateDecode(object): rowlength = columns + 1 assert len(data) % rowlength == 0 prev_rowdata = (0,) * rowlength - for row in range(len(data) / rowlength): + for row in range(len(data) // rowlength): rowdata = [ord(x) for x in data[(row*rowlength):((row+1)*rowlength)]] filterByte = rowdata[0] if filterByte == 0: ",PyPDF2/filters.py,"ReplaceText(target='//' @(120,43)->(120,44))","class FlateDecode(object): rowlength = columns + 1 assert len(data) % rowlength == 0 prev_rowdata = (0,) * rowlength for row in range(len(data) / rowlength): rowdata = [ord(x) for x in data[(row*rowlength):((row+1)*rowlength)]] filterByte = rowdata[0] if filterByte == 0:","class FlateDecode(object): rowlength = columns + 1 assert len(data) % rowlength == 0 prev_rowdata = (0,) * rowlength for row in range(len(data) // rowlength): rowdata = [ord(x) for x in data[(row*rowlength):((row+1)*rowlength)]] filterByte = rowdata[0] if filterByte == 0:" 773,https://:@github.com/HUJI-Deep/FlowKet.git,cfb8f9d326ceeeb03c9daa2a4be25e9a1e74064d,"@@ -42,7 +42,7 @@ class ExactVariational(object): if self.num_of_states % batch_size != 0: raise Exception('In exact the batch size must divide the total number of states in the system') self.batch_size = batch_size - self.num_of_batch_until_full_cycle = self.num_of_states / self.batch_size + self.num_of_batch_until_full_cycle = self.num_of_states // self.batch_size self.batch_complex_local_energies = np.zeros((self.batch_size, ), dtype=np.complex128) self.batch_naive_complex_local_energies = np.zeros((self.batch_size, ), dtype=np.complex128) ",src/pyket/optimization/exact_variational.py,"ReplaceText(target='//' @(45,64)->(45,65))","class ExactVariational(object): if self.num_of_states % batch_size != 0: raise Exception('In exact the batch size must divide the total number of states in the system') self.batch_size = batch_size self.num_of_batch_until_full_cycle = self.num_of_states / self.batch_size self.batch_complex_local_energies = np.zeros((self.batch_size, ), dtype=np.complex128) self.batch_naive_complex_local_energies = np.zeros((self.batch_size, ), dtype=np.complex128) ","class ExactVariational(object): if self.num_of_states % batch_size != 0: raise Exception('In exact the batch size must divide the total number of states in the system') self.batch_size = batch_size self.num_of_batch_until_full_cycle = self.num_of_states // self.batch_size self.batch_complex_local_energies = np.zeros((self.batch_size, ), dtype=np.complex128) self.batch_naive_complex_local_energies = np.zeros((self.batch_size, ), dtype=np.complex128) " 774,https://:@github.com/eriknyquist/text_game_maker.git,a890d63064b801645a425df5d2d69ad4a9056d8f,"@@ -61,7 +61,7 @@ def craft(name, word, inventory): item = None if name in craftables: - items, item = craftables[item] + items, item = craftables[name] else: for k in craftables: if k.startswith(name) or k.endswith(name) or (k in name): ",text_game_maker/crafting/crafting.py,"ReplaceText(target='name' @(64,33)->(64,37))","def craft(name, word, inventory): item = None if name in craftables: items, item = craftables[item] else: for k in craftables: if k.startswith(name) or k.endswith(name) or (k in name):","def craft(name, word, inventory): item = None if name in craftables: items, item = craftables[name] else: for k in craftables: if k.startswith(name) or k.endswith(name) or (k in name):" 775,https://:@github.com/eriknyquist/text_game_maker.git,2868976cf5790d39282843924148eae25102c6be,"@@ -55,7 +55,7 @@ def help_text(): def _find_item(item, items): for i in items: if (i.name == item.name) and isinstance(i, item.__class__): - return item + return i return None ",text_game_maker/crafting/crafting.py,"ReplaceText(target='i' @(58,19)->(58,23))","def help_text(): def _find_item(item, items): for i in items: if (i.name == item.name) and isinstance(i, item.__class__): return item return None ","def help_text(): def _find_item(item, items): for i in items: if (i.name == item.name) and isinstance(i, item.__class__): return i return None " 776,https://:@github.com/SkyTruth/gpsd_format.git,07dd93add6bd9e448eb4ac87ed6fdc43cc94f5d2,"@@ -92,6 +92,6 @@ def etl(ctx, infile, outfile, filter_expr, sort_field, do=output_driver_opts, co=output_compression_opts) as dst: - iterator = gpsdio.filter(src, filter_expr) if filter_expr else src + iterator = gpsdio.filter(filter_expr, src) if filter_expr else src for msg in gpsdio.sort(iterator, sort_field) if sort_field else iterator: dst.write(msg) ",gpsdio/cli/etl.py,"ArgSwap(idxs=0<->1 @(95,23)->(95,36))","def etl(ctx, infile, outfile, filter_expr, sort_field, do=output_driver_opts, co=output_compression_opts) as dst: iterator = gpsdio.filter(src, filter_expr) if filter_expr else src for msg in gpsdio.sort(iterator, sort_field) if sort_field else iterator: dst.write(msg)","def etl(ctx, infile, outfile, filter_expr, sort_field, do=output_driver_opts, co=output_compression_opts) as dst: iterator = gpsdio.filter(filter_expr, src) if filter_expr else src for msg in gpsdio.sort(iterator, sort_field) if sort_field else iterator: dst.write(msg)" 777,https://:@github.com/barry-lab/openEPhys_DACQ.git,14df7f0f939a8dace7020265f1695e06451d7f87,"@@ -67,7 +67,7 @@ def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_lengt sys.stdout.write('%s |%s| %s%s %s\r' % (prefix, bar, percents, '%', suffix)), - if iteration == total: + if iteration >= total: sys.stdout.write('\n') sys.stdout.flush() # # ",HelperFunctions.py,"ReplaceText(target='>=' @(70,17)->(70,19))","def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_lengt sys.stdout.write('%s |%s| %s%s %s\r' % (prefix, bar, percents, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush() # # ","def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_lengt sys.stdout.write('%s |%s| %s%s %s\r' % (prefix, bar, percents, '%', suffix)), if iteration >= total: sys.stdout.write('\n') sys.stdout.flush() # # " 778,https://:@github.com/fy0/mapi.git,3c322eb25527f719a55a7de8eec82bd6620546d2,"@@ -530,7 +530,7 @@ class AbstractSQLView(BaseView): logger.debug('set data: %s' % values) code, data = await self._sql.update(info, values) if code == RETCODE.SUCCESS: - await async_call(self.after_update, data) + await async_call(self.after_update, values) self.finish(code, data) async def new(self): ",slim/base/view.py,"ReplaceText(target='values' @(533,48)->(533,52))","class AbstractSQLView(BaseView): logger.debug('set data: %s' % values) code, data = await self._sql.update(info, values) if code == RETCODE.SUCCESS: await async_call(self.after_update, data) self.finish(code, data) async def new(self):","class AbstractSQLView(BaseView): logger.debug('set data: %s' % values) code, data = await self._sql.update(info, values) if code == RETCODE.SUCCESS: await async_call(self.after_update, values) self.finish(code, data) async def new(self):" 779,https://:@github.com/fy0/mapi.git,d340368fbcf91c1c9377fabcb5722ffdef798501,"@@ -15,7 +15,7 @@ def require_role(role=None): def request_role(role=None): def _(func): async def __(view: AbstractSQLView, *args, **kwargs): - if role == view.current_request_role: + if role != view.current_request_role: return view.finish(RETCODE.INVALID_ROLE) return await func(view, *args, **kwargs) return __ ",slim/ext/decorator.py,"ReplaceText(target='!=' @(18,20)->(18,22))","def require_role(role=None): def request_role(role=None): def _(func): async def __(view: AbstractSQLView, *args, **kwargs): if role == view.current_request_role: return view.finish(RETCODE.INVALID_ROLE) return await func(view, *args, **kwargs) return __","def require_role(role=None): def request_role(role=None): def _(func): async def __(view: AbstractSQLView, *args, **kwargs): if role != view.current_request_role: return view.finish(RETCODE.INVALID_ROLE) return await func(view, *args, **kwargs) return __" 780,https://:@github.com/Gurbert/micawber_bs4_classes.git,7a07d3b013c907c11a54cf2cedc7954c554770de,"@@ -164,7 +164,7 @@ def _is_standalone(soup_elem): def _inside_skip(soup_elem): parent = soup_elem.parent while parent is not None: - if parent.name not in skip_elements: + if parent.name in skip_elements: return True parent = parent.parent return False ",micawber/parsers.py,"ReplaceText(target=' in ' @(167,22)->(167,30))","def _is_standalone(soup_elem): def _inside_skip(soup_elem): parent = soup_elem.parent while parent is not None: if parent.name not in skip_elements: return True parent = parent.parent return False","def _is_standalone(soup_elem): def _inside_skip(soup_elem): parent = soup_elem.parent while parent is not None: if parent.name in skip_elements: return True parent = parent.parent return False" 781,https://:@github.com/pgeurin/autoregression.git,dc4b2c89e719c6a94f3a4e0ab632aec2a5990c35,"@@ -488,7 +488,7 @@ def compare_predictions(df, y_var_name, percent_data=None, timeit(plot_rocs, models, df_X, y) plt.show() print(f'MAKE SUBSAMPLE TIME: {time() - starttotal}') - return names, results, models, pipeline, df_X + return names, results, fit_models, pipeline, df_X def bootstrap_train_premade(model, X, y, bootstraps=1000, **kwargs): """"""Train a (linear) model on multiple bootstrap samples of some data and ",autoregression/autoregression.py,"ReplaceText(target='fit_models' @(491,27)->(491,33))","def compare_predictions(df, y_var_name, percent_data=None, timeit(plot_rocs, models, df_X, y) plt.show() print(f'MAKE SUBSAMPLE TIME: {time() - starttotal}') return names, results, models, pipeline, df_X def bootstrap_train_premade(model, X, y, bootstraps=1000, **kwargs): """"""Train a (linear) model on multiple bootstrap samples of some data and","def compare_predictions(df, y_var_name, percent_data=None, timeit(plot_rocs, models, df_X, y) plt.show() print(f'MAKE SUBSAMPLE TIME: {time() - starttotal}') return names, results, fit_models, pipeline, df_X def bootstrap_train_premade(model, X, y, bootstraps=1000, **kwargs): """"""Train a (linear) model on multiple bootstrap samples of some data and" 782,https://:@github.com/xRodney/suds-sw.git,8b72570029cb884a8b5bf46aa00deedadb150c3c,"@@ -130,7 +130,7 @@ class UMBase: return content.data lang = attributes.lang() if not len(node.children) and content.text is None: - if self.nillable(content.data) and content.node.isnil(): + if self.nillable(content.data) or content.node.isnil(): return None else: return xlstr.string('', lang) ",suds/bindings/unmarshaller.py,"ReplaceText(target='or' @(133,43)->(133,46))","class UMBase: return content.data lang = attributes.lang() if not len(node.children) and content.text is None: if self.nillable(content.data) and content.node.isnil(): return None else: return xlstr.string('', lang)","class UMBase: return content.data lang = attributes.lang() if not len(node.children) and content.text is None: if self.nillable(content.data) or content.node.isnil(): return None else: return xlstr.string('', lang)" 783,https://:@github.com/xRodney/suds-sw.git,c2ef63c56cdb827e47426ce8debd547275122cc6,"@@ -113,6 +113,6 @@ class Options(Skin): Definition('retxml', bool, False), Definition('autoblend', bool, False), Definition('cachingpolicy', int, 0), - Definition('plugins', [], (list, tuple)), + Definition('plugins', (list, tuple), []), ] Skin.__init__(self, domain, definitions, kwargs) ",suds/options.py,"ArgSwap(idxs=1<->2 @(116,12)->(116,22))","class Options(Skin): Definition('retxml', bool, False), Definition('autoblend', bool, False), Definition('cachingpolicy', int, 0), Definition('plugins', [], (list, tuple)), ] Skin.__init__(self, domain, definitions, kwargs)","class Options(Skin): Definition('retxml', bool, False), Definition('autoblend', bool, False), Definition('cachingpolicy', int, 0), Definition('plugins', (list, tuple), []), ] Skin.__init__(self, domain, definitions, kwargs)" 784,https://:@gitlab.com/frkl/bring.git,ccb052917ef3d193526ee99eec8968df96a1c199,"@@ -306,7 +306,7 @@ class Bring(SimpleTing): ctx: BringDynamicContextTing = self._tingistry_obj.create_ting( # type: ignore ""bring_dynamic_context_ting"", f""{BRING_CONTEXT_NAMESPACE}.{context_name}"" ) - indexes = [folder] + indexes = [_path] ctx.input.set_values( # type: ignore ting_dict={""indexes"": indexes} ) ",src/bring/bring.py,"ReplaceText(target='_path' @(309,19)->(309,25))","class Bring(SimpleTing): ctx: BringDynamicContextTing = self._tingistry_obj.create_ting( # type: ignore ""bring_dynamic_context_ting"", f""{BRING_CONTEXT_NAMESPACE}.{context_name}"" ) indexes = [folder] ctx.input.set_values( # type: ignore ting_dict={""indexes"": indexes} )","class Bring(SimpleTing): ctx: BringDynamicContextTing = self._tingistry_obj.create_ting( # type: ignore ""bring_dynamic_context_ting"", f""{BRING_CONTEXT_NAMESPACE}.{context_name}"" ) indexes = [_path] ctx.input.set_values( # type: ignore ting_dict={""indexes"": indexes} )" 785,https://:@gitlab.com/frkl/bring.git,8e4f6b2742ec941ab386856234415827f8f77429,"@@ -10,7 +10,7 @@ app_name = ""bring"" _hi = load_modules(BRINGISTRY_PRELOAD_MODULES) # type: ignore pyinstaller = {""hiddenimports"": [x.__name__ for x in _hi]} -if os.name != ""nt"": +if os.name == ""nt"": import pkgutil import jinxed.terminfo ",src/bring/_meta.py,"ReplaceText(target='==' @(13,11)->(13,13))","app_name = ""bring"" _hi = load_modules(BRINGISTRY_PRELOAD_MODULES) # type: ignore pyinstaller = {""hiddenimports"": [x.__name__ for x in _hi]} if os.name != ""nt"": import pkgutil import jinxed.terminfo ","app_name = ""bring"" _hi = load_modules(BRINGISTRY_PRELOAD_MODULES) # type: ignore pyinstaller = {""hiddenimports"": [x.__name__ for x in _hi]} if os.name == ""nt"": import pkgutil import jinxed.terminfo " 786,https://:@gitlab.com/frkl/bring.git,d67c17a6b4f41c01764315a5f6205a1264b6d3f0,"@@ -242,4 +242,4 @@ class BringContextTing(InheriTing, SimpleTing): _all_values[""_bring_metadata_timestamp""] = str(arrow.now()) - return all_values + return _all_values ",src/bring/context/__init__.py,"ReplaceText(target='_all_values' @(245,15)->(245,25))","class BringContextTing(InheriTing, SimpleTing): _all_values[""_bring_metadata_timestamp""] = str(arrow.now()) return all_values","class BringContextTing(InheriTing, SimpleTing): _all_values[""_bring_metadata_timestamp""] = str(arrow.now()) return _all_values" 787,https://:@gitlab.com/frkl/bring.git,112f00eaba6972dab7ead12bea4ca077f4ef5a6c,"@@ -110,7 +110,7 @@ def create_table_from_pkg_args( _allowed_strings = [] for _arg, _aliases in _allowed.items(): - if not aliases: + if not _aliases: a = _arg elif len(_aliases) == 1: a = f""{_arg} (alias: {_aliases[0]})"" ",src/bring/display/args.py,"ReplaceText(target='_aliases' @(113,23)->(113,30))","def create_table_from_pkg_args( _allowed_strings = [] for _arg, _aliases in _allowed.items(): if not aliases: a = _arg elif len(_aliases) == 1: a = f""{_arg} (alias: {_aliases[0]})""","def create_table_from_pkg_args( _allowed_strings = [] for _arg, _aliases in _allowed.items(): if not _aliases: a = _arg elif len(_aliases) == 1: a = f""{_arg} (alias: {_aliases[0]})""" 788,https://:@gitlab.com/frkl/bring.git,6ebf8d8d3c86da43d5fe0505544d7329e4c6abf5,"@@ -135,7 +135,7 @@ class BringInstallGroup(FrklBaseCommand): install_args = {} if target: install_args[""target""] = target - if install_args: + if target_config: install_args[""target_config""] = target_config # install_args[""merge_strategy""] = merge_strategy ",src/bring/interfaces/cli/install.py,"ReplaceText(target='target_config' @(138,11)->(138,23))","class BringInstallGroup(FrklBaseCommand): install_args = {} if target: install_args[""target""] = target if install_args: install_args[""target_config""] = target_config # install_args[""merge_strategy""] = merge_strategy","class BringInstallGroup(FrklBaseCommand): install_args = {} if target: install_args[""target""] = target if target_config: install_args[""target_config""] = target_config # install_args[""merge_strategy""] = merge_strategy" 789,https://:@github.com/glyph/twitter-text-py.git,197cbd58689e6f12f0b2e931c615eb816b6a8051,"@@ -60,7 +60,7 @@ class HitHighlighter(object): if index % 2: # we're inside a continue - chunk_start = len(u''.join(text_chunks[0:index / 2])) + chunk_start = len(u''.join(text_chunks[0:index // 2])) chunk_end = chunk_start + len(chunk) if hit_start >= chunk_start and hit_start < chunk_end: chunk = chunk[:hit_start - chunk_start] + tags[0] + chunk[hit_start - chunk_start:] ",twitter_text/highlighter.py,"ReplaceText(target='//' @(63,63)->(63,64))","class HitHighlighter(object): if index % 2: # we're inside a continue chunk_start = len(u''.join(text_chunks[0:index / 2])) chunk_end = chunk_start + len(chunk) if hit_start >= chunk_start and hit_start < chunk_end: chunk = chunk[:hit_start - chunk_start] + tags[0] + chunk[hit_start - chunk_start:]","class HitHighlighter(object): if index % 2: # we're inside a continue chunk_start = len(u''.join(text_chunks[0:index // 2])) chunk_end = chunk_start + len(chunk) if hit_start >= chunk_start and hit_start < chunk_end: chunk = chunk[:hit_start - chunk_start] + tags[0] + chunk[hit_start - chunk_start:]" 790,https://:@github.com/lbovet/yglu.git,73ec7a7721281cf2ab16b00be2a64da5ba43697f,"@@ -42,7 +42,7 @@ def import_definition(context, root): errors = root.doc.errors else: errors = None - result = build(file, filename, errors) + result = build(file, filepath, errors) return Holder(result) context['$import'] = import_function ",yglu/functions.py,"ReplaceText(target='filepath' @(45,33)->(45,41))","def import_definition(context, root): errors = root.doc.errors else: errors = None result = build(file, filename, errors) return Holder(result) context['$import'] = import_function","def import_definition(context, root): errors = root.doc.errors else: errors = None result = build(file, filepath, errors) return Holder(result) context['$import'] = import_function" 791,https://:@github.com/inforian/django-password-manager.git,5e7e6c14fa393d7e814556c9b02869d9f3adcd84,"@@ -77,7 +77,7 @@ def check_password_expired(user): # get latest password info latest = user.password_history.latest(""pk"") except PasswordHistory.DoesNotExist: - return False + return True now = datetime.now(tz=pytz.UTC) expiration = latest.timestamp + timedelta(days=expiry) ",pass_manager/utils.py,"ReplaceText(target='True' @(80,15)->(80,20))","def check_password_expired(user): # get latest password info latest = user.password_history.latest(""pk"") except PasswordHistory.DoesNotExist: return False now = datetime.now(tz=pytz.UTC) expiration = latest.timestamp + timedelta(days=expiry)","def check_password_expired(user): # get latest password info latest = user.password_history.latest(""pk"") except PasswordHistory.DoesNotExist: return True now = datetime.now(tz=pytz.UTC) expiration = latest.timestamp + timedelta(days=expiry)" 792,https://:@github.com/koriavinash1/DeepBrainSeg.git,a09812c3f5b8348b1bbfc0e06669490c9a204ec7,"@@ -109,7 +109,7 @@ def GenerateCSV(model, dataset_path, logs_root, iteration = 0): spath['seg'] = os.path.join(subject_path, subject + '_seg.nii.gz') spath['t1'] = os.path.join(subject_path, subject + '_t1.nii.gz') spath['t2'] = os.path.join(subject_path, subject + '_t2.nii.gz') - spath['mask'] = os.path.join(dataset_path, 'mask.nii.gz') + spath['mask'] = os.path.join(subject_path, 'mask.nii.gz') vol, seg, affine = nii_loader(spath) predictions = _GenerateSegmentation_(subject_path, vol, seg, size = 64, nclasses = 5) ",DeepBrainSeg/tumor/finetune/generateCSV.py,"ReplaceText(target='subject_path' @(112,42)->(112,54))","def GenerateCSV(model, dataset_path, logs_root, iteration = 0): spath['seg'] = os.path.join(subject_path, subject + '_seg.nii.gz') spath['t1'] = os.path.join(subject_path, subject + '_t1.nii.gz') spath['t2'] = os.path.join(subject_path, subject + '_t2.nii.gz') spath['mask'] = os.path.join(dataset_path, 'mask.nii.gz') vol, seg, affine = nii_loader(spath) predictions = _GenerateSegmentation_(subject_path, vol, seg, size = 64, nclasses = 5)","def GenerateCSV(model, dataset_path, logs_root, iteration = 0): spath['seg'] = os.path.join(subject_path, subject + '_seg.nii.gz') spath['t1'] = os.path.join(subject_path, subject + '_t1.nii.gz') spath['t2'] = os.path.join(subject_path, subject + '_t2.nii.gz') spath['mask'] = os.path.join(subject_path, 'mask.nii.gz') vol, seg, affine = nii_loader(spath) predictions = _GenerateSegmentation_(subject_path, vol, seg, size = 64, nclasses = 5)" 793,https://:@github.com/codepost-io/codePost-python.git,00320258dd53e987c66c9af2d021fb93b38ac20c,"@@ -812,7 +812,7 @@ def remove_comments(api_key, submission_id=None, file_id=None): headers=auth_headers ) - if r.status_code != 204: + if r.status_code == 204: comments_to_delete += r.json().get(""comments"", list()) deleted_comments += 1 except: ",codePost_api/helpers.py,"ReplaceText(target='==' @(815,29)->(815,31))","def remove_comments(api_key, submission_id=None, file_id=None): headers=auth_headers ) if r.status_code != 204: comments_to_delete += r.json().get(""comments"", list()) deleted_comments += 1 except:","def remove_comments(api_key, submission_id=None, file_id=None): headers=auth_headers ) if r.status_code == 204: comments_to_delete += r.json().get(""comments"", list()) deleted_comments += 1 except:" 794,https://:@github.com/yuvipanda/python-mwapi.git,908d0cbc6945c46acc6f9536d95ad78dc3e157e9,"@@ -16,7 +16,7 @@ import sys import os -sys.path.insert("".."", 0) +sys.path.insert(0, "".."") import mwapi ",doc/conf.py,"ArgSwap(idxs=0<->1 @(19,0)->(19,15))","-16,7 +16,7 @@ import sys import os sys.path.insert("".."", 0) import mwapi ","-16,7 +16,7 @@ import sys import os sys.path.insert(0, "".."") import mwapi " 795,https://:@github.com/jplusplus/thenmap-python.git,70432b792f441d2bac26c2da2744fa5d67f47af3,"@@ -26,7 +26,7 @@ def point_from_coordinates(input_): for sep in ["","", "";"", ""|""]: if len(input_.split(sep)) in range(2, 3): t = input_.split(sep) - if isinstance(input_, string_types): + if isinstance(t, string_types): raise Exception(""Invalid coordinates: %s"" % input_) elif isinstance(input_, Iterable): ",thenmap/thenmap.py,"ReplaceText(target='t' @(29,22)->(29,28))","def point_from_coordinates(input_): for sep in ["","", "";"", ""|""]: if len(input_.split(sep)) in range(2, 3): t = input_.split(sep) if isinstance(input_, string_types): raise Exception(""Invalid coordinates: %s"" % input_) elif isinstance(input_, Iterable):","def point_from_coordinates(input_): for sep in ["","", "";"", ""|""]: if len(input_.split(sep)) in range(2, 3): t = input_.split(sep) if isinstance(t, string_types): raise Exception(""Invalid coordinates: %s"" % input_) elif isinstance(input_, Iterable):" 796,https://:@github.com/cardsurf/xcrawler.git,79aaaca3e4cbf7f79efa5f3a9168fb9089b73d40,"@@ -13,4 +13,4 @@ class UrlInfo: def is_relative(self, url): domain = self.url_splitter.get_domain(url) - return len(domain) > 0 + return len(domain) == 0 ",xcrawler/http/urls/url_info.py,"ReplaceText(target='==' @(16,27)->(16,28))","class UrlInfo: def is_relative(self, url): domain = self.url_splitter.get_domain(url) return len(domain) > 0","class UrlInfo: def is_relative(self, url): domain = self.url_splitter.get_domain(url) return len(domain) == 0" 797,https://:@github.com/asafpr/pro_clash.git,f487619296c37a989d4dc647d1c204c1acc15e44,"@@ -898,7 +898,7 @@ def get_names(gname, uid_names, annotations): p1_desc = '-' p0_desc += ' : %s'%p1_desc - elif len(gname)>2: + elif len(gname)>=2: p0_name += '_%s'%gname[1] return p0_name, p0_desc ",pro_clash/__init__.py,"ReplaceText(target='>=' @(901,19)->(901,20))","def get_names(gname, uid_names, annotations): p1_desc = '-' p0_desc += ' : %s'%p1_desc elif len(gname)>2: p0_name += '_%s'%gname[1] return p0_name, p0_desc","def get_names(gname, uid_names, annotations): p1_desc = '-' p0_desc += ' : %s'%p1_desc elif len(gname)>=2: p0_name += '_%s'%gname[1] return p0_name, p0_desc" 798,https://:@github.com/asafpr/pro_clash.git,fcb3edb3acefd3224f0e5473495435d197989c81,"@@ -525,7 +525,7 @@ def read_bam_file(bamfile, chrnames_bam, max_NM=0): for al in alt_list: apos = int(al[1][1:]) # test this alternative only if its NM is as the original one - if int(apos[3])>nm_num: + if int(al[3])>nm_num: continue if apos < min_pos: min_pos = apos ",pro_clash/__init__.py,"ReplaceText(target='al' @(528,23)->(528,27))","def read_bam_file(bamfile, chrnames_bam, max_NM=0): for al in alt_list: apos = int(al[1][1:]) # test this alternative only if its NM is as the original one if int(apos[3])>nm_num: continue if apos < min_pos: min_pos = apos","def read_bam_file(bamfile, chrnames_bam, max_NM=0): for al in alt_list: apos = int(al[1][1:]) # test this alternative only if its NM is as the original one if int(al[3])>nm_num: continue if apos < min_pos: min_pos = apos" 799,https://:@github.com/Anastadev/anastasia.git,03a356f19a8c995ff2dec074b8b133244fab1c2c,"@@ -21,7 +21,7 @@ steam_handler.setLevel(logging.DEBUG) steam_handler.setFormatter(formatter) log.addHandler(steam_handler) -updater = Updater(token=sys.argv[0]) +updater = Updater(token=sys.argv[1]) dispatcher = updater.dispatcher ",Main.py,"ReplaceText(target='1' @(24,33)->(24,34))","steam_handler.setLevel(logging.DEBUG) steam_handler.setFormatter(formatter) log.addHandler(steam_handler) updater = Updater(token=sys.argv[0]) dispatcher = updater.dispatcher ","steam_handler.setLevel(logging.DEBUG) steam_handler.setFormatter(formatter) log.addHandler(steam_handler) updater = Updater(token=sys.argv[1]) dispatcher = updater.dispatcher " 800,https://:@github.com/ankush13r/BvSalud.git,10216a189e9f63ab1a1d8cf7c647a026b7b941bb,"@@ -195,7 +195,7 @@ def get_mesh_major_list(document_dict,decsCodes_list_dict,with_header): #Method else: if len(header_before_slash) != 0: final_header = str(header_code) +'/'+ str(header_after_slash) - elif len(header_after_slash) == 0: + elif len(header_before_slash) == 0: final_header = '/' + str(decsCodes_list_dict) else: print(header,""--"",header_before_slash,""--"",header_after_slash) ",BvSalud/makeSet.py,"ReplaceText(target='header_before_slash' @(198,21)->(198,39))","def get_mesh_major_list(document_dict,decsCodes_list_dict,with_header): #Method else: if len(header_before_slash) != 0: final_header = str(header_code) +'/'+ str(header_after_slash) elif len(header_after_slash) == 0: final_header = '/' + str(decsCodes_list_dict) else: print(header,""--"",header_before_slash,""--"",header_after_slash)","def get_mesh_major_list(document_dict,decsCodes_list_dict,with_header): #Method else: if len(header_before_slash) != 0: final_header = str(header_code) +'/'+ str(header_after_slash) elif len(header_before_slash) == 0: final_header = '/' + str(decsCodes_list_dict) else: print(header,""--"",header_before_slash,""--"",header_after_slash)" 801,https://:@github.com/Hypers-HFA/paraer.git,8a5fd8156012b94e50b1e6a3413244b95f3e323b,"@@ -112,7 +112,7 @@ def para_ok_or_400(itemset): ] value = None # 与 '' 区别 para = paramap.get(name) - if required and para not in (None, ''): # 如果是post方法并且传参是json的话,para可能为0 + if required and para in (None, ''): # 如果是post方法并且传参是json的话,para可能为0 result.error(name, 'required') if para is not None: if para: ",paraer/para.py,"ReplaceText(target=' in ' @(115,36)->(115,44))","def para_ok_or_400(itemset): ] value = None # 与 '' 区别 para = paramap.get(name) if required and para not in (None, ''): # 如果是post方法并且传参是json的话,para可能为0 result.error(name, 'required') if para is not None: if para:","def para_ok_or_400(itemset): ] value = None # 与 '' 区别 para = paramap.get(name) if required and para in (None, ''): # 如果是post方法并且传参是json的话,para可能为0 result.error(name, 'required') if para is not None: if para:" 802,https://:@github.com/davidenunes/tensorx.git,34fb24ae4eeca927a7d7b5f376aeeddbb0b7aacd,"@@ -2604,7 +2604,7 @@ class SaltPepperNoise(Layer): else: batch_size = noise_shape[0] - noise = salt_pepper_noise(batch_size, noise_shape[1], density, salt_value, pepper_value, seed) + noise = salt_pepper_noise(noise_shape[1], batch_size, density, salt_value, pepper_value, seed) if layer.is_sparse(): tensor = transform.sparse_put(layer.tensor, noise) ",tensorx/layers.py,"ArgSwap(idxs=0<->1 @(2607,24)->(2607,41))","class SaltPepperNoise(Layer): else: batch_size = noise_shape[0] noise = salt_pepper_noise(batch_size, noise_shape[1], density, salt_value, pepper_value, seed) if layer.is_sparse(): tensor = transform.sparse_put(layer.tensor, noise)","class SaltPepperNoise(Layer): else: batch_size = noise_shape[0] noise = salt_pepper_noise(noise_shape[1], batch_size, density, salt_value, pepper_value, seed) if layer.is_sparse(): tensor = transform.sparse_put(layer.tensor, noise)" 803,https://:@github.com/sauliusl/dgw.git,9120263028d2e64983b9b9babe31c46b8f2caedd,"@@ -98,7 +98,7 @@ def dtw_std(x, y, metric='sqeuclidean', dist_only=True, constraint=None, k=None, path_rev = (_reverse_path(path[0]), path[1]) if scale_first: - path_rev = _scaled_path(path, scaling_path, flip_paths) + path_rev = _scaled_path(path_rev, scaling_path, flip_paths) # TODO: Reverse cost matrix here cost = None ",dgw/dtw/distance.py,"ReplaceText(target='path_rev' @(101,40)->(101,44))","def dtw_std(x, y, metric='sqeuclidean', dist_only=True, constraint=None, k=None, path_rev = (_reverse_path(path[0]), path[1]) if scale_first: path_rev = _scaled_path(path, scaling_path, flip_paths) # TODO: Reverse cost matrix here cost = None","def dtw_std(x, y, metric='sqeuclidean', dist_only=True, constraint=None, k=None, path_rev = (_reverse_path(path[0]), path[1]) if scale_first: path_rev = _scaled_path(path_rev, scaling_path, flip_paths) # TODO: Reverse cost matrix here cost = None" 804,https://:@bitbucket.org/slicedice/aboutyou-shop-sdk-python.git,c125675219cbb473f47c78c57e9205d1be44d4f2,"@@ -439,7 +439,7 @@ class Search(object): else: product = Product(self.easy, p) - self.easy.product_cach[p.id] = product + self.easy.product_cach[product.id] = product self.products.buffer[i+offset] = product ",collins/easy.py,"ReplaceText(target='product' @(442,35)->(442,36))","class Search(object): else: product = Product(self.easy, p) self.easy.product_cach[p.id] = product self.products.buffer[i+offset] = product ","class Search(object): else: product = Product(self.easy, p) self.easy.product_cach[product.id] = product self.products.buffer[i+offset] = product " 805,https://:@github.com/neizod/extmath.git,b66496463e3d724a29d652e97867f41e4e1d2aea,"@@ -117,7 +117,7 @@ def factorized(n): break while not n % i: factor.append(i) - n /= i + n //= i if n == 1: break return factor ",mathapi/__init__.py,"ReplaceText(target='//=' @(120,14)->(120,16))","def factorized(n): break while not n % i: factor.append(i) n /= i if n == 1: break return factor","def factorized(n): break while not n % i: factor.append(i) n //= i if n == 1: break return factor" 806,https://:@github.com/storborg/axibot.git,4ffd9fc0f715bbe4ae8c1708fbeae45186d35f6e,"@@ -64,7 +64,7 @@ async def handle_user_message(app, ws, msg): except Exception as e: notify_error(app, ws, str(e)) else: - app['document'] = msg.document + app['document'] = job.document app['job'] = job app['estimated_time'] = job.duration().total_seconds() notify_new_document(app, exclude_client=ws) ",axibot/server/handlers.py,"ReplaceText(target='job' @(67,30)->(67,33))","async def handle_user_message(app, ws, msg): except Exception as e: notify_error(app, ws, str(e)) else: app['document'] = msg.document app['job'] = job app['estimated_time'] = job.duration().total_seconds() notify_new_document(app, exclude_client=ws)","async def handle_user_message(app, ws, msg): except Exception as e: notify_error(app, ws, str(e)) else: app['document'] = job.document app['job'] = job app['estimated_time'] = job.duration().total_seconds() notify_new_document(app, exclude_client=ws)" 807,https://:@github.com/storborg/axibot.git,4ad752828696a789ef25fa001f1489f87344c3e4,"@@ -116,7 +116,7 @@ async def client_handler(request): elif raw_msg.tp == aiohttp.MsgType.closed: break elif raw_msg.tp == aiohttp.MsgType.error: - log.info(""User websocket error: %s"", msg) + log.info(""User websocket error: %s"", raw_msg) break else: log.error(""Unknown user message type: %s, ignoring."", ",axibot/server/handlers.py,"ReplaceText(target='raw_msg' @(119,53)->(119,56))","async def client_handler(request): elif raw_msg.tp == aiohttp.MsgType.closed: break elif raw_msg.tp == aiohttp.MsgType.error: log.info(""User websocket error: %s"", msg) break else: log.error(""Unknown user message type: %s, ignoring."",","async def client_handler(request): elif raw_msg.tp == aiohttp.MsgType.closed: break elif raw_msg.tp == aiohttp.MsgType.error: log.info(""User websocket error: %s"", raw_msg) break else: log.error(""Unknown user message type: %s, ignoring.""," 808,https://:@github.com/tsuyukimakoto/biisan.git,4465b109a4e71dcb64499c14b579c762e54b4db4,"@@ -116,7 +116,7 @@ def process_image(elm, registry, container): img.alt = subitem[1] elif subitem[0] == 'witdh': img.witdh = subitem[1] - elif subitem[1] == 'height': + elif subitem[0] == 'height': img.height = subitem[1] elif subitem[0] == 'uri': img.uri = subitem[1] ",biisan/processors/__init__.py,"ReplaceText(target='0' @(119,21)->(119,22))","def process_image(elm, registry, container): img.alt = subitem[1] elif subitem[0] == 'witdh': img.witdh = subitem[1] elif subitem[1] == 'height': img.height = subitem[1] elif subitem[0] == 'uri': img.uri = subitem[1]","def process_image(elm, registry, container): img.alt = subitem[1] elif subitem[0] == 'witdh': img.witdh = subitem[1] elif subitem[0] == 'height': img.height = subitem[1] elif subitem[0] == 'uri': img.uri = subitem[1]" 809,https://:@github.com/csm10495/csmlog.git,010e00e53545842d2dc1342c375c068c90138ca2,"@@ -262,7 +262,7 @@ def test_gsheets_calculate_periodic_loop_sleep_time(gsheets_handler_no_thread): def test_gsheets_add_rows_to_active_sheet_sets_add_rows_time(gsheets_handler_no_thread): gsheets_handler_no_thread._add_rows_time = 99 assert isinstance(gsheets_handler_no_thread._add_rows_to_active_sheet([]), unittest.mock.Mock) - assert gsheets_handler_no_thread._add_rows_time < 99 and gsheets_handler_no_thread._add_rows_time > 0 + assert gsheets_handler_no_thread._add_rows_time < 99 and gsheets_handler_no_thread._add_rows_time >= 0 def test_gsheets_add_rows_to_active_sheet_set_coerce_to_correct_exceptions(gsheets_handler_no_thread): with unittest.mock.patch.object(gsheets_handler_no_thread.sheet, 'append_rows', side_effect=Exception(""RESOURCE_EXHAUSTED uh-oh"")) as mock: ",csmlog/tests/test_google_sheets_handler.py,"ReplaceText(target='>=' @(265,102)->(265,103))","def test_gsheets_calculate_periodic_loop_sleep_time(gsheets_handler_no_thread): def test_gsheets_add_rows_to_active_sheet_sets_add_rows_time(gsheets_handler_no_thread): gsheets_handler_no_thread._add_rows_time = 99 assert isinstance(gsheets_handler_no_thread._add_rows_to_active_sheet([]), unittest.mock.Mock) assert gsheets_handler_no_thread._add_rows_time < 99 and gsheets_handler_no_thread._add_rows_time > 0 def test_gsheets_add_rows_to_active_sheet_set_coerce_to_correct_exceptions(gsheets_handler_no_thread): with unittest.mock.patch.object(gsheets_handler_no_thread.sheet, 'append_rows', side_effect=Exception(""RESOURCE_EXHAUSTED uh-oh"")) as mock:","def test_gsheets_calculate_periodic_loop_sleep_time(gsheets_handler_no_thread): def test_gsheets_add_rows_to_active_sheet_sets_add_rows_time(gsheets_handler_no_thread): gsheets_handler_no_thread._add_rows_time = 99 assert isinstance(gsheets_handler_no_thread._add_rows_to_active_sheet([]), unittest.mock.Mock) assert gsheets_handler_no_thread._add_rows_time < 99 and gsheets_handler_no_thread._add_rows_time >= 0 def test_gsheets_add_rows_to_active_sheet_set_coerce_to_correct_exceptions(gsheets_handler_no_thread): with unittest.mock.patch.object(gsheets_handler_no_thread.sheet, 'append_rows', side_effect=Exception(""RESOURCE_EXHAUSTED uh-oh"")) as mock:" 810,https://:@github.com/JorrandeWit/django-oscar-fees.git,7d18c7bdbeb881f4af5f81c1adf989422e134995,"@@ -26,7 +26,7 @@ class FeeApplications(object): 'fee': fee, 'result': result, 'name': fee.name, - 'description': result.description, + 'description': fee.description, 'freq': 0, 'amount': D('0.00')} self.applications[fee.id]['amount'] += result.fee ",django_oscar_fees/results.py,"ReplaceText(target='fee' @(29,31)->(29,37))","class FeeApplications(object): 'fee': fee, 'result': result, 'name': fee.name, 'description': result.description, 'freq': 0, 'amount': D('0.00')} self.applications[fee.id]['amount'] += result.fee","class FeeApplications(object): 'fee': fee, 'result': result, 'name': fee.name, 'description': fee.description, 'freq': 0, 'amount': D('0.00')} self.applications[fee.id]['amount'] += result.fee" 811,https://:@gitlab.com/yhtang/graphdot.git,2ac46e719092b1e78bc2bd860bce1dd23e152638,"@@ -27,7 +27,7 @@ class OctileGraph(object): nnz = len(edges) ''' add phantom label if none exists to facilitate C++ interop ''' - assert(len(edges.columns) >= 1) + assert(len(nodes.columns) >= 1) if len(nodes.columns) == 1: nodes['labeled'] = np.zeros(len(nodes), np.bool_) ",graphdot/kernel/marginalized/_octilegraph.py,"ReplaceText(target='nodes' @(30,19)->(30,24))","class OctileGraph(object): nnz = len(edges) ''' add phantom label if none exists to facilitate C++ interop ''' assert(len(edges.columns) >= 1) if len(nodes.columns) == 1: nodes['labeled'] = np.zeros(len(nodes), np.bool_) ","class OctileGraph(object): nnz = len(edges) ''' add phantom label if none exists to facilitate C++ interop ''' assert(len(nodes.columns) >= 1) if len(nodes.columns) == 1: nodes['labeled'] = np.zeros(len(nodes), np.bool_) " 812,https://:@gitlab.com/yhtang/graphdot.git,c1d46fe384aaac63a6e32b0a30cf6f3aa2b04183,"@@ -315,7 +315,7 @@ class MarginalizedGraphKernel: if traits.eval_gradient is True: output_shape = (output_length, 1 + self.n_dims) else: - output_shape = (output_shape, 1) + output_shape = (output_length, 1) output = backend.empty(int(np.prod(output_shape)), np.float32) timer.toc('creating output buffer') ",graphdot/kernel/marginalized/_kernel.py,"ReplaceText(target='output_length' @(318,28)->(318,40))","class MarginalizedGraphKernel: if traits.eval_gradient is True: output_shape = (output_length, 1 + self.n_dims) else: output_shape = (output_shape, 1) output = backend.empty(int(np.prod(output_shape)), np.float32) timer.toc('creating output buffer') ","class MarginalizedGraphKernel: if traits.eval_gradient is True: output_shape = (output_length, 1 + self.n_dims) else: output_shape = (output_length, 1) output = backend.empty(int(np.prod(output_shape)), np.float32) timer.toc('creating output buffer') " 813,https://:@gitlab.com/yhtang/graphdot.git,f1499423ac76e790b77f729e92b2cc3223d64f58,"@@ -117,7 +117,7 @@ class SpectralApprox(FactorApprox): def __init__(self, X, rcut=0, acut=0): if isinstance(X, np.ndarray): U, S, _ = np.linalg.svd(X, full_matrices=False) - mask = (S >= S.max() * rcut) | (S >= acut) + mask = (S >= S.max() * rcut) & (S >= acut) self.U = U[:, mask] self.S = S[mask] elif isinstance(X, tuple) and len(X) == 2: ",graphdot/linalg/low_rank.py,"ReplaceText(target='&' @(120,41)->(120,42))","class SpectralApprox(FactorApprox): def __init__(self, X, rcut=0, acut=0): if isinstance(X, np.ndarray): U, S, _ = np.linalg.svd(X, full_matrices=False) mask = (S >= S.max() * rcut) | (S >= acut) self.U = U[:, mask] self.S = S[mask] elif isinstance(X, tuple) and len(X) == 2:","class SpectralApprox(FactorApprox): def __init__(self, X, rcut=0, acut=0): if isinstance(X, np.ndarray): U, S, _ = np.linalg.svd(X, full_matrices=False) mask = (S >= S.max() * rcut) & (S >= acut) self.U = U[:, mask] self.S = S[mask] elif isinstance(X, tuple) and len(X) == 2:" 814,https://:@github.com/straga/micropython.git,1679696612007107dac55d936006b1923eda2475,"@@ -7,7 +7,7 @@ desc = { data = bytearray(b""01234567"") -S = uctypes.struct(desc, uctypes.addressof(data), uctypes.LITTLE_ENDIAN) +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) # Arrays of UINT8 are accessed as bytearrays print(S.arr) ",tests/extmod/uctypes_bytearray.py,"ArgSwap(idxs=0<->1 @(10,4)->(10,18))","desc = { data = bytearray(b""01234567"") S = uctypes.struct(desc, uctypes.addressof(data), uctypes.LITTLE_ENDIAN) # Arrays of UINT8 are accessed as bytearrays print(S.arr)","desc = { data = bytearray(b""01234567"") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) # Arrays of UINT8 are accessed as bytearrays print(S.arr)" 815,https://:@github.com/straga/micropython.git,1679696612007107dac55d936006b1923eda2475,"@@ -22,7 +22,7 @@ desc = { data = bytearray(b""01"") -S = uctypes.struct(desc, uctypes.addressof(data), uctypes.LITTLE_ENDIAN) +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) #print(S) print(hex(S.s0)) ",tests/extmod/uctypes_le.py,"ArgSwap(idxs=0<->1 @(25,4)->(25,18))","desc = { data = bytearray(b""01"") S = uctypes.struct(desc, uctypes.addressof(data), uctypes.LITTLE_ENDIAN) #print(S) print(hex(S.s0))","desc = { data = bytearray(b""01"") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) #print(S) print(hex(S.s0))" 816,https://:@github.com/straga/micropython.git,1679696612007107dac55d936006b1923eda2475,"@@ -31,7 +31,7 @@ desc = { data = bytearray(b""01"") -S = uctypes.struct(desc, uctypes.addressof(data), uctypes.NATIVE) +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) #print(S) print(hex(S.s0)) ",tests/extmod/uctypes_native_le.py,"ArgSwap(idxs=0<->1 @(34,4)->(34,18))","desc = { data = bytearray(b""01"") S = uctypes.struct(desc, uctypes.addressof(data), uctypes.NATIVE) #print(S) print(hex(S.s0))","desc = { data = bytearray(b""01"") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) #print(S) print(hex(S.s0))" 817,https://:@github.com/straga/micropython.git,1679696612007107dac55d936006b1923eda2475,"@@ -16,7 +16,7 @@ bytes = b""01"" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc)) -S = uctypes.struct(desc, uctypes.addressof(buf), uctypes.LITTLE_ENDIAN) +S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.LITTLE_ENDIAN) print(S.ptr[0]) assert S.ptr[0] == ord(""0"") ",tests/extmod/uctypes_ptr_le.py,"ArgSwap(idxs=0<->1 @(19,4)->(19,18))","bytes = b""01"" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc)) S = uctypes.struct(desc, uctypes.addressof(buf), uctypes.LITTLE_ENDIAN) print(S.ptr[0]) assert S.ptr[0] == ord(""0"")","bytes = b""01"" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc)) S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.LITTLE_ENDIAN) print(S.ptr[0]) assert S.ptr[0] == ord(""0"")" 818,https://:@github.com/IL2HorusTeam/il2fb-ds-airbridge.git,bc69d1a47a4994071d0b46c7dd29aebf6a7d4169,"@@ -60,7 +60,7 @@ class TextFileWatchDog: def stop(self) -> None: with self._stop_lock: - self._do_stop = False + self._do_stop = True def run(self) -> None: try: ",il2fb/ds/airbridge/watch_dog.py,"ReplaceText(target='True' @(63,28)->(63,33))","class TextFileWatchDog: def stop(self) -> None: with self._stop_lock: self._do_stop = False def run(self) -> None: try:","class TextFileWatchDog: def stop(self) -> None: with self._stop_lock: self._do_stop = True def run(self) -> None: try:" 819,https://:@github.com/south-coast-science/scs_dfe_eng.git,060bd36c51a20f4586ed199b1e3996c70b0318a7,"@@ -49,7 +49,7 @@ class AFE(object): self.__wrk_adc = ADS1115(ADS1115.ADDR_WRK, AFE.__RATE) self.__aux_adc = ADS1115(ADS1115.ADDR_AUX, AFE.__RATE) - self.__pt1000_adc = pt1000_conf.adc(MCP342X.GAIN_4, MCP342X.RATE_15) if pt1000_conf else None + self.__pt1000_adc = pt1000_conf.adc(MCP342X.GAIN_4, MCP342X.RATE_15) if pt1000 else None self.__tconv = self.__wrk_adc.tconv ",scs_dfe/gas/afe.py,"ReplaceText(target='pt1000' @(52,80)->(52,91))","class AFE(object): self.__wrk_adc = ADS1115(ADS1115.ADDR_WRK, AFE.__RATE) self.__aux_adc = ADS1115(ADS1115.ADDR_AUX, AFE.__RATE) self.__pt1000_adc = pt1000_conf.adc(MCP342X.GAIN_4, MCP342X.RATE_15) if pt1000_conf else None self.__tconv = self.__wrk_adc.tconv ","class AFE(object): self.__wrk_adc = ADS1115(ADS1115.ADDR_WRK, AFE.__RATE) self.__aux_adc = ADS1115(ADS1115.ADDR_AUX, AFE.__RATE) self.__pt1000_adc = pt1000_conf.adc(MCP342X.GAIN_4, MCP342X.RATE_15) if pt1000 else None self.__tconv = self.__wrk_adc.tconv " 820,https://:@github.com/ionox0/toil.git,3f065a27c433b1cb9c5266ed4c28b643419d4466,"@@ -456,7 +456,7 @@ def mainLoop(config, batchSystem): reissueOverLongJobs(updatedJobFiles, jobBatcher, config, batchSystem, childJobFileToParentJob, childCounts) logger.info(""Reissued any over long jobs"") - hasNoMissingJobs = reissueMissingJobs(updatedJobFiles, jobBatcher, batchSystem, childJobFileToParentJob, config, childCounts) + hasNoMissingJobs = reissueMissingJobs(updatedJobFiles, jobBatcher, batchSystem, childJobFileToParentJob, childCounts, config) if hasNoMissingJobs: timeSinceJobsLastRescued = time.time() else: ",src/master.py,"ArgSwap(idxs=4<->5 @(459,35)->(459,53))","def mainLoop(config, batchSystem): reissueOverLongJobs(updatedJobFiles, jobBatcher, config, batchSystem, childJobFileToParentJob, childCounts) logger.info(""Reissued any over long jobs"") hasNoMissingJobs = reissueMissingJobs(updatedJobFiles, jobBatcher, batchSystem, childJobFileToParentJob, config, childCounts) if hasNoMissingJobs: timeSinceJobsLastRescued = time.time() else:","def mainLoop(config, batchSystem): reissueOverLongJobs(updatedJobFiles, jobBatcher, config, batchSystem, childJobFileToParentJob, childCounts) logger.info(""Reissued any over long jobs"") hasNoMissingJobs = reissueMissingJobs(updatedJobFiles, jobBatcher, batchSystem, childJobFileToParentJob, childCounts, config) if hasNoMissingJobs: timeSinceJobsLastRescued = time.time() else:" 821,https://:@github.com/ionox0/toil.git,a0e4eadb87f09791088b6c11dc6aec0bf8002991,"@@ -99,7 +99,7 @@ please ensure you re-import targets defined in main"" % self.__class__.__name__) """"""Takes a file (as a path) and uploads it to to the global file store, returns an ID that can be used to retrieve the file. """""" - return self.jobStore.writeFile(localFileName, self.job.jobStoreID) + return self.jobStore.writeFile(self.job.jobStoreID, localFileName) def updateGlobalFile(self, fileStoreID, localFileName): """"""Replaces the existing version of a file in the global file store, keyed by the fileStoreID. ",src/target.py,"ArgSwap(idxs=0<->1 @(102,15)->(102,38))","please ensure you re-import targets defined in main"" % self.__class__.__name__) """"""Takes a file (as a path) and uploads it to to the global file store, returns an ID that can be used to retrieve the file. """""" return self.jobStore.writeFile(localFileName, self.job.jobStoreID) def updateGlobalFile(self, fileStoreID, localFileName): """"""Replaces the existing version of a file in the global file store, keyed by the fileStoreID. ","please ensure you re-import targets defined in main"" % self.__class__.__name__) """"""Takes a file (as a path) and uploads it to to the global file store, returns an ID that can be used to retrieve the file. """""" return self.jobStore.writeFile(self.job.jobStoreID, localFileName) def updateGlobalFile(self, fileStoreID, localFileName): """"""Replaces the existing version of a file in the global file store, keyed by the fileStoreID. " 822,https://:@github.com/ionox0/toil.git,06718f425d5981afabd30bcfa39d866edb5c09b4,"@@ -46,7 +46,7 @@ class Job( object ): #The IDs of predecessors that have finished. #When len(predecessorsFinished) == predecessorNumber then the #job can be run. - self.predecessorsFinished = predecessorNumber or set() + self.predecessorsFinished = predecessorsFinished or set() #The list of successor jobs to run. Successor jobs are stored #as 4-tuples of the form (jobStoreId, memory, cpu, predecessorNumber). ",src/jobTree/job.py,"ReplaceText(target='predecessorsFinished' @(49,36)->(49,53))","class Job( object ): #The IDs of predecessors that have finished. #When len(predecessorsFinished) == predecessorNumber then the #job can be run. self.predecessorsFinished = predecessorNumber or set() #The list of successor jobs to run. Successor jobs are stored #as 4-tuples of the form (jobStoreId, memory, cpu, predecessorNumber).","class Job( object ): #The IDs of predecessors that have finished. #When len(predecessorsFinished) == predecessorNumber then the #job can be run. self.predecessorsFinished = predecessorsFinished or set() #The list of successor jobs to run. Successor jobs are stored #as 4-tuples of the form (jobStoreId, memory, cpu, predecessorNumber)." 823,https://:@github.com/ionox0/toil.git,47ec5287d747036c524100cc49fa4262a73293cf,"@@ -107,7 +107,7 @@ class JobWrapper( object ): """""" if self.logJobStoreFileID is not None: self.clearLogFile(jobStore) - self.logJobStoreFileID = jobStore.writeFile( self.jobStoreID, logFile ) + self.logJobStoreFileID = jobStore.writeFile( logFile, self.jobStoreID ) assert self.logJobStoreFileID is not None def getLogFileHandle( self, jobStore ): ",src/toil/jobWrapper.py,"ArgSwap(idxs=0<->1 @(110,33)->(110,51))","class JobWrapper( object ): """""" if self.logJobStoreFileID is not None: self.clearLogFile(jobStore) self.logJobStoreFileID = jobStore.writeFile( self.jobStoreID, logFile ) assert self.logJobStoreFileID is not None def getLogFileHandle( self, jobStore ):","class JobWrapper( object ): """""" if self.logJobStoreFileID is not None: self.clearLogFile(jobStore) self.logJobStoreFileID = jobStore.writeFile( logFile, self.jobStoreID ) assert self.logJobStoreFileID is not None def getLogFileHandle( self, jobStore ):" 824,https://:@github.com/ionox0/toil.git,cad17f6cbe391264e00675c51a8bfe9221ba1091,"@@ -159,7 +159,7 @@ class AbstractJobStore( object ): break #Reset the retry count of the jobWrapper - if jobWrapper.remainingRetryCount < self._defaultTryCount(): + if jobWrapper.remainingRetryCount != self._defaultTryCount(): jobWrapper.remainingRetryCount = self._defaultTryCount() changed = True ",src/toil/jobStores/abstractJobStore.py,"ReplaceText(target='!=' @(162,46)->(162,47))","class AbstractJobStore( object ): break #Reset the retry count of the jobWrapper if jobWrapper.remainingRetryCount < self._defaultTryCount(): jobWrapper.remainingRetryCount = self._defaultTryCount() changed = True ","class AbstractJobStore( object ): break #Reset the retry count of the jobWrapper if jobWrapper.remainingRetryCount != self._defaultTryCount(): jobWrapper.remainingRetryCount = self._defaultTryCount() changed = True " 825,https://:@github.com/ionox0/toil.git,dcd5e6f86c0f9d376140f4626e97666348683b73,"@@ -437,7 +437,7 @@ class ModuleDescriptor(namedtuple('ModuleDescriptor', ('dirPath', 'name'))): :rtype: toil.resource.Resource """""" - if self._runningOnWorker(): + if not self._runningOnWorker(): log.warn('The localize() method should only be invoked on a worker.') resource = Resource.lookup(self._resourcePath) if resource is None: ",src/toil/resource.py,"ReplaceText(target='not ' @(440,11)->(440,11))","class ModuleDescriptor(namedtuple('ModuleDescriptor', ('dirPath', 'name'))): :rtype: toil.resource.Resource """""" if self._runningOnWorker(): log.warn('The localize() method should only be invoked on a worker.') resource = Resource.lookup(self._resourcePath) if resource is None:","class ModuleDescriptor(namedtuple('ModuleDescriptor', ('dirPath', 'name'))): :rtype: toil.resource.Resource """""" if not self._runningOnWorker(): log.warn('The localize() method should only be invoked on a worker.') resource = Resource.lookup(self._resourcePath) if resource is None:" 826,https://:@github.com/ionox0/toil.git,bee00f3fc4f68af0e7c00b884627f728ca20f792,"@@ -649,7 +649,7 @@ def main(args=None, stdout=sys.stdout): if options.logLevel: cwllogger.setLevel(options.logLevel) - useStrict = not args.not_strict + useStrict = not options.not_strict try: t = cwltool.load_tool.load_tool(options.cwltool, cwltool.workflow.defaultMakeTool, resolver=cwltool.resolver.tool_resolver, strict=useStrict) ",src/toil/cwl/cwltoil.py,"ReplaceText(target='options' @(652,20)->(652,24))","def main(args=None, stdout=sys.stdout): if options.logLevel: cwllogger.setLevel(options.logLevel) useStrict = not args.not_strict try: t = cwltool.load_tool.load_tool(options.cwltool, cwltool.workflow.defaultMakeTool, resolver=cwltool.resolver.tool_resolver, strict=useStrict)","def main(args=None, stdout=sys.stdout): if options.logLevel: cwllogger.setLevel(options.logLevel) useStrict = not options.not_strict try: t = cwltool.load_tool.load_tool(options.cwltool, cwltool.workflow.defaultMakeTool, resolver=cwltool.resolver.tool_resolver, strict=useStrict)" 827,https://:@github.com/ionox0/toil.git,231b6665bde956aae5b3469a7147e2358097fca4,"@@ -143,7 +143,7 @@ class SingleMachineBatchSystem(BatchSystemSupport): startTime = time.time() # Time job is started popen = None statusCode = None - forkWorker = not (self.debugWorker and ""_toil_worker"" not in jobCommand) + forkWorker = not (self.debugWorker and ""_toil_worker"" in jobCommand) if forkWorker: with self.popenLock: popen = subprocess.Popen(jobCommand, ",src/toil/batchSystems/singleMachine.py,"ReplaceText(target=' in ' @(146,61)->(146,69))","class SingleMachineBatchSystem(BatchSystemSupport): startTime = time.time() # Time job is started popen = None statusCode = None forkWorker = not (self.debugWorker and ""_toil_worker"" not in jobCommand) if forkWorker: with self.popenLock: popen = subprocess.Popen(jobCommand,","class SingleMachineBatchSystem(BatchSystemSupport): startTime = time.time() # Time job is started popen = None statusCode = None forkWorker = not (self.debugWorker and ""_toil_worker"" in jobCommand) if forkWorker: with self.popenLock: popen = subprocess.Popen(jobCommand," 828,https://:@github.com/ionox0/toil.git,f5054aca67788f976c72b1e3f42334afe3a1dfaa,"@@ -138,7 +138,7 @@ class AbstractProvisioner(with_metaclass(ABCMeta, object)): self._spotBidsMap[nodeType] = bid else: self.nodeTypes.append(nodeTypeStr) - self.nodeShapes.append(self.getNodeShape(nodeType, preemptable=False)) + self.nodeShapes.append(self.getNodeShape(nodeTypeStr, preemptable=False)) @staticmethod def retryPredicate(e): ",src/toil/provisioners/abstractProvisioner.py,"ReplaceText(target='nodeTypeStr' @(141,57)->(141,65))","class AbstractProvisioner(with_metaclass(ABCMeta, object)): self._spotBidsMap[nodeType] = bid else: self.nodeTypes.append(nodeTypeStr) self.nodeShapes.append(self.getNodeShape(nodeType, preemptable=False)) @staticmethod def retryPredicate(e):","class AbstractProvisioner(with_metaclass(ABCMeta, object)): self._spotBidsMap[nodeType] = bid else: self.nodeTypes.append(nodeTypeStr) self.nodeShapes.append(self.getNodeShape(nodeTypeStr, preemptable=False)) @staticmethod def retryPredicate(e):" 829,https://:@github.com/ionox0/toil.git,59f716aed0363adba211e7c1f18ebe3802edb636,"@@ -108,7 +108,7 @@ class GridEngineBatchSystem(AbstractGridEngineBatchSystem): if not self.boss.config.manualMemArgs: # for UGE instead of SGE; see #2309 reqline += ['vf=' + memStr, 'h_vmem=' + memStr] - elif self.boss.config.manualMemArgs and sgeArgs: + elif self.boss.config.manualMemArgs and not sgeArgs: raise ValueError(""--manualMemArgs set to True, but TOIL_GRIDGENGINE_ARGS is not set."" ""Please set TOIL_GRIDGENGINE_ARGS to specify memory allocation for "" ""your system. Default adds the arguments: vf= h_vmem= "" ",src/toil/batchSystems/gridengine.py,"ReplaceText(target='not ' @(111,56)->(111,56))","class GridEngineBatchSystem(AbstractGridEngineBatchSystem): if not self.boss.config.manualMemArgs: # for UGE instead of SGE; see #2309 reqline += ['vf=' + memStr, 'h_vmem=' + memStr] elif self.boss.config.manualMemArgs and sgeArgs: raise ValueError(""--manualMemArgs set to True, but TOIL_GRIDGENGINE_ARGS is not set."" ""Please set TOIL_GRIDGENGINE_ARGS to specify memory allocation for "" ""your system. Default adds the arguments: vf= h_vmem= ""","class GridEngineBatchSystem(AbstractGridEngineBatchSystem): if not self.boss.config.manualMemArgs: # for UGE instead of SGE; see #2309 reqline += ['vf=' + memStr, 'h_vmem=' + memStr] elif self.boss.config.manualMemArgs and not sgeArgs: raise ValueError(""--manualMemArgs set to True, but TOIL_GRIDGENGINE_ARGS is not set."" ""Please set TOIL_GRIDGENGINE_ARGS to specify memory allocation for "" ""your system. Default adds the arguments: vf= h_vmem= """ 830,https://:@github.com/tkf/railgun.git,f49414f39ca7c6bbbd5e000d45db46b77a4e514d,"@@ -64,7 +64,7 @@ DATA_TEST_CDEC_PARSE = [ (""int a[i] =2"", dict_cdec_parse('int', 'a', tuple('i'), 1, 2)), (""int a[i][j]=3"", dict_cdec_parse('int', 'a', tuple('ij'), 2, 3)), ('num_i = 10', dict_cdec_parse('int', 'num_i', default=10)), - (cmem('obj', DmyCDT), dict_cdec_parse(DmyCDT, 'obj', valtype='object')), + (cmem(DmyCDT, 'obj'), dict_cdec_parse(DmyCDT, 'obj', valtype='object')), ] ",tests/test_cdata.py,"ArgSwap(idxs=0<->1 @(67,5)->(67,9))","DATA_TEST_CDEC_PARSE = [ (""int a[i] =2"", dict_cdec_parse('int', 'a', tuple('i'), 1, 2)), (""int a[i][j]=3"", dict_cdec_parse('int', 'a', tuple('ij'), 2, 3)), ('num_i = 10', dict_cdec_parse('int', 'num_i', default=10)), (cmem('obj', DmyCDT), dict_cdec_parse(DmyCDT, 'obj', valtype='object')), ] ","DATA_TEST_CDEC_PARSE = [ (""int a[i] =2"", dict_cdec_parse('int', 'a', tuple('i'), 1, 2)), (""int a[i][j]=3"", dict_cdec_parse('int', 'a', tuple('ij'), 2, 3)), ('num_i = 10', dict_cdec_parse('int', 'num_i', default=10)), (cmem(DmyCDT, 'obj'), dict_cdec_parse(DmyCDT, 'obj', valtype='object')), ] " 831,https://:@github.com/hubzero/hublib.git,8921395b8feda7af6d59ed2133dd1a4068ae9803,"@@ -486,7 +486,7 @@ def copy_files(errnum, etime, toolname, runName): else: # nonparametric run. Results are in current working directory. # Use the timestamp to copy all newer files to the cacheName. - if errnum > 0: + if errnum == 0: files = os.listdir('.') for f in files: if os.path.getmtime(f) > self.start_time: ",hublib/ui/submit.py,"ReplaceText(target='==' @(489,18)->(489,19))","def copy_files(errnum, etime, toolname, runName): else: # nonparametric run. Results are in current working directory. # Use the timestamp to copy all newer files to the cacheName. if errnum > 0: files = os.listdir('.') for f in files: if os.path.getmtime(f) > self.start_time:","def copy_files(errnum, etime, toolname, runName): else: # nonparametric run. Results are in current working directory. # Use the timestamp to copy all newer files to the cacheName. if errnum == 0: files = os.listdir('.') for f in files: if os.path.getmtime(f) > self.start_time:" 832,https://:@github.com/tjstretchalot/ignite-simple.git,944f32fd5421cb01c0c75be5959277e1a1a2c741,"@@ -240,7 +240,7 @@ class ParamsTaskQueue(disp.TaskQueue, ps.SweepListener): # remove from params_to_task # add to in_progress # return built disp.Task - if cores > self.sweep_cores and self.sweeps: + if cores >= self.sweep_cores and self.sweeps: swp: ParamsTask = self.sweeps.pop() del self.params_to_sweeps_ind[swp.params] self._len -= 1 ",ignite_simple/gen_sweep/sweeper.py,"ReplaceText(target='>=' @(243,17)->(243,18))","class ParamsTaskQueue(disp.TaskQueue, ps.SweepListener): # remove from params_to_task # add to in_progress # return built disp.Task if cores > self.sweep_cores and self.sweeps: swp: ParamsTask = self.sweeps.pop() del self.params_to_sweeps_ind[swp.params] self._len -= 1","class ParamsTaskQueue(disp.TaskQueue, ps.SweepListener): # remove from params_to_task # add to in_progress # return built disp.Task if cores >= self.sweep_cores and self.sweeps: swp: ParamsTask = self.sweeps.pop() del self.params_to_sweeps_ind[swp.params] self._len -= 1" 833,https://:@github.com/jessemyers/lxmlbind.git,35bb1bbc635ea9dca813dffe25165b14576c4a00,"@@ -75,7 +75,7 @@ class Base(object): child = etree.SubElement(parent, head) else: return None - return self.search(child, tail, create) if tail else child + return self.search(tail, child, create) if tail else child def __str__(self): """""" ",lxmlbind/base.py,"ArgSwap(idxs=0<->1 @(78,15)->(78,26))","class Base(object): child = etree.SubElement(parent, head) else: return None return self.search(child, tail, create) if tail else child def __str__(self): """"""","class Base(object): child = etree.SubElement(parent, head) else: return None return self.search(tail, child, create) if tail else child def __str__(self): """"""" 834,https://:@github.com/dieterv/etk.docking.git,f7e423f2e5d2a68183238c2d1eb39dcb4cf7ec30,"@@ -521,7 +521,7 @@ class DockPaned(gtk.Container): width = max(width, w) height += h # Store the minimum weight for usage in do_size_allocate - item.min_size = w + item.min_size = h # Add handles if self._orientation == gtk.ORIENTATION_HORIZONTAL: ",lib/etk/docking/dockpaned.py,"ReplaceText(target='h' @(524,32)->(524,33))","class DockPaned(gtk.Container): width = max(width, w) height += h # Store the minimum weight for usage in do_size_allocate item.min_size = w # Add handles if self._orientation == gtk.ORIENTATION_HORIZONTAL:","class DockPaned(gtk.Container): width = max(width, w) height += h # Store the minimum weight for usage in do_size_allocate item.min_size = h # Add handles if self._orientation == gtk.ORIENTATION_HORIZONTAL:" 835,https://:@github.com/isnok/asciidrumming.git,66e35371a4b96774d931516f7131e19ccf6e2c43,"@@ -42,7 +42,7 @@ def assemble_pieces(phrases, pieces): def clean_phrases(phrases): for phrase in phrases.values(): phrase['pattern'] = ''.join(phrase['pattern']).replace(' ', '') - phrase['length'] = (len(phrase['pattern']) // phrase['beat']) + bool(len(phrase['pattern']) % phrase['beat']) + phrase['length'] = (len(phrase['pattern']) / phrase['beat']) + bool(len(phrase['pattern']) % phrase['beat']) def assemble_phrases(config): ",asciidrumming/assemble.py,"ReplaceText(target='/' @(45,51)->(45,53))","def assemble_pieces(phrases, pieces): def clean_phrases(phrases): for phrase in phrases.values(): phrase['pattern'] = ''.join(phrase['pattern']).replace(' ', '') phrase['length'] = (len(phrase['pattern']) // phrase['beat']) + bool(len(phrase['pattern']) % phrase['beat']) def assemble_phrases(config):","def assemble_pieces(phrases, pieces): def clean_phrases(phrases): for phrase in phrases.values(): phrase['pattern'] = ''.join(phrase['pattern']).replace(' ', '') phrase['length'] = (len(phrase['pattern']) / phrase['beat']) + bool(len(phrase['pattern']) % phrase['beat']) def assemble_phrases(config):" 836,https://:@github.com/FedericoCinus/WoMG.git,75addc91cd520c8e7ebf8975ceaf24b79b2cf49f,"@@ -390,7 +390,7 @@ class LDA(TLTTopicModel): saved_model_fname = str(hash(saved_model))+'.model' if os.path.exists(saved_model_fname): #lda_model = pickle.load(os.path.abspath(saved_model)) - lda_model = gensim.models.ldamodel.LdaModel.load(os.path.abspath(saved_model)) + lda_model = gensim.models.ldamodel.LdaModel.load(os.path.abspath(saved_model_fname)) else: lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=self.dictionary, ",src/test_version/topic/lda.py,"ReplaceText(target='saved_model_fname' @(393,77)->(393,88))","class LDA(TLTTopicModel): saved_model_fname = str(hash(saved_model))+'.model' if os.path.exists(saved_model_fname): #lda_model = pickle.load(os.path.abspath(saved_model)) lda_model = gensim.models.ldamodel.LdaModel.load(os.path.abspath(saved_model)) else: lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=self.dictionary,","class LDA(TLTTopicModel): saved_model_fname = str(hash(saved_model))+'.model' if os.path.exists(saved_model_fname): #lda_model = pickle.load(os.path.abspath(saved_model)) lda_model = gensim.models.ldamodel.LdaModel.load(os.path.abspath(saved_model_fname)) else: lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=self.dictionary," 837,https://:@github.com/waikato-datamining/wai-annotations.git,1c1e29a44b802c45c83af7278b1637aa98855a68,"@@ -63,4 +63,4 @@ def get_all_sharded_filenames(filename: str) -> Tuple[str, ...]: if shards == 0: raise ValueError(f""{filename} is not a shard filename"") - return tuple(format_sharded_filename(base_name, shards, i) for i in range(index)) + return tuple(format_sharded_filename(base_name, shards, i) for i in range(shards)) ",src/wai/annotations/tf/utils/_sharded_filenames.py,"ReplaceText(target='shards' @(66,78)->(66,83))","def get_all_sharded_filenames(filename: str) -> Tuple[str, ...]: if shards == 0: raise ValueError(f""{filename} is not a shard filename"") return tuple(format_sharded_filename(base_name, shards, i) for i in range(index))","def get_all_sharded_filenames(filename: str) -> Tuple[str, ...]: if shards == 0: raise ValueError(f""{filename} is not a shard filename"") return tuple(format_sharded_filename(base_name, shards, i) for i in range(shards))" 838,https://:@github.com/broundal/Pytolemaic.git,c407b7b2410fe04641d0261ca209a2e57a728ded,"@@ -220,7 +220,7 @@ class SensitivityAnalysis(): vulnerability_report = self._vulnerability_report( shuffled_sensitivity=self.shuffled_sensitivity, missing_sensitivity=self.missing_sensitivity, - shuffled_sensitivity_stats=missing_stats_report) + shuffled_sensitivity_stats=shuffle_stats_report) return SensitivityFullReport( shuffle_report=self.shuffled_sensitivity, ",pytolemaic/analysis_logic/model_analysis/sensitivity/sensitivity.py,"ReplaceText(target='shuffle_stats_report' @(223,39)->(223,59))","class SensitivityAnalysis(): vulnerability_report = self._vulnerability_report( shuffled_sensitivity=self.shuffled_sensitivity, missing_sensitivity=self.missing_sensitivity, shuffled_sensitivity_stats=missing_stats_report) return SensitivityFullReport( shuffle_report=self.shuffled_sensitivity,","class SensitivityAnalysis(): vulnerability_report = self._vulnerability_report( shuffled_sensitivity=self.shuffled_sensitivity, missing_sensitivity=self.missing_sensitivity, shuffled_sensitivity_stats=shuffle_stats_report) return SensitivityFullReport( shuffle_report=self.shuffled_sensitivity," 839,https://:@github.com/damoti/shipmaster.git,f81614acecb36da1343ec9e114679b06f0d8b0ba,"@@ -94,7 +94,7 @@ class LayerBase: # Only tag image if container was built successfully. repository, tag = self.image_name, None if ':' in repository: - repository, tag = tag.split(':') + repository, tag = repository.split(':') conf = client.create_container_config(self.image_name, cmd, working_dir=APP_PATH) client.commit(container, repository=repository, tag=tag, conf=conf) client.remove_container(container) ",shipmaster/base/builder.py,"ReplaceText(target='repository' @(97,34)->(97,37))","class LayerBase: # Only tag image if container was built successfully. repository, tag = self.image_name, None if ':' in repository: repository, tag = tag.split(':') conf = client.create_container_config(self.image_name, cmd, working_dir=APP_PATH) client.commit(container, repository=repository, tag=tag, conf=conf) client.remove_container(container)","class LayerBase: # Only tag image if container was built successfully. repository, tag = self.image_name, None if ':' in repository: repository, tag = repository.split(':') conf = client.create_container_config(self.image_name, cmd, working_dir=APP_PATH) client.commit(container, repository=repository, tag=tag, conf=conf) client.remove_container(container)" 840,https://:@github.com/ldo/pybidi.git,ef93e8fdd0220fb446238060c7b4f30422251943,"@@ -1352,7 +1352,7 @@ def remove_bidi_marks(string, positions_to_this = None, position_from_this_list if position_from_this_list != None : c_position_from_this_list = seq_to_ct(position_from_this_list, FRIBIDI.StrIndex) else : - position_from_this_list = None + c_position_from_this_list = None #end if if embedding_levels != None : c_embedding_levels = seq_to_ct(embedding_levels, FRIBIDI.StrIndex) ",fribidi.py,"ReplaceText(target='c_position_from_this_list' @(1355,8)->(1355,31))","def remove_bidi_marks(string, positions_to_this = None, position_from_this_list if position_from_this_list != None : c_position_from_this_list = seq_to_ct(position_from_this_list, FRIBIDI.StrIndex) else : position_from_this_list = None #end if if embedding_levels != None : c_embedding_levels = seq_to_ct(embedding_levels, FRIBIDI.StrIndex)","def remove_bidi_marks(string, positions_to_this = None, position_from_this_list if position_from_this_list != None : c_position_from_this_list = seq_to_ct(position_from_this_list, FRIBIDI.StrIndex) else : c_position_from_this_list = None #end if if embedding_levels != None : c_embedding_levels = seq_to_ct(embedding_levels, FRIBIDI.StrIndex)" 841,https://:@github.com/wbolster/cardinality.git,cfc729bc337f8d796d7bfe11a64ef3a3d516575b,"@@ -68,7 +68,7 @@ def between(min, max, iterable): """""" if min < 0: raise ValueError(""'min' must be positive (or zero)"") - if min < 0: + if max < 0: raise ValueError(""'max' must be positive (or zero)"") if min > max: raise ValueError(""'max' must be greater or equal than 'min'"") ",cardinality.py,"ReplaceText(target='max' @(71,7)->(71,10))","def between(min, max, iterable): """""" if min < 0: raise ValueError(""'min' must be positive (or zero)"") if min < 0: raise ValueError(""'max' must be positive (or zero)"") if min > max: raise ValueError(""'max' must be greater or equal than 'min'"")","def between(min, max, iterable): """""" if min < 0: raise ValueError(""'min' must be positive (or zero)"") if max < 0: raise ValueError(""'max' must be positive (or zero)"") if min > max: raise ValueError(""'max' must be greater or equal than 'min'"")" 842,https://:@github.com/zongzhenh/pymysql-pool.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" 843,https://:@github.com/kanzure/python-vba-wrapper.git,98edf03512c8f7960f10fa615867269cdf0821d6,"@@ -315,7 +315,7 @@ class VBA(object): # 29 registers buf = (ctypes.c_int32 * self.register_count)() buf[:] = registers - self._vba.set_registers(registers) + self._vba.set_registers(buf) def _get_max_save_size(self): return self._vba.get_max_save_size() ",vba_wrapper/core.py,"ReplaceText(target='buf' @(318,32)->(318,41))","class VBA(object): # 29 registers buf = (ctypes.c_int32 * self.register_count)() buf[:] = registers self._vba.set_registers(registers) def _get_max_save_size(self): return self._vba.get_max_save_size()","class VBA(object): # 29 registers buf = (ctypes.c_int32 * self.register_count)() buf[:] = registers self._vba.set_registers(buf) def _get_max_save_size(self): return self._vba.get_max_save_size()" 844,https://:@github.com/severb/flowy.git,82cbab85d672880b7c3db69b5e1707e90da7686e,"@@ -191,7 +191,7 @@ class DecisionPoller(object): elif e_type == 'StartChildWorkflowExecutionFailed': SCWEFEA = 'startChildWorkflowExecutionFailedEventAttributes' id = _subworkflow_id(e[SCWEFEA]['workflowId']) - reason = e[SCWEIEA]['cause'] + reason = e[SCWEFEA]['cause'] errors[id] = reason elif e_type == 'TimerStarted': id = e['timerStartedEventAttributes']['timerId'] ",flowy/swf/poller.py,"ReplaceText(target='SCWEFEA' @(194,27)->(194,34))","class DecisionPoller(object): elif e_type == 'StartChildWorkflowExecutionFailed': SCWEFEA = 'startChildWorkflowExecutionFailedEventAttributes' id = _subworkflow_id(e[SCWEFEA]['workflowId']) reason = e[SCWEIEA]['cause'] errors[id] = reason elif e_type == 'TimerStarted': id = e['timerStartedEventAttributes']['timerId']","class DecisionPoller(object): elif e_type == 'StartChildWorkflowExecutionFailed': SCWEFEA = 'startChildWorkflowExecutionFailedEventAttributes' id = _subworkflow_id(e[SCWEFEA]['workflowId']) reason = e[SCWEFEA]['cause'] errors[id] = reason elif e_type == 'TimerStarted': id = e['timerStartedEventAttributes']['timerId']" 845,https://:@github.com/brthor/codetransformer-py2.git,7c327683df810265d01a995d2704c9f8218b0ef7,"@@ -141,7 +141,7 @@ class Instruction(InstructionMeta._marker, metaclass=InstructionMeta): 'little', ) - yield cls(arg) + yield instr(arg) @classmethod def from_opcode(cls, opcode): ",codetransformer/instructions.py,"ReplaceText(target='instr' @(144,18)->(144,21))","class Instruction(InstructionMeta._marker, metaclass=InstructionMeta): 'little', ) yield cls(arg) @classmethod def from_opcode(cls, opcode):","class Instruction(InstructionMeta._marker, metaclass=InstructionMeta): 'little', ) yield instr(arg) @classmethod def from_opcode(cls, opcode):" 846,https://:@github.com/bacadra/bacadra.git,74346189dfe3cac99821fd0a32ddeb3290886c4d,"@@ -1256,7 +1256,7 @@ class texme(TeXM, object, metaclass=texmemeta): elif type(inherit)==str: self.store(inherit, tex) elif inherit is False: - self.data = [tex + '\n%'] + self.data += [tex + '\n%'] if self.echo: print('[texme.' + name + ']\n' + tex) ",bacadra/pinky/texme/texme.py,"ReplaceText(target='+=' @(1259,22)->(1259,23))","class texme(TeXM, object, metaclass=texmemeta): elif type(inherit)==str: self.store(inherit, tex) elif inherit is False: self.data = [tex + '\n%'] if self.echo: print('[texme.' + name + ']\n' + tex) ","class texme(TeXM, object, metaclass=texmemeta): elif type(inherit)==str: self.store(inherit, tex) elif inherit is False: self.data += [tex + '\n%'] if self.echo: print('[texme.' + name + ']\n' + tex) " 847,https://:@github.com/bacadra/bacadra.git,3e4cd62c6a0769ea886aaae2104aeb5dff18dbea,"@@ -1131,7 +1131,7 @@ class texme(metaclass=texmemeta): return self.add( submodule = _name1, - code = code, + code = tex, inherit = inherit, echo = echo, ) ",bacadra/pinky/texme/texme.py,"ReplaceText(target='tex' @(1134,24)->(1134,28))","class texme(metaclass=texmemeta): return self.add( submodule = _name1, code = code, inherit = inherit, echo = echo, )","class texme(metaclass=texmemeta): return self.add( submodule = _name1, code = tex, inherit = inherit, echo = echo, )" 848,https://:@github.com/ulif/diceware-list.git,744223382d439315c8195d3ddff170e3542d80f0,"@@ -92,4 +92,4 @@ def local_android_download(request, monkeypatch, tmpdir): monkeypatch.setattr( ""diceware_list.libwordlist.AndroidWordList.base_url"", fake_base_url) - return dictfile + return tmpdir ",tests/conftest.py,"ReplaceText(target='tmpdir' @(95,11)->(95,19))","def local_android_download(request, monkeypatch, tmpdir): monkeypatch.setattr( ""diceware_list.libwordlist.AndroidWordList.base_url"", fake_base_url) return dictfile","def local_android_download(request, monkeypatch, tmpdir): monkeypatch.setattr( ""diceware_list.libwordlist.AndroidWordList.base_url"", fake_base_url) return tmpdir" 849,https://:@github.com/AeGean-Studio/pysolr_aio.git,056f4e2d4284fc740bcc7862fabab673ea1a439b,"@@ -747,7 +747,7 @@ class Solr(object): m = force_unicode(m) end_time = time.time() - self.log.debug(""Built add request of %s docs in %0.2f seconds."", len(docs), end_time - start_time) + self.log.debug(""Built add request of %s docs in %0.2f seconds."", len(message), end_time - start_time) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher) def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None): ",pysolr.py,"ReplaceText(target='message' @(750,77)->(750,81))","class Solr(object): m = force_unicode(m) end_time = time.time() self.log.debug(""Built add request of %s docs in %0.2f seconds."", len(docs), end_time - start_time) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher) def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None):","class Solr(object): m = force_unicode(m) end_time = time.time() self.log.debug(""Built add request of %s docs in %0.2f seconds."", len(message), end_time - start_time) return self._update(m, commit=commit, waitFlush=waitFlush, waitSearcher=waitSearcher) def delete(self, id=None, q=None, commit=True, waitFlush=None, waitSearcher=None):" 850,https://:@bitbucket.org/nidusfr/grapheekdb.git,4f9ca53b0ea54eb7b531290818619a0a2082750f,"@@ -49,7 +49,7 @@ class Optimizer(object): def get_kind_ids(self, txn, kind): ENTITY_COUNTER = METADATA_VERTEX_COUNTER if kind == KIND_VERTEX else METADATA_EDGE_COUNTER METADATA_ID_LIST_PREFIX = METADATA_VERTEX_ID_LIST_PREFIX if kind == KIND_VERTEX else METADATA_EDGE_ID_LIST_PREFIX - limit = int(self._graph._get(None, ENTITY_COUNTER)) / CHUNK_SIZE + limit = int(self._graph._get(None, ENTITY_COUNTER)) // CHUNK_SIZE keys = [build_key(METADATA_ID_LIST_PREFIX, i) for i in range(0, limit + 1)] list_entity_ids = self._graph._bulk_get_lst(txn, keys) for entity_ids in list_entity_ids: ",grapheekdb/backends/data/optimizer.py,"ReplaceText(target='//' @(52,60)->(52,61))","class Optimizer(object): def get_kind_ids(self, txn, kind): ENTITY_COUNTER = METADATA_VERTEX_COUNTER if kind == KIND_VERTEX else METADATA_EDGE_COUNTER METADATA_ID_LIST_PREFIX = METADATA_VERTEX_ID_LIST_PREFIX if kind == KIND_VERTEX else METADATA_EDGE_ID_LIST_PREFIX limit = int(self._graph._get(None, ENTITY_COUNTER)) / CHUNK_SIZE keys = [build_key(METADATA_ID_LIST_PREFIX, i) for i in range(0, limit + 1)] list_entity_ids = self._graph._bulk_get_lst(txn, keys) for entity_ids in list_entity_ids:","class Optimizer(object): def get_kind_ids(self, txn, kind): ENTITY_COUNTER = METADATA_VERTEX_COUNTER if kind == KIND_VERTEX else METADATA_EDGE_COUNTER METADATA_ID_LIST_PREFIX = METADATA_VERTEX_ID_LIST_PREFIX if kind == KIND_VERTEX else METADATA_EDGE_ID_LIST_PREFIX limit = int(self._graph._get(None, ENTITY_COUNTER)) // CHUNK_SIZE keys = [build_key(METADATA_ID_LIST_PREFIX, i) for i in range(0, limit + 1)] list_entity_ids = self._graph._bulk_get_lst(txn, keys) for entity_ids in list_entity_ids:" 851,https://:@github.com/AnonSolutions/django-indy-community.git,274dcaf28dd3b433f5205f8bef13063a09047fa7,"@@ -559,7 +559,7 @@ def send_claims_for_proof_request(wallet, connection, my_conversation, credentia except: raise - return proof_data + return my_conversation ###################################################################### ",indy_community_demo/indy_community/agent_utils.py,"ReplaceText(target='my_conversation' @(562,11)->(562,21))","def send_claims_for_proof_request(wallet, connection, my_conversation, credentia except: raise return proof_data ######################################################################","def send_claims_for_proof_request(wallet, connection, my_conversation, credentia except: raise return my_conversation ######################################################################" 852,https://:@github.com/AnonSolutions/django-indy-community.git,7c1d4634416f608a4886444e51691036e6ba5e70,"@@ -336,7 +336,7 @@ def check_connection_status(wallet, connection, initialize_vcx=True): my_connection.status = return_state my_connection.save() - check_connection_callback(connection, prev_status) + check_connection_callback(my_connection, prev_status) except: raise finally: ",indy_community_demo/indy_community/agent_utils.py,"ReplaceText(target='my_connection' @(339,34)->(339,44))","def check_connection_status(wallet, connection, initialize_vcx=True): my_connection.status = return_state my_connection.save() check_connection_callback(connection, prev_status) except: raise finally:","def check_connection_status(wallet, connection, initialize_vcx=True): my_connection.status = return_state my_connection.save() check_connection_callback(my_connection, prev_status) except: raise finally:" 853,https://:@github.com/jisson/django-simple-domain.git,794a491f075a8d43fbc12f18aa6ace33a590bc86,"@@ -48,7 +48,7 @@ class DjangoSimpleSiteConfig(AppConfig): if SIMPLE_DOMAIN_ENABLED is True """""" std_logger.info(""Checking if module should be enabled..."") - return simple_site_settings.ENABLED and simple_site_utils.is_item_in_list_a_in_list_b( + return simple_site_settings.ENABLED and not simple_site_utils.is_item_in_list_a_in_list_b( simple_site_settings.DEACTIVATING_COMMANDS, sys.argv ) ",django_simple_domain/app.py,"ReplaceText(target='not ' @(51,48)->(51,48))","class DjangoSimpleSiteConfig(AppConfig): if SIMPLE_DOMAIN_ENABLED is True """""" std_logger.info(""Checking if module should be enabled..."") return simple_site_settings.ENABLED and simple_site_utils.is_item_in_list_a_in_list_b( simple_site_settings.DEACTIVATING_COMMANDS, sys.argv ) ","class DjangoSimpleSiteConfig(AppConfig): if SIMPLE_DOMAIN_ENABLED is True """""" std_logger.info(""Checking if module should be enabled..."") return simple_site_settings.ENABLED and not simple_site_utils.is_item_in_list_a_in_list_b( simple_site_settings.DEACTIVATING_COMMANDS, sys.argv ) " 854,https://:@github.com/pkumza/libradar.git,5c3676fd09674f198c20b17d4462e0b6e528bc30,"@@ -318,7 +318,7 @@ class Tree(object): # JSON support utg_lib_obj = dict() # untagged library object utg_lib_obj[""Package""] = node.pn - utg_lib_obj[""Standard Package""] = u + utg_lib_obj[""Standard Package""] = a utg_lib_obj[""Library""] = ""Unknown"" utg_lib_obj[""Popularity""] = int(c) utg_lib_obj[""Weight""] = node.weight ",LibRadar/dex_tree.py,"ReplaceText(target='a' @(321,42)->(321,43))","class Tree(object): # JSON support utg_lib_obj = dict() # untagged library object utg_lib_obj[""Package""] = node.pn utg_lib_obj[""Standard Package""] = u utg_lib_obj[""Library""] = ""Unknown"" utg_lib_obj[""Popularity""] = int(c) utg_lib_obj[""Weight""] = node.weight","class Tree(object): # JSON support utg_lib_obj = dict() # untagged library object utg_lib_obj[""Package""] = node.pn utg_lib_obj[""Standard Package""] = a utg_lib_obj[""Library""] = ""Unknown"" utg_lib_obj[""Popularity""] = int(c) utg_lib_obj[""Weight""] = node.weight" 855,https://:@github.com/moremoban/gease.git,492b0e368076bf3f48eafce06e4eb960d9188360,"@@ -83,5 +83,5 @@ def which_org_has(repo): org_repo = Repo(org_info['repos_url']) for arepo in org_repo.get_all_repos(): if repo == arepo['name']: - return arepo['login'] + return org_info['login'] return None ",gease/release.py,"ReplaceText(target='org_info' @(86,23)->(86,28))","def which_org_has(repo): org_repo = Repo(org_info['repos_url']) for arepo in org_repo.get_all_repos(): if repo == arepo['name']: return arepo['login'] return None","def which_org_has(repo): org_repo = Repo(org_info['repos_url']) for arepo in org_repo.get_all_repos(): if repo == arepo['name']: return org_info['login'] return None" 856,https://:@github.com/eflynch/dspy.git,27d706cdf4e25c5750560d957e34319cfd51e145,"@@ -21,7 +21,7 @@ def rechannel(buf, in_channels, out_channels): in_channel = (in_channel + 1) % in_channels elif out_channels > in_channels: out_channel = 0 - for in_channel in range(out_channels): + for in_channel in range(in_channels): output[out_channel::out_channels] += buf[in_channel::in_channels] out_channel = (out_channel + 1) % out_channels ",dspy/lib.py,"ReplaceText(target='in_channels' @(24,32)->(24,44))","def rechannel(buf, in_channels, out_channels): in_channel = (in_channel + 1) % in_channels elif out_channels > in_channels: out_channel = 0 for in_channel in range(out_channels): output[out_channel::out_channels] += buf[in_channel::in_channels] out_channel = (out_channel + 1) % out_channels ","def rechannel(buf, in_channels, out_channels): in_channel = (in_channel + 1) % in_channels elif out_channels > in_channels: out_channel = 0 for in_channel in range(in_channels): output[out_channel::out_channels] += buf[in_channel::in_channels] out_channel = (out_channel + 1) % out_channels " 857,https://:@gitlab.com/AmosEgel/smuthi.git,3de13ee6ce0382c2657d94d62dab15c6bc0dca0f,"@@ -168,7 +168,7 @@ class PiecewiseFieldExpansion(FieldExpansion): else: pfe_sum.expansion_list.append(fex) if not added: - pfe_sum.expansion_list.append(fex) + pfe_sum.expansion_list.append(other) return pfe_sum ",smuthi/field_expansion.py,"ReplaceText(target='other' @(171,46)->(171,49))","class PiecewiseFieldExpansion(FieldExpansion): else: pfe_sum.expansion_list.append(fex) if not added: pfe_sum.expansion_list.append(fex) return pfe_sum ","class PiecewiseFieldExpansion(FieldExpansion): else: pfe_sum.expansion_list.append(fex) if not added: pfe_sum.expansion_list.append(other) return pfe_sum " 858,https://:@github.com/inkeye/cyscore.git,f7b659afcfa4dce73a8915e8fccd916a68248d83,"@@ -40,4 +40,4 @@ class Score: ""--nodisplays"", orcname, sconame]) - return fname + return outname ",cyscore/score.py,"ReplaceText(target='outname' @(43,15)->(43,20))","class Score: ""--nodisplays"", orcname, sconame]) return fname","class Score: ""--nodisplays"", orcname, sconame]) return outname" 859,https://:@github.com/DMSC-Instrument-Data/lewis.git,b2797261ac0f3ab9f02dc67f28db1620732d3f0b,"@@ -101,7 +101,7 @@ class TestAdapterCollection(unittest.TestCase): collection.device = 'foo' self.assertEqual(mock_adapter1.device, 'foo') - self.assertEqual(mock_adapter1.device, 'foo') + self.assertEqual(mock_adapter2.device, 'foo') mock_adapter3 = MagicMock() mock_adapter3.device = 'other' ",test/test_core_adapters.py,"ReplaceText(target='mock_adapter2' @(104,25)->(104,38))","class TestAdapterCollection(unittest.TestCase): collection.device = 'foo' self.assertEqual(mock_adapter1.device, 'foo') self.assertEqual(mock_adapter1.device, 'foo') mock_adapter3 = MagicMock() mock_adapter3.device = 'other'","class TestAdapterCollection(unittest.TestCase): collection.device = 'foo' self.assertEqual(mock_adapter1.device, 'foo') self.assertEqual(mock_adapter2.device, 'foo') mock_adapter3 = MagicMock() mock_adapter3.device = 'other'" 860,https://:@github.com/DMSC-Instrument-Data/lewis.git,50911fba54fc6f9b4099191c7c81f52f66a6ba47,"@@ -82,7 +82,7 @@ class ExposedObject(object): exposed_members = members if members else self._public_members() exclude = list(exclude or []) - if not exclude_inherited: + if exclude_inherited: for base in inspect.getmro(type(obj))[1:]: exclude += dir(base) ",lewis/core/control_server.py,"ReplaceText(target='' @(85,11)->(85,15))","class ExposedObject(object): exposed_members = members if members else self._public_members() exclude = list(exclude or []) if not exclude_inherited: for base in inspect.getmro(type(obj))[1:]: exclude += dir(base) ","class ExposedObject(object): exposed_members = members if members else self._public_members() exclude = list(exclude or []) if exclude_inherited: for base in inspect.getmro(type(obj))[1:]: exclude += dir(base) " 861,https://:@github.com/fafhrd91/player.git,8bffaa237459e1d9a79c8ba6cd01a482f72ce2f8,"@@ -41,7 +41,7 @@ def add_layer(cfg, layer, name='', path='', description=''): layers.insert(0, intr) cfg.action(discr, introspectables=(intr,)) - log.info(""Add layer: %s path:%s""%(layer, directory)) + log.info(""Add layer: %s path:%s""%(layer, path)) def add_layers(cfg, name='', path='', description=''): ",player/layer.py,"ReplaceText(target='path' @(44,45)->(44,54))","def add_layer(cfg, layer, name='', path='', description=''): layers.insert(0, intr) cfg.action(discr, introspectables=(intr,)) log.info(""Add layer: %s path:%s""%(layer, directory)) def add_layers(cfg, name='', path='', description=''):","def add_layer(cfg, layer, name='', path='', description=''): layers.insert(0, intr) cfg.action(discr, introspectables=(intr,)) log.info(""Add layer: %s path:%s""%(layer, path)) def add_layers(cfg, name='', path='', description=''):" 862,https://:@github.com/clumsyme/ziroom_watcher.git,91498a31498833d88401888b7cfc7c32cffb7464,"@@ -58,7 +58,7 @@ class Watcher: self.info_url, headers=self.headers) info = json.loads(response.text) status = info['data']['status'] - if status == 'tzpzz': + if status != 'tzpzz': self.sendmail('房源状态已更新', '状态更新了') else: raise NotDoneError(status) ",ziroom_watcher.py,"ReplaceText(target='!=' @(61,18)->(61,20))","class Watcher: self.info_url, headers=self.headers) info = json.loads(response.text) status = info['data']['status'] if status == 'tzpzz': self.sendmail('房源状态已更新', '状态更新了') else: raise NotDoneError(status)","class Watcher: self.info_url, headers=self.headers) info = json.loads(response.text) status = info['data']['status'] if status != 'tzpzz': self.sendmail('房源状态已更新', '状态更新了') else: raise NotDoneError(status)" 863,https://:@github.com/kovpas/itc.cli.git,ed0f4e9946469673f2d75ca713ade2b69ac19c25,"@@ -244,7 +244,7 @@ class ITCServerParser(BaseParser): for ratingTr in appRatingTable: inputs = ratingTr.xpath('.//input') - if len(inputs) != 2: + if len(inputs) < 2: continue appRating = {'name': inputs[0].attrib['name'], 'ratings': []} for inpt in inputs: ",itc/parsers/serverparser.py,"ReplaceText(target='<' @(247,27)->(247,29))","class ITCServerParser(BaseParser): for ratingTr in appRatingTable: inputs = ratingTr.xpath('.//input') if len(inputs) != 2: continue appRating = {'name': inputs[0].attrib['name'], 'ratings': []} for inpt in inputs:","class ITCServerParser(BaseParser): for ratingTr in appRatingTable: inputs = ratingTr.xpath('.//input') if len(inputs) < 2: continue appRating = {'name': inputs[0].attrib['name'], 'ratings': []} for inpt in inputs:" 864,https://:@github.com/seebye/media-layer.git,e906f0a4648683f27aa99a5a549020064052edd5,"@@ -170,7 +170,7 @@ class ForcedCoverImageScaler(DistortImageScaler, OffsetImageScaler): width: int, height: int): width, height = self.calculate_resolution(image, width, height) image_width, image_height = image.width, image.height - if image_width < image_height: + if image_width > image_height: image_height = int(image_height * width / image_width) image_width = width else: ",ueberzug/scaling.py,"ReplaceText(target='>' @(173,23)->(173,24))","class ForcedCoverImageScaler(DistortImageScaler, OffsetImageScaler): width: int, height: int): width, height = self.calculate_resolution(image, width, height) image_width, image_height = image.width, image.height if image_width < image_height: image_height = int(image_height * width / image_width) image_width = width else:","class ForcedCoverImageScaler(DistortImageScaler, OffsetImageScaler): width: int, height: int): width, height = self.calculate_resolution(image, width, height) image_width, image_height = image.width, image.height if image_width > image_height: image_height = int(image_height * width / image_width) image_width = width else:" 865,https://:@github.com/lvapeab/multimodal_keras_wrapper.git,965b970084e59e945036df9cc7cd836d052cb279,"@@ -1286,7 +1286,7 @@ class Dataset(object): elif(type_out == 'binary'): y = np.array(y).astype(np.uint8) elif(type_out == 'text'): - y = self.loadText(y, self.vocabulary[id_out], self.max_text_len[id_out], self.text_offset[id_in]) + y = self.loadText(y, self.vocabulary[id_out], self.max_text_len[id_out], self.text_offset[id_out]) #if max_len == 0: y_aux = np.zeros(list(y.shape)+[self.n_classes_text[id_out]]).astype(np.uint8) for idx in range(y.shape[0]): ",keras_wrapper/dataset.py,"ReplaceText(target='id_out' @(1289,110)->(1289,115))","class Dataset(object): elif(type_out == 'binary'): y = np.array(y).astype(np.uint8) elif(type_out == 'text'): y = self.loadText(y, self.vocabulary[id_out], self.max_text_len[id_out], self.text_offset[id_in]) #if max_len == 0: y_aux = np.zeros(list(y.shape)+[self.n_classes_text[id_out]]).astype(np.uint8) for idx in range(y.shape[0]):","class Dataset(object): elif(type_out == 'binary'): y = np.array(y).astype(np.uint8) elif(type_out == 'text'): y = self.loadText(y, self.vocabulary[id_out], self.max_text_len[id_out], self.text_offset[id_out]) #if max_len == 0: y_aux = np.zeros(list(y.shape)+[self.n_classes_text[id_out]]).astype(np.uint8) for idx in range(y.shape[0]):" 866,https://:@github.com/mic159/komodo.git,9b5fcd652ace81e3ee53bedec1eadc1189b08efc,"@@ -94,7 +94,7 @@ class Server(object): scheduler = Scheduler() if not self.without_checks: for name, server in servers.items(): - scheduler.register(name, server) + scheduler.register(server, name) checks_thread = threading.Thread(target=self.start_checks, args=(scheduler, self.thread_stopper, )) checks_thread.daemon = True ",python_dashing/server/server.py,"ArgSwap(idxs=0<->1 @(97,20)->(97,38))","class Server(object): scheduler = Scheduler() if not self.without_checks: for name, server in servers.items(): scheduler.register(name, server) checks_thread = threading.Thread(target=self.start_checks, args=(scheduler, self.thread_stopper, )) checks_thread.daemon = True","class Server(object): scheduler = Scheduler() if not self.without_checks: for name, server in servers.items(): scheduler.register(server, name) checks_thread = threading.Thread(target=self.start_checks, args=(scheduler, self.thread_stopper, )) checks_thread.daemon = True" 867,https://:@github.com/mic159/komodo.git,10d4ba791b59d5873a561d58ee8a096ad104a581,"@@ -32,7 +32,7 @@ class JsonDataStore(object): def save(self): with open(self.location, 'wb') as fle: - return json.dump(fle, self.data) + return json.dump(self.data, fle) def set(self, prefix, key, value): self.data[prefix][key] = value ",dashmat/datastore.py,"ArgSwap(idxs=0<->1 @(35,19)->(35,28))","class JsonDataStore(object): def save(self): with open(self.location, 'wb') as fle: return json.dump(fle, self.data) def set(self, prefix, key, value): self.data[prefix][key] = value","class JsonDataStore(object): def save(self): with open(self.location, 'wb') as fle: return json.dump(self.data, fle) def set(self, prefix, key, value): self.data[prefix][key] = value" 868,https://:@github.com/krvss/graph-talk.git,f91b24ea9c154f6659faecc806f562ef1ee448e3,"@@ -103,6 +103,6 @@ def get_callable(c): def tuples(*args): res = () for arg in args: - res += tuple(arg) if is_list(args) else (arg, ) + res += tuple(arg) if is_list(arg) else (arg, ) return res ",utils.py,"ReplaceText(target='arg' @(106,37)->(106,41))","def get_callable(c): def tuples(*args): res = () for arg in args: res += tuple(arg) if is_list(args) else (arg, ) return res","def get_callable(c): def tuples(*args): res = () for arg in args: res += tuple(arg) if is_list(arg) else (arg, ) return res" 869,https://:@github.com/reichlab/zoltpy.git,8653aa031af8e1dfd2a33e63eb25b642ab719acd,"@@ -70,7 +70,7 @@ def upload_forecast(project_name, model_name, timezero_date, forecast_csv_file): print('* working with', model) # upload a new forecast - upload_file_job = model.upload_forecast(timezero_date, forecast_csv_file) + upload_file_job = model.upload_forecast(forecast_csv_file, timezero_date) busy_poll_upload_file_job(upload_file_job) # get the new forecast from the upload_file_job by parsing the generic 'output_json' field ",zoltpy/functions.py,"ArgSwap(idxs=0<->1 @(73,22)->(73,43))","def upload_forecast(project_name, model_name, timezero_date, forecast_csv_file): print('* working with', model) # upload a new forecast upload_file_job = model.upload_forecast(timezero_date, forecast_csv_file) busy_poll_upload_file_job(upload_file_job) # get the new forecast from the upload_file_job by parsing the generic 'output_json' field","def upload_forecast(project_name, model_name, timezero_date, forecast_csv_file): print('* working with', model) # upload a new forecast upload_file_job = model.upload_forecast(forecast_csv_file, timezero_date) busy_poll_upload_file_job(upload_file_job) # get the new forecast from the upload_file_job by parsing the generic 'output_json' field" 870,https://:@github.com/awbirdsall/popmodel.git,918e2083f541a4c85145fea3f007ed646bc60d19,"@@ -34,7 +34,7 @@ def k_solved(hpar, par): def k_sweep(hpar, par): par_sweep = deepcopy(par) par_sweep['sweep']['dosweep'] = True - k_sweep = pm.KineticsRun(hpar, **par) + k_sweep = pm.KineticsRun(hpar, **par_sweep) k_sweep.solveode() return k_sweep ",tests/test_main.py,"ReplaceText(target='par_sweep' @(37,37)->(37,40))","def k_solved(hpar, par): def k_sweep(hpar, par): par_sweep = deepcopy(par) par_sweep['sweep']['dosweep'] = True k_sweep = pm.KineticsRun(hpar, **par) k_sweep.solveode() return k_sweep ","def k_solved(hpar, par): def k_sweep(hpar, par): par_sweep = deepcopy(par) par_sweep['sweep']['dosweep'] = True k_sweep = pm.KineticsRun(hpar, **par_sweep) k_sweep.solveode() return k_sweep " 871,https://:@github.com/jezeniel/jellyfish-wheel.git,22e790ad922b0122ad40293d594d32e2819d6387,"@@ -422,7 +422,7 @@ def metaphone(s): elif next == 'h' and nextnext and nextnext not in 'aeiou': i += 1 elif c == 'h': - if i == 0 or next in 'aeiou' or s[i-1] in 'aeiou': + if i == 0 or next in 'aeiou' or s[i-1] not in 'aeiou': result.append('h') elif c == 'k': if i == 0 or s[i-1] != 'c': ",jellyfish/_jellyfish.py,"ReplaceText(target=' not in ' @(425,50)->(425,54))","def metaphone(s): elif next == 'h' and nextnext and nextnext not in 'aeiou': i += 1 elif c == 'h': if i == 0 or next in 'aeiou' or s[i-1] in 'aeiou': result.append('h') elif c == 'k': if i == 0 or s[i-1] != 'c':","def metaphone(s): elif next == 'h' and nextnext and nextnext not in 'aeiou': i += 1 elif c == 'h': if i == 0 or next in 'aeiou' or s[i-1] not in 'aeiou': result.append('h') elif c == 'k': if i == 0 or s[i-1] != 'c':" 872,https://:@github.com/tourbillonpy/tourbillon-log.git,cee5b1f59349b7b95b7d9c406b36eab609ef386e,"@@ -27,7 +27,7 @@ def get_logfile_metrics(agent): db_config['duration'], db_config['replication'], db_config['name']) - logger.info('database ""%s"" created successfully', config['name']) + logger.info('database ""%s"" created successfully', db_config['name']) except: pass ",tourbillon/log/log.py,"ReplaceText(target='db_config' @(30,58)->(30,64))","def get_logfile_metrics(agent): db_config['duration'], db_config['replication'], db_config['name']) logger.info('database ""%s"" created successfully', config['name']) except: pass ","def get_logfile_metrics(agent): db_config['duration'], db_config['replication'], db_config['name']) logger.info('database ""%s"" created successfully', db_config['name']) except: pass " 873,https://:@github.com/OriHoch/ckanext-upload_via_email.git,9f12f3b51b7a1ac8db665a673f8cca571a840529,"@@ -33,7 +33,7 @@ def get_sender_organization_id(from_email, to_email, allowed_senders, config): default_sender_organization_id = config.get('default_sender_organization_id') if default_sender_to_address and default_sender_organization_id: default_sender_to_address = default_sender_to_address.lower().strip() - if is_email_match(from_email, default_sender_to_address): + if is_email_match(to_email, default_sender_to_address): return default_sender_organization_id return None ",ckanext/upload_via_email/pipelines/download_messages.py,"ReplaceText(target='to_email' @(36,30)->(36,40))","def get_sender_organization_id(from_email, to_email, allowed_senders, config): default_sender_organization_id = config.get('default_sender_organization_id') if default_sender_to_address and default_sender_organization_id: default_sender_to_address = default_sender_to_address.lower().strip() if is_email_match(from_email, default_sender_to_address): return default_sender_organization_id return None ","def get_sender_organization_id(from_email, to_email, allowed_senders, config): default_sender_organization_id = config.get('default_sender_organization_id') if default_sender_to_address and default_sender_organization_id: default_sender_to_address = default_sender_to_address.lower().strip() if is_email_match(to_email, default_sender_to_address): return default_sender_organization_id return None " 874,https://:@github.com/portfors-lab/sparkle.git,5be995abef4100cdce6e2feb5cee977476140a84,"@@ -62,7 +62,7 @@ class ProtocolRunner(ListAcquisitionRunner): self.avg_buffer[irep,:] = response if irep == self.nreps -1: avg_response = self.avg_buffer.mean(axis=0) - self.datafile.append(self.current_dataset_name, response) + self.datafile.append(self.current_dataset_name, avg_response) self.avg_buffer = np.zeros_like(self.avg_buffer) else: self.datafile.append(self.current_dataset_name, response) ",sparkle/run/protocol_runner.py,"ReplaceText(target='avg_response' @(65,68)->(65,76))","class ProtocolRunner(ListAcquisitionRunner): self.avg_buffer[irep,:] = response if irep == self.nreps -1: avg_response = self.avg_buffer.mean(axis=0) self.datafile.append(self.current_dataset_name, response) self.avg_buffer = np.zeros_like(self.avg_buffer) else: self.datafile.append(self.current_dataset_name, response)","class ProtocolRunner(ListAcquisitionRunner): self.avg_buffer[irep,:] = response if irep == self.nreps -1: avg_response = self.avg_buffer.mean(axis=0) self.datafile.append(self.current_dataset_name, avg_response) self.avg_buffer = np.zeros_like(self.avg_buffer) else: self.datafile.append(self.current_dataset_name, response)" 875,https://:@github.com/a1ezzz/wasp-general.git,5795c4cb45c70e120a94c0dd3598762505131b29,"@@ -59,7 +59,7 @@ def test_abstract(): pytest.raises(NotImplementedError, WSignalSourceProto.remove_callback, None, 'signal', C()) pytest.raises(TypeError, WSignalCallbackProto) - pytest.raises(NotImplementedError, WSignalCallbackProto.__call__, None, 'signal', S(), 1) + pytest.raises(NotImplementedError, WSignalCallbackProto.__call__, None, S(), 'signal', 1) pytest.raises(TypeError, WSignalProxyProto.ProxiedMessageProto) pytest.raises(NotImplementedError, WSignalProxyProto.ProxiedMessageProto.is_weak, None) ",tests/wasp_general_signals_proto_test.py,"ArgSwap(idxs=3<->4 @(62,1)->(62,14))","def test_abstract(): pytest.raises(NotImplementedError, WSignalSourceProto.remove_callback, None, 'signal', C()) pytest.raises(TypeError, WSignalCallbackProto) pytest.raises(NotImplementedError, WSignalCallbackProto.__call__, None, 'signal', S(), 1) pytest.raises(TypeError, WSignalProxyProto.ProxiedMessageProto) pytest.raises(NotImplementedError, WSignalProxyProto.ProxiedMessageProto.is_weak, None)","def test_abstract(): pytest.raises(NotImplementedError, WSignalSourceProto.remove_callback, None, 'signal', C()) pytest.raises(TypeError, WSignalCallbackProto) pytest.raises(NotImplementedError, WSignalCallbackProto.__call__, None, S(), 'signal', 1) pytest.raises(TypeError, WSignalProxyProto.ProxiedMessageProto) pytest.raises(NotImplementedError, WSignalProxyProto.ProxiedMessageProto.is_weak, None)" 876,https://:@github.com/drasmuss/hessianfree.git,883099364fb68ec67b538fffa804a3783d23ad02,"@@ -80,7 +80,7 @@ class CrossEntropy(LossFunction): class ClassificationError(LossFunction): @output_loss def loss(self, output, targets): - return (np.argmax(output, axis=-1) == + return (np.argmax(output, axis=-1) != np.argmax(np.nan_to_num(targets), axis=-1)) # note: not defining d_loss or d2_loss; classification error should only ",hessianfree/loss_funcs.py,"ReplaceText(target='!=' @(83,43)->(83,45))","class CrossEntropy(LossFunction): class ClassificationError(LossFunction): @output_loss def loss(self, output, targets): return (np.argmax(output, axis=-1) == np.argmax(np.nan_to_num(targets), axis=-1)) # note: not defining d_loss or d2_loss; classification error should only","class CrossEntropy(LossFunction): class ClassificationError(LossFunction): @output_loss def loss(self, output, targets): return (np.argmax(output, axis=-1) != np.argmax(np.nan_to_num(targets), axis=-1)) # note: not defining d_loss or d2_loss; classification error should only" 877,https://:@github.com/GalakVince/dermoscopic_symmetry.git,cbad346417689f3a698035f0393fef710ae6dedd,"@@ -338,7 +338,7 @@ def classifierTrainer(maxLeafNodes, data=None, data_backup_file='patchesDataSet/ clf: The fitted classifier. acc: The accuracy score of the classifier """""" - if data is not None: + if data is None: data = pd.read_csv(f""{package_path()}/data/patchesDataSet/{data_backup_file}.csv"", index_col=False) features = list(data) del features[0] ",dermoscopic_symmetry/classifier_feeder.py,"ReplaceText(target=' is ' @(341,11)->(341,19))","def classifierTrainer(maxLeafNodes, data=None, data_backup_file='patchesDataSet/ clf: The fitted classifier. acc: The accuracy score of the classifier """""" if data is not None: data = pd.read_csv(f""{package_path()}/data/patchesDataSet/{data_backup_file}.csv"", index_col=False) features = list(data) del features[0]","def classifierTrainer(maxLeafNodes, data=None, data_backup_file='patchesDataSet/ clf: The fitted classifier. acc: The accuracy score of the classifier """""" if data is None: data = pd.read_csv(f""{package_path()}/data/patchesDataSet/{data_backup_file}.csv"", index_col=False) features = list(data) del features[0]" 878,https://:@github.com/interputed/grapi.git,8174ec31bc0572ec562f147a2becc65498774d56,"@@ -47,7 +47,7 @@ class Grapi: keys = kwargs.keys() endpoints.check(keys, self._endpoint) - if date_step: + if not date_step: return self._methods(method.lower())(**kwargs) else: ",grapi/grapi.py,"ReplaceText(target='not ' @(50,11)->(50,11))","class Grapi: keys = kwargs.keys() endpoints.check(keys, self._endpoint) if date_step: return self._methods(method.lower())(**kwargs) else:","class Grapi: keys = kwargs.keys() endpoints.check(keys, self._endpoint) if not date_step: return self._methods(method.lower())(**kwargs) else:" 879,https://:@github.com/chen0040/pycompressor.git,273f7e1592566e82b62afa250d29c08b0bbcacdd,"@@ -19,7 +19,7 @@ class Node(object): def char_at(text, i): - if len(text) - 1 <= i: + if len(text) - 1 < i: return -1 return ord(text[i]) ",pycompressor/huffman.py,"ReplaceText(target='<' @(22,21)->(22,23))","class Node(object): def char_at(text, i): if len(text) - 1 <= i: return -1 return ord(text[i]) ","class Node(object): def char_at(text, i): if len(text) - 1 < i: return -1 return ord(text[i]) " 880,https://:@github.com/scattering-central/saxskit.git,e696feaed288160cf35a34d4f43de44e4af4b90f,"@@ -114,7 +114,7 @@ def train_classification_models(data,hyper_parameters_search=False): print('--> average unweighted f1: {}, accuracy: {}'.format(f1_score,acc)) else: print('--> {} untrainable- default value: {}'.format(model_id,model.default_val)) - cls_models['main_classifiers'][struct_nm] = model + cls_models['main_classifiers'][model_id] = model # There are 2**n possible outcomes for n binary classifiers. # For the (2**n)-1 non-null outcomes, a second classifier is used, ",xrsdkit/models/train.py,"ReplaceText(target='model_id' @(117,39)->(117,48))","def train_classification_models(data,hyper_parameters_search=False): print('--> average unweighted f1: {}, accuracy: {}'.format(f1_score,acc)) else: print('--> {} untrainable- default value: {}'.format(model_id,model.default_val)) cls_models['main_classifiers'][struct_nm] = model # There are 2**n possible outcomes for n binary classifiers. # For the (2**n)-1 non-null outcomes, a second classifier is used,","def train_classification_models(data,hyper_parameters_search=False): print('--> average unweighted f1: {}, accuracy: {}'.format(f1_score,acc)) else: print('--> {} untrainable- default value: {}'.format(model_id,model.default_val)) cls_models['main_classifiers'][model_id] = model # There are 2**n possible outcomes for n binary classifiers. # For the (2**n)-1 non-null outcomes, a second classifier is used," 881,https://:@github.com/scattering-central/saxskit.git,4e384359736c5191648f3a5971ccc7d34fb98b27,"@@ -413,7 +413,7 @@ class XRSDFitGUI(object): # TODO: toggles for hyperparam selection? feature selection? dataset_dir = self._vars['io_control']['dataset_dir'].get() output_dir = self._vars['io_control']['output_dir'].get() - model_config_path = os.path.join(dataset_dir,'model_config.yml') + model_config_path = os.path.join(output_dir,'model_config.yml') self._print_to_listbox(display,'LOADING DATASET FROM: {}'.format(dataset_dir)) df, idx_df = read_local_dataset(dataset_dir,downsampling_distance=1., message_callback=partial(self._print_to_listbox,display)) ",xrsdkit/visualization/gui.py,"ReplaceText(target='output_dir' @(416,41)->(416,52))","class XRSDFitGUI(object): # TODO: toggles for hyperparam selection? feature selection? dataset_dir = self._vars['io_control']['dataset_dir'].get() output_dir = self._vars['io_control']['output_dir'].get() model_config_path = os.path.join(dataset_dir,'model_config.yml') self._print_to_listbox(display,'LOADING DATASET FROM: {}'.format(dataset_dir)) df, idx_df = read_local_dataset(dataset_dir,downsampling_distance=1., message_callback=partial(self._print_to_listbox,display))","class XRSDFitGUI(object): # TODO: toggles for hyperparam selection? feature selection? dataset_dir = self._vars['io_control']['dataset_dir'].get() output_dir = self._vars['io_control']['output_dir'].get() model_config_path = os.path.join(output_dir,'model_config.yml') self._print_to_listbox(display,'LOADING DATASET FROM: {}'.format(dataset_dir)) df, idx_df = read_local_dataset(dataset_dir,downsampling_distance=1., message_callback=partial(self._print_to_listbox,display))" 882,https://:@github.com/rohinkumar/correlcalc.git,9a13668ff7ef2396ce22175d3f21599af7279766,"@@ -18,7 +18,7 @@ def generate_rand_from_pdf(pdf, x_grid, N): cdf = cdf / cdf[-1] values = np.random.rand(N) value_bins = np.searchsorted(cdf, values) - random_from_cdf, nz = x_grid[value_bins], cdf[value_bins] + random_from_cdf, nz = x_grid[value_bins], pdf[value_bins] return random_from_cdf, nz ",correlcalc/genrand.py,"ReplaceText(target='pdf' @(21,46)->(21,49))","def generate_rand_from_pdf(pdf, x_grid, N): cdf = cdf / cdf[-1] values = np.random.rand(N) value_bins = np.searchsorted(cdf, values) random_from_cdf, nz = x_grid[value_bins], cdf[value_bins] return random_from_cdf, nz ","def generate_rand_from_pdf(pdf, x_grid, N): cdf = cdf / cdf[-1] values = np.random.rand(N) value_bins = np.searchsorted(cdf, values) random_from_cdf, nz = x_grid[value_bins], pdf[value_bins] return random_from_cdf, nz " 883,https://:@github.com/deepfield/builder.git,4410007757b043e278d5a9a8deec2ae7cd5da2b6,"@@ -489,7 +489,7 @@ class Job(object): str_targets = collections.defaultdict(list) for target_type, targets in targets_dict.iteritems(): for target in targets: - str_dependencies[target_type].append(target.unexpanded_id) + str_targets[target_type].append(target.unexpanded_id) this_dict = {""depends"": str_dependencies, ""targets"": str_targets} ",jobs.py,"ReplaceText(target='str_targets' @(492,16)->(492,32))","class Job(object): str_targets = collections.defaultdict(list) for target_type, targets in targets_dict.iteritems(): for target in targets: str_dependencies[target_type].append(target.unexpanded_id) this_dict = {""depends"": str_dependencies, ""targets"": str_targets} ","class Job(object): str_targets = collections.defaultdict(list) for target_type, targets in targets_dict.iteritems(): for target in targets: str_targets[target_type].append(target.unexpanded_id) this_dict = {""depends"": str_dependencies, ""targets"": str_targets} " 884,https://:@github.com/allonkleinlab/scrublet.git,afe329d90fa0bddadccf9e707112f835fe83e46e,"@@ -66,7 +66,7 @@ def sparse_zscore(E, gene_mean=None, gene_stdev=None): ''' z-score normalize each column of E ''' if gene_mean is None: - gene_stdev = E.mean(0) + gene_mean = E.mean(0) if gene_stdev is None: gene_stdev = np.sqrt(sparse_var(E)) return sparse_multiply((E - gene_mean).T, 1/gene_stdev).T ",src/scrublet/helper_functions.py,"ReplaceText(target='gene_mean' @(69,8)->(69,18))","def sparse_zscore(E, gene_mean=None, gene_stdev=None): ''' z-score normalize each column of E ''' if gene_mean is None: gene_stdev = E.mean(0) if gene_stdev is None: gene_stdev = np.sqrt(sparse_var(E)) return sparse_multiply((E - gene_mean).T, 1/gene_stdev).T","def sparse_zscore(E, gene_mean=None, gene_stdev=None): ''' z-score normalize each column of E ''' if gene_mean is None: gene_mean = E.mean(0) if gene_stdev is None: gene_stdev = np.sqrt(sparse_var(E)) return sparse_multiply((E - gene_mean).T, 1/gene_stdev).T" 885,https://:@github.com/SheldonYS/Zappa.git,513bfe44f24cee37e8dc720f3a55c8f8d0c73163,"@@ -1053,7 +1053,7 @@ class Zappa(object): if count: # We can end up in a situation where we have more resources being created # than anticipated. - if (count - current_resources) >= 0: + if (count - current_resources) > 0: progress.update(count - current_resources) current_resources = count progress.close() ",zappa/zappa.py,"ReplaceText(target='>' @(1056,51)->(1056,53))","class Zappa(object): if count: # We can end up in a situation where we have more resources being created # than anticipated. if (count - current_resources) >= 0: progress.update(count - current_resources) current_resources = count progress.close()","class Zappa(object): if count: # We can end up in a situation where we have more resources being created # than anticipated. if (count - current_resources) > 0: progress.update(count - current_resources) current_resources = count progress.close()" 886,https://:@github.com/moser/pylint.git,4d29d8e4559938bef1eb52b1613d2596aeba395b,"@@ -174,7 +174,7 @@ class ClassDiagram(Figure, FilterMixIn): value = value._proxied try: ass_obj = self.object_from_node(value) - self.add_relationship(obj, ass_obj, 'association', name) + self.add_relationship(ass_obj, obj, 'association', name) except KeyError: continue ",pyreverse/diagrams.py,"ArgSwap(idxs=0<->1 @(177,24)->(177,45))","class ClassDiagram(Figure, FilterMixIn): value = value._proxied try: ass_obj = self.object_from_node(value) self.add_relationship(obj, ass_obj, 'association', name) except KeyError: continue ","class ClassDiagram(Figure, FilterMixIn): value = value._proxied try: ass_obj = self.object_from_node(value) self.add_relationship(ass_obj, obj, 'association', name) except KeyError: continue " 887,https://:@github.com/moser/pylint.git,2ac99b2a24d44a3b56c035a889f6bd78f4f41b7f,"@@ -242,7 +242,7 @@ builtins. Remember that you should avoid to define new builtins when possible.' if node.name.startswith('cb_') or \ node.name.endswith('_cb'): continue - self.add_message('W0613', args=name, node=node) + self.add_message('W0613', args=name, node=stmt) else: self.add_message('W0612', args=name, node=stmt) ",checkers/variables.py,"ReplaceText(target='stmt' @(245,58)->(245,62))","builtins. Remember that you should avoid to define new builtins when possible.' if node.name.startswith('cb_') or \ node.name.endswith('_cb'): continue self.add_message('W0613', args=name, node=node) else: self.add_message('W0612', args=name, node=stmt) ","builtins. Remember that you should avoid to define new builtins when possible.' if node.name.startswith('cb_') or \ node.name.endswith('_cb'): continue self.add_message('W0613', args=name, node=stmt) else: self.add_message('W0612', args=name, node=stmt) " 888,https://:@github.com/moser/pylint.git,dbb2f3e65b9a452cf981e1bda318ec019b43bd8c,"@@ -714,7 +714,7 @@ class BasicErrorChecker(_BasicChecker): if defined_self is not node and not astroid.are_exclusive(node, defined_self): dummy_variables_rgx = lint_utils.get_global_option( self, 'dummy-variables-rgx', default=None) - if dummy_variables_rgx and dummy_variables_rgx.match(defined_self.name): + if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message('function-redefined', node=node, args=(redeftype, defined_self.fromlineno)) ",pylint/checkers/base.py,"ReplaceText(target='node' @(717,65)->(717,77))","class BasicErrorChecker(_BasicChecker): if defined_self is not node and not astroid.are_exclusive(node, defined_self): dummy_variables_rgx = lint_utils.get_global_option( self, 'dummy-variables-rgx', default=None) if dummy_variables_rgx and dummy_variables_rgx.match(defined_self.name): return self.add_message('function-redefined', node=node, args=(redeftype, defined_self.fromlineno))","class BasicErrorChecker(_BasicChecker): if defined_self is not node and not astroid.are_exclusive(node, defined_self): dummy_variables_rgx = lint_utils.get_global_option( self, 'dummy-variables-rgx', default=None) if dummy_variables_rgx and dummy_variables_rgx.match(node.name): return self.add_message('function-redefined', node=node, args=(redeftype, defined_self.fromlineno))" 889,https://:@github.com/moser/pylint.git,02688062140cc7ffa9c4f1a1f04c13d6f198a400,"@@ -697,7 +697,7 @@ def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool: error_type = (error_type,) # type: ignore expected_errors = {stringify_error(error) for error in error_type} # type: ignore if not handler.type: - return True + return False return handler.catch(expected_errors) ",pylint/checkers/utils.py,"ReplaceText(target='False' @(700,15)->(700,19))","def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool: error_type = (error_type,) # type: ignore expected_errors = {stringify_error(error) for error in error_type} # type: ignore if not handler.type: return True return handler.catch(expected_errors) ","def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool: error_type = (error_type,) # type: ignore expected_errors = {stringify_error(error) for error in error_type} # type: ignore if not handler.type: return False return handler.catch(expected_errors) " 890,https://:@github.com/ogrisel/pygbm.git,2e019bfc2b3ea35ec5bd7c3c56301f8fc7a64b60,"@@ -426,7 +426,7 @@ def _find_best_bin_to_split_helper(context, feature_idx, histogram, n_samples): context.sum_gradients, context.sum_hessians, context.l2_regularization) - if gain > best_split.gain and gain >= context.min_gain_to_split: + if gain > best_split.gain and gain > context.min_gain_to_split: best_split.gain = gain best_split.feature_idx = feature_idx best_split.bin_idx = bin_idx ",pygbm/splitting.py,"ReplaceText(target='>' @(429,43)->(429,45))","def _find_best_bin_to_split_helper(context, feature_idx, histogram, n_samples): context.sum_gradients, context.sum_hessians, context.l2_regularization) if gain > best_split.gain and gain >= context.min_gain_to_split: best_split.gain = gain best_split.feature_idx = feature_idx best_split.bin_idx = bin_idx","def _find_best_bin_to_split_helper(context, feature_idx, histogram, n_samples): context.sum_gradients, context.sum_hessians, context.l2_regularization) if gain > best_split.gain and gain > context.min_gain_to_split: best_split.gain = gain best_split.feature_idx = feature_idx best_split.bin_idx = bin_idx" 891,https://:@github.com/happz/ducky.git,e56b0f3d47fb108865973efe411e6767d51d72a1,"@@ -330,7 +330,7 @@ class MathCoprocessor(ISnapshotable, Coprocessor): i = i32(tos.value).value j = i32(lr.value).value D(' i=%i, j=%i (%s, %s)', i, j, type(i), type(j)) - i /= j + i //= j D(' i=%i (%s)', i, type(i)) tos.value = i ",ducky/cpu/coprocessor/math_copro.py,"ReplaceText(target='//=' @(333,6)->(333,8))","class MathCoprocessor(ISnapshotable, Coprocessor): i = i32(tos.value).value j = i32(lr.value).value D(' i=%i, j=%i (%s, %s)', i, j, type(i), type(j)) i /= j D(' i=%i (%s)', i, type(i)) tos.value = i ","class MathCoprocessor(ISnapshotable, Coprocessor): i = i32(tos.value).value j = i32(lr.value).value D(' i=%i, j=%i (%s, %s)', i, j, type(i), type(j)) i //= j D(' i=%i (%s)', i, type(i)) tos.value = i " 892,https://:@github.com/happz/ducky.git,fb1a93bdb8055874aef7077850e784dc90e8295c,"@@ -680,7 +680,7 @@ class Machine(ISnapshotable, IMachineWorker): self.hdt.create() - pages = self.memory.alloc_pages(segment = 0x00, count = align(PAGE_SIZE, self.hdt.size()) / PAGE_SIZE) + pages = self.memory.alloc_pages(segment = 0x00, count = align(PAGE_SIZE, self.hdt.size()) // PAGE_SIZE) self.memory.update_pages_flags(pages[0].index, len(pages), 'read', True) self.hdt_address = pages[0].base_address ",ducky/machine.py,"ReplaceText(target='//' @(683,94)->(683,95))","class Machine(ISnapshotable, IMachineWorker): self.hdt.create() pages = self.memory.alloc_pages(segment = 0x00, count = align(PAGE_SIZE, self.hdt.size()) / PAGE_SIZE) self.memory.update_pages_flags(pages[0].index, len(pages), 'read', True) self.hdt_address = pages[0].base_address ","class Machine(ISnapshotable, IMachineWorker): self.hdt.create() pages = self.memory.alloc_pages(segment = 0x00, count = align(PAGE_SIZE, self.hdt.size()) // PAGE_SIZE) self.memory.update_pages_flags(pages[0].index, len(pages), 'read', True) self.hdt_address = pages[0].base_address " 893,https://:@github.com/happz/ducky.git,f266fb16a7f0e10e19cba8d17eb15d0d69d3c24a,"@@ -134,7 +134,7 @@ def show_pages(logger, state): CPR = 32 - for i in range(0, 256 / CPR): + for i in range(0, 256 // CPR): s = [] t = [] ",ducky/tools/coredump.py,"ReplaceText(target='//' @(137,26)->(137,27))","def show_pages(logger, state): CPR = 32 for i in range(0, 256 / CPR): s = [] t = [] ","def show_pages(logger, state): CPR = 32 for i in range(0, 256 // CPR): s = [] t = [] " 894,https://:@github.com/tpircher/quine-mccluskey.git,31df780f3ec5a14d70840e755f23da133a8fc282,"@@ -372,7 +372,7 @@ class QuineMcCluskey: # Add the unused terms to the list of marked terms for g in list(groups.values()): - marked |= group - used + marked |= g - used if len(used) == 0: done = True ",quine_mccluskey/qm.py,"ReplaceText(target='g' @(375,26)->(375,31))","class QuineMcCluskey: # Add the unused terms to the list of marked terms for g in list(groups.values()): marked |= group - used if len(used) == 0: done = True","class QuineMcCluskey: # Add the unused terms to the list of marked terms for g in list(groups.values()): marked |= g - used if len(used) == 0: done = True" 895,https://:@github.com/SUSE/azurectl.git,09c62dc074497f862c0a4fee6798ffee14f7e61c,"@@ -81,7 +81,7 @@ class Image: service_call = service.add_os_image( label, media_link, name, 'Linux' ) - add_os_image_result = service_call.get_operation_status( + add_os_image_result = service.get_operation_status( service_call.request_id ) status = add_os_image_result.status ",azurectl/image.py,"ReplaceText(target='service' @(84,34)->(84,46))","class Image: service_call = service.add_os_image( label, media_link, name, 'Linux' ) add_os_image_result = service_call.get_operation_status( service_call.request_id ) status = add_os_image_result.status","class Image: service_call = service.add_os_image( label, media_link, name, 'Linux' ) add_os_image_result = service.get_operation_status( service_call.request_id ) status = add_os_image_result.status" 896,https://:@github.com/robocomp/learnbot.git,e0af147e7b8ab58add721fefe425c6ac28183043,"@@ -1,6 +1,6 @@ def obstacle_free(lbot, threshold= 200, verbose=False): sonarsValue = lbot.getSonars() - if min(sonarsValue) > threshold: + if min(sonarsValue) < threshold: if verbose: print('No obstacles around Learnbot') return True ",learnbot_dsl/functions/perceptual/obstacle_free.py,"ReplaceText(target='<' @(3,21)->(3,22))","-1,6 +1,6 @@ def obstacle_free(lbot, threshold= 200, verbose=False): sonarsValue = lbot.getSonars() if min(sonarsValue) > threshold: if verbose: print('No obstacles around Learnbot') return True","-1,6 +1,6 @@ def obstacle_free(lbot, threshold= 200, verbose=False): sonarsValue = lbot.getSonars() if min(sonarsValue) < threshold: if verbose: print('No obstacles around Learnbot') return True" 897,https://:@github.com/robocomp/learnbot.git,f43f97e705c26d2e6d1a9fded44ee913dbba6e84,"@@ -9,7 +9,7 @@ from learnbot_dsl.learnbotCode.Language import getLanguage import tempfile, uuid, sys def str2hex(text): - if sys.version_info[0]>3: + if sys.version_info[0]>=3: return text.encode('utf-8').hex() else: return str(binascii.hexlify(bytes(text))) ",learnbot_dsl/learnbotCode/Button.py,"ReplaceText(target='>=' @(12,26)->(12,27))","from learnbot_dsl.learnbotCode.Language import getLanguage import tempfile, uuid, sys def str2hex(text): if sys.version_info[0]>3: return text.encode('utf-8').hex() else: return str(binascii.hexlify(bytes(text)))","from learnbot_dsl.learnbotCode.Language import getLanguage import tempfile, uuid, sys def str2hex(text): if sys.version_info[0]>=3: return text.encode('utf-8').hex() else: return str(binascii.hexlify(bytes(text)))" 898,https://:@github.com/robocomp/learnbot.git,b5f0d9f8bc119b2c1f05c2b8c0a8e7e8b40ed8e0,"@@ -1,4 +1,4 @@ def look_front(lbot): - lbot.setJointAngle(""CAMERA"",0) + lbot.setJointAngle(0, ""CAMERA"") ",learnbot_dsl/functions/motor/jointmotor/look_front.py,"ArgSwap(idxs=0<->1 @(4,4)->(4,22))","-1,4 +1,4 @@ def look_front(lbot): lbot.setJointAngle(""CAMERA"",0)","-1,4 +1,4 @@ def look_front(lbot): lbot.setJointAngle(0, ""CAMERA"")" 899,https://:@github.com/robocomp/learnbot.git,b5f0d9f8bc119b2c1f05c2b8c0a8e7e8b40ed8e0,"@@ -1,4 +1,4 @@ def setAngleCamera(lbot,angle): - lbot.setJointAngle(""CAMERA"", angle) + lbot.setJointAngle(angle, ""CAMERA"") ",learnbot_dsl/functions/motor/jointmotor/setAngleCamera.py,"ArgSwap(idxs=0<->1 @(4,4)->(4,22))","-1,4 +1,4 @@ def setAngleCamera(lbot,angle): lbot.setJointAngle(""CAMERA"", angle)","-1,4 +1,4 @@ def setAngleCamera(lbot,angle): lbot.setJointAngle(angle, ""CAMERA"")" 900,https://:@github.com/chanedwin/pydistinct.git,2920f6fe09daa3362513fbc516c711035bcb8c6a,"@@ -109,7 +109,7 @@ def _get_confidence_interval(bootstrap_dist, stat_val, alpha, is_pivotal): low = _np.percentile(bootstrap_dist, 100 * ((alpha / 2))) val = _np.percentile(bootstrap_dist, 50) high = _np.percentile(bootstrap_dist, 100 * (1 - (alpha / 2))) - return BootstrapResults(low, stat_val, high) + return BootstrapResults(low, val, high) def _needs_sparse_unification(values_lists): ",pydistinct/bootstrap.py,"ReplaceText(target='val' @(112,33)->(112,41))","def _get_confidence_interval(bootstrap_dist, stat_val, alpha, is_pivotal): low = _np.percentile(bootstrap_dist, 100 * ((alpha / 2))) val = _np.percentile(bootstrap_dist, 50) high = _np.percentile(bootstrap_dist, 100 * (1 - (alpha / 2))) return BootstrapResults(low, stat_val, high) def _needs_sparse_unification(values_lists):","def _get_confidence_interval(bootstrap_dist, stat_val, alpha, is_pivotal): low = _np.percentile(bootstrap_dist, 100 * ((alpha / 2))) val = _np.percentile(bootstrap_dist, 50) high = _np.percentile(bootstrap_dist, 100 * (1 - (alpha / 2))) return BootstrapResults(low, val, high) def _needs_sparse_unification(values_lists):" 901,https://:@github.com/coreofscience/python-wostools.git,2163905ba13f68da61ed6b7a4da0c2f524399039,"@@ -47,7 +47,7 @@ class Article: self.year: Optional[int] = year self.journal: Optional[str] = journal self.volume: Optional[str] = volume - self.issue: Optional[str] = volume + self.issue: Optional[str] = issue self.page: Optional[str] = page self.doi: Optional[str] = doi self.references: List[str] = references or [] ",wostools/article.py,"ReplaceText(target='issue' @(50,36)->(50,42))","class Article: self.year: Optional[int] = year self.journal: Optional[str] = journal self.volume: Optional[str] = volume self.issue: Optional[str] = volume self.page: Optional[str] = page self.doi: Optional[str] = doi self.references: List[str] = references or []","class Article: self.year: Optional[int] = year self.journal: Optional[str] = journal self.volume: Optional[str] = volume self.issue: Optional[str] = issue self.page: Optional[str] = page self.doi: Optional[str] = doi self.references: List[str] = references or []" 902,https://:@github.com/snipsco/respeaker_python_library.git,0f5991317aa815356f8225f6088f85cd2f3bc27f,"@@ -66,7 +66,7 @@ class WebRTCVAD: break elif len(self.history) == self.history.maxlen and sum(self.history) == 0: sys.stdout.write('Todo: increase capture volume') - for _ in range(self.history.maxlen / 2): + for _ in range(self.history.maxlen // 2): self.history.popleft() else: ",respeaker/vad.py,"ReplaceText(target='//' @(69,55)->(69,56))","class WebRTCVAD: break elif len(self.history) == self.history.maxlen and sum(self.history) == 0: sys.stdout.write('Todo: increase capture volume') for _ in range(self.history.maxlen / 2): self.history.popleft() else:","class WebRTCVAD: break elif len(self.history) == self.history.maxlen and sum(self.history) == 0: sys.stdout.write('Todo: increase capture volume') for _ in range(self.history.maxlen // 2): self.history.popleft() else:" 903,https://:@github.com/luphord/longstaff_schwartz.git,a70ee9438f4a36cfc25498c1091b5f8fc6879151,"@@ -91,7 +91,7 @@ def american_put_exercise_barrier(mdl, strike): exercises = [] payoff = put_payoff(strike) for cnt, s, ex, opt in mdl.evaluate_american_exercisable_iter(payoff): - ex_idx = ex > cnt + ex_idx = ex >= cnt ex_spots = s[ex_idx] exercises.append(ex_spots.max() if ex_idx.any() else None) exercises.reverse() ",longstaff_schwartz/binomial.py,"ReplaceText(target='>=' @(94,20)->(94,21))","def american_put_exercise_barrier(mdl, strike): exercises = [] payoff = put_payoff(strike) for cnt, s, ex, opt in mdl.evaluate_american_exercisable_iter(payoff): ex_idx = ex > cnt ex_spots = s[ex_idx] exercises.append(ex_spots.max() if ex_idx.any() else None) exercises.reverse()","def american_put_exercise_barrier(mdl, strike): exercises = [] payoff = put_payoff(strike) for cnt, s, ex, opt in mdl.evaluate_american_exercisable_iter(payoff): ex_idx = ex >= cnt ex_spots = s[ex_idx] exercises.append(ex_spots.max() if ex_idx.any() else None) exercises.reverse()" 904,https://:@github.com/ietf-tools/RfcEditor.git,9e509f9cbc2995ab8ad72636fe3a4739c23515bb,"@@ -174,7 +174,7 @@ def check(el, depth=0): if ns is not None and ns not in wp.xmlns_urls: log.error(""Element '{0}' does not allow attributes with namespace '{1}'"". format(element, ns), where=el) - attribs_to_remove.append(attr) + attribs_to_remove.append(nsAttrib) continue # look to see if the attribute is either an attribute for a specific ",svgcheck/svgcheck/checksvg.py,"ReplaceText(target='nsAttrib' @(177,37)->(177,41))","def check(el, depth=0): if ns is not None and ns not in wp.xmlns_urls: log.error(""Element '{0}' does not allow attributes with namespace '{1}'"". format(element, ns), where=el) attribs_to_remove.append(attr) continue # look to see if the attribute is either an attribute for a specific","def check(el, depth=0): if ns is not None and ns not in wp.xmlns_urls: log.error(""Element '{0}' does not allow attributes with namespace '{1}'"". format(element, ns), where=el) attribs_to_remove.append(nsAttrib) continue # look to see if the attribute is either an attribute for a specific" 905,https://:@github.com/ietf-tools/RfcEditor.git,2086136adaeb71096ae8075d0b540ed0391608ad,"@@ -242,7 +242,7 @@ def main(): # Validate any embedded ABNF if not options.no_abnf: - checker = AbnfChecker(options) + checker = AbnfChecker(config) checker.validate(xmlrfc.tree) ",rfclint/rfclint/run.py,"ReplaceText(target='config' @(245,30)->(245,37))","def main(): # Validate any embedded ABNF if not options.no_abnf: checker = AbnfChecker(options) checker.validate(xmlrfc.tree) ","def main(): # Validate any embedded ABNF if not options.no_abnf: checker = AbnfChecker(config) checker.validate(xmlrfc.tree) " 906,https://:@github.com/openlegis-br/sagl.git,9ea9984b17df551e9b7600c3c9ba7eb6a4f914e3,"@@ -53,7 +53,7 @@ for periodo in context.zsql.periodo_comp_comissao_obter_zsql(data = DateTime(),c destinatarios=[] for composicao_comissao in context.zsql.composicao_comissao_obter_zsql(cod_comissao=comissao.cod_comissao,cod_periodo_comp=periodo.cod_periodo_comp): - if composicao_comissao.dat_desligamento == None or composicao_comissao.dat_desligamento <= DateTime(): + if composicao_comissao.dat_desligamento == None or composicao_comissao.dat_desligamento >= DateTime(): for destinatario in context.zsql.autor_obter_zsql(cod_parlamentar=composicao_comissao.cod_parlamentar): dic={} dic['end_email'] = destinatario.end_email ",branches/3.1_buildout/il/sapl/skins/pysc/envia_despacho_comissao_pysc.py,"ReplaceText(target='>=' @(56,89)->(56,91))","for periodo in context.zsql.periodo_comp_comissao_obter_zsql(data = DateTime(),c destinatarios=[] for composicao_comissao in context.zsql.composicao_comissao_obter_zsql(cod_comissao=comissao.cod_comissao,cod_periodo_comp=periodo.cod_periodo_comp): if composicao_comissao.dat_desligamento == None or composicao_comissao.dat_desligamento <= DateTime(): for destinatario in context.zsql.autor_obter_zsql(cod_parlamentar=composicao_comissao.cod_parlamentar): dic={} dic['end_email'] = destinatario.end_email","for periodo in context.zsql.periodo_comp_comissao_obter_zsql(data = DateTime(),c destinatarios=[] for composicao_comissao in context.zsql.composicao_comissao_obter_zsql(cod_comissao=comissao.cod_comissao,cod_periodo_comp=periodo.cod_periodo_comp): if composicao_comissao.dat_desligamento == None or composicao_comissao.dat_desligamento >= DateTime(): for destinatario in context.zsql.autor_obter_zsql(cod_parlamentar=composicao_comissao.cod_parlamentar): dic={} dic['end_email'] = destinatario.end_email" 907,https://:@github.com/Mellcap/MellPlayer.git,8f5bcc0ee48e58743f595df9f738a6c1c0c158a6,"@@ -98,7 +98,7 @@ class Netease(object): 'song_name': d['name'], 'song_url': d['mp3Url'], 'song_artists': ';'.join(map(lambda a: a['name'], d['artists'])) - } for d in data] + } for d in tracks] elif parse_type == 'lyric_detail': if 'lrc' in data: res = { ",MellPlayer/api.py,"ReplaceText(target='tracks' @(101,23)->(101,27))","class Netease(object): 'song_name': d['name'], 'song_url': d['mp3Url'], 'song_artists': ';'.join(map(lambda a: a['name'], d['artists'])) } for d in data] elif parse_type == 'lyric_detail': if 'lrc' in data: res = {","class Netease(object): 'song_name': d['name'], 'song_url': d['mp3Url'], 'song_artists': ';'.join(map(lambda a: a['name'], d['artists'])) } for d in tracks] elif parse_type == 'lyric_detail': if 'lrc' in data: res = {" 908,https://:@github.com/kobejohn/investigators.git,678d9eeee6cb90d3ad60bea640f8170ba9cc0473,"@@ -64,7 +64,7 @@ class ImageIdentifier(object): scale = min(h_scale, w_scale) # min --> most shrinking scaled_h = int(round(scale * template_h)) scaled_w = int(round(scale * template_w)) - eq_template = cv2.resize(image, (scaled_w, scaled_h), + eq_template = cv2.resize(template, (scaled_w, scaled_h), interpolation=cv2.INTER_AREA) return eq_template, eq_image ",investigators/visuals.py,"ReplaceText(target='template' @(67,37)->(67,42))","class ImageIdentifier(object): scale = min(h_scale, w_scale) # min --> most shrinking scaled_h = int(round(scale * template_h)) scaled_w = int(round(scale * template_w)) eq_template = cv2.resize(image, (scaled_w, scaled_h), interpolation=cv2.INTER_AREA) return eq_template, eq_image ","class ImageIdentifier(object): scale = min(h_scale, w_scale) # min --> most shrinking scaled_h = int(round(scale * template_h)) scaled_w = int(round(scale * template_w)) eq_template = cv2.resize(template, (scaled_w, scaled_h), interpolation=cv2.INTER_AREA) return eq_template, eq_image " 909,https://:@github.com/swfiua/karmapi.git,10471bc3be40e81ed93d809a865e27e4fcf95b08,"@@ -101,7 +101,7 @@ class WeatherHat(pig.Widget): self.interval = 1 # build a Grid and add to self - monitor = pig.Grid(meta, self) + monitor = pig.Grid(self, meta) self.monitor = monitor layout.addWidget(monitor) ",karmapi/sense.py,"ArgSwap(idxs=0<->1 @(104,18)->(104,26))","class WeatherHat(pig.Widget): self.interval = 1 # build a Grid and add to self monitor = pig.Grid(meta, self) self.monitor = monitor layout.addWidget(monitor) ","class WeatherHat(pig.Widget): self.interval = 1 # build a Grid and add to self monitor = pig.Grid(self, meta) self.monitor = monitor layout.addWidget(monitor) " 910,https://:@github.com/swfiua/karmapi.git,3b50b753a4309fb9eced9736c77b3bf9afea5227,"@@ -95,7 +95,7 @@ def pick_pixels(image, size=8): width, height = len(image), len(image[0]) pwidth = int(width / size) - pheight = int(width / size) + pheight = int(height / size) pickx = random.randint(0, pwidth-1) picky = random.randint(0, pheight-1) ",karmapi/backends/hatpig.py,"ReplaceText(target='height' @(98,18)->(98,23))","def pick_pixels(image, size=8): width, height = len(image), len(image[0]) pwidth = int(width / size) pheight = int(width / size) pickx = random.randint(0, pwidth-1) picky = random.randint(0, pheight-1)","def pick_pixels(image, size=8): width, height = len(image), len(image[0]) pwidth = int(width / size) pheight = int(height / size) pickx = random.randint(0, pwidth-1) picky = random.randint(0, pheight-1)" 911,https://:@github.com/swfiua/karmapi.git,b0380f746dc68f7fec78d6ab0e425b6259336ce8,"@@ -792,7 +792,7 @@ class JeuxSansFrontieres: wteam = group.winner() setattr(kgame, label, wteam) if group.is_finished(): - wteam.games.append(game) + wteam.games.append(kgame) kgame, label = self.seconds[key] steam = group.second() ",karmapi/wc.py,"ReplaceText(target='kgame' @(795,35)->(795,39))","class JeuxSansFrontieres: wteam = group.winner() setattr(kgame, label, wteam) if group.is_finished(): wteam.games.append(game) kgame, label = self.seconds[key] steam = group.second()","class JeuxSansFrontieres: wteam = group.winner() setattr(kgame, label, wteam) if group.is_finished(): wteam.games.append(kgame) kgame, label = self.seconds[key] steam = group.second()" 912,https://:@github.com/swfiua/karmapi.git,e6231e7cbc0d0b521c361bc5ac2fae3be0e8f194,"@@ -154,7 +154,7 @@ class BeanStalk: def draw(self, canvas, width, height, colour): xx = self.xx * width - yy = self.yy * width + yy = self.yy * height canvas.create_text( ",karmapi/beanstalk.py,"ReplaceText(target='height' @(157,23)->(157,28))","class BeanStalk: def draw(self, canvas, width, height, colour): xx = self.xx * width yy = self.yy * width canvas.create_text(","class BeanStalk: def draw(self, canvas, width, height, colour): xx = self.xx * width yy = self.yy * height canvas.create_text(" 913,https://:@github.com/swfiua/karmapi.git,16cae396fa2510bbebd47239d9ffb2eb5f70882d,"@@ -216,7 +216,7 @@ class Sphere: for ix, (r, g, b) in enumerate(value): self.red[ix] = r self.green[ix] = g - self.blue[ix] = r + self.blue[ix] = b def quantise(self, value): ",karmapi/cpr.py,"ReplaceText(target='b' @(219,28)->(219,29))","class Sphere: for ix, (r, g, b) in enumerate(value): self.red[ix] = r self.green[ix] = g self.blue[ix] = r def quantise(self, value): ","class Sphere: for ix, (r, g, b) in enumerate(value): self.red[ix] = r self.green[ix] = g self.blue[ix] = b def quantise(self, value): " 914,https://:@github.com/yetone/baidu_tts.git,c9fb8ff550735a0dd776324b8cf10da53bf2fa25,"@@ -32,7 +32,7 @@ class BaiduTTS(object): url = 'https://openapi.baidu.com/oauth/2.0/token' key = 'access_token' res = self.cache.get(key) - if res and res['expire_time'] < time.time(): + if res and res['expire_time'] > time.time(): return res['data'] resp = requests.get( url, ",baidu_tts/__init__.py,"ReplaceText(target='>' @(35,38)->(35,39))","class BaiduTTS(object): url = 'https://openapi.baidu.com/oauth/2.0/token' key = 'access_token' res = self.cache.get(key) if res and res['expire_time'] < time.time(): return res['data'] resp = requests.get( url,","class BaiduTTS(object): url = 'https://openapi.baidu.com/oauth/2.0/token' key = 'access_token' res = self.cache.get(key) if res and res['expire_time'] > time.time(): return res['data'] resp = requests.get( url," 915,https://:@github.com/Btibert3/pypeds.git,705d6a5d4636e573c20825eff40da5822c2e0d55,"@@ -18,7 +18,7 @@ def zip_parser(url=None, survey=None): # path = ""/tmp/pypeds/"" + str(int(time.time())) + ""/"" # hacky way to make unique path to extract time _today = datetime.datetime.today().strftime('%Y%m%d') survey_lower = survey.lower() - path = ""/tmp/"" + str(_today) + str(survey) + ""/"" # hacky way to make unique path to extract date and survey + path = ""/tmp/"" + str(_today) + str(survey_lower) + ""/"" # hacky way to make unique path to extract date and survey file = survey + "".zip"" # naive way to do cacheing - if the path for today exists, dont do anything, if it doesnt, get the data ",pypeds/ipeds.py,"ReplaceText(target='survey_lower' @(21,39)->(21,45))","def zip_parser(url=None, survey=None): # path = ""/tmp/pypeds/"" + str(int(time.time())) + ""/"" # hacky way to make unique path to extract time _today = datetime.datetime.today().strftime('%Y%m%d') survey_lower = survey.lower() path = ""/tmp/"" + str(_today) + str(survey) + ""/"" # hacky way to make unique path to extract date and survey file = survey + "".zip"" # naive way to do cacheing - if the path for today exists, dont do anything, if it doesnt, get the data","def zip_parser(url=None, survey=None): # path = ""/tmp/pypeds/"" + str(int(time.time())) + ""/"" # hacky way to make unique path to extract time _today = datetime.datetime.today().strftime('%Y%m%d') survey_lower = survey.lower() path = ""/tmp/"" + str(_today) + str(survey_lower) + ""/"" # hacky way to make unique path to extract date and survey file = survey + "".zip"" # naive way to do cacheing - if the path for today exists, dont do anything, if it doesnt, get the data" 916,https://:@github.com/FabriceSalvaire/Pyterate.git,b23a194f0f7785ef190d0cec7171b65d4313d455,"@@ -49,7 +49,7 @@ def setup_logging(application_name=APPLICATION_NAME, config_file=None): formatter_config = logging_config['formatters']['ansi']['format'] logging_config['formatters']['ansi']['format'] = formatter_config.replace('', '\033') - if ConfigInstall.OS.on_windows and ConfigInstall.OS.on_osx: + if ConfigInstall.OS.on_windows or ConfigInstall.OS.on_osx: formatter = 'simple' else: formatter = 'ansi' ",Pyterate/Logging/Logging.py,"ReplaceText(target='or' @(52,35)->(52,38))","def setup_logging(application_name=APPLICATION_NAME, config_file=None): formatter_config = logging_config['formatters']['ansi']['format'] logging_config['formatters']['ansi']['format'] = formatter_config.replace('', '\033') if ConfigInstall.OS.on_windows and ConfigInstall.OS.on_osx: formatter = 'simple' else: formatter = 'ansi'","def setup_logging(application_name=APPLICATION_NAME, config_file=None): formatter_config = logging_config['formatters']['ansi']['format'] logging_config['formatters']['ansi']['format'] = formatter_config.replace('', '\033') if ConfigInstall.OS.on_windows or ConfigInstall.OS.on_osx: formatter = 'simple' else: formatter = 'ansi'" 917,https://:@github.com/andrewsanchez/genbank-qc.git,1f822c8490c0187631a666e420704f28c4d653f7,"@@ -64,7 +64,7 @@ class FilteredSpecies(Species): """""" self.passed = self.stats[self.stats[""N_Count""] <= self.max_n_count] self._criteria_dict[""N_Count""][""failed""] = self.stats.index[ - self.stats[""N_Count""] >= self.max_n_count] + self.stats[""N_Count""] > self.max_n_count] # self.failed_N_Count = self.stats.index[self.stats[""N_Count""] >= # self.max_n_count] ",genbankfilter/filter.py,"ReplaceText(target='>' @(67,34)->(67,36))","class FilteredSpecies(Species): """""" self.passed = self.stats[self.stats[""N_Count""] <= self.max_n_count] self._criteria_dict[""N_Count""][""failed""] = self.stats.index[ self.stats[""N_Count""] >= self.max_n_count] # self.failed_N_Count = self.stats.index[self.stats[""N_Count""] >= # self.max_n_count] ","class FilteredSpecies(Species): """""" self.passed = self.stats[self.stats[""N_Count""] <= self.max_n_count] self._criteria_dict[""N_Count""][""failed""] = self.stats.index[ self.stats[""N_Count""] > self.max_n_count] # self.failed_N_Count = self.stats.index[self.stats[""N_Count""] >= # self.max_n_count] " 918,https://:@github.com/andrewsanchez/genbank-qc.git,2aa87a49e09fefbbe7fe2cba2e6074bba157322b,"@@ -38,7 +38,7 @@ def cli(filter_level, max_unknowns, c_deviations, s_deviations, m_deviations, print(""Completed "", s.species) print(s) except Exception: - print('Failed ', species.species) + print('Failed ', s.species) traceback.print_exc() else: from genbankqc import Genbank ",genbankqc/__main__.py,"ReplaceText(target='s' @(41,29)->(41,36))","def cli(filter_level, max_unknowns, c_deviations, s_deviations, m_deviations, print(""Completed "", s.species) print(s) except Exception: print('Failed ', species.species) traceback.print_exc() else: from genbankqc import Genbank","def cli(filter_level, max_unknowns, c_deviations, s_deviations, m_deviations, print(""Completed "", s.species) print(s) except Exception: print('Failed ', s.species) traceback.print_exc() else: from genbankqc import Genbank" 919,https://:@github.com/andrewsanchez/genbank-qc.git,807883f82e4ab00bb0231c80f221e9777bf7a6e3,"@@ -22,7 +22,7 @@ def test_download_assembly_summary(): @pytest.fixture() def biosample(): temp = Path(tempfile.mkdtemp()) - biosample = metadata.BioSample(""inbox.asanchez@gmail.com"", temp, sample=100) + biosample = metadata.BioSample(temp, ""inbox.asanchez@gmail.com"", sample=100) yield biosample shutil.rmtree(temp) ",test/metadata_test.py,"ArgSwap(idxs=0<->1 @(25,16)->(25,34))","def test_download_assembly_summary(): @pytest.fixture() def biosample(): temp = Path(tempfile.mkdtemp()) biosample = metadata.BioSample(""inbox.asanchez@gmail.com"", temp, sample=100) yield biosample shutil.rmtree(temp) ","def test_download_assembly_summary(): @pytest.fixture() def biosample(): temp = Path(tempfile.mkdtemp()) biosample = metadata.BioSample(temp, ""inbox.asanchez@gmail.com"", sample=100) yield biosample shutil.rmtree(temp) " 920,https://:@github.com/atilaneves/ropemode.git,c37cfc181d56d5b8bb67bcb7501b8ac4eac6a747,"@@ -579,7 +579,7 @@ class _CodeAssist(object): for assist in import_assists: p = codeassist.CompletionProposal(' : '.join(assist), 'autoimport') - import_assists.append(p) + proposals.append(p) return proposals def _insert_import(self, name, module): ",ropemode/interface.py,"ReplaceText(target='proposals' @(582,20)->(582,34))","class _CodeAssist(object): for assist in import_assists: p = codeassist.CompletionProposal(' : '.join(assist), 'autoimport') import_assists.append(p) return proposals def _insert_import(self, name, module):","class _CodeAssist(object): for assist in import_assists: p = codeassist.CompletionProposal(' : '.join(assist), 'autoimport') proposals.append(p) return proposals def _insert_import(self, name, module):" 921,https://:@github.com/pcraster/lue.git,7b961a25b3c8a55f443705d700924bef21ac918b,"@@ -129,7 +129,7 @@ def sort_benchmarks_by_time( time_points = [item[0] for item in items] idxs = [item[1] for item in items] - assert all(t1 < t2 for t1, t2 in zip(time_points, time_points[1:])), time_points + assert all(t1 <= t2 for t1, t2 in zip(time_points, time_points[1:])), time_points epoch = time_points[0] return idxs, epoch ",benchmark/lue/benchmark/util.py,"ReplaceText(target='<=' @(132,18)->(132,19))","def sort_benchmarks_by_time( time_points = [item[0] for item in items] idxs = [item[1] for item in items] assert all(t1 < t2 for t1, t2 in zip(time_points, time_points[1:])), time_points epoch = time_points[0] return idxs, epoch","def sort_benchmarks_by_time( time_points = [item[0] for item in items] idxs = [item[1] for item in items] assert all(t1 <= t2 for t1, t2 in zip(time_points, time_points[1:])), time_points epoch = time_points[0] return idxs, epoch" 922,https://:@github.com/dutradda/falcon-swagger.git,1c532bf5a816b895a7964e5725c633a540a50b24,"@@ -53,7 +53,7 @@ model.__routes__.add(Route('/test/{id}', 'POST', action)) @pytest.fixture def app(session): - return HttpAPI(session.bind, [model]) + return HttpAPI([model], session.bind) class TestUsersModelIntegrationWithAuthorizationHook(object): ",tests/integration/domain/users/test_users_model_integration.py,"ArgSwap(idxs=0<->1 @(56,11)->(56,18))","model.__routes__.add(Route('/test/{id}', 'POST', action)) @pytest.fixture def app(session): return HttpAPI(session.bind, [model]) class TestUsersModelIntegrationWithAuthorizationHook(object):","model.__routes__.add(Route('/test/{id}', 'POST', action)) @pytest.fixture def app(session): return HttpAPI([model], session.bind) class TestUsersModelIntegrationWithAuthorizationHook(object):" 923,https://:@github.com/dutradda/falcon-swagger.git,4fbd5298af47fb91f80a602671e1920751bb6936,"@@ -226,7 +226,7 @@ class ModelJobsMetaMixin(type): def _set_job(cls, job_hash, status, session): key = cls._build_jobs_key() session.redis_bind.hset(key, job_hash, json.dumps(status)) - if session.redis_bind.ttl(key) > 0: + if session.redis_bind.ttl(key) < 0: session.redis_bind.expire(key, 7*24*60*60) def _build_jobs_key(cls): ",falconswagger/models/orm/http.py,"ReplaceText(target='<' @(229,39)->(229,40))","class ModelJobsMetaMixin(type): def _set_job(cls, job_hash, status, session): key = cls._build_jobs_key() session.redis_bind.hset(key, job_hash, json.dumps(status)) if session.redis_bind.ttl(key) > 0: session.redis_bind.expire(key, 7*24*60*60) def _build_jobs_key(cls):","class ModelJobsMetaMixin(type): def _set_job(cls, job_hash, status, session): key = cls._build_jobs_key() session.redis_bind.hset(key, job_hash, json.dumps(status)) if session.redis_bind.ttl(key) < 0: session.redis_bind.expire(key, 7*24*60*60) def _build_jobs_key(cls):" 924,https://:@github.com/peter-schmidbauer/pythovolve.git,85961b03f0086d97a01d82bcaa520be1a4fde052,"@@ -40,7 +40,7 @@ class Individual: if not isinstance(other, Individual): return NotImplemented try: - return self.score < other.score + return self.score == other.score except ValueError: return NotImplemented ",pythovolve/individuals.py,"ReplaceText(target='==' @(43,30)->(43,31))","class Individual: if not isinstance(other, Individual): return NotImplemented try: return self.score < other.score except ValueError: return NotImplemented ","class Individual: if not isinstance(other, Individual): return NotImplemented try: return self.score == other.score except ValueError: return NotImplemented " 925,https://:@github.com/Balandat/pyDR.git,d9405eb75fa03ad09891816342e0e210b29d8d7f,"@@ -668,7 +668,7 @@ def get_energy_charges(index, tariff, isRT=False, LMP=None, cidx = chronRates.index pdpind = ((cidx.hour >= 12) & (cidx.hour < 18) & (cidx.normalize().isin(pdp_days))) - chronRates.loc[pdpind, 'EnergyCharge'] = pdpchrg + chronRates.loc[pdpind, 'EnergyCharge'] += pdpchrg chronRates = chronRates.tz_convert('GMT') if isRT: chronRates['EnergyCharge'] += LMP.loc[index[0]:index[-1]] / 1000.0 ",pyDR/utils.py,"ReplaceText(target='+=' @(671,47)->(671,48))","def get_energy_charges(index, tariff, isRT=False, LMP=None, cidx = chronRates.index pdpind = ((cidx.hour >= 12) & (cidx.hour < 18) & (cidx.normalize().isin(pdp_days))) chronRates.loc[pdpind, 'EnergyCharge'] = pdpchrg chronRates = chronRates.tz_convert('GMT') if isRT: chronRates['EnergyCharge'] += LMP.loc[index[0]:index[-1]] / 1000.0","def get_energy_charges(index, tariff, isRT=False, LMP=None, cidx = chronRates.index pdpind = ((cidx.hour >= 12) & (cidx.hour < 18) & (cidx.normalize().isin(pdp_days))) chronRates.loc[pdpind, 'EnergyCharge'] += pdpchrg chronRates = chronRates.tz_convert('GMT') if isRT: chronRates['EnergyCharge'] += LMP.loc[index[0]:index[-1]] / 1000.0" 926,https://:@github.com/Toranktto/CraftProtocol.git,83edf8e43fcac26d0fb517f3bc4890e5350c93de,"@@ -35,7 +35,7 @@ class WindowItemsPacket(BasePacket): for slot_data in packet.get_slots(): StreamIO.write_short(stream, slot_data.get_id()) - if slot_data.is_empty(): + if not slot_data.is_empty(): StreamIO.write_byte(stream, slot_data.get_count()) StreamIO.write_short(stream, slot_data.get_damage()) NBTSerializer.write(stream, slot_data.get_tag()) ",CraftProtocol/Protocol/v1_10/Packet/Play/WindowItemsPacket.py,"ReplaceText(target='not ' @(38,15)->(38,15))","class WindowItemsPacket(BasePacket): for slot_data in packet.get_slots(): StreamIO.write_short(stream, slot_data.get_id()) if slot_data.is_empty(): StreamIO.write_byte(stream, slot_data.get_count()) StreamIO.write_short(stream, slot_data.get_damage()) NBTSerializer.write(stream, slot_data.get_tag())","class WindowItemsPacket(BasePacket): for slot_data in packet.get_slots(): StreamIO.write_short(stream, slot_data.get_id()) if not slot_data.is_empty(): StreamIO.write_byte(stream, slot_data.get_count()) StreamIO.write_short(stream, slot_data.get_damage()) NBTSerializer.write(stream, slot_data.get_tag())" 927,https://:@github.com/Christensen-Lab-Dartmouth/PyMethylProcess.git,01ff59ea0c1b13bfc3bac07e16851209ac279f21,"@@ -299,7 +299,7 @@ def combine_methylation_arrays(input_pkls, optional_input_pkl_dir, output_pkl, e input_pkls=glob.glob(os.path.join(optional_input_pkl_dir,'*','methyl_array.pkl')) if exclude: input_pkls=(np.array(input_pkls)[~np.isin(np.vectorize(lambda x: x.split('/')[-2])(input_pkls),np.array(exclude))]).tolist() - if len(input_pkls) > 0: + if len(input_pkls) > 1: base_methyl_array=MethylationArray(*extract_pheno_beta_df_from_pickle_dict(pickle.load(open(input_pkls[0],'rb')), '')) methyl_arrays_generator = (MethylationArray(*extract_pheno_beta_df_from_pickle_dict(pickle.load(open(input_pkl,'rb')), '')) for input_pkl in input_pkls[1:]) list_methyl_arrays = MethylationArrays([base_methyl_array]) ",build/lib/pymethylprocess/preprocess.py,"ReplaceText(target='1' @(302,25)->(302,26))","def combine_methylation_arrays(input_pkls, optional_input_pkl_dir, output_pkl, e input_pkls=glob.glob(os.path.join(optional_input_pkl_dir,'*','methyl_array.pkl')) if exclude: input_pkls=(np.array(input_pkls)[~np.isin(np.vectorize(lambda x: x.split('/')[-2])(input_pkls),np.array(exclude))]).tolist() if len(input_pkls) > 0: base_methyl_array=MethylationArray(*extract_pheno_beta_df_from_pickle_dict(pickle.load(open(input_pkls[0],'rb')), '')) methyl_arrays_generator = (MethylationArray(*extract_pheno_beta_df_from_pickle_dict(pickle.load(open(input_pkl,'rb')), '')) for input_pkl in input_pkls[1:]) list_methyl_arrays = MethylationArrays([base_methyl_array])","def combine_methylation_arrays(input_pkls, optional_input_pkl_dir, output_pkl, e input_pkls=glob.glob(os.path.join(optional_input_pkl_dir,'*','methyl_array.pkl')) if exclude: input_pkls=(np.array(input_pkls)[~np.isin(np.vectorize(lambda x: x.split('/')[-2])(input_pkls),np.array(exclude))]).tolist() if len(input_pkls) > 1: base_methyl_array=MethylationArray(*extract_pheno_beta_df_from_pickle_dict(pickle.load(open(input_pkls[0],'rb')), '')) methyl_arrays_generator = (MethylationArray(*extract_pheno_beta_df_from_pickle_dict(pickle.load(open(input_pkl,'rb')), '')) for input_pkl in input_pkls[1:]) list_methyl_arrays = MethylationArrays([base_methyl_array])" 928,https://:@github.com/AndreasSteiner/python-pptx.git,3a66082b1326a4263ea6f624a3a263faad65d4c5,"@@ -998,7 +998,7 @@ def then_categories_levels_contains_count_CategoryLevel_objs(context, count): def then_categories_number_format_is_value(context, value): expected_value = value number_format = context.categories.number_format - assert number_format == expected_value, 'got %s' % expected_value + assert number_format == expected_value, 'got %s' % number_format @then('category.add_sub_category(name) is a Category object') ",features/steps/chart.py,"ReplaceText(target='number_format' @(1001,55)->(1001,69))","def then_categories_levels_contains_count_CategoryLevel_objs(context, count): def then_categories_number_format_is_value(context, value): expected_value = value number_format = context.categories.number_format assert number_format == expected_value, 'got %s' % expected_value @then('category.add_sub_category(name) is a Category object')","def then_categories_levels_contains_count_CategoryLevel_objs(context, count): def then_categories_number_format_is_value(context, value): expected_value = value number_format = context.categories.number_format assert number_format == expected_value, 'got %s' % number_format @then('category.add_sub_category(name) is a Category object')" 929,https://:@github.com/dtkav/specific.git,44fc513eaa8f8746eafce36749b8564a0a03a0e8,"@@ -127,7 +127,7 @@ def validate_array(schema, data): return error # Run each sub-item through the list of validators. for func in VALIDATORS: - error = func(subschema, subval) + error = func(subschema, converted_value) if error: return error ",connexion/decorators/validation.py,"ReplaceText(target='converted_value' @(130,36)->(130,42))","def validate_array(schema, data): return error # Run each sub-item through the list of validators. for func in VALIDATORS: error = func(subschema, subval) if error: return error ","def validate_array(schema, data): return error # Run each sub-item through the list of validators. for func in VALIDATORS: error = func(subschema, converted_value) if error: return error " 930,https://:@github.com/kreczko/gitlab-migrate.git,8dd6f993bc443574e0d3e45776726b6f71141037,"@@ -36,7 +36,7 @@ def migration_instructions(conn_src, conn_dst, migrate): if user: names = None if user['projects'] != '--all--': - names = content['projects'] + names = user['projects'] user_projects = glc.user_projects(conn_src, names=names, statistics=False) return instructions, user_projects ",gitlab_migrate/migrate.py,"ReplaceText(target='user' @(39,20)->(39,27))","def migration_instructions(conn_src, conn_dst, migrate): if user: names = None if user['projects'] != '--all--': names = content['projects'] user_projects = glc.user_projects(conn_src, names=names, statistics=False) return instructions, user_projects ","def migration_instructions(conn_src, conn_dst, migrate): if user: names = None if user['projects'] != '--all--': names = user['projects'] user_projects = glc.user_projects(conn_src, names=names, statistics=False) return instructions, user_projects " 931,https://:@github.com/kreczko/gitlab-migrate.git,ec939be20fccea9337bda4fafce7605170bb31be,"@@ -57,7 +57,7 @@ def cli(config_file, version, plain, noop): dst_server = config.servers['destination'] gl_src = glc.connect(src_server.url, src_server.auth_token, ssl_verify=src_server.ssl_verify) - gl_dst = glc.connect(dst_server.url, dst_server.auth_token, ssl_verify=src_server.ssl_verify) + gl_dst = glc.connect(dst_server.url, dst_server.auth_token, ssl_verify=dst_server.ssl_verify) group_instructions, user_instructions = migration_instructions(gl_src, gl_dst, config.migrate) ",gitlab_migrate/migrate.py,"ReplaceText(target='dst_server' @(60,75)->(60,85))","def cli(config_file, version, plain, noop): dst_server = config.servers['destination'] gl_src = glc.connect(src_server.url, src_server.auth_token, ssl_verify=src_server.ssl_verify) gl_dst = glc.connect(dst_server.url, dst_server.auth_token, ssl_verify=src_server.ssl_verify) group_instructions, user_instructions = migration_instructions(gl_src, gl_dst, config.migrate) ","def cli(config_file, version, plain, noop): dst_server = config.servers['destination'] gl_src = glc.connect(src_server.url, src_server.auth_token, ssl_verify=src_server.ssl_verify) gl_dst = glc.connect(dst_server.url, dst_server.auth_token, ssl_verify=dst_server.ssl_verify) group_instructions, user_instructions = migration_instructions(gl_src, gl_dst, config.migrate) " 932,https://:@github.com/igrek51/cliglue.git,2de2f9599f15422234a4ccdb9d62c08bd88074ce,"@@ -116,7 +116,7 @@ def test_default_help_when_no_arguments(): def test_hiding_internal_options(): with MockIO('--help') as mockio: CliBuilder(hide_internal=True).run() - assert '--bash-install' in mockio.output() + assert '--bash-install' not in mockio.output() assert '--bash-autocomplete' not in mockio.output() with MockIO('--help') as mockio: CliBuilder(hide_internal=False).run() ",tests/help/test_help.py,"ReplaceText(target=' not in ' @(119,31)->(119,35))","def test_default_help_when_no_arguments(): def test_hiding_internal_options(): with MockIO('--help') as mockio: CliBuilder(hide_internal=True).run() assert '--bash-install' in mockio.output() assert '--bash-autocomplete' not in mockio.output() with MockIO('--help') as mockio: CliBuilder(hide_internal=False).run()","def test_default_help_when_no_arguments(): def test_hiding_internal_options(): with MockIO('--help') as mockio: CliBuilder(hide_internal=True).run() assert '--bash-install' not in mockio.output() assert '--bash-autocomplete' not in mockio.output() with MockIO('--help') as mockio: CliBuilder(hide_internal=False).run()" 933,https://:@github.com/alex-fe/Graphml-to-SVG-converter.git,759cb682f91e023a80f64fa4234edf0cded4fd5f,"@@ -53,7 +53,7 @@ class Graph(NameMixin): **label_kwargs ): if geometry is None: - geometry = Geometry(height, width, x, y) + geometry = Geometry(width, height, x, y) if fill is None: fill = Fill(fill_color, transparent) if border is None: ",app.py,"ArgSwap(idxs=0<->1 @(56,23)->(56,31))","class Graph(NameMixin): **label_kwargs ): if geometry is None: geometry = Geometry(height, width, x, y) if fill is None: fill = Fill(fill_color, transparent) if border is None:","class Graph(NameMixin): **label_kwargs ): if geometry is None: geometry = Geometry(width, height, x, y) if fill is None: fill = Fill(fill_color, transparent) if border is None:" 934,https://:@bitbucket.org/mbachett/maltpynt.git,f79c6b6ff1fb7e6bb0f3d33a866e220f0b9ff0ed,"@@ -14,7 +14,7 @@ def mp_calc_lags(freqs, cpds, pds1, pds2, n_chunks, rebin): lags = np.angle(cpds) / (2 * np.pi * freqs) sigcpd = np.absolute(cpds) - rawcof = (sigcpd) ** 2 / ((pds1) * (pds1)) + rawcof = (sigcpd) ** 2 / ((pds1) * (pds2)) dum = (1. - rawcof) / (2. * rawcof) ",maltpynt/mp_lags.py,"ReplaceText(target='pds2' @(17,40)->(17,44))","def mp_calc_lags(freqs, cpds, pds1, pds2, n_chunks, rebin): lags = np.angle(cpds) / (2 * np.pi * freqs) sigcpd = np.absolute(cpds) rawcof = (sigcpd) ** 2 / ((pds1) * (pds1)) dum = (1. - rawcof) / (2. * rawcof) ","def mp_calc_lags(freqs, cpds, pds1, pds2, n_chunks, rebin): lags = np.angle(cpds) / (2 * np.pi * freqs) sigcpd = np.absolute(cpds) rawcof = (sigcpd) ** 2 / ((pds1) * (pds2)) dum = (1. - rawcof) / (2. * rawcof) " 935,https://:@github.com/Lantero/battlebots.git,253d8e64895f7b7490e8d79e6b65fb39249f0257,"@@ -41,7 +41,7 @@ class Board(object): def transposed_index(self, index): """""" Return the transposed index """""" - return index % self.row_size * self.row_size + index / self.row_size + return index % self.row_size * self.row_size + index // self.row_size def transposed_board(self): """""" Return the transposed board """""" ",battlebots/board.py,"ReplaceText(target='//' @(44,61)->(44,62))","class Board(object): def transposed_index(self, index): """""" Return the transposed index """""" return index % self.row_size * self.row_size + index / self.row_size def transposed_board(self): """""" Return the transposed board """"""","class Board(object): def transposed_index(self, index): """""" Return the transposed index """""" return index % self.row_size * self.row_size + index // self.row_size def transposed_board(self): """""" Return the transposed board """"""" 936,https://:@github.com/narfman0/jeeves.git,a4e0401053c41d7d584d316d05845ec75d79c9a8,"@@ -30,7 +30,7 @@ class Conversation(object): plugin, text = self.brain.query(input) if plugin and text: try: - plugin.handle(input, self.mic) + plugin.handle(text, self.mic) except Exception: self._logger.error('Failed to execute module', exc_info=True) ",client/conversation.py,"ReplaceText(target='text' @(33,38)->(33,43))","class Conversation(object): plugin, text = self.brain.query(input) if plugin and text: try: plugin.handle(input, self.mic) except Exception: self._logger.error('Failed to execute module', exc_info=True)","class Conversation(object): plugin, text = self.brain.query(input) if plugin and text: try: plugin.handle(text, self.mic) except Exception: self._logger.error('Failed to execute module', exc_info=True)" 937,https://:@bitbucket.org/dranew/remixt.git,6aa375e5e1ba81d06e3b5f9d1739e79b22678d9c,"@@ -22,5 +22,5 @@ if __name__ == '__main__': if args['config'] is not None: execfile(args['config'], {}, config) - remixt.ref_data.create_ref_data(ref_data_dir, config) - + remixt.ref_data.create_ref_data(config, ref_data_dir) + ",remixt/setup/remixt_create_ref_data.py,"ArgSwap(idxs=0<->1 @(25,4)->(25,35))","if __name__ == '__main__': if args['config'] is not None: execfile(args['config'], {}, config) remixt.ref_data.create_ref_data(ref_data_dir, config) ","if __name__ == '__main__': if args['config'] is not None: execfile(args['config'], {}, config) remixt.ref_data.create_ref_data(config, ref_data_dir) " 938,https://:@bitbucket.org/dranew/remixt.git,6aa375e5e1ba81d06e3b5f9d1739e79b22678d9c,"@@ -28,7 +28,7 @@ if __name__ == '__main__': pyp = pypeliner.app.Pypeline(config=config) - workflow = remixt.mappability.bwa.workflow.create_bwa_mappability_workflow(ref_data_dir, config) + workflow = remixt.mappability.bwa.workflow.create_bwa_mappability_workflow(config, ref_data_dir) pyp.run(workflow) ",remixt/setup/remixt_mappability_bwa.py,"ArgSwap(idxs=0<->1 @(31,15)->(31,78))","if __name__ == '__main__': pyp = pypeliner.app.Pypeline(config=config) workflow = remixt.mappability.bwa.workflow.create_bwa_mappability_workflow(ref_data_dir, config) pyp.run(workflow) ","if __name__ == '__main__': pyp = pypeliner.app.Pypeline(config=config) workflow = remixt.mappability.bwa.workflow.create_bwa_mappability_workflow(config, ref_data_dir) pyp.run(workflow) " 939,https://:@github.com/visym/vipy.git,8ac8b78489487631a161fa7ed71cd700ea700154,"@@ -375,7 +375,7 @@ class Image(object): def url(self, url=None, username=None, password=None, sha1=None, ignoreUrlErrors=None): """"""Image URL and URL download properties"""""" - if url is None: + if url is not None: self._url = url # this does not change anything else, better to use constructor if username is not None: self._urluser = username # basic authentication ",vipy/image.py,"ReplaceText(target=' is not ' @(378,14)->(378,18))","class Image(object): def url(self, url=None, username=None, password=None, sha1=None, ignoreUrlErrors=None): """"""Image URL and URL download properties"""""" if url is None: self._url = url # this does not change anything else, better to use constructor if username is not None: self._urluser = username # basic authentication","class Image(object): def url(self, url=None, username=None, password=None, sha1=None, ignoreUrlErrors=None): """"""Image URL and URL download properties"""""" if url is not None: self._url = url # this does not change anything else, better to use constructor if username is not None: self._urluser = username # basic authentication" 940,https://:@github.com/scubbx/webguitest.git,ad615df8b42c2adadf5759951ed1029e7a186217,"@@ -35,7 +35,7 @@ if pyautoguiAvailable: numTries += 1 time.sleep(1) if elemToClick is None: - print("" (x): could not locate image {}"".format(elemToClick)) + print("" (x): could not locate image {}"".format(imagepath)) return False time.sleep(1) pyautogui.click(pyautogui.center(elemToClick)) ",webguitest/clickGraphic.py,"ReplaceText(target='imagepath' @(38,62)->(38,73))","if pyautoguiAvailable: numTries += 1 time.sleep(1) if elemToClick is None: print("" (x): could not locate image {}"".format(elemToClick)) return False time.sleep(1) pyautogui.click(pyautogui.center(elemToClick))","if pyautoguiAvailable: numTries += 1 time.sleep(1) if elemToClick is None: print("" (x): could not locate image {}"".format(imagepath)) return False time.sleep(1) pyautogui.click(pyautogui.center(elemToClick))" 941,https://:@github.com/PragmaticMates/django-inventor.git,2762f3a34313372dd548e0bda6fd24db622bf703,"@@ -11,5 +11,5 @@ class PlanQuerySet(models.QuerySet): class UserPlanQuerySet(models.QuerySet): def expires_in(self, days=7): - threshold = now() - timedelta(days=days) + threshold = now() + timedelta(days=days) return self.filter(expiration=threshold.date()) ",inventor/core/subscriptions/querysets.py,"ReplaceText(target='+' @(14,26)->(14,27))","class PlanQuerySet(models.QuerySet): class UserPlanQuerySet(models.QuerySet): def expires_in(self, days=7): threshold = now() - timedelta(days=days) return self.filter(expiration=threshold.date())","class PlanQuerySet(models.QuerySet): class UserPlanQuerySet(models.QuerySet): def expires_in(self, days=7): threshold = now() + timedelta(days=days) return self.filter(expiration=threshold.date())" 942,https://:@github.com/brentp/combined-pvalues.git,7726e0f8b5b35bb43059ae547ca2297bee54f5ec,"@@ -141,7 +141,7 @@ def pipeline(col_num, step, dist, prefix, threshold, seed, bed_files, mlog=False fregions = prefix + "".regions.bed"" with open(fregions, ""w"") as fh: list(peaks.peaks(prefix + "".fdr.bed"", -1, threshold, seed, - step, fh, operator.le)) + dist, fh, operator.le)) n_regions = sum(1 for _ in open(fregions)) print >>sys.stderr, ""wrote: %s (%i regions)"" % (fregions, n_regions) ",cpv/pipeline.py,"ReplaceText(target='dist' @(144,12)->(144,16))","def pipeline(col_num, step, dist, prefix, threshold, seed, bed_files, mlog=False fregions = prefix + "".regions.bed"" with open(fregions, ""w"") as fh: list(peaks.peaks(prefix + "".fdr.bed"", -1, threshold, seed, step, fh, operator.le)) n_regions = sum(1 for _ in open(fregions)) print >>sys.stderr, ""wrote: %s (%i regions)"" % (fregions, n_regions) ","def pipeline(col_num, step, dist, prefix, threshold, seed, bed_files, mlog=False fregions = prefix + "".regions.bed"" with open(fregions, ""w"") as fh: list(peaks.peaks(prefix + "".fdr.bed"", -1, threshold, seed, dist, fh, operator.le)) n_regions = sum(1 for _ in open(fregions)) print >>sys.stderr, ""wrote: %s (%i regions)"" % (fregions, n_regions) " 943,https://:@github.com/axiomabsolute/cs410-information-retrieval.git,18725a0cb50a579dc3ad2c32b6fc54451bdb23b3,"@@ -24,7 +24,7 @@ by_lookup_match_piece = by(by_lookup_match, by_piece_id) by_lookup_match_stem = by(by_lookup_match, by_stem) def bm25_idf(N, df): - assert(N > df) + assert(N >= df) return log( (N - df + 0.5) / (df + 0.5) ) def bm25_tf(tf, k=1.2): ",firms/graders.py,"ReplaceText(target='>=' @(27,13)->(27,14))","by_lookup_match_piece = by(by_lookup_match, by_piece_id) by_lookup_match_stem = by(by_lookup_match, by_stem) def bm25_idf(N, df): assert(N > df) return log( (N - df + 0.5) / (df + 0.5) ) def bm25_tf(tf, k=1.2):","by_lookup_match_piece = by(by_lookup_match, by_piece_id) by_lookup_match_stem = by(by_lookup_match, by_stem) def bm25_idf(N, df): assert(N >= df) return log( (N - df + 0.5) / (df + 0.5) ) def bm25_tf(tf, k=1.2):" 944,https://:@github.com/JayYip/bert-multitask-service.git,a22de7ec24ba873f699e989533122f36b4f6f693,"@@ -169,7 +169,7 @@ class BertModel(object): if token_type_ids is None: token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32) - with tf.variable_scope(""bert"", scope): + with tf.variable_scope(scope, ""bert""): with tf.variable_scope(""embeddings""): # Perform embedding lookup on the word ids. (self.embedding_output, self.embedding_table) = embedding_lookup( ",modeling.py,"ArgSwap(idxs=0<->1 @(172,9)->(172,26))","class BertModel(object): if token_type_ids is None: token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32) with tf.variable_scope(""bert"", scope): with tf.variable_scope(""embeddings""): # Perform embedding lookup on the word ids. (self.embedding_output, self.embedding_table) = embedding_lookup(","class BertModel(object): if token_type_ids is None: token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32) with tf.variable_scope(scope, ""bert""): with tf.variable_scope(""embeddings""): # Perform embedding lookup on the word ids. (self.embedding_output, self.embedding_table) = embedding_lookup(" 945,https://:@github.com/JayYip/bert-multitask-service.git,52d354bf04ba003a32b5c175775a574064569dcc,"@@ -22,7 +22,7 @@ def get_args(): args = parser.parse_args() param_str = '\n'.join(['%20s = %s' % (k, v) for k, v in sorted(vars(args).items())]) print('usage:\n{0}\nparameters: \n{1}'.format(' '.join([x for x in sys.argv]), param_str)) - return parser + return args if __name__ == '__main__': ",app.py,"ReplaceText(target='args' @(25,11)->(25,17))","def get_args(): args = parser.parse_args() param_str = '\n'.join(['%20s = %s' % (k, v) for k, v in sorted(vars(args).items())]) print('usage:\n{0}\nparameters: \n{1}'.format(' '.join([x for x in sys.argv]), param_str)) return parser if __name__ == '__main__':","def get_args(): args = parser.parse_args() param_str = '\n'.join(['%20s = %s' % (k, v) for k, v in sorted(vars(args).items())]) print('usage:\n{0}\nparameters: \n{1}'.format(' '.join([x for x in sys.argv]), param_str)) return args if __name__ == '__main__':" 946,https://:@github.com/JayYip/bert-multitask-service.git,4edc2497de0d8ea45d1afdbe636f20e51f2fa044,"@@ -166,7 +166,7 @@ class BertWorker(Process): def input_fn_builder(self, worker): def gen(): - while not True: + while True: if self.result: num_result = len(self.result) worker.send_multipart([ident, b'', pickle.dumps(self.result)]) ",service/server.py,"ReplaceText(target='' @(169,18)->(169,22))","class BertWorker(Process): def input_fn_builder(self, worker): def gen(): while not True: if self.result: num_result = len(self.result) worker.send_multipart([ident, b'', pickle.dumps(self.result)])","class BertWorker(Process): def input_fn_builder(self, worker): def gen(): while True: if self.result: num_result = len(self.result) worker.send_multipart([ident, b'', pickle.dumps(self.result)])" 947,https://:@github.com/WZBSocialScienceCenter/patternlite.git,cdb9262675a96df4ce7b5d25f53b7dc22f043078,"@@ -129,7 +129,7 @@ m.save(f, final=True) print(""loading model..."") f = os.path.join(os.path.dirname(__file__), ""en-model.slp"") -lexicon.model = Model.load(lexicon, f) +lexicon.model = Model.load(f, lexicon) # To test the accuracy of the language model, # we can compare a tagged corpus to the predicted tags. ",examples/05-vector/07-slp.py,"ArgSwap(idxs=0<->1 @(132,16)->(132,26))","m.save(f, final=True) print(""loading model..."") f = os.path.join(os.path.dirname(__file__), ""en-model.slp"") lexicon.model = Model.load(lexicon, f) # To test the accuracy of the language model, # we can compare a tagged corpus to the predicted tags.","m.save(f, final=True) print(""loading model..."") f = os.path.join(os.path.dirname(__file__), ""en-model.slp"") lexicon.model = Model.load(f, lexicon) # To test the accuracy of the language model, # we can compare a tagged corpus to the predicted tags." 948,https://:@github.com/jsh9/python-plot-utilities.git,bbf48002e85a5c27afa879e256184dfa185943ce,"@@ -1174,7 +1174,7 @@ def piechart(target_array, class_names=None, dropna=False, top_n=None, val = int(round(pct*total/100.0)) return '{p:.1f}% ({v:d})'.format(p=pct, v=val) return my_autopct - autopct = make_autopct(x) + autopct = make_autopct(counts) elif display == None: autopct = '' else: ",plot_utils.py,"ReplaceText(target='counts' @(1177,31)->(1177,32))","def piechart(target_array, class_names=None, dropna=False, top_n=None, val = int(round(pct*total/100.0)) return '{p:.1f}% ({v:d})'.format(p=pct, v=val) return my_autopct autopct = make_autopct(x) elif display == None: autopct = '' else:","def piechart(target_array, class_names=None, dropna=False, top_n=None, val = int(round(pct*total/100.0)) return '{p:.1f}% ({v:d})'.format(p=pct, v=val) return my_autopct autopct = make_autopct(counts) elif display == None: autopct = '' else:" 949,https://:@github.com/maurosilber/binlet.git,0c47b4979709a285c437e1090ca6503e6d3dfccf,"@@ -57,7 +57,7 @@ def binlet_level(inputs, threshold, valfun, covfun, bin_args, args, level, axes) # Calculate current level inputs_coeffs = tuple(modwt_level_nd(x, level, axes) for x in inputs) - bin_args = tuple(modwt_level_nd(x, level, axes, approx_only=True) for x in inputs) + bin_args = tuple(modwt_level_nd(x, level, axes, approx_only=True) for x in bin_args) # Threshold current level for key, mask in threshold_masks.items(): ",binlet/binlet.py,"ReplaceText(target='bin_args' @(60,79)->(60,85))","def binlet_level(inputs, threshold, valfun, covfun, bin_args, args, level, axes) # Calculate current level inputs_coeffs = tuple(modwt_level_nd(x, level, axes) for x in inputs) bin_args = tuple(modwt_level_nd(x, level, axes, approx_only=True) for x in inputs) # Threshold current level for key, mask in threshold_masks.items():","def binlet_level(inputs, threshold, valfun, covfun, bin_args, args, level, axes) # Calculate current level inputs_coeffs = tuple(modwt_level_nd(x, level, axes) for x in inputs) bin_args = tuple(modwt_level_nd(x, level, axes, approx_only=True) for x in bin_args) # Threshold current level for key, mask in threshold_masks.items():" 950,https://:@gitlab.com/betse/betsee.git,83abaec314e607797890d3f25983c03bc6727ab8,"@@ -120,7 +120,7 @@ def sanitize_classifiers( # formally classify this version as such. for python_version_minor in range( python_version_min_parts[1], python_version_minor_max): - classifiers.append( + classifiers_sane.append( 'Programming Language :: Python :: {}.{}'.format( PYTHON_VERSION_MAJOR, python_version_minor,)) # print('classifiers: {}'.format(_CLASSIFIERS)) ",betsee_setup/beuputil.py,"ReplaceText(target='classifiers_sane' @(123,8)->(123,19))","def sanitize_classifiers( # formally classify this version as such. for python_version_minor in range( python_version_min_parts[1], python_version_minor_max): classifiers.append( 'Programming Language :: Python :: {}.{}'.format( PYTHON_VERSION_MAJOR, python_version_minor,)) # print('classifiers: {}'.format(_CLASSIFIERS))","def sanitize_classifiers( # formally classify this version as such. for python_version_minor in range( python_version_min_parts[1], python_version_minor_max): classifiers_sane.append( 'Programming Language :: Python :: {}.{}'.format( PYTHON_VERSION_MAJOR, python_version_minor,)) # print('classifiers: {}'.format(_CLASSIFIERS))" 951,https://:@github.com/lensvol/pybetter.git,625e8fc854c7544df702d6001a57e46838b7df70,"@@ -15,7 +15,7 @@ class EqualsNoneIsNoneTransformer(cst.CSTTransformer): ): return original_node - return original_node.with_changes( + return updated_node.with_changes( operator=cst.Is( whitespace_after=original_node.operator.whitespace_after, whitespace_before=original_node.operator.whitespace_before, ",pybetter/transformers/equals_none.py,"ReplaceText(target='updated_node' @(18,15)->(18,28))","class EqualsNoneIsNoneTransformer(cst.CSTTransformer): ): return original_node return original_node.with_changes( operator=cst.Is( whitespace_after=original_node.operator.whitespace_after, whitespace_before=original_node.operator.whitespace_before,","class EqualsNoneIsNoneTransformer(cst.CSTTransformer): ): return original_node return updated_node.with_changes( operator=cst.Is( whitespace_after=original_node.operator.whitespace_after, whitespace_before=original_node.operator.whitespace_before," 952,https://:@github.com/lensvol/pybetter.git,625e8fc854c7544df702d6001a57e46838b7df70,"@@ -14,4 +14,4 @@ class RemoveParenthesesFromReturn(cst.CSTTransformer): changed_tuple = original_node.value.with_changes(lpar=[], rpar=[]) - return original_node.with_changes(value=changed_tuple) + return updated_node.with_changes(value=changed_tuple) ",pybetter/transformers/parenthesized_return.py,"ReplaceText(target='updated_node' @(17,15)->(17,28))","class RemoveParenthesesFromReturn(cst.CSTTransformer): changed_tuple = original_node.value.with_changes(lpar=[], rpar=[]) return original_node.with_changes(value=changed_tuple)","class RemoveParenthesesFromReturn(cst.CSTTransformer): changed_tuple = original_node.value.with_changes(lpar=[], rpar=[]) return updated_node.with_changes(value=changed_tuple)" 953,https://:@github.com/leprikon-cz/leprikon.git,1c31a9f054d79c1f75ee4bcd82be41d903e4f0f3,"@@ -149,7 +149,7 @@ class EventRegistration(SubjectRegistration): if discount.accounted.date() <= d and discount.explanation.strip() ) return PaymentStatus( - price=self.price if self.approved and self.approved.date() < d else 0, + price=self.price if self.approved and self.approved.date() <= d else 0, discount=self.get_discounted(d), explanation=explanation, paid=self.get_paid(d), ",leprikon/models/events.py,"ReplaceText(target='<=' @(152,71)->(152,72))","class EventRegistration(SubjectRegistration): if discount.accounted.date() <= d and discount.explanation.strip() ) return PaymentStatus( price=self.price if self.approved and self.approved.date() < d else 0, discount=self.get_discounted(d), explanation=explanation, paid=self.get_paid(d),","class EventRegistration(SubjectRegistration): if discount.accounted.date() <= d and discount.explanation.strip() ) return PaymentStatus( price=self.price if self.approved and self.approved.date() <= d else 0, discount=self.get_discounted(d), explanation=explanation, paid=self.get_paid(d)," 954,https://:@github.com/openclimatedata/openscm.git,1f492d38db2808bf7730b707266d53f35f0a2e09,"@@ -1036,7 +1036,7 @@ class ScmDataFrameBase: # pylint: disable=too-many-public-methods # Convert from ParameterType to str parameter_type_str = ( ""average"" - if parameter_type == ParameterType.AVERAGE_TIMESERIES + if p_type == ParameterType.AVERAGE_TIMESERIES else ""point"" ) res._meta.loc[grp.index] = res._meta.loc[grp.index].assign( ",openscm/scmdataframe/base.py,"ReplaceText(target='p_type' @(1039,19)->(1039,33))","class ScmDataFrameBase: # pylint: disable=too-many-public-methods # Convert from ParameterType to str parameter_type_str = ( ""average"" if parameter_type == ParameterType.AVERAGE_TIMESERIES else ""point"" ) res._meta.loc[grp.index] = res._meta.loc[grp.index].assign(","class ScmDataFrameBase: # pylint: disable=too-many-public-methods # Convert from ParameterType to str parameter_type_str = ( ""average"" if p_type == ParameterType.AVERAGE_TIMESERIES else ""point"" ) res._meta.loc[grp.index] = res._meta.loc[grp.index].assign(" 955,https://:@github.com/jvs/sourcer.git,f8175948d0ed0721ceb555837439b77246cdd0f9,"@@ -341,7 +341,7 @@ class Parser(object): def _parse_text(self, term, pos): end = pos + len(term) part = self.source[pos : end] - yield ParseResult(part, end) if part == term else ParseFailure + yield ParseResult(term, end) if part == term else ParseFailure def _parse_token(self, term, pos): if pos >= len(self.source): ",peg.py,"ReplaceText(target='term' @(344,26)->(344,30))","class Parser(object): def _parse_text(self, term, pos): end = pos + len(term) part = self.source[pos : end] yield ParseResult(part, end) if part == term else ParseFailure def _parse_token(self, term, pos): if pos >= len(self.source):","class Parser(object): def _parse_text(self, term, pos): end = pos + len(term) part = self.source[pos : end] yield ParseResult(term, end) if part == term else ParseFailure def _parse_token(self, term, pos): if pos >= len(self.source):" 956,https://:@github.com/SergSHV/SLRIC.git,30dccd92ce43affef13bd2731d20c525dcca6a31,"@@ -38,7 +38,7 @@ def indirect_paths(g, path_lim, aggregation, criterion): if path_lim % 2 == 0: return indirect_paths(compute_path(g, g, aggregation, criterion), path_lim // 2, type, criterion) else: - return compute_path(g, indirect_paths(g, path_lim - 1, aggregation, criterion), type, criterion) + return compute_path(indirect_paths(g, path_lim - 1, aggregation, criterion), g, type, criterion) # Evaluate path strength [criterion: 0 (sum), 1 (min), 2 (multiplication)] ",SLRIC/methods/indirect_influence.py,"ArgSwap(idxs=0<->1 @(41,19)->(41,31))","def indirect_paths(g, path_lim, aggregation, criterion): if path_lim % 2 == 0: return indirect_paths(compute_path(g, g, aggregation, criterion), path_lim // 2, type, criterion) else: return compute_path(g, indirect_paths(g, path_lim - 1, aggregation, criterion), type, criterion) # Evaluate path strength [criterion: 0 (sum), 1 (min), 2 (multiplication)]","def indirect_paths(g, path_lim, aggregation, criterion): if path_lim % 2 == 0: return indirect_paths(compute_path(g, g, aggregation, criterion), path_lim // 2, type, criterion) else: return compute_path(indirect_paths(g, path_lim - 1, aggregation, criterion), g, type, criterion) # Evaluate path strength [criterion: 0 (sum), 1 (min), 2 (multiplication)]" 957,https://:@github.com/jianhuupenn/ItClust.git,e09c84bfe42ededd15d95a5f618e83e3ded26271,"@@ -163,7 +163,7 @@ class transfer_learning_clf(object): adata_test.obs[""trajectory_""+str(i)]=trajectory_l[i] #labels=change_to_continuous(q_pred) - y_pred=np.asarray(np.argmax(q,axis=1),dtype=int) + y_pred=np.asarray(np.argmax(q_pred,axis=1),dtype=int) labels=y_pred.astype('U') labels=pd.Categorical(values=labels,categories=natsorted(np.unique(y_pred).astype('U'))) ",ItClust_package/ItClust/ItClust.py,"ReplaceText(target='q_pred' @(166,36)->(166,37))","class transfer_learning_clf(object): adata_test.obs[""trajectory_""+str(i)]=trajectory_l[i] #labels=change_to_continuous(q_pred) y_pred=np.asarray(np.argmax(q,axis=1),dtype=int) labels=y_pred.astype('U') labels=pd.Categorical(values=labels,categories=natsorted(np.unique(y_pred).astype('U'))) ","class transfer_learning_clf(object): adata_test.obs[""trajectory_""+str(i)]=trajectory_l[i] #labels=change_to_continuous(q_pred) y_pred=np.asarray(np.argmax(q_pred,axis=1),dtype=int) labels=y_pred.astype('U') labels=pd.Categorical(values=labels,categories=natsorted(np.unique(y_pred).astype('U'))) " 958,https://:@github.com/datalad/git-annex-ria-remote.git,556dd2877b24dd277160c36ebeeb03082d19706f,"@@ -117,7 +117,7 @@ class Install(Clone): path=path, dataset=dataset, description=description, - reckless=ephemeral, + reckless=reckless, alt_sources=alt_sources, result_filter=None, result_renderer='disabled', ",ria_remote/install.py,"ReplaceText(target='reckless' @(120,25)->(120,34))","class Install(Clone): path=path, dataset=dataset, description=description, reckless=ephemeral, alt_sources=alt_sources, result_filter=None, result_renderer='disabled',","class Install(Clone): path=path, dataset=dataset, description=description, reckless=reckless, alt_sources=alt_sources, result_filter=None, result_renderer='disabled'," 959,https://:@github.com/dmnfarrell/smallrnaseq.git,e4d03158818e7b2d8a67428ace3c1ba9c0723c14,"@@ -544,7 +544,7 @@ def print_read_stack(reads, refseq=None, outfile=None, cutoff=0, by=None, label= else: seqlen = reads.end.max() f = None - reads = reads[reads.reads>cutoff] + reads = reads[reads.reads>=cutoff] if by is not None: reads = reads.sort_values(by, ascending=False) ",smallrnaseq/utils.py,"ReplaceText(target='>=' @(547,29)->(547,30))","def print_read_stack(reads, refseq=None, outfile=None, cutoff=0, by=None, label= else: seqlen = reads.end.max() f = None reads = reads[reads.reads>cutoff] if by is not None: reads = reads.sort_values(by, ascending=False) ","def print_read_stack(reads, refseq=None, outfile=None, cutoff=0, by=None, label= else: seqlen = reads.end.max() f = None reads = reads[reads.reads>=cutoff] if by is not None: reads = reads.sort_values(by, ascending=False) " 960,https://:@github.com/dmnfarrell/smallrnaseq.git,eeed9c4b43346501da633ce78ac4d22440df4608,"@@ -70,7 +70,7 @@ def run(opts): #novel prediction if ref_genome != '': print ('predicting novel mirnas..') - allreads = utils.combine_aligned_reads(temp_path, files, ref_genome) + allreads = utils.combine_aligned_reads(path, files, ref_genome) new,cl = novel.find_mirnas(allreads, cow_fasta) new.to_csv(os.path.join(out,'novel.csv'), index=False) novel.create_report(new, cl, species, filename=os.path.join(out, 'novel.html')) ",smallrnaseq/app.py,"ReplaceText(target='path' @(73,51)->(73,60))","def run(opts): #novel prediction if ref_genome != '': print ('predicting novel mirnas..') allreads = utils.combine_aligned_reads(temp_path, files, ref_genome) new,cl = novel.find_mirnas(allreads, cow_fasta) new.to_csv(os.path.join(out,'novel.csv'), index=False) novel.create_report(new, cl, species, filename=os.path.join(out, 'novel.html'))","def run(opts): #novel prediction if ref_genome != '': print ('predicting novel mirnas..') allreads = utils.combine_aligned_reads(path, files, ref_genome) new,cl = novel.find_mirnas(allreads, cow_fasta) new.to_csv(os.path.join(out,'novel.csv'), index=False) novel.create_report(new, cl, species, filename=os.path.join(out, 'novel.html'))" 961,https://:@gitlab.com/danwin/fairways_py.git,28c15f9a3e5f59d8767bb803ec8024488b0bf4bd,"@@ -64,7 +64,7 @@ class HttpQueryTemplate: rq_kwargs[""headers""] = headers body = encoded_data if body: - rq_kwargs[""data""] = data + rq_kwargs[""data""] = encoded_data return rq_kwargs ",fairways/io/generic/net.py,"ReplaceText(target='encoded_data' @(67,32)->(67,36))","class HttpQueryTemplate: rq_kwargs[""headers""] = headers body = encoded_data if body: rq_kwargs[""data""] = data return rq_kwargs ","class HttpQueryTemplate: rq_kwargs[""headers""] = headers body = encoded_data if body: rq_kwargs[""data""] = encoded_data return rq_kwargs " 962,https://:@github.com/clusterking/clusterking.git,86816095fc6c1383b3088dbd93c72c16df8c9710,"@@ -129,7 +129,7 @@ class BMFOM(FOM): (data1.df[""cluster""] == cluster) & data1.df[""bpoint""] ] bpoints2 = data2.df[ - (data1.df[""cluster""] == cluster) & data2.df[""bpoint""] + (data2.df[""cluster""] == cluster) & data2.df[""bpoint""] ] msg = ""Found {} bpoints instead of 1 for dataset {}."" if len(bpoints1) != 1: ",clusterking/stability/fom.py,"ReplaceText(target='data2' @(132,17)->(132,22))","class BMFOM(FOM): (data1.df[""cluster""] == cluster) & data1.df[""bpoint""] ] bpoints2 = data2.df[ (data1.df[""cluster""] == cluster) & data2.df[""bpoint""] ] msg = ""Found {} bpoints instead of 1 for dataset {}."" if len(bpoints1) != 1:","class BMFOM(FOM): (data1.df[""cluster""] == cluster) & data1.df[""bpoint""] ] bpoints2 = data2.df[ (data2.df[""cluster""] == cluster) & data2.df[""bpoint""] ] msg = ""Found {} bpoints instead of 1 for dataset {}."" if len(bpoints1) != 1:" 963,https://:@github.com/clusterking/clusterking.git,bdc88d5a931d268d77e5f00119fcca5f16bd562a,"@@ -611,7 +611,7 @@ class BundlePlot(object): plot_histogram(self.ax, self._bins, data, **hist_kw) hf_kw = dict(color=light_color) - hf_kw.update(hist_kwargs) + hf_kw.update(hist_fill_kwargs) plot_histogram_fill( self.ax, self._bins, data - err_low, data + err_high, **hf_kw ",clusterking/plots/plot_bundles.py,"ReplaceText(target='hist_fill_kwargs' @(614,21)->(614,32))","class BundlePlot(object): plot_histogram(self.ax, self._bins, data, **hist_kw) hf_kw = dict(color=light_color) hf_kw.update(hist_kwargs) plot_histogram_fill( self.ax, self._bins, data - err_low, data + err_high, **hf_kw","class BundlePlot(object): plot_histogram(self.ax, self._bins, data, **hist_kw) hf_kw = dict(color=light_color) hf_kw.update(hist_fill_kwargs) plot_histogram_fill( self.ax, self._bins, data - err_low, data + err_high, **hf_kw" 964,https://:@github.com/julien6387/supvisors.git,5163605677362dbe30e3999bc45a44696e2222d9,"@@ -60,7 +60,7 @@ class ProcessRules(object): a required process that is not in the starting sequence is forced to optional If addresses are not defined, all addresses are applicable """""" # required MUST have start_sequence, so force to optional if no start_sequence - if self.required and self.start_sequence <= 0: + if self.required and self.start_sequence == 0: self.logger.warn('required forced to False because no start_sequence defined') self.required = False # if no addresses, consider all addresses ",supervisors/process.py,"ReplaceText(target='==' @(63,49)->(63,51))","class ProcessRules(object): a required process that is not in the starting sequence is forced to optional If addresses are not defined, all addresses are applicable """""" # required MUST have start_sequence, so force to optional if no start_sequence if self.required and self.start_sequence <= 0: self.logger.warn('required forced to False because no start_sequence defined') self.required = False # if no addresses, consider all addresses","class ProcessRules(object): a required process that is not in the starting sequence is forced to optional If addresses are not defined, all addresses are applicable """""" # required MUST have start_sequence, so force to optional if no start_sequence if self.required and self.start_sequence == 0: self.logger.warn('required forced to False because no start_sequence defined') self.required = False # if no addresses, consider all addresses" 965,https://:@github.com/hncuong/topicmodel-lib.git,6257da7e5c9bf7d70d504a6acb62a538dbf91694,"@@ -344,7 +344,7 @@ def load_mini_batch_term_frequency_from_term_frequency_file(fp, batch_size): tf = list_word[j].split("":"") doc_terms[j - 1] = int(tf[0]) doc_frequency[j - 1] = int(tf[1]) - mini_batch.append_doc(doc, doc_frequency) + mini_batch.append_doc(doc_terms, doc_frequency) return mini_batch, end_file except Exception as inst: logging.error(inst) ",tmlib/datasets/base.py,"ReplaceText(target='doc_terms' @(347,34)->(347,37))","def load_mini_batch_term_frequency_from_term_frequency_file(fp, batch_size): tf = list_word[j].split("":"") doc_terms[j - 1] = int(tf[0]) doc_frequency[j - 1] = int(tf[1]) mini_batch.append_doc(doc, doc_frequency) return mini_batch, end_file except Exception as inst: logging.error(inst)","def load_mini_batch_term_frequency_from_term_frequency_file(fp, batch_size): tf = list_word[j].split("":"") doc_terms[j - 1] = int(tf[0]) doc_frequency[j - 1] = int(tf[1]) mini_batch.append_doc(doc_terms, doc_frequency) return mini_batch, end_file except Exception as inst: logging.error(inst)" 966,https://:@github.com/adaptivescale/lxdui.git,fce2cbadebf5400fa109a7055fcf2059613c463d,"@@ -48,7 +48,7 @@ def createContainer(): for container in input: client = LXCContainer(container) result.append(client.create()) - return response.reply(result, message='Container {} created successfully.'.format(input.get('name'))) + return response.reply(result, message='Container {} created successfully.'.format(container.get('name'))) except ValueError as ex: return response.reply(message=ex.__str__(), status=403) ",app/api/controllers/container.py,"ReplaceText(target='container' @(51,90)->(51,95))","def createContainer(): for container in input: client = LXCContainer(container) result.append(client.create()) return response.reply(result, message='Container {} created successfully.'.format(input.get('name'))) except ValueError as ex: return response.reply(message=ex.__str__(), status=403) ","def createContainer(): for container in input: client = LXCContainer(container) result.append(client.create()) return response.reply(result, message='Container {} created successfully.'.format(container.get('name'))) except ValueError as ex: return response.reply(message=ex.__str__(), status=403) " 967,https://:@github.com/desihub/desiutil.git,51e58e1174bb9bba78a3fbbe8491c2f6f4ae2d91,"@@ -66,7 +66,7 @@ def setdep(header, name, version): verkey = 'DEPVER{:02d}'.format(i) if namekey in header: if header[namekey] == name: - header[namekey] = version + header[verkey] = version return else: continue ",py/desiutil/depend.py,"ReplaceText(target='verkey' @(69,23)->(69,30))","def setdep(header, name, version): verkey = 'DEPVER{:02d}'.format(i) if namekey in header: if header[namekey] == name: header[namekey] = version return else: continue","def setdep(header, name, version): verkey = 'DEPVER{:02d}'.format(i) if namekey in header: if header[namekey] == name: header[verkey] = version return else: continue" 968,https://:@github.com/jmoiron/par2ools.git,74b8d8885c8ad90f5649a8eb8228c62a840c5f3a,"@@ -75,7 +75,7 @@ class Par2File(object): else: self.contents = obj_or_path.read() if getattr(obj_or_path, 'name', None): - self.path = f.name + self.path = obj_or_path.name self.packets = self.read_packets() def read_packets(self): ",par2ools/par2.py,"ReplaceText(target='obj_or_path' @(78,28)->(78,29))","class Par2File(object): else: self.contents = obj_or_path.read() if getattr(obj_or_path, 'name', None): self.path = f.name self.packets = self.read_packets() def read_packets(self):","class Par2File(object): else: self.contents = obj_or_path.read() if getattr(obj_or_path, 'name', None): self.path = obj_or_path.name self.packets = self.read_packets() def read_packets(self):" 969,https://:@github.com/futurecolors/django-cked.git,e61ce34219c69582f131dbd922763d0253c2ba83,"@@ -33,7 +33,7 @@ def elfinder(request): 'dictionary type.') return render(request, 'cked/elfinder.html', { - 'options': json_encode(options), + 'options': json_encode(user_options), }) ",cked/views.py,"ReplaceText(target='user_options' @(36,31)->(36,38))","def elfinder(request): 'dictionary type.') return render(request, 'cked/elfinder.html', { 'options': json_encode(options), }) ","def elfinder(request): 'dictionary type.') return render(request, 'cked/elfinder.html', { 'options': json_encode(user_options), }) " 970,https://:@github.com/divi255/bakauditor.git,4604cdef011cd2a4d5c4307704a69e1b87d0bb2f,"@@ -12,7 +12,7 @@ def check(**kwargs): result.time = t result.size = size if 'min-size' in kwargs: - result.ok = size > kwargs.get('min-size') + result.ok = size >= kwargs.get('min-size') if not result.ok: result.err = 'Too small' else: ",bakauditor/plugins/file.py,"ReplaceText(target='>=' @(15,25)->(15,26))","def check(**kwargs): result.time = t result.size = size if 'min-size' in kwargs: result.ok = size > kwargs.get('min-size') if not result.ok: result.err = 'Too small' else:","def check(**kwargs): result.time = t result.size = size if 'min-size' in kwargs: result.ok = size >= kwargs.get('min-size') if not result.ok: result.err = 'Too small' else:" 971,https://:@github.com/cwebber/xudd.git,69a387685cb87e3e9fd0a68f3161fe21e3eb60fb,"@@ -139,7 +139,7 @@ class Hive(Thread): """""" message_id = id or self.gen_message_id() message = Message( - to=to, directive=to, from_id=from_id, body=body, + to=to, directive=directive, from_id=from_id, body=body, in_reply_to=in_reply_to, id=message_id) self.hive_action_queue.put( (""queue_message"", message)) ",xudd/hive.py,"ReplaceText(target='directive' @(142,29)->(142,31))","class Hive(Thread): """""" message_id = id or self.gen_message_id() message = Message( to=to, directive=to, from_id=from_id, body=body, in_reply_to=in_reply_to, id=message_id) self.hive_action_queue.put( (""queue_message"", message))","class Hive(Thread): """""" message_id = id or self.gen_message_id() message = Message( to=to, directive=directive, from_id=from_id, body=body, in_reply_to=in_reply_to, id=message_id) self.hive_action_queue.put( (""queue_message"", message))" 972,https://:@github.com/NotYetGames/po-excel-translate.git,5a50131472f50d15354df8a274395d69d8a937b5,"@@ -219,7 +219,7 @@ def ConvertPoXls(): for (i, cat) in enumerate(catalogs): cat = cat[1] msg = cat.find(msgid) - if msgid is not None: + if msg is not None: if 'fuzzy' in msg.flags: sheet.write(row, column, msg.msgstr, italic_style) else: ",lingua/xlsconvert.py,"ReplaceText(target='msg' @(222,15)->(222,20))","def ConvertPoXls(): for (i, cat) in enumerate(catalogs): cat = cat[1] msg = cat.find(msgid) if msgid is not None: if 'fuzzy' in msg.flags: sheet.write(row, column, msg.msgstr, italic_style) else:","def ConvertPoXls(): for (i, cat) in enumerate(catalogs): cat = cat[1] msg = cat.find(msgid) if msg is not None: if 'fuzzy' in msg.flags: sheet.write(row, column, msg.msgstr, italic_style) else:" 973,https://:@github.com/chen0040/pyalgs.git,52de8860e4a4e4fdde27c055064d1a4de5dd7074,"@@ -13,7 +13,7 @@ class BinarySelection(object): hi = len(a) - 1 while lo <= hi: - mid = lo + (hi - lo) / 2 + mid = lo + (hi - lo) // 2 if less(x, a[mid]): hi = mid - 1 elif less(a[mid], x): ",pyalgs/algorithms/commons/selecting.py,"ReplaceText(target='//' @(16,33)->(16,34))","class BinarySelection(object): hi = len(a) - 1 while lo <= hi: mid = lo + (hi - lo) / 2 if less(x, a[mid]): hi = mid - 1 elif less(a[mid], x):","class BinarySelection(object): hi = len(a) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if less(x, a[mid]): hi = mid - 1 elif less(a[mid], x):" 974,https://:@github.com/jvivian/rnaseq-lib.git,c72b002e39cd0a0646e3a4f228970e5078fecac6,"@@ -75,7 +75,7 @@ class Holoview: :rtype: hv.Overlay """""" # Subset dataframe by tissue and gene - df = self._subset(tissue, gene) + df = self._subset(gene, tissue) # Subset by dataset tumor, normal, gtex = subset_by_dataset(df) ",src/rnaseq_lib/plot/__init__.py,"ArgSwap(idxs=0<->1 @(78,13)->(78,25))","class Holoview: :rtype: hv.Overlay """""" # Subset dataframe by tissue and gene df = self._subset(tissue, gene) # Subset by dataset tumor, normal, gtex = subset_by_dataset(df)","class Holoview: :rtype: hv.Overlay """""" # Subset dataframe by tissue and gene df = self._subset(gene, tissue) # Subset by dataset tumor, normal, gtex = subset_by_dataset(df)" 975,https://:@github.com/tylertrussell/gae-catnado.git,1c469d607226dec29e79b09d3b9a63fc6b558dee,"@@ -33,4 +33,4 @@ class TestImmutableProperty(SimpleAppEngineTestCase): self.assertEqual(refetched_entity.name, NAME) with self.assertRaises(ImmutablePropertyException): - entity.name = 'anything' + refetched_entity.name = 'anything' ",catnado/properties/test/test_immutable_property.py,"ReplaceText(target='refetched_entity' @(36,6)->(36,12))","class TestImmutableProperty(SimpleAppEngineTestCase): self.assertEqual(refetched_entity.name, NAME) with self.assertRaises(ImmutablePropertyException): entity.name = 'anything'","class TestImmutableProperty(SimpleAppEngineTestCase): self.assertEqual(refetched_entity.name, NAME) with self.assertRaises(ImmutablePropertyException): refetched_entity.name = 'anything'" 976,https://:@github.com/oscar-franzen/adobo.git,9c42ed1fad2799077765cb76d531c4218399ef66,"@@ -183,7 +183,7 @@ https://oscar-franzen.github.io/adobo/adobo.html#adobo.normalize.norm') comp, contr = svd(data, ncomp) else: raise Exception('Unkown PCA method spefified. Valid choices are: irlb and svd') - obj.index = data.columns + comp.index = data.columns obj.norm_data[k]['dr']['pca'] = {'comp' : comp, 'contr' : contr, 'method' : method} ",adobo/dr.py,"ReplaceText(target='comp' @(186,8)->(186,11))","https://oscar-franzen.github.io/adobo/adobo.html#adobo.normalize.norm') comp, contr = svd(data, ncomp) else: raise Exception('Unkown PCA method spefified. Valid choices are: irlb and svd') obj.index = data.columns obj.norm_data[k]['dr']['pca'] = {'comp' : comp, 'contr' : contr, 'method' : method}","https://oscar-franzen.github.io/adobo/adobo.html#adobo.normalize.norm') comp, contr = svd(data, ncomp) else: raise Exception('Unkown PCA method spefified. Valid choices are: irlb and svd') comp.index = data.columns obj.norm_data[k]['dr']['pca'] = {'comp' : comp, 'contr' : contr, 'method' : method}" 977,https://:@github.com/ngmarchant/oasis.git,3b39116447a4d3e4662790e357c257027d398435,"@@ -62,7 +62,7 @@ def verify_consistency(predictions, scores, proba): def verify_unit_interval(value): """"""Throw an exception if the value is not on the unit interval [0,1]. """""" - if not (value >= 0 or value <= 1): + if not (value >= 0 and value <= 1): raise ValueError(""expected value on the interval [0, 1]."") return value ",oasis/input_verification.py,"ReplaceText(target='and' @(65,23)->(65,25))","def verify_consistency(predictions, scores, proba): def verify_unit_interval(value): """"""Throw an exception if the value is not on the unit interval [0,1]. """""" if not (value >= 0 or value <= 1): raise ValueError(""expected value on the interval [0, 1]."") return value ","def verify_consistency(predictions, scores, proba): def verify_unit_interval(value): """"""Throw an exception if the value is not on the unit interval [0,1]. """""" if not (value >= 0 and value <= 1): raise ValueError(""expected value on the interval [0, 1]."") return value " 978,https://:@github.com/featurelabs/henchman.git,283c4812767a4d5b8701e2e7a0077343da8cec57,"@@ -135,7 +135,7 @@ class Dendrogram(): self.graphs = templist def transform(self, df, n_feats=10): - assert df.shape[1] <= n_feats + assert df.shape[1] >= n_feats step = self.find_set_of_size(n_feats) return df[self.features_at_step(step)] ",henchman/selection.py,"ReplaceText(target='>=' @(138,27)->(138,29))","class Dendrogram(): self.graphs = templist def transform(self, df, n_feats=10): assert df.shape[1] <= n_feats step = self.find_set_of_size(n_feats) return df[self.features_at_step(step)] ","class Dendrogram(): self.graphs = templist def transform(self, df, n_feats=10): assert df.shape[1] >= n_feats step = self.find_set_of_size(n_feats) return df[self.features_at_step(step)] " 979,https://:@github.com/jackuoll/ultima-py.git,de0b3c0964cda0accc65e79e8b6b9c1e260d559f,"@@ -53,7 +53,7 @@ class Gumps: copy = bitmap.copy() if hue: hue = (hue & 0x3FFF) - 1 - return Hues.HUES[hue].apply_to(bitmap, only_grey_pixels=partial_hue) + return Hues.HUES[hue].apply_to(copy, only_grey_pixels=partial_hue) return copy ",ultimapy/sdk/gumps.py,"ReplaceText(target='copy' @(56,43)->(56,49))","class Gumps: copy = bitmap.copy() if hue: hue = (hue & 0x3FFF) - 1 return Hues.HUES[hue].apply_to(bitmap, only_grey_pixels=partial_hue) return copy ","class Gumps: copy = bitmap.copy() if hue: hue = (hue & 0x3FFF) - 1 return Hues.HUES[hue].apply_to(copy, only_grey_pixels=partial_hue) return copy " 980,https://:@github.com/duguyue100/minesweeper.git,7d48ad6eb8e1d65b8e61f370e181e246443092f2,"@@ -39,7 +39,7 @@ class MSGame(object): if (board_height <= 0): raise ValueError(""the board height cannot be non-positive!"") else: - self.board_height = board_width + self.board_height = board_height if (num_mines >= (board_width*board_height)): raise ValueError(""The number of mines cannot be larger than "" ",minesweeper/msgame.py,"ReplaceText(target='board_height' @(42,32)->(42,43))","class MSGame(object): if (board_height <= 0): raise ValueError(""the board height cannot be non-positive!"") else: self.board_height = board_width if (num_mines >= (board_width*board_height)): raise ValueError(""The number of mines cannot be larger than ""","class MSGame(object): if (board_height <= 0): raise ValueError(""the board height cannot be non-positive!"") else: self.board_height = board_height if (num_mines >= (board_width*board_height)): raise ValueError(""The number of mines cannot be larger than """ 981,https://:@github.com/duguyue100/minesweeper.git,e65fd9f5f46cb9c409746889d68d1e8cdc32876d,"@@ -33,7 +33,7 @@ class MSBoard(object): if (board_height <= 0): raise ValueError(""the board height cannot be non-positive!"") else: - self.board_height = board_width + self.board_height = board_height if (num_mines >= (board_width*board_height)): raise ValueError(""The number of mines cannot be larger than "" ",minesweeper/msboard.py,"ReplaceText(target='board_height' @(36,32)->(36,43))","class MSBoard(object): if (board_height <= 0): raise ValueError(""the board height cannot be non-positive!"") else: self.board_height = board_width if (num_mines >= (board_width*board_height)): raise ValueError(""The number of mines cannot be larger than ""","class MSBoard(object): if (board_height <= 0): raise ValueError(""the board height cannot be non-positive!"") else: self.board_height = board_height if (num_mines >= (board_width*board_height)): raise ValueError(""The number of mines cannot be larger than """ 982,https://:@github.com/mtgreenway/python-openid.git,8b6d87a5a95552814265911c9d449932c39db768,"@@ -90,7 +90,7 @@ class DiffieHelmanAssociator(object): 'openid.session_type':'DH-SHA1', 'openid.dh_modulus': to_b64(long2a(p)), 'openid.dh_gen': to_b64(long2a(g)), - 'openid.dh_consumer_public': to_b64(long2a(pow(p, priv_key, p))), + 'openid.dh_consumer_public': to_b64(long2a(pow(g, priv_key, p))), } body = urllib.urlencode(args) ",association.py,"ReplaceText(target='g' @(93,59)->(93,60))","class DiffieHelmanAssociator(object): 'openid.session_type':'DH-SHA1', 'openid.dh_modulus': to_b64(long2a(p)), 'openid.dh_gen': to_b64(long2a(g)), 'openid.dh_consumer_public': to_b64(long2a(pow(p, priv_key, p))), } body = urllib.urlencode(args)","class DiffieHelmanAssociator(object): 'openid.session_type':'DH-SHA1', 'openid.dh_modulus': to_b64(long2a(p)), 'openid.dh_gen': to_b64(long2a(g)), 'openid.dh_consumer_public': to_b64(long2a(pow(g, priv_key, p))), } body = urllib.urlencode(args)" 983,https://:@github.com/hhuuggoo/kitchensink.git,752722df9109ca74a4fd321915e710eb7def9cb5,"@@ -33,7 +33,7 @@ def make_app(redis_connection_obj, port, host_url, host_name, datadir): rpcblueprint.task_queue = TaskQueue(rpcblueprint.r) server_manager = Servers(rpcblueprint.r) settings.setup_server(rpcblueprint.r, datadir, host_url, host_name, - Catalog(rpcblueprint.r, datadir, host_url), + Catalog(rpcblueprint.r, datadir, host_name), server_manager ) rpcblueprint.heartbeat_thread = HeartbeatThread() ",kitchensink/rpc/server.py,"ReplaceText(target='host_name' @(36,59)->(36,67))","def make_app(redis_connection_obj, port, host_url, host_name, datadir): rpcblueprint.task_queue = TaskQueue(rpcblueprint.r) server_manager = Servers(rpcblueprint.r) settings.setup_server(rpcblueprint.r, datadir, host_url, host_name, Catalog(rpcblueprint.r, datadir, host_url), server_manager ) rpcblueprint.heartbeat_thread = HeartbeatThread()","def make_app(redis_connection_obj, port, host_url, host_name, datadir): rpcblueprint.task_queue = TaskQueue(rpcblueprint.r) server_manager = Servers(rpcblueprint.r) settings.setup_server(rpcblueprint.r, datadir, host_url, host_name, Catalog(rpcblueprint.r, datadir, host_name), server_manager ) rpcblueprint.heartbeat_thread = HeartbeatThread()" 984,https://:@github.com/hhuuggoo/kitchensink.git,752722df9109ca74a4fd321915e710eb7def9cb5,"@@ -45,7 +45,7 @@ def run(redis_connection, node_url, node_name, queue, datadir): db=redis_connection_obj['db']) server_manager = Servers(r) settings.setup_server(r, datadir, node_url, node_name, - Catalog(r, datadir, node_url), + Catalog(r, datadir, node_name), server_manager ) if queue is None: ",kitchensink/scripts/start_worker.py,"ReplaceText(target='node_name' @(48,46)->(48,54))","def run(redis_connection, node_url, node_name, queue, datadir): db=redis_connection_obj['db']) server_manager = Servers(r) settings.setup_server(r, datadir, node_url, node_name, Catalog(r, datadir, node_url), server_manager ) if queue is None:","def run(redis_connection, node_url, node_name, queue, datadir): db=redis_connection_obj['db']) server_manager = Servers(r) settings.setup_server(r, datadir, node_url, node_name, Catalog(r, datadir, node_name), server_manager ) if queue is None:" 985,https://:@github.com/MPBA/pyphysio.git,a86854cc97f7c917f35d6cb424b1edc27e3167ee,"@@ -317,7 +317,7 @@ class UnevenlySignal(Signal): if start_time is None: start_time = x_values[0] else: - assert start_time >= x_values[0], ""More than one sample at or before start_time"" + assert start_time <= x_values[0], ""More than one sample at or before start_time"" # WARN: limitation to 10 decimals due to workaround to prevent wrong cast flooring # (e.g. np.floor(0.29 * 100) == 28) x_values = _np.round((x_values - start_time) * sampling_freq, 10).astype(int) ",pyphysio/Signal.py,"ReplaceText(target='<=' @(320,34)->(320,36))","class UnevenlySignal(Signal): if start_time is None: start_time = x_values[0] else: assert start_time >= x_values[0], ""More than one sample at or before start_time"" # WARN: limitation to 10 decimals due to workaround to prevent wrong cast flooring # (e.g. np.floor(0.29 * 100) == 28) x_values = _np.round((x_values - start_time) * sampling_freq, 10).astype(int)","class UnevenlySignal(Signal): if start_time is None: start_time = x_values[0] else: assert start_time <= x_values[0], ""More than one sample at or before start_time"" # WARN: limitation to 10 decimals due to workaround to prevent wrong cast flooring # (e.g. np.floor(0.29 * 100) == 28) x_values = _np.round((x_values - start_time) * sampling_freq, 10).astype(int)" 986,https://:@github.com/rhasspy/rhasspy-hermes.git,aec600af8dfa1112fdd20e0d2187b777e0f1799f,"@@ -84,7 +84,7 @@ class NluIntent(Message): @classmethod def from_dict(cls, message_dict: typing.Dict[str, typing.Any]): """"""Construct message from dictionary."""""" - message_dict = message_dict.only_fields(message_dict) + message_dict = cls.only_fields(message_dict) intent_dict = message_dict.pop(""intent"", {}) slot_dicts = message_dict.pop(""slots"", []) message = NluIntent( # type: ignore ",rhasspyhermes/nlu.py,"ReplaceText(target='cls' @(87,23)->(87,35))","class NluIntent(Message): @classmethod def from_dict(cls, message_dict: typing.Dict[str, typing.Any]): """"""Construct message from dictionary."""""" message_dict = message_dict.only_fields(message_dict) intent_dict = message_dict.pop(""intent"", {}) slot_dicts = message_dict.pop(""slots"", []) message = NluIntent( # type: ignore","class NluIntent(Message): @classmethod def from_dict(cls, message_dict: typing.Dict[str, typing.Any]): """"""Construct message from dictionary."""""" message_dict = cls.only_fields(message_dict) intent_dict = message_dict.pop(""intent"", {}) slot_dicts = message_dict.pop(""slots"", []) message = NluIntent( # type: ignore" 987,https://:@github.com/alpacahq/alpaca-backtrader-api.git,f198c13c87b8736d0903498fbdb233310ef6f09c,"@@ -469,7 +469,7 @@ class AlpacaStore(with_metaclass(MetaSingleton, object)): # (https://stackoverflow.com/a/1592837/2739124) cdl = cdl.loc[ pytz.timezone(NY).localize(dtbegin): - pytz.timezone(NY).localize(dtbegin) + pytz.timezone(NY).localize(dtend) ].dropna(subset=['high']) records = cdl.reset_index().to_dict('records') for r in records: ",alpaca_backtrader_api/alpacastore.py,"ReplaceText(target='dtend' @(472,41)->(472,48))","class AlpacaStore(with_metaclass(MetaSingleton, object)): # (https://stackoverflow.com/a/1592837/2739124) cdl = cdl.loc[ pytz.timezone(NY).localize(dtbegin): pytz.timezone(NY).localize(dtbegin) ].dropna(subset=['high']) records = cdl.reset_index().to_dict('records') for r in records:","class AlpacaStore(with_metaclass(MetaSingleton, object)): # (https://stackoverflow.com/a/1592837/2739124) cdl = cdl.loc[ pytz.timezone(NY).localize(dtbegin): pytz.timezone(NY).localize(dtend) ].dropna(subset=['high']) records = cdl.reset_index().to_dict('records') for r in records:" 988,https://:@github.com/willforde/urlquick.git,3023fbbb7646f0e0dfb0393912720137f11165f7,"@@ -854,7 +854,7 @@ class Session(CacheAdapter): reqParams = UnicodeDict(self._params, params) # Add cookies to headers - if reqCookies and not u""Cookie"" in headers: + if reqCookies and not u""Cookie"" in reqHeaders: header = u""; "".join([u""{}={}"".format(key, value) for key, value in reqCookies.items()]) reqHeaders[u""Cookie""] = header ",urlquick.py,"ReplaceText(target='reqHeaders' @(857,43)->(857,50))","class Session(CacheAdapter): reqParams = UnicodeDict(self._params, params) # Add cookies to headers if reqCookies and not u""Cookie"" in headers: header = u""; "".join([u""{}={}"".format(key, value) for key, value in reqCookies.items()]) reqHeaders[u""Cookie""] = header ","class Session(CacheAdapter): reqParams = UnicodeDict(self._params, params) # Add cookies to headers if reqCookies and not u""Cookie"" in reqHeaders: header = u""; "".join([u""{}={}"".format(key, value) for key, value in reqCookies.items()]) reqHeaders[u""Cookie""] = header " 989,https://:@github.com/willforde/urlquick.git,d207cf47f7bf35163849f35f919a024b001a0f33,"@@ -962,7 +962,7 @@ class Session(ConnectionManager): if req_cookies: logger.debug(""Request cookies: %s"", req_cookies) if json: - logger.debug(""Request json: %s"", req_cookies) + logger.debug(""Request json: %s"", json) if data: logger.debug(""Request data: %s"", data) ",urlquick.py,"ReplaceText(target='json' @(965,45)->(965,56))","class Session(ConnectionManager): if req_cookies: logger.debug(""Request cookies: %s"", req_cookies) if json: logger.debug(""Request json: %s"", req_cookies) if data: logger.debug(""Request data: %s"", data) ","class Session(ConnectionManager): if req_cookies: logger.debug(""Request cookies: %s"", req_cookies) if json: logger.debug(""Request json: %s"", json) if data: logger.debug(""Request data: %s"", data) " 990,https://:@github.com/dlukes/corpy.git,4bf35b8dd0ed5971bd05896adda646f4452e47a8,"@@ -23,7 +23,7 @@ def print_position(lines, line_no): ""represent the same corpus?"" ) position.extend(line[1:]) - print(""\t"".join(line)) + print(""\t"".join(position)) @cli.command() ",corpy/scripts/zip_verticals.py,"ReplaceText(target='position' @(26,20)->(26,24))","def print_position(lines, line_no): ""represent the same corpus?"" ) position.extend(line[1:]) print(""\t"".join(line)) @cli.command()","def print_position(lines, line_no): ""represent the same corpus?"" ) position.extend(line[1:]) print(""\t"".join(position)) @cli.command()" 991,https://:@github.com/steinitzu/humblebee.git,d95954f99098481ab17e935f63ca734dc8bdf519,"@@ -50,7 +50,7 @@ def zero_prefix_int(num): strnum = str(num) if len(strnum) == 1: return '0'+strnum - return num + return strnum def timestamp(dt): return mktime(dt.timetuple()) ",src/tvunfucker/util.py,"ReplaceText(target='strnum' @(53,11)->(53,14))","def zero_prefix_int(num): strnum = str(num) if len(strnum) == 1: return '0'+strnum return num def timestamp(dt): return mktime(dt.timetuple())","def zero_prefix_int(num): strnum = str(num) if len(strnum) == 1: return '0'+strnum return strnum def timestamp(dt): return mktime(dt.timetuple())" 992,https://:@github.com/ramasrirama99/AlgoTradeFramework.git,011a70532972aa883c66bb9d4f32351bcc24a922,"@@ -6,7 +6,7 @@ def chunks(l, n): n = max(1, n) step = int(len(l) / n) for i in range(0, len(l), step): - big_list.append(l[i:i+n]) + big_list.append(l[i:i+step]) return big_list ",algotaf/backend/config.py,"ReplaceText(target='step' @(9,30)->(9,31))","def chunks(l, n): n = max(1, n) step = int(len(l) / n) for i in range(0, len(l), step): big_list.append(l[i:i+n]) return big_list ","def chunks(l, n): n = max(1, n) step = int(len(l) / n) for i in range(0, len(l), step): big_list.append(l[i:i+step]) return big_list " 993,https://:@github.com/JonnyTran/OpenOmics.git,d49006c61b12a8013c9c1f4a12c5ff390980f9e3,"@@ -454,7 +454,7 @@ class LncRNAExpression(GenomicData): if gene_name not in lnc_seq: lnc_seq[gene_name] = str(record.seq) else: - if len(lnc_seq[gene_name]) > len(str(record.seq)): + if len(lnc_seq[gene_name]) < len(str(record.seq)): lnc_seq[gene_name] = str(record.seq) # Multiple transcripts each lncRNA gene ",TCGAMultiOmics/genomic.py,"ReplaceText(target='<' @(457,43)->(457,44))","class LncRNAExpression(GenomicData): if gene_name not in lnc_seq: lnc_seq[gene_name] = str(record.seq) else: if len(lnc_seq[gene_name]) > len(str(record.seq)): lnc_seq[gene_name] = str(record.seq) # Multiple transcripts each lncRNA gene","class LncRNAExpression(GenomicData): if gene_name not in lnc_seq: lnc_seq[gene_name] = str(record.seq) else: if len(lnc_seq[gene_name]) < len(str(record.seq)): lnc_seq[gene_name] = str(record.seq) # Multiple transcripts each lncRNA gene" 994,https://:@github.com/JonnyTran/OpenOmics.git,b034a1b50639f3d302e6da13280093662394b35d,"@@ -95,7 +95,7 @@ class GeneOntology(Dataset): leaf_terms = self.get_child_terms() go_terms_parents = annotation.map( - lambda x: list({term for term in x if term not in leaf_terms}) \ + lambda x: list({term for term in x if term in leaf_terms}) \ if isinstance(x, list) else None) return go_terms_parents ",openomics/database/ontology.py,"ReplaceText(target=' in ' @(98,54)->(98,62))","class GeneOntology(Dataset): leaf_terms = self.get_child_terms() go_terms_parents = annotation.map( lambda x: list({term for term in x if term not in leaf_terms}) \ if isinstance(x, list) else None) return go_terms_parents ","class GeneOntology(Dataset): leaf_terms = self.get_child_terms() go_terms_parents = annotation.map( lambda x: list({term for term in x if term in leaf_terms}) \ if isinstance(x, list) else None) return go_terms_parents " 995,https://:@github.com/JonnyTran/OpenOmics.git,153599d5ce118fcd4c4fb6c44eba9c28fd762983,"@@ -95,7 +95,7 @@ class GeneOntology(Dataset): leaf_terms = self.get_child_terms() go_terms_parents = annotation.map( - lambda x: list({term for term in x if term not in leaf_terms}) \ + lambda x: list({term for term in x if term in leaf_terms}) \ if isinstance(x, list) else None) return go_terms_parents ",openomics/database/ontology.py,"ReplaceText(target=' in ' @(98,54)->(98,62))","class GeneOntology(Dataset): leaf_terms = self.get_child_terms() go_terms_parents = annotation.map( lambda x: list({term for term in x if term not in leaf_terms}) \ if isinstance(x, list) else None) return go_terms_parents ","class GeneOntology(Dataset): leaf_terms = self.get_child_terms() go_terms_parents = annotation.map( lambda x: list({term for term in x if term in leaf_terms}) \ if isinstance(x, list) else None) return go_terms_parents " 996,https://:@github.com/jqb/django-settings.git,6b594eca70c7addfc9e1b30d8e91334da3c6254f,"@@ -106,7 +106,7 @@ class DataAPI(object): # XXX: fix this mechanism def _set_cache_for(self, name, value): - self.get._cache_set(value, name) + self.get._cache_set(name, value) data = DataAPI() ",django_settings/dataapi.py,"ArgSwap(idxs=0<->1 @(109,8)->(109,27))","class DataAPI(object): # XXX: fix this mechanism def _set_cache_for(self, name, value): self.get._cache_set(value, name) data = DataAPI()","class DataAPI(object): # XXX: fix this mechanism def _set_cache_for(self, name, value): self.get._cache_set(name, value) data = DataAPI()" 997,https://:@github.com/jqb/django-settings.git,72acf0e93c8b2a4bc8dd0c78fa1c703e63b7a26f,"@@ -11,7 +11,7 @@ def initialize_data(sender, **kwargs): for name, type_name_and_value in DEFAULT_SETTINGS.items(): type_name, value = type_name_and_value - if not dataapi.data.exists(type_name): + if not dataapi.data.exists(name): dataapi.data.set(type_name, name, value) signals.post_syncdb.connect(initialize_data, sender=models) ",django_settings/management.py,"ReplaceText(target='name' @(14,35)->(14,44))","def initialize_data(sender, **kwargs): for name, type_name_and_value in DEFAULT_SETTINGS.items(): type_name, value = type_name_and_value if not dataapi.data.exists(type_name): dataapi.data.set(type_name, name, value) signals.post_syncdb.connect(initialize_data, sender=models)","def initialize_data(sender, **kwargs): for name, type_name_and_value in DEFAULT_SETTINGS.items(): type_name, value = type_name_and_value if not dataapi.data.exists(name): dataapi.data.set(type_name, name, value) signals.post_syncdb.connect(initialize_data, sender=models)" 998,https://:@github.com/qutech/qtune.git,a6ca5b76c17a8092c67f2d495c7f422d038008f5,"@@ -45,5 +45,5 @@ def find_lead_transition(data: np.ndarray, center: float, scan_range: float, npo y_red = np.absolute(y_red) max_index = int(np.argmax(y_red) + int(round(n / 2))) - return x_red[max_index] + return x[max_index] ",qtune/util.py,"ReplaceText(target='x' @(48,11)->(48,16))","def find_lead_transition(data: np.ndarray, center: float, scan_range: float, npo y_red = np.absolute(y_red) max_index = int(np.argmax(y_red) + int(round(n / 2))) return x_red[max_index] ","def find_lead_transition(data: np.ndarray, center: float, scan_range: float, npo y_red = np.absolute(y_red) max_index = int(np.argmax(y_red) + int(round(n / 2))) return x[max_index] " 999,https://:@github.com/qutech/qtune.git,b68e78b9da5d2150450fcda75d7266d388794caf,"@@ -42,7 +42,7 @@ class SubsetTunerTest(unittest.TestCase): # assert that the solver is called with the right arguments self.assertEqual(solver.update_after_step.call_count, 1) - pd.testing.assert_series_equal(solver_voltages, solver.update_after_step.call_args[0][0]) + pd.testing.assert_series_equal(full_voltages, solver.update_after_step.call_args[0][0]) parameter = pd.Series(data=[10 * i for i in range(n_evaluator)], index=[""parameter_"" + str(i) for i in range(n_evaluator)]) ",tests/test_parameter_tuner.py,"ReplaceText(target='full_voltages' @(45,39)->(45,54))","class SubsetTunerTest(unittest.TestCase): # assert that the solver is called with the right arguments self.assertEqual(solver.update_after_step.call_count, 1) pd.testing.assert_series_equal(solver_voltages, solver.update_after_step.call_args[0][0]) parameter = pd.Series(data=[10 * i for i in range(n_evaluator)], index=[""parameter_"" + str(i) for i in range(n_evaluator)])","class SubsetTunerTest(unittest.TestCase): # assert that the solver is called with the right arguments self.assertEqual(solver.update_after_step.call_count, 1) pd.testing.assert_series_equal(full_voltages, solver.update_after_step.call_args[0][0]) parameter = pd.Series(data=[10 * i for i in range(n_evaluator)], index=[""parameter_"" + str(i) for i in range(n_evaluator)])" 1000,https://:@github.com/plonegovbr/brasil.gov.vlibrasnews.git,7d9a28d0b1c48e2599dd6e87fbc9c277c1ea5bd8,"@@ -18,6 +18,6 @@ class VLibrasVideoViewlet(ViewletBase): super(VLibrasVideoViewlet, self).update() self.youtube_url = get_video_url(self.context) self.is_ready = self.youtube_url is not None - self.enabled = self.is_ready and not api.user.is_anonymous() + self.enabled = self.is_ready or not api.user.is_anonymous() if self.is_ready: self.klass = 'ready' ",src/brasil/gov/vlibrasvideo/browser/vlibrasvideo.py,"ReplaceText(target='or' @(21,37)->(21,40))","class VLibrasVideoViewlet(ViewletBase): super(VLibrasVideoViewlet, self).update() self.youtube_url = get_video_url(self.context) self.is_ready = self.youtube_url is not None self.enabled = self.is_ready and not api.user.is_anonymous() if self.is_ready: self.klass = 'ready'","class VLibrasVideoViewlet(ViewletBase): super(VLibrasVideoViewlet, self).update() self.youtube_url = get_video_url(self.context) self.is_ready = self.youtube_url is not None self.enabled = self.is_ready or not api.user.is_anonymous() if self.is_ready: self.klass = 'ready'" 1001,https://:@github.com/ch3pjw/format_cef.git,91a70b8e6d42edf64d1d4a94a447cb87fa77254e,"@@ -85,7 +85,7 @@ def str_sanitiser(regex_str='.*', escape_chars='', min_len=0, max_len=None): s = s.encode('utf-8') s = escape(s) if max_len is None: - if len(s) <= min_len: + if len(s) < min_len: raise ValueError( '{}: String longer than {} characters'.format( debug_name, min_len)) ",format_cef/cef.py,"ReplaceText(target='<' @(88,26)->(88,28))","def str_sanitiser(regex_str='.*', escape_chars='', min_len=0, max_len=None): s = s.encode('utf-8') s = escape(s) if max_len is None: if len(s) <= min_len: raise ValueError( '{}: String longer than {} characters'.format( debug_name, min_len))","def str_sanitiser(regex_str='.*', escape_chars='', min_len=0, max_len=None): s = s.encode('utf-8') s = escape(s) if max_len is None: if len(s) < min_len: raise ValueError( '{}: String longer than {} characters'.format( debug_name, min_len))" 1002,https://:@github.com/hyan15/proxyscrape.git,14c34e8e90643885f1839878b3ac55f4b51bcd29,"@@ -238,7 +238,7 @@ class Collector: self._extend_filter(combined_filter_opts, filter_opts) self._refresh_resources(False) - return self._store.get_proxy(filter_opts, self._blacklist) + return self._store.get_proxy(combined_filter_opts, self._blacklist) def remove_proxy(self, proxies): if not _is_iterable(proxies): ",proxyscrape/proxyscrape.py,"ReplaceText(target='combined_filter_opts' @(241,37)->(241,48))","class Collector: self._extend_filter(combined_filter_opts, filter_opts) self._refresh_resources(False) return self._store.get_proxy(filter_opts, self._blacklist) def remove_proxy(self, proxies): if not _is_iterable(proxies):","class Collector: self._extend_filter(combined_filter_opts, filter_opts) self._refresh_resources(False) return self._store.get_proxy(combined_filter_opts, self._blacklist) def remove_proxy(self, proxies): if not _is_iterable(proxies):" 1003,https://:@github.com/Axilent/Djax.git,6ed7214dd303d0358b6adda49eca86511a12e430,"@@ -203,7 +203,7 @@ def sync_content(token=None,content_type_to_sync=None): log.info('Syncing %s.' % content_type_to_sync) try: content_type = content_registry[content_type_to_sync] - sync_content_type(content_type) + sync_content_type(content_type_to_sync) except KeyError: log.error('%s is not in the content registry.' % content_type_to_sync) else: ",djax/content.py,"ReplaceText(target='content_type_to_sync' @(206,30)->(206,42))","def sync_content(token=None,content_type_to_sync=None): log.info('Syncing %s.' % content_type_to_sync) try: content_type = content_registry[content_type_to_sync] sync_content_type(content_type) except KeyError: log.error('%s is not in the content registry.' % content_type_to_sync) else:","def sync_content(token=None,content_type_to_sync=None): log.info('Syncing %s.' % content_type_to_sync) try: content_type = content_registry[content_type_to_sync] sync_content_type(content_type_to_sync) except KeyError: log.error('%s is not in the content registry.' % content_type_to_sync) else:" 1004,https://:@github.com/Axilent/Djax.git,60b81a3f9e104bdebfe9fa0668da6644f8fd058f,"@@ -518,7 +518,7 @@ class ContentManager(Manager): channel_results = self._channel(queryset,channel=channel,profile=profile,basekey=basekey,flavor=flavor,limit=limit,include_endorsements=True) remainder_results = queryset.exclude(pk__in=[item.pk for item in channel_results]) final_results = channel_results + [ContentItemWrapper(item,0) for item in remainder_results] - final_results.sort(cmp=lambda x,y: cmp(x.rlevel,y.rlevel)) + final_results.sort(cmp=lambda x,y: cmp(y.rlevel,x.rlevel)) return final_results class ContentItemWrapper(object): ",djax/content.py,"ArgSwap(idxs=0<->1 @(521,43)->(521,46))","class ContentManager(Manager): channel_results = self._channel(queryset,channel=channel,profile=profile,basekey=basekey,flavor=flavor,limit=limit,include_endorsements=True) remainder_results = queryset.exclude(pk__in=[item.pk for item in channel_results]) final_results = channel_results + [ContentItemWrapper(item,0) for item in remainder_results] final_results.sort(cmp=lambda x,y: cmp(x.rlevel,y.rlevel)) return final_results class ContentItemWrapper(object):","class ContentManager(Manager): channel_results = self._channel(queryset,channel=channel,profile=profile,basekey=basekey,flavor=flavor,limit=limit,include_endorsements=True) remainder_results = queryset.exclude(pk__in=[item.pk for item in channel_results]) final_results = channel_results + [ContentItemWrapper(item,0) for item in remainder_results] final_results.sort(cmp=lambda x,y: cmp(y.rlevel,x.rlevel)) return final_results class ContentItemWrapper(object):" 1005,https://:@github.com/baverman/supplement.git,c1611d29a5ebe5347ddd5107f9f549f256204780,"@@ -148,7 +148,7 @@ def assist(project, source, position, filename): if not ctx: names = get_scope_names(scope, lineno) else: - obj = infer(ctx, scope, position) + obj = infer(ctx, scope, lineno) names = [obj.get_names()] elif ctx_type == 'import': names = (project.get_possible_imports(ctx, filename),) ",supplement/assistant.py,"ReplaceText(target='lineno' @(151,36)->(151,44))","def assist(project, source, position, filename): if not ctx: names = get_scope_names(scope, lineno) else: obj = infer(ctx, scope, position) names = [obj.get_names()] elif ctx_type == 'import': names = (project.get_possible_imports(ctx, filename),)","def assist(project, source, position, filename): if not ctx: names = get_scope_names(scope, lineno) else: obj = infer(ctx, scope, lineno) names = [obj.get_names()] elif ctx_type == 'import': names = (project.get_possible_imports(ctx, filename),)" 1006,https://:@github.com/baverman/supplement.git,82ec55dee23f33c890ab1d8a0e55e694e00dc0b0,"@@ -105,7 +105,7 @@ class CallDB(object): if not args: continue try: - func = scope.eval(func, False) + func = s.eval(func, False) except: continue ",supplement/calls.py,"ReplaceText(target='s' @(108,27)->(108,32))","class CallDB(object): if not args: continue try: func = scope.eval(func, False) except: continue ","class CallDB(object): if not args: continue try: func = s.eval(func, False) except: continue " 1007,https://:@github.com/keiserlab/e3fp.git,5f5bed7e36138fddc8c64108f9d352260f061d55,"@@ -332,7 +332,7 @@ def mol_to_sdf(mol, out_file, conf_num=None): writer = rdkit.Chem.SDWriter(fobj) conf_ids = [conf.GetId() for conf in mol.GetConformers()] for i in conf_ids: - if conf_num in {-1, None} and i >= conf_num: + if conf_num not in {-1, None} and i >= conf_num: break writer.write(mol, confId=i) writer.close() ",e3fp/conformer/util.py,"ReplaceText(target=' not in ' @(335,23)->(335,27))","def mol_to_sdf(mol, out_file, conf_num=None): writer = rdkit.Chem.SDWriter(fobj) conf_ids = [conf.GetId() for conf in mol.GetConformers()] for i in conf_ids: if conf_num in {-1, None} and i >= conf_num: break writer.write(mol, confId=i) writer.close()","def mol_to_sdf(mol, out_file, conf_num=None): writer = rdkit.Chem.SDWriter(fobj) conf_ids = [conf.GetId() for conf in mol.GetConformers()] for i in conf_ids: if conf_num not in {-1, None} and i >= conf_num: break writer.write(mol, confId=i) writer.close()" 1008,https://:@github.com/dbrnz/biosignalml-corelib.git,ad805bbdf30919348b05a8e0b6c7a86081dd93dd,"@@ -91,7 +91,7 @@ class HDF5Signal(BSMLSignal): if isinstance(self.clock, UniformClock): yield DataSegment(self.clock[startpos], UniformTimeSeries(data, self.clock.rate)) else: - yield DataSegment(0, TimeSeries(self.clock[startpos: startpos+maxpoints], data)) + yield DataSegment(0, TimeSeries(data, self.clock[startpos: startpos+maxpoints])) startpos += len(data) length -= len(data) ",formats/hdf5/__init__.py,"ArgSwap(idxs=0<->1 @(94,29)->(94,39))","class HDF5Signal(BSMLSignal): if isinstance(self.clock, UniformClock): yield DataSegment(self.clock[startpos], UniformTimeSeries(data, self.clock.rate)) else: yield DataSegment(0, TimeSeries(self.clock[startpos: startpos+maxpoints], data)) startpos += len(data) length -= len(data) ","class HDF5Signal(BSMLSignal): if isinstance(self.clock, UniformClock): yield DataSegment(self.clock[startpos], UniformTimeSeries(data, self.clock.rate)) else: yield DataSegment(0, TimeSeries(data, self.clock[startpos: startpos+maxpoints])) startpos += len(data) length -= len(data) " 1009,https://:@github.com/SOBotics/Redunda-lib-Python.git,6187143b32f4f3c4ca9809c347349be1b537cf30,"@@ -83,7 +83,7 @@ class Redunda: try: if filename.endswith ("".pickle"") or ispickle == True: - dict = eval (filename) + dict = eval (filedata) try: pickle.dump (dict, filename) except pickle.PickleError as perr: ",Redunda.py,"ReplaceText(target='filedata' @(86,29)->(86,37))","class Redunda: try: if filename.endswith ("".pickle"") or ispickle == True: dict = eval (filename) try: pickle.dump (dict, filename) except pickle.PickleError as perr:","class Redunda: try: if filename.endswith ("".pickle"") or ispickle == True: dict = eval (filedata) try: pickle.dump (dict, filename) except pickle.PickleError as perr:" 1010,https://:@github.com/averagehuman/kez.git,e923c7dad180ba4f6d8250074b112b2dd7416329,"@@ -20,7 +20,7 @@ class BuildController(object): self.src = src self.dst = dst self.options = options or {} - self.settings = options or {} + self.settings = settings or {} self.logfile = pathjoin(self.dst, 'melba.log') self.status = None self.exc_info = None ",melba/builders/base.py,"ReplaceText(target='settings' @(23,24)->(23,31))","class BuildController(object): self.src = src self.dst = dst self.options = options or {} self.settings = options or {} self.logfile = pathjoin(self.dst, 'melba.log') self.status = None self.exc_info = None","class BuildController(object): self.src = src self.dst = dst self.options = options or {} self.settings = settings or {} self.logfile = pathjoin(self.dst, 'melba.log') self.status = None self.exc_info = None" 1011,https://:@github.com/fsecada01/TextSpitter.git,c7ca706cc19d2d76fa562c045dd8de7a3bc96643,"@@ -22,7 +22,7 @@ def PdfFileRead(file): i += 1 else: pdf_file = open(file, 'rb') - pdf_reader = PyPDF2.PdfFileReader(file) + pdf_reader = PyPDF2.PdfFileReader(pdf_file) while i < pdf_reader.numPages: payload = pdf_reader.getPage(i).extractText().replace('\n', '') text += payload.encode('ascii', 'ignore').decode('unicode_escape') ",TextSpitter/core.py,"ReplaceText(target='pdf_file' @(25,42)->(25,46))","def PdfFileRead(file): i += 1 else: pdf_file = open(file, 'rb') pdf_reader = PyPDF2.PdfFileReader(file) while i < pdf_reader.numPages: payload = pdf_reader.getPage(i).extractText().replace('\n', '') text += payload.encode('ascii', 'ignore').decode('unicode_escape')","def PdfFileRead(file): i += 1 else: pdf_file = open(file, 'rb') pdf_reader = PyPDF2.PdfFileReader(pdf_file) while i < pdf_reader.numPages: payload = pdf_reader.getPage(i).extractText().replace('\n', '') text += payload.encode('ascii', 'ignore').decode('unicode_escape')" 1012,https://:@github.com/WHenderson/HashDb.git,4544c95147266221be975c3da18341641078575f,"@@ -11,7 +11,7 @@ def walk(top, topdown=True, onerror=None, followlinks=False): filename = basename(top) try: - scandir_it = scandir(top) + scandir_it = scandir(dirpath) except OSError as error: onerror(error) return ",hashdb2/walk.py,"ReplaceText(target='dirpath' @(14,33)->(14,36))","def walk(top, topdown=True, onerror=None, followlinks=False): filename = basename(top) try: scandir_it = scandir(top) except OSError as error: onerror(error) return","def walk(top, topdown=True, onerror=None, followlinks=False): filename = basename(top) try: scandir_it = scandir(dirpath) except OSError as error: onerror(error) return" 1013,https://:@github.com/namuyan/bc4py.git,946e2296029195123c663840d49d921b517853a8,"@@ -609,7 +609,7 @@ class TransactionBuilder: def put_unconfirmed(self, tx): assert tx.height is None, 'Not unconfirmed tx {}'.format(tx) - if tx.type not in (C.TX_POW_REWARD, C.TX_POS_REWARD): + if tx.type in (C.TX_POW_REWARD, C.TX_POS_REWARD): return # It is Reword tx elif tx.hash in self.unconfirmed: logging.debug('Already unconfirmed tx. {}'.format(tx)) ",bc4py/database/builder.py,"ReplaceText(target=' in ' @(612,18)->(612,26))","class TransactionBuilder: def put_unconfirmed(self, tx): assert tx.height is None, 'Not unconfirmed tx {}'.format(tx) if tx.type not in (C.TX_POW_REWARD, C.TX_POS_REWARD): return # It is Reword tx elif tx.hash in self.unconfirmed: logging.debug('Already unconfirmed tx. {}'.format(tx))","class TransactionBuilder: def put_unconfirmed(self, tx): assert tx.height is None, 'Not unconfirmed tx {}'.format(tx) if tx.type in (C.TX_POW_REWARD, C.TX_POS_REWARD): return # It is Reword tx elif tx.hash in self.unconfirmed: logging.debug('Already unconfirmed tx. {}'.format(tx))" 1014,https://:@github.com/namuyan/bc4py.git,1d2b8ad52307769c0ac32ab65dadb0d0bf606532,"@@ -198,7 +198,7 @@ def contract_signature_check(extra_tx: TX, v: Validator, include_block: Block): raise BlockChainError('Unrelated signature include, reject={}'.format(reject_cks)) elif include_block: # check satisfy require? - if len(accept_cks) != v.require: + if len(accept_cks) >= v.require: raise BlockChainError('Not satisfied require signature. [signed={}, accepted={}, require={}]' .format(signed_cks, accept_cks, v.require)) else: ",bc4py/chain/checking/tx_contract.py,"ReplaceText(target='>=' @(201,27)->(201,29))","def contract_signature_check(extra_tx: TX, v: Validator, include_block: Block): raise BlockChainError('Unrelated signature include, reject={}'.format(reject_cks)) elif include_block: # check satisfy require? if len(accept_cks) != v.require: raise BlockChainError('Not satisfied require signature. [signed={}, accepted={}, require={}]' .format(signed_cks, accept_cks, v.require)) else:","def contract_signature_check(extra_tx: TX, v: Validator, include_block: Block): raise BlockChainError('Unrelated signature include, reject={}'.format(reject_cks)) elif include_block: # check satisfy require? if len(accept_cks) >= v.require: raise BlockChainError('Not satisfied require signature. [signed={}, accepted={}, require={}]' .format(signed_cks, accept_cks, v.require)) else:" 1015,https://:@github.com/namuyan/bc4py.git,87defc8330c37c6c4a4d32a3187c70d36081a8cf,"@@ -96,7 +96,7 @@ def validator_fill_iter(v: Validator, best_block=None, best_chain=None): c_address, address, flag, sig_diff = decode(tx.message) if c_address != v.c_address: continue - index = tx.height * 0xffffffff + block.txs.index(tx) + index = block.height * 0xffffffff + block.txs.index(tx) yield index, flag, address, sig_diff, tx.hash # unconfirmed if best_block is None: ",bc4py/database/validator.py,"ReplaceText(target='block' @(99,20)->(99,22))","def validator_fill_iter(v: Validator, best_block=None, best_chain=None): c_address, address, flag, sig_diff = decode(tx.message) if c_address != v.c_address: continue index = tx.height * 0xffffffff + block.txs.index(tx) yield index, flag, address, sig_diff, tx.hash # unconfirmed if best_block is None:","def validator_fill_iter(v: Validator, best_block=None, best_chain=None): c_address, address, flag, sig_diff = decode(tx.message) if c_address != v.c_address: continue index = block.height * 0xffffffff + block.txs.index(tx) yield index, flag, address, sig_diff, tx.hash # unconfirmed if best_block is None:" 1016,https://:@github.com/namuyan/bc4py.git,2083e976751938af11f53bff7f9b303a1e16a29d,"@@ -147,7 +147,7 @@ async def new_address(request): cur = db.cursor() user_name = request.query.get('account', C.account2name[C.ANT_UNKNOWN]) user_id = read_name2user(user_name, cur) - address = create_new_user_keypair(user_name, cur) + address = create_new_user_keypair(user_id, cur) db.commit() if user_id == C.ANT_CONTRACT: address = convert_address(address, V.BLOCK_CONTRACT_PREFIX) ",bc4py/user/api/accountinfo.py,"ReplaceText(target='user_id' @(150,42)->(150,51))","async def new_address(request): cur = db.cursor() user_name = request.query.get('account', C.account2name[C.ANT_UNKNOWN]) user_id = read_name2user(user_name, cur) address = create_new_user_keypair(user_name, cur) db.commit() if user_id == C.ANT_CONTRACT: address = convert_address(address, V.BLOCK_CONTRACT_PREFIX)","async def new_address(request): cur = db.cursor() user_name = request.query.get('account', C.account2name[C.ANT_UNKNOWN]) user_id = read_name2user(user_name, cur) address = create_new_user_keypair(user_id, cur) db.commit() if user_id == C.ANT_CONTRACT: address = convert_address(address, V.BLOCK_CONTRACT_PREFIX)" 1017,https://:@github.com/namuyan/bc4py.git,21ac4f74d4d4ec9322e90556e2a4506c5ca1a705,"@@ -53,7 +53,7 @@ def check_already_started(): new_pid = os.getpid() with open(pid_path, mode='w') as fp: fp.write(str(new_pid)) - log.info(""create new process lock file pid={}"".format(pid)) + log.info(""create new process lock file pid={}"".format(new_pid)) class AESCipher: ",bc4py/utils.py,"ReplaceText(target='new_pid' @(56,58)->(56,61))","def check_already_started(): new_pid = os.getpid() with open(pid_path, mode='w') as fp: fp.write(str(new_pid)) log.info(""create new process lock file pid={}"".format(pid)) class AESCipher:","def check_already_started(): new_pid = os.getpid() with open(pid_path, mode='w') as fp: fp.write(str(new_pid)) log.info(""create new process lock file pid={}"".format(new_pid)) class AESCipher:" 1018,https://:@github.com/agtumulak/dabbiew.git,58b7fdb7ede8e0ae216e5b4088ff6c4d1bcd6f0e,"@@ -571,7 +571,7 @@ def run(stdscr, df): left, right, top, bottom, moving_right, moving_down = jump( left, right, top, bottom, rows, cols, found_row, found_col, resizing) if keypress in [ord('g')]: - if not keystroke_history and keystroke_history[-1] == 'g': + if keystroke_history and keystroke_history[-1] == 'g': left, right, top, bottom, moving_right, moving_down = jump( left, right, top, bottom, rows, cols, 0, right, resizing) if keypress in [ord('G')]: ",src/dabbiew.py,"ReplaceText(target='' @(574,15)->(574,19))","def run(stdscr, df): left, right, top, bottom, moving_right, moving_down = jump( left, right, top, bottom, rows, cols, found_row, found_col, resizing) if keypress in [ord('g')]: if not keystroke_history and keystroke_history[-1] == 'g': left, right, top, bottom, moving_right, moving_down = jump( left, right, top, bottom, rows, cols, 0, right, resizing) if keypress in [ord('G')]:","def run(stdscr, df): left, right, top, bottom, moving_right, moving_down = jump( left, right, top, bottom, rows, cols, found_row, found_col, resizing) if keypress in [ord('g')]: if keystroke_history and keystroke_history[-1] == 'g': left, right, top, bottom, moving_right, moving_down = jump( left, right, top, bottom, rows, cols, 0, right, resizing) if keypress in [ord('G')]:" 1019,https://:@github.com/arquolo/glow.git,d5b0d511214ff7588ca148819c5d3aa7a5b635d8,"@@ -20,7 +20,7 @@ def timer(name=''): yield finally: duration = time() - start - if name: + if not name: logging.warning('done in %.4g seconds', duration) else: logging.warning('%s - done in %.4g seconds', name, duration) ",ort/debug.py,"ReplaceText(target='not ' @(23,11)->(23,11))","def timer(name=''): yield finally: duration = time() - start if name: logging.warning('done in %.4g seconds', duration) else: logging.warning('%s - done in %.4g seconds', name, duration)","def timer(name=''): yield finally: duration = time() - start if not name: logging.warning('done in %.4g seconds', duration) else: logging.warning('%s - done in %.4g seconds', name, duration)" 1020,https://:@github.com/joaduo/smoothtest.git,f70861b38425b6511e05469e4fb2bb6f5ee989b6,"@@ -155,7 +155,7 @@ class SmokeCommand(SmoothTestBase): for m in s.get_missing(pkg): pth = m.__file__ if pth.endswith('.pyc'): - pth = f[:-1] + pth = pth[:-1] s.log('Missing test in module %s' % m) s.log(formatPathPrint(pth)) #return results ",smoothtest/smoke/SmokeTestDiscover.py,"ReplaceText(target='pth' @(158,30)->(158,31))","class SmokeCommand(SmoothTestBase): for m in s.get_missing(pkg): pth = m.__file__ if pth.endswith('.pyc'): pth = f[:-1] s.log('Missing test in module %s' % m) s.log(formatPathPrint(pth)) #return results","class SmokeCommand(SmoothTestBase): for m in s.get_missing(pkg): pth = m.__file__ if pth.endswith('.pyc'): pth = pth[:-1] s.log('Missing test in module %s' % m) s.log(formatPathPrint(pth)) #return results" 1021,https://:@github.com/timmykuo/mitopipeline.git,3888bab80cbcff6a6fbd28c15c1941f1c557d611,"@@ -36,7 +36,7 @@ class PipelineBuilder(): #write in the steps requested into the pipeline for step in steps: #if Complete Genomics data, i.e., did split gap then pipeline requires different scripts with shorter reads due to splitting into multiple reads at the gap - if 'split_gap' in steps and step == 'remove_numts': + if 'split_gap' not in steps and step == 'remove_numts': job_name = 'remove_numts_no_split_gap.sh' #step only is name of the step, not the name of the script else: ",mitopipeline/pipeline_builder.py,"ReplaceText(target=' not in ' @(39,30)->(39,34))","class PipelineBuilder(): #write in the steps requested into the pipeline for step in steps: #if Complete Genomics data, i.e., did split gap then pipeline requires different scripts with shorter reads due to splitting into multiple reads at the gap if 'split_gap' in steps and step == 'remove_numts': job_name = 'remove_numts_no_split_gap.sh' #step only is name of the step, not the name of the script else:","class PipelineBuilder(): #write in the steps requested into the pipeline for step in steps: #if Complete Genomics data, i.e., did split gap then pipeline requires different scripts with shorter reads due to splitting into multiple reads at the gap if 'split_gap' not in steps and step == 'remove_numts': job_name = 'remove_numts_no_split_gap.sh' #step only is name of the step, not the name of the script else:" 1022,https://:@github.com/maqifrnswa/scimpy.git,4bec9f14ba49a033bccbaf1fd26fd1102c44126d,"@@ -208,7 +208,7 @@ def calc_impedance(plotwidget, ax_power.set_ylabel('SPL (dB 1W1m)', color='b') # ax_phase.set_ylabel('Phase (degrees)') ax_groupdelay.set_ylabel('Group Delay (ms)', color='r') - ax_groupdelay.set_xlabel('Frequency (Hz)') + ax_power.set_xlabel('Frequency (Hz)') ax_power.set_xscale('log') ax_power.set_xlim([20, 20000]) ax_power.xaxis.set_major_formatter( ",scimpy/speakermodel.py,"ReplaceText(target='ax_power' @(211,4)->(211,17))","def calc_impedance(plotwidget, ax_power.set_ylabel('SPL (dB 1W1m)', color='b') # ax_phase.set_ylabel('Phase (degrees)') ax_groupdelay.set_ylabel('Group Delay (ms)', color='r') ax_groupdelay.set_xlabel('Frequency (Hz)') ax_power.set_xscale('log') ax_power.set_xlim([20, 20000]) ax_power.xaxis.set_major_formatter(","def calc_impedance(plotwidget, ax_power.set_ylabel('SPL (dB 1W1m)', color='b') # ax_phase.set_ylabel('Phase (degrees)') ax_groupdelay.set_ylabel('Group Delay (ms)', color='r') ax_power.set_xlabel('Frequency (Hz)') ax_power.set_xscale('log') ax_power.set_xlim([20, 20000]) ax_power.xaxis.set_major_formatter(" 1023,https://:@github.com/CS207-Project-Group-9/cs207-FinalProject.git,0a9f635bd112ddcee71faa0560cf7c364f1af02d,"@@ -428,7 +428,7 @@ def create_r(vals): ''' if np.array(vals).ndim == 0: return rAD(vals) - elif np.array(vals).ndim > 2: + elif np.array(vals).ndim >= 2: raise ValueError('Input is at most 2D.') else: ADs = [rAD(val) for val in vals] ",AutoDiff/AutoDiff.py,"ReplaceText(target='>=' @(431,29)->(431,30))","def create_r(vals): ''' if np.array(vals).ndim == 0: return rAD(vals) elif np.array(vals).ndim > 2: raise ValueError('Input is at most 2D.') else: ADs = [rAD(val) for val in vals]","def create_r(vals): ''' if np.array(vals).ndim == 0: return rAD(vals) elif np.array(vals).ndim >= 2: raise ValueError('Input is at most 2D.') else: ADs = [rAD(val) for val in vals]" 1024,https://:@github.com/CS207-Project-Group-9/cs207-FinalProject.git,8157501baf379f85b5f84f4516ac0ba83edfac34,"@@ -428,7 +428,7 @@ def create_r(vals): ''' if np.array(vals).ndim == 0: return rAD(vals) - elif np.array(vals).ndim >= 2: + elif np.array(vals).ndim > 2: raise ValueError('Input is at most 2D.') else: ADs = [rAD(val) for val in vals] ",AutoDiff/AutoDiff.py,"ReplaceText(target='>' @(431,29)->(431,31))","def create_r(vals): ''' if np.array(vals).ndim == 0: return rAD(vals) elif np.array(vals).ndim >= 2: raise ValueError('Input is at most 2D.') else: ADs = [rAD(val) for val in vals]","def create_r(vals): ''' if np.array(vals).ndim == 0: return rAD(vals) elif np.array(vals).ndim > 2: raise ValueError('Input is at most 2D.') else: ADs = [rAD(val) for val in vals]" 1025,https://:@github.com/LucumaTeam/DataQualityHDFS.git,d601249bacb744cadc09cfc9d80e4d5fbec61958,"@@ -49,6 +49,6 @@ class Table: return self._is_load_information def load_dataset(self): - if(self._source is None): + if(self._source is not None): self._data_set = self._source.retrieve_dataset() self._is_load_information = True ",src/main/Core/Table.py,"ReplaceText(target=' is not ' @(52,23)->(52,27))","class Table: return self._is_load_information def load_dataset(self): if(self._source is None): self._data_set = self._source.retrieve_dataset() self._is_load_information = True","class Table: return self._is_load_information def load_dataset(self): if(self._source is not None): self._data_set = self._source.retrieve_dataset() self._is_load_information = True" 1026,https://:@github.com/niklasf/python-asyncdgt.git,836508723a0cfd71fc752538ab59608819184ac6,"@@ -52,7 +52,7 @@ def usage(): def main(port_globs): loop = asyncio.get_event_loop() - dgt = asyncdgt.auto_connect(port_globs, loop) + dgt = asyncdgt.auto_connect(loop, port_globs) @dgt.on(""connected"") def on_connected(port): ",asyncdgt/__main__.py,"ArgSwap(idxs=0<->1 @(55,10)->(55,31))","def usage(): def main(port_globs): loop = asyncio.get_event_loop() dgt = asyncdgt.auto_connect(port_globs, loop) @dgt.on(""connected"") def on_connected(port):","def usage(): def main(port_globs): loop = asyncio.get_event_loop() dgt = asyncdgt.auto_connect(loop, port_globs) @dgt.on(""connected"") def on_connected(port):" 1027,https://:@github.com/hackty/elasticsearch-py.git,18f2ac12310a8dc4e69ee0a262663232fe0fb6ea,"@@ -205,7 +205,7 @@ def reindex(client, source_index, target_index, target_client=None, chunk_size=5 :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search """""" - target_client = client if target_client is None else target_index + target_client = client if target_client is None else target_client docs = scan(client, index=source_index, scroll=scroll) def _change_doc_index(hits, index): ",elasticsearch/helpers.py,"ReplaceText(target='target_client' @(208,57)->(208,69))","def reindex(client, source_index, target_index, target_client=None, chunk_size=5 :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search """""" target_client = client if target_client is None else target_index docs = scan(client, index=source_index, scroll=scroll) def _change_doc_index(hits, index):","def reindex(client, source_index, target_index, target_client=None, chunk_size=5 :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search """""" target_client = client if target_client is None else target_client docs = scan(client, index=source_index, scroll=scroll) def _change_doc_index(hits, index):" 1028,https://:@github.com/ShineyDev/github.py.git,84f7746b34d378990a15a0b7a685e1739b4f9350,"@@ -815,7 +815,7 @@ class Fragment(): fields = data.get(""fields"", list()) for (field) in fields: field = Field.from_dict(field) - fragment.add_field(fields) + fragment.add_field(field) return fragment ",github/query/builder.py,"ReplaceText(target='field' @(818,31)->(818,37))","class Fragment(): fields = data.get(""fields"", list()) for (field) in fields: field = Field.from_dict(field) fragment.add_field(fields) return fragment ","class Fragment(): fields = data.get(""fields"", list()) for (field) in fields: field = Field.from_dict(field) fragment.add_field(field) return fragment " 1029,https://:@github.com/ShineyDev/github.py.git,2dfbdd085dada2ec7bf898180514644b617e08b5,"@@ -47,7 +47,7 @@ class Topic(Node, Type): for (topic) in data: topics.append(cls(topic)) - return topic + return topics @property def name(self) -> str: ",github/objects/topic.py,"ReplaceText(target='topics' @(50,19)->(50,24))","class Topic(Node, Type): for (topic) in data: topics.append(cls(topic)) return topic @property def name(self) -> str:","class Topic(Node, Type): for (topic) in data: topics.append(cls(topic)) return topics @property def name(self) -> str:" 1030,https://:@github.com/openbadges/badgecheck.git,a1d552fc5142f268640c949dabdeba309c741486,"@@ -62,7 +62,7 @@ def detect_input_type(state, task_meta=None, **options): new_actions.append(set_input_type(detected_type)) if detected_type == 'url': new_actions.append(add_task(FETCH_HTTP_NODE, url=id_url)) - new_actions.append(set_validation_subject(input_value)) + new_actions.append(set_validation_subject(id_url)) elif input_is_jws(input_value): detected_type = 'jws' new_actions.append(set_input_type(detected_type)) ",badgecheck/tasks/input.py,"ReplaceText(target='id_url' @(65,54)->(65,65))","def detect_input_type(state, task_meta=None, **options): new_actions.append(set_input_type(detected_type)) if detected_type == 'url': new_actions.append(add_task(FETCH_HTTP_NODE, url=id_url)) new_actions.append(set_validation_subject(input_value)) elif input_is_jws(input_value): detected_type = 'jws' new_actions.append(set_input_type(detected_type))","def detect_input_type(state, task_meta=None, **options): new_actions.append(set_input_type(detected_type)) if detected_type == 'url': new_actions.append(add_task(FETCH_HTTP_NODE, url=id_url)) new_actions.append(set_validation_subject(id_url)) elif input_is_jws(input_value): detected_type = 'jws' new_actions.append(set_input_type(detected_type))" 1031,https://:@github.com/tungminhphan/street_intersection.git,b400ad94e424cae8ef8eec6d898508b2044dde1e,"@@ -78,7 +78,7 @@ def collision_free(object1, object2, car_scale_factor, pedestrian_scale_factor): #the if else statements determines whether the object is pedestrian or not so it can unpack its coordinates and angle orientation, and determines if it should get the vertices of a car or pedestrian #it returns True if no collision has happened, False otherwise object1_vertices, x, y, radius = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor) - object2_vertices, x2, y2, radius2 = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor) + object2_vertices, x2, y2, radius2 = get_bounding_box(object2, car_scale_factor, pedestrian_scale_factor) #takes the distance of the centers and compares it to the sum of radius, if the distance is greater then collision not possible if no_collision_by_radius_check(x, y, radius, x2, y2, radius2): ",traffic_intersection/prepare/collision_check.py,"ReplaceText(target='object2' @(81,57)->(81,64))","def collision_free(object1, object2, car_scale_factor, pedestrian_scale_factor): #the if else statements determines whether the object is pedestrian or not so it can unpack its coordinates and angle orientation, and determines if it should get the vertices of a car or pedestrian #it returns True if no collision has happened, False otherwise object1_vertices, x, y, radius = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor) object2_vertices, x2, y2, radius2 = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor) #takes the distance of the centers and compares it to the sum of radius, if the distance is greater then collision not possible if no_collision_by_radius_check(x, y, radius, x2, y2, radius2):","def collision_free(object1, object2, car_scale_factor, pedestrian_scale_factor): #the if else statements determines whether the object is pedestrian or not so it can unpack its coordinates and angle orientation, and determines if it should get the vertices of a car or pedestrian #it returns True if no collision has happened, False otherwise object1_vertices, x, y, radius = get_bounding_box(object1, car_scale_factor, pedestrian_scale_factor) object2_vertices, x2, y2, radius2 = get_bounding_box(object2, car_scale_factor, pedestrian_scale_factor) #takes the distance of the centers and compares it to the sum of radius, if the distance is greater then collision not possible if no_collision_by_radius_check(x, y, radius, x2, y2, radius2):" 1032,https://:@github.com/aclark4life/Parse2Plone.git,49817c3b81b7def16843ae55b30e6145ab21a9a5,"@@ -676,7 +676,7 @@ class Parse2Plone(object): else: folder = self.create_folder(parent, utils._remove_ext(obj), _replace_types_map) - self.set_title(page, utils._remove_ext(obj)) + self.set_title(folder, utils._remove_ext(obj)) create_spreadsheets(folder, obj, parent_path, import_dir) _COUNT['files'] += 1 commit() ",parse2plone.py,"ReplaceText(target='folder' @(679,43)->(679,47))","class Parse2Plone(object): else: folder = self.create_folder(parent, utils._remove_ext(obj), _replace_types_map) self.set_title(page, utils._remove_ext(obj)) create_spreadsheets(folder, obj, parent_path, import_dir) _COUNT['files'] += 1 commit()","class Parse2Plone(object): else: folder = self.create_folder(parent, utils._remove_ext(obj), _replace_types_map) self.set_title(folder, utils._remove_ext(obj)) create_spreadsheets(folder, obj, parent_path, import_dir) _COUNT['files'] += 1 commit()" 1033,https://:@github.com/jjyr/mmr.py.git,373d5799f4682f4ee94aada12ad1558f9c38ea2b,"@@ -60,7 +60,7 @@ def get_peaks(mmr_size) -> List[int]: poss.append(pos) while height > 0: height, pos = get_right_peak(height, pos, mmr_size) - if height > 0: + if height >= 0: poss.append(pos) return poss ",mmr/mmr.py,"ReplaceText(target='>=' @(63,18)->(63,19))","def get_peaks(mmr_size) -> List[int]: poss.append(pos) while height > 0: height, pos = get_right_peak(height, pos, mmr_size) if height > 0: poss.append(pos) return poss ","def get_peaks(mmr_size) -> List[int]: poss.append(pos) while height > 0: height, pos = get_right_peak(height, pos, mmr_size) if height >= 0: poss.append(pos) return poss " 1034,https://:@github.com/dtkav/datalake-common.git,4093508498f0fabcfa451d333a141d307fdfd615,"@@ -25,7 +25,7 @@ def random_hex(length): def random_interval(): now = datetime.now() start = now - timedelta(days=random.randint(0, 365*3)) - end = start - timedelta(days=random.randint(1, 10)) + end = start + timedelta(days=random.randint(1, 10)) return start.isoformat(), end.isoformat() def random_work_id(): ",datalake_common/tests/conftest.py,"ReplaceText(target='+' @(28,16)->(28,17))","def random_hex(length): def random_interval(): now = datetime.now() start = now - timedelta(days=random.randint(0, 365*3)) end = start - timedelta(days=random.randint(1, 10)) return start.isoformat(), end.isoformat() def random_work_id():","def random_hex(length): def random_interval(): now = datetime.now() start = now - timedelta(days=random.randint(0, 365*3)) end = start + timedelta(days=random.randint(1, 10)) return start.isoformat(), end.isoformat() def random_work_id():" 1035,https://:@github.com/cungnv/scrapex.git,9a2b814ea328f79ee330381423ebeaddb9b11852,"@@ -208,7 +208,7 @@ class DB(object): for log in self._db.logs.find(query): - logs.append(logs) + logs.append(log) return logs ",scrapex/db.py,"ReplaceText(target='log' @(211,15)->(211,19))","class DB(object): for log in self._db.logs.find(query): logs.append(logs) return logs ","class DB(object): for log in self._db.logs.find(query): logs.append(log) return logs " 1036,https://:@github.com/erdc/quest.git,b0b34875f72a05122cd33f5f1b4148dedecdfe89,"@@ -139,7 +139,7 @@ class CoopsPyoos(DataServiceBase): with open(csvFile_path, 'w') as f: f.write(response) - data_files[location][parameter] = filename + data_files[location][parameter] = csvFile_path else: data_files[location][parameter] = None ",dsl/services/coops_pyoos.py,"ReplaceText(target='csvFile_path' @(142,58)->(142,66))","class CoopsPyoos(DataServiceBase): with open(csvFile_path, 'w') as f: f.write(response) data_files[location][parameter] = filename else: data_files[location][parameter] = None ","class CoopsPyoos(DataServiceBase): with open(csvFile_path, 'w') as f: f.write(response) data_files[location][parameter] = csvFile_path else: data_files[location][parameter] = None " 1037,https://:@github.com/erdc/quest.git,016b54452d1170029e57bcbe117e94513a62702c,"@@ -96,7 +96,7 @@ class RstMerge(FilterBase): # update feature geometry metadata with rasterio.open(dst) as f: - geometry = util.bbox2poly(f.bounds.left, f.bounds.right, f.bounds.bottom, f.bounds.top, as_shapely=True) + geometry = util.bbox2poly(f.bounds.left, f.bounds.bottom, f.bounds.right, f.bounds.top, as_shapely=True) update_metadata(feature, quest_metadata={'geometry': geometry.to_wkt()}) # update dataset metadata ",quest/filters/raster/rst_merge.py,"ArgSwap(idxs=1<->2 @(99,23)->(99,37))","class RstMerge(FilterBase): # update feature geometry metadata with rasterio.open(dst) as f: geometry = util.bbox2poly(f.bounds.left, f.bounds.right, f.bounds.bottom, f.bounds.top, as_shapely=True) update_metadata(feature, quest_metadata={'geometry': geometry.to_wkt()}) # update dataset metadata","class RstMerge(FilterBase): # update feature geometry metadata with rasterio.open(dst) as f: geometry = util.bbox2poly(f.bounds.left, f.bounds.bottom, f.bounds.right, f.bounds.top, as_shapely=True) update_metadata(feature, quest_metadata={'geometry': geometry.to_wkt()}) # update dataset metadata" 1038,https://:@github.com/erdc/quest.git,088fce2676801d8ac47d93652d14040296deca36,"@@ -140,7 +140,7 @@ class RstWatershedDelineation(FilterBase): if snap.lower() == 'jenson': stream_threshold_pct = options.get('stream_threshold_pct') stream_threshold_abs = options.get('stream_threshold_abs') - outlet_points = snap_points_jenson(flow_accumulation, proj_points, + proj_points = snap_points_jenson(flow_accumulation, proj_points, stream_threshold_pct=stream_threshold_pct, stream_threshold_abs=stream_threshold_abs) if p.is_latlong(): snapped_points = [src.xy(*point) for point in proj_points] ",quest/filters/raster/rst_watershed.py,"ReplaceText(target='proj_points' @(143,20)->(143,33))","class RstWatershedDelineation(FilterBase): if snap.lower() == 'jenson': stream_threshold_pct = options.get('stream_threshold_pct') stream_threshold_abs = options.get('stream_threshold_abs') outlet_points = snap_points_jenson(flow_accumulation, proj_points, stream_threshold_pct=stream_threshold_pct, stream_threshold_abs=stream_threshold_abs) if p.is_latlong(): snapped_points = [src.xy(*point) for point in proj_points]","class RstWatershedDelineation(FilterBase): if snap.lower() == 'jenson': stream_threshold_pct = options.get('stream_threshold_pct') stream_threshold_abs = options.get('stream_threshold_abs') proj_points = snap_points_jenson(flow_accumulation, proj_points, stream_threshold_pct=stream_threshold_pct, stream_threshold_abs=stream_threshold_abs) if p.is_latlong(): snapped_points = [src.xy(*point) for point in proj_points]" 1039,https://:@github.com/erdc/quest.git,c8e7db0a0b850f8f785e63892e708f2334018d5c,"@@ -180,7 +180,7 @@ def copy(uris, destination_collection): if resource == 'datasets': dataset_metadata = get_metadata(uri)[uri] - collection_path = os.path.join(project_path, feature_metadata['collection']) + collection_path = os.path.join(project_path, dataset_metadata['collection']) feature = dataset_metadata['feature'] ",quest/api/manage.py,"ReplaceText(target='dataset_metadata' @(183,57)->(183,73))","def copy(uris, destination_collection): if resource == 'datasets': dataset_metadata = get_metadata(uri)[uri] collection_path = os.path.join(project_path, feature_metadata['collection']) feature = dataset_metadata['feature'] ","def copy(uris, destination_collection): if resource == 'datasets': dataset_metadata = get_metadata(uri)[uri] collection_path = os.path.join(project_path, dataset_metadata['collection']) feature = dataset_metadata['feature'] " 1040,https://:@github.com/next-security-lab/deep-confusables-cli.git,fe2f6fe46f14778cfcb74852d817d1876d171352,"@@ -92,7 +92,7 @@ def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: - print_diff(d, args.domain) + print_diff(args.domain, d) if write: f.write(d + ""\n"") if (args.check): ",v2d/main.py,"ArgSwap(idxs=0<->1 @(95,16)->(95,26))","def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: print_diff(d, args.domain) if write: f.write(d + ""\n"") if (args.check):","def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: print_diff(args.domain, d) if write: f.write(d + ""\n"") if (args.check):" 1041,https://:@github.com/jkittley/RFM69.git,bcf1e92ee49342ee2ac1d39be7b95671c1ddd6d3,"@@ -143,7 +143,7 @@ class RFM69(): self.writeReg(REG_PACKETCONFIG2, 0) def readReg(self, addr): - return self.spi.xfer([addr | 0x7F, 0]) + return self.spi.xfer([addr & 0x7F, 0]) def writeReg(self, addr, value): self.spi.xfer([addr | 0x80, value]) ",RFM69.py,"ReplaceText(target='&' @(146,31)->(146,32))","class RFM69(): self.writeReg(REG_PACKETCONFIG2, 0) def readReg(self, addr): return self.spi.xfer([addr | 0x7F, 0]) def writeReg(self, addr, value): self.spi.xfer([addr | 0x80, value])","class RFM69(): self.writeReg(REG_PACKETCONFIG2, 0) def readReg(self, addr): return self.spi.xfer([addr & 0x7F, 0]) def writeReg(self, addr, value): self.spi.xfer([addr | 0x80, value])" 1042,https://:@github.com/schuderer/mllaunchpad.git,93c87d9c160b3270319e6b344f1d1831d4323014,"@@ -50,7 +50,7 @@ def train_model(complete_conf): logger.warning(""Model's class is not a subclass of ModelInterface: %s"", model) model_store = resource.ModelStore(complete_conf) - model_store.dump_trained_model(model_conf, model, metrics) + model_store.dump_trained_model(complete_conf, model, metrics) logger.info(""Created and stored trained model %s, version %s, metrics %s"", model_conf['name'], model_conf['version'], metrics) ",launchpad/train.py,"ReplaceText(target='complete_conf' @(53,35)->(53,45))","def train_model(complete_conf): logger.warning(""Model's class is not a subclass of ModelInterface: %s"", model) model_store = resource.ModelStore(complete_conf) model_store.dump_trained_model(model_conf, model, metrics) logger.info(""Created and stored trained model %s, version %s, metrics %s"", model_conf['name'], model_conf['version'], metrics) ","def train_model(complete_conf): logger.warning(""Model's class is not a subclass of ModelInterface: %s"", model) model_store = resource.ModelStore(complete_conf) model_store.dump_trained_model(complete_conf, model, metrics) logger.info(""Created and stored trained model %s, version %s, metrics %s"", model_conf['name'], model_conf['version'], metrics) " 1043,https://:@github.com/daanvdk/is_valid.git,0c78bad8195b8c4b702b368e9d13d1ccaf573382,"@@ -158,4 +158,4 @@ def is_set_of(predicate): return (True, explanation) if valid else (False, { elems[i]: value for i, value in explanation.items() }) - return is_if(is_set, predicate, else_valid=False) + return is_if(is_set, is_valid, else_valid=False) ",is_valid/structure_predicates.py,"ReplaceText(target='is_valid' @(161,25)->(161,34))","def is_set_of(predicate): return (True, explanation) if valid else (False, { elems[i]: value for i, value in explanation.items() }) return is_if(is_set, predicate, else_valid=False)","def is_set_of(predicate): return (True, explanation) if valid else (False, { elems[i]: value for i, value in explanation.items() }) return is_if(is_set, is_valid, else_valid=False)" 1044,https://:@github.com/riptano/cdm.git,cb0de67c9a5418a052d77575a0c81b9159e0089a,"@@ -59,7 +59,7 @@ class Importer(object): for _ in pool.imap_unordered(save, self.iter()): i += 1 if i % 10 == 0: - pool.update(i) + p.update(i) ",cdm/importer.py,"ReplaceText(target='p' @(62,20)->(62,24))","class Importer(object): for _ in pool.imap_unordered(save, self.iter()): i += 1 if i % 10 == 0: pool.update(i) ","class Importer(object): for _ in pool.imap_unordered(save, self.iter()): i += 1 if i % 10 == 0: p.update(i) " 1045,https://:@github.com/moggers87/exhibition.git,18f720dd34997c6da7235f2ea1344e09a670f308,"@@ -95,7 +95,7 @@ class Config: if self.parent is not None: for k in self.parent.keys(): - if k in _keys_set: + if k not in _keys_set: _keys_set.add(k) yield k ",exhibition/main.py,"ReplaceText(target=' not in ' @(98,20)->(98,24))","class Config: if self.parent is not None: for k in self.parent.keys(): if k in _keys_set: _keys_set.add(k) yield k ","class Config: if self.parent is not None: for k in self.parent.keys(): if k not in _keys_set: _keys_set.add(k) yield k " 1046,https://:@github.com/moggers87/exhibition.git,49a8eb6842d2eedecd239f35c651e4afde69cb87,"@@ -486,7 +486,7 @@ def serve(settings): path = pathlib.Path(settings[""deploy_path""], path) - if not (path.exists() and path.suffix): + if not (path.exists() or path.suffix): for ext in Node._strip_exts: new_path = path.with_suffix(ext) if new_path.exists(): ",exhibition/main.py,"ReplaceText(target='or' @(489,34)->(489,37))","def serve(settings): path = pathlib.Path(settings[""deploy_path""], path) if not (path.exists() and path.suffix): for ext in Node._strip_exts: new_path = path.with_suffix(ext) if new_path.exists():","def serve(settings): path = pathlib.Path(settings[""deploy_path""], path) if not (path.exists() or path.suffix): for ext in Node._strip_exts: new_path = path.with_suffix(ext) if new_path.exists():" 1047,https://:@github.com/civrev/rlrisk.git,fb9ba4a28cd8dced235e9cb97b861130baa351a9,"@@ -575,7 +575,7 @@ class Risk: t_count=3 #now add to amount recruited - recruit+=t_count + recruit=t_count #calculate for continents for continent in self.continents: ",rlrisk/environment/risk.py,"ReplaceText(target='=' @(578,15)->(578,17))","class Risk: t_count=3 #now add to amount recruited recruit+=t_count #calculate for continents for continent in self.continents:","class Risk: t_count=3 #now add to amount recruited recruit=t_count #calculate for continents for continent in self.continents:" 1048,https://:@gitlab.com/philn/fb2feed.git,9e6dc0b80947383a54e0fe99c656d419a4ede2c9,"@@ -126,7 +126,7 @@ async def page_to_atom(browser, page_id, root_dir, media_dir, media_url_slug): fe = fg.add_entry() fe.author(name=page_id, email=""%s.facebook.no-reply@fb2feed.org"" % page_id) - fe.id(post_url) + fe.id(post_id) fe.link(href=post_url, rel=""alternate"") fe.published(timestamp) fe.updated(timestamp) ",fb2feed.py,"ReplaceText(target='post_id' @(129,18)->(129,26))","async def page_to_atom(browser, page_id, root_dir, media_dir, media_url_slug): fe = fg.add_entry() fe.author(name=page_id, email=""%s.facebook.no-reply@fb2feed.org"" % page_id) fe.id(post_url) fe.link(href=post_url, rel=""alternate"") fe.published(timestamp) fe.updated(timestamp)","async def page_to_atom(browser, page_id, root_dir, media_dir, media_url_slug): fe = fg.add_entry() fe.author(name=page_id, email=""%s.facebook.no-reply@fb2feed.org"" % page_id) fe.id(post_id) fe.link(href=post_url, rel=""alternate"") fe.published(timestamp) fe.updated(timestamp)" 1049,https://:@github.com/sputt/req-compile.git,f76edf2e9821dcef6d7bc851282731821e569d81,"@@ -111,7 +111,7 @@ class DistributionCollection(object): self.nodes[key] = node # If a new extra is being supplied, update the metadata - if reason and node.metadata and reason.extras and set(reason.extras) & node.extras: + if reason and node.metadata and reason.extras and set(reason.extras) - node.extras: metadata_to_apply = node.metadata if source is not None and source.key in self.nodes: ",req_compile/dists.py,"ReplaceText(target='-' @(114,77)->(114,78))","class DistributionCollection(object): self.nodes[key] = node # If a new extra is being supplied, update the metadata if reason and node.metadata and reason.extras and set(reason.extras) & node.extras: metadata_to_apply = node.metadata if source is not None and source.key in self.nodes:","class DistributionCollection(object): self.nodes[key] = node # If a new extra is being supplied, update the metadata if reason and node.metadata and reason.extras and set(reason.extras) - node.extras: metadata_to_apply = node.metadata if source is not None and source.key in self.nodes:" 1050,https://:@github.com/inovonics/cloud-datastore.git,72b1cb9760973b300b5ebf3bad1d6836b15d908a,"@@ -113,7 +113,7 @@ class InoObjectBase: def _validate_oid(self): # Verify the oid is a UUID type variable - if isinstance(getattr(self, 'oid'), uuid.UUID): + if not isinstance(getattr(self, 'oid'), uuid.UUID): return ""oid not of type uuid.UUID but type {}, value {}"".format(type(getattr(self, 'oid')), getattr(self, 'oid')) return None ",inovonics/cloud/datastore/bases.py,"ReplaceText(target='not ' @(116,11)->(116,11))","class InoObjectBase: def _validate_oid(self): # Verify the oid is a UUID type variable if isinstance(getattr(self, 'oid'), uuid.UUID): return ""oid not of type uuid.UUID but type {}, value {}"".format(type(getattr(self, 'oid')), getattr(self, 'oid')) return None ","class InoObjectBase: def _validate_oid(self): # Verify the oid is a UUID type variable if not isinstance(getattr(self, 'oid'), uuid.UUID): return ""oid not of type uuid.UUID but type {}, value {}"".format(type(getattr(self, 'oid')), getattr(self, 'oid')) return None " 1051,https://:@github.com/shawnbrown/squint.git,9912b140bc25d6d8679819ee8c4fd037a0b01b54,"@@ -116,7 +116,7 @@ class Result(Iterator): value = __next__(self) finally: self._started_iteration = True - bound_method = __next__.__get__(self.__class__, self) + bound_method = __next__.__get__(self, self.__class__) self.__next__ = bound_method # <- Replace __next__ method! return value ",squint/result.py,"ArgSwap(idxs=0<->1 @(119,27)->(119,43))","class Result(Iterator): value = __next__(self) finally: self._started_iteration = True bound_method = __next__.__get__(self.__class__, self) self.__next__ = bound_method # <- Replace __next__ method! return value ","class Result(Iterator): value = __next__(self) finally: self._started_iteration = True bound_method = __next__.__get__(self, self.__class__) self.__next__ = bound_method # <- Replace __next__ method! return value " 1052,https://:@github.com/kav2k/singularity-pipeline.git,4eacf7dfa1ddcdd7feec8ff928d8cac3ee170c72,"@@ -136,7 +136,7 @@ class Pipeline(): self.eprint.bold(""# Running pipeline...\n"") if not self.dry_run: - if os.path.isfile(self.imagefile): + if not os.path.isfile(self.imagefile): raise RuntimeError(""Image {} does not exist"".format(self.imagefile)) for spec in self.binds: ",singularity_pipeline/pipeline.py,"ReplaceText(target='not ' @(139,15)->(139,15))","class Pipeline(): self.eprint.bold(""# Running pipeline...\n"") if not self.dry_run: if os.path.isfile(self.imagefile): raise RuntimeError(""Image {} does not exist"".format(self.imagefile)) for spec in self.binds:","class Pipeline(): self.eprint.bold(""# Running pipeline...\n"") if not self.dry_run: if not os.path.isfile(self.imagefile): raise RuntimeError(""Image {} does not exist"".format(self.imagefile)) for spec in self.binds:" 1053,https://:@github.com/mvinii94/aws-lambda-log-collector.git,682850f282b70aa18663699c7e5e32bc4f6a8be1,"@@ -25,7 +25,7 @@ def cli(function_name, profile, region, output, start_time, end_time, pattern, l epoch_start_time = parse_time(start_time) epoch_end_time = parse_time(end_time) - if epoch_start_time < epoch_end_time: + if epoch_start_time > epoch_end_time: raise Exception(INVALID_DATES) available_profiles = get_profiles() ",collector/cli.py,"ReplaceText(target='>' @(28,25)->(28,26))","def cli(function_name, profile, region, output, start_time, end_time, pattern, l epoch_start_time = parse_time(start_time) epoch_end_time = parse_time(end_time) if epoch_start_time < epoch_end_time: raise Exception(INVALID_DATES) available_profiles = get_profiles()","def cli(function_name, profile, region, output, start_time, end_time, pattern, l epoch_start_time = parse_time(start_time) epoch_end_time = parse_time(end_time) if epoch_start_time > epoch_end_time: raise Exception(INVALID_DATES) available_profiles = get_profiles()" 1054,https://:@github.com/peteshadbolt/abp.git,9d859145d8a6ec45a7831235bfc05f45932709a7,"@@ -58,7 +58,7 @@ class CircuitModel(object): def act_cz(self, control, target): """""" Act a CU somewhere """""" control = 1 << control - target = 1 << control + target = 1 << target for i in xrange(self.d): if (i & control) and (i & target): self.state[i, 0] *= -1 ",abp/qi.py,"ReplaceText(target='target' @(61,22)->(61,29))","class CircuitModel(object): def act_cz(self, control, target): """""" Act a CU somewhere """""" control = 1 << control target = 1 << control for i in xrange(self.d): if (i & control) and (i & target): self.state[i, 0] *= -1","class CircuitModel(object): def act_cz(self, control, target): """""" Act a CU somewhere """""" control = 1 << control target = 1 << target for i in xrange(self.d): if (i & control) and (i & target): self.state[i, 0] *= -1" 1055,https://:@github.com/peteshadbolt/abp.git,1b787c47377d73a0519f60cc77657b2b09577b49,"@@ -134,7 +134,7 @@ class GraphState(object): ci = self.get_connection_info(a, b) if ci[""non1""] and not clifford.is_diagonal(self.node[a][""vop""]): debug(""cphase: left one needs treatment again -> putting it to Id"") - self.remove_vop(b, a) + self.remove_vop(a, b) self.cz_with_table(a, b) ",abp/graphstate.py,"ArgSwap(idxs=0<->1 @(137,12)->(137,27))","class GraphState(object): ci = self.get_connection_info(a, b) if ci[""non1""] and not clifford.is_diagonal(self.node[a][""vop""]): debug(""cphase: left one needs treatment again -> putting it to Id"") self.remove_vop(b, a) self.cz_with_table(a, b) ","class GraphState(object): ci = self.get_connection_info(a, b) if ci[""non1""] and not clifford.is_diagonal(self.node[a][""vop""]): debug(""cphase: left one needs treatment again -> putting it to Id"") self.remove_vop(a, b) self.cz_with_table(a, b) " 1056,https://:@github.com/jsbroks/imantics.git,a9919325c1628d65cc0baf150599e3d04d6cf1be,"@@ -43,7 +43,7 @@ class Annotation(Semantic): :param polygons: bbox to create annotation from :type polygons: :class:`BBox`, list, tuple """""" - return cls(image=image, category=image, bbox=bbox) + return cls(image=image, category=category, bbox=bbox) @classmethod def from_polygons(cls, polygons, image=None, category=None): ",imantics/annotation.py,"ReplaceText(target='category' @(46,41)->(46,46))","class Annotation(Semantic): :param polygons: bbox to create annotation from :type polygons: :class:`BBox`, list, tuple """""" return cls(image=image, category=image, bbox=bbox) @classmethod def from_polygons(cls, polygons, image=None, category=None):","class Annotation(Semantic): :param polygons: bbox to create annotation from :type polygons: :class:`BBox`, list, tuple """""" return cls(image=image, category=category, bbox=bbox) @classmethod def from_polygons(cls, polygons, image=None, category=None):" 1057,https://:@github.com/278mt/cotohappy.git,09e71e8a654b93db750a1e5f55b1c063b3070470,"@@ -26,7 +26,7 @@ class Reshape(object): Reshape(mode='links', data=link) for link in chunk_info['links'] ] - self.predicate = chunk_info['predicate'] if 'predicate' in data else [] + self.predicate = chunk_info['predicate'] if 'predicate' in chunk_info else [] self.tokens = [ Reshape(mode='tokens', data=token) ",cotohappy/reshape.py,"ReplaceText(target='chunk_info' @(29,72)->(29,76))","class Reshape(object): Reshape(mode='links', data=link) for link in chunk_info['links'] ] self.predicate = chunk_info['predicate'] if 'predicate' in data else [] self.tokens = [ Reshape(mode='tokens', data=token)","class Reshape(object): Reshape(mode='links', data=link) for link in chunk_info['links'] ] self.predicate = chunk_info['predicate'] if 'predicate' in chunk_info else [] self.tokens = [ Reshape(mode='tokens', data=token)" 1058,https://:@github.com/AntoineToubhans/MongoTs.git,79fa91c7f9f3ecd0e0d22ca01a67a9efc84a9611,"@@ -82,4 +82,4 @@ class MongoTSCollection(): raw_data = list(self._collection.aggregate(pipeline)) - return build_dataframe(raw_data, aggregateby, groupby) + return build_dataframe(raw_data, parsed_aggregateby, groupby) ",mongots/collection.py,"ReplaceText(target='parsed_aggregateby' @(85,41)->(85,52))","class MongoTSCollection(): raw_data = list(self._collection.aggregate(pipeline)) return build_dataframe(raw_data, aggregateby, groupby)","class MongoTSCollection(): raw_data = list(self._collection.aggregate(pipeline)) return build_dataframe(raw_data, parsed_aggregateby, groupby)" 1059,https://:@github.com/thenewguy/django-randomfields.git,983d6a2940e17a42326137b6592e0ed3ea3de8bd,"@@ -49,7 +49,7 @@ class RandomStringFieldBase(RandomFieldBase): 'min_length': self.min_length, } defaults.update(kwargs) - return super(RandomStringFieldBase, self).formfield(**kwargs) + return super(RandomStringFieldBase, self).formfield(**defaults) class RandomCharField(RandomStringFieldBase, models.CharField): def check(self, **kwargs): ",randomfields/models/fields/string.py,"ReplaceText(target='defaults' @(52,62)->(52,68))","class RandomStringFieldBase(RandomFieldBase): 'min_length': self.min_length, } defaults.update(kwargs) return super(RandomStringFieldBase, self).formfield(**kwargs) class RandomCharField(RandomStringFieldBase, models.CharField): def check(self, **kwargs):","class RandomStringFieldBase(RandomFieldBase): 'min_length': self.min_length, } defaults.update(kwargs) return super(RandomStringFieldBase, self).formfield(**defaults) class RandomCharField(RandomStringFieldBase, models.CharField): def check(self, **kwargs):" 1060,https://:@github.com/mathcamp/devbox.git,b014314770fe44557b57c7d9d024959be9fb4f4a,"@@ -175,7 +175,7 @@ def git_describe(describe_args): if proc.returncode != 0: print(""Error parsing git revision! Make sure that you have tagged a "" ""commit, and that the tag matches the 'tag_match' argument"") - print(""Git output: "" + output) + print(""Git output: "" + description) return { 'tag': 'unknown', 'description': 'unknown', ",version_helper.py,"ReplaceText(target='description' @(178,31)->(178,37))","def git_describe(describe_args): if proc.returncode != 0: print(""Error parsing git revision! Make sure that you have tagged a "" ""commit, and that the tag matches the 'tag_match' argument"") print(""Git output: "" + output) return { 'tag': 'unknown', 'description': 'unknown',","def git_describe(describe_args): if proc.returncode != 0: print(""Error parsing git revision! Make sure that you have tagged a "" ""commit, and that the tag matches the 'tag_match' argument"") print(""Git output: "" + description) return { 'tag': 'unknown', 'description': 'unknown'," 1061,https://:@github.com/mathcamp/devbox.git,54a298fc2018e1b4328a68c08740f5bd49f0864a,"@@ -213,7 +213,7 @@ def unbox(repo, dest=None, no_deps=False, *parents): LOG.info(""Installing into %s"", install_dir) dest_conf = load_conf(install_dir) venv = dest_conf.get('env') - with pushd(dest): + with pushd(install_dir): if venv is not None: venv['path'] = os.path.abspath(venv['path']) run_commands(conf.get('post_setup', []), venv) ",devbox/unbox.py,"ReplaceText(target='install_dir' @(216,19)->(216,23))","def unbox(repo, dest=None, no_deps=False, *parents): LOG.info(""Installing into %s"", install_dir) dest_conf = load_conf(install_dir) venv = dest_conf.get('env') with pushd(dest): if venv is not None: venv['path'] = os.path.abspath(venv['path']) run_commands(conf.get('post_setup', []), venv)","def unbox(repo, dest=None, no_deps=False, *parents): LOG.info(""Installing into %s"", install_dir) dest_conf = load_conf(install_dir) venv = dest_conf.get('env') with pushd(install_dir): if venv is not None: venv['path'] = os.path.abspath(venv['path']) run_commands(conf.get('post_setup', []), venv)" 1062,https://:@github.com/ccxtechnologies/adbus.git,58d6866e77afaac02195d40348e207d9258b4fc2,"@@ -177,7 +177,7 @@ class Method: self.name = x.attrib['name'] if x.tag == 'arg': if x.attrib['direction'] == 'out': - self.return_signature = x.attrib['type'] + self.return_signature += x.attrib['type'] elif x.attrib['direction'] == 'in': self.arg_signatures.append(x.attrib['type']) ",adbus/client/proxy.py,"ReplaceText(target='+=' @(180,42)->(180,43))","class Method: self.name = x.attrib['name'] if x.tag == 'arg': if x.attrib['direction'] == 'out': self.return_signature = x.attrib['type'] elif x.attrib['direction'] == 'in': self.arg_signatures.append(x.attrib['type']) ","class Method: self.name = x.attrib['name'] if x.tag == 'arg': if x.attrib['direction'] == 'out': self.return_signature += x.attrib['type'] elif x.attrib['direction'] == 'in': self.arg_signatures.append(x.attrib['type']) " 1063,https://:@github.com/balazstothofficial/models.git,d0b6a34bb0dbd981e3785661f04f04cde9c4222b,"@@ -107,7 +107,7 @@ def run_mnist_eager(flags_obj): # Automatically determine device and data_format (device, data_format) = ('/gpu:0', 'channels_first') - if flags_obj.no_gpu or tf.test.is_gpu_available(): + if flags_obj.no_gpu or not tf.test.is_gpu_available(): (device, data_format) = ('/cpu:0', 'channels_last') # If data_format is defined in FLAGS, overwrite automatically set value. if flags_obj.data_format is not None: ",official/mnist/mnist_eager.py,"ReplaceText(target='not ' @(110,25)->(110,25))","def run_mnist_eager(flags_obj): # Automatically determine device and data_format (device, data_format) = ('/gpu:0', 'channels_first') if flags_obj.no_gpu or tf.test.is_gpu_available(): (device, data_format) = ('/cpu:0', 'channels_last') # If data_format is defined in FLAGS, overwrite automatically set value. if flags_obj.data_format is not None:","def run_mnist_eager(flags_obj): # Automatically determine device and data_format (device, data_format) = ('/gpu:0', 'channels_first') if flags_obj.no_gpu or not tf.test.is_gpu_available(): (device, data_format) = ('/cpu:0', 'channels_last') # If data_format is defined in FLAGS, overwrite automatically set value. if flags_obj.data_format is not None:" 1064,https://:@github.com/balazstothofficial/models.git,e9dbef6be831bac9c5cbacf6b3b13e4557e4777c,"@@ -353,7 +353,7 @@ class Worker(threading.Thread): policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions, logits=logits) policy_loss *= tf.stop_gradient(advantage) - policy_loss = 0.01 * entropy + policy_loss -= 0.01 * entropy total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss)) return total_loss ",research/a3c_blogpost/a3c_cartpole.py,"ReplaceText(target='-=' @(356,16)->(356,17))","class Worker(threading.Thread): policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions, logits=logits) policy_loss *= tf.stop_gradient(advantage) policy_loss = 0.01 * entropy total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss)) return total_loss ","class Worker(threading.Thread): policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions, logits=logits) policy_loss *= tf.stop_gradient(advantage) policy_loss -= 0.01 * entropy total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss)) return total_loss " 1065,https://:@github.com/idigbio/idq.git,c3c53aa2eab9d4a958f5ac338c4daac8fae2d192,"@@ -31,7 +31,7 @@ def create_harness(w): for f in w.required_fields: f_name = f.replace("":"",""_"") - setattr(SingleForm,f_name,StringField(f_name)) + setattr(SingleForm,f_name,StringField(f)) setattr(SingleForm,""submit"",SubmitField(u'Process')) ",idq/harness/__init__.py,"ReplaceText(target='f' @(34,46)->(34,52))","def create_harness(w): for f in w.required_fields: f_name = f.replace("":"",""_"") setattr(SingleForm,f_name,StringField(f_name)) setattr(SingleForm,""submit"",SubmitField(u'Process')) ","def create_harness(w): for f in w.required_fields: f_name = f.replace("":"",""_"") setattr(SingleForm,f_name,StringField(f)) setattr(SingleForm,""submit"",SubmitField(u'Process')) " 1066,https://:@github.com/iMerica/dj-models.git,659ab9846e81d95bb75dbb3c00147324bf0d6541,"@@ -22,7 +22,7 @@ def login(request): else: errors = {} response = HttpResponse() - response.session.set_test_cookie() + request.session.set_test_cookie() t = template_loader.get_template('registration/login') c = Context(request, { 'form': formfields.FormWrapper(manipulator, request.POST, errors), ",django/views/auth/login.py,"ReplaceText(target='request' @(25,4)->(25,12))","def login(request): else: errors = {} response = HttpResponse() response.session.set_test_cookie() t = template_loader.get_template('registration/login') c = Context(request, { 'form': formfields.FormWrapper(manipulator, request.POST, errors),","def login(request): else: errors = {} response = HttpResponse() request.session.set_test_cookie() t = template_loader.get_template('registration/login') c = Context(request, { 'form': formfields.FormWrapper(manipulator, request.POST, errors)," 1067,https://:@github.com/iMerica/dj-models.git,a97648a7e03fb95b09e888e5d59d82d57fb289b7,"@@ -105,7 +105,7 @@ class DecoratorsTest(TestCase): """""" def my_view(request): return ""response"" - my_view_cached = cache_page(123, my_view) + my_view_cached = cache_page(my_view, 123) self.assertEqual(my_view_cached(HttpRequest()), ""response"") class MethodDecoratorAdapterTests(TestCase): ",tests/regressiontests/decorators/tests.py,"ArgSwap(idxs=0<->1 @(108,25)->(108,35))","class DecoratorsTest(TestCase): """""" def my_view(request): return ""response"" my_view_cached = cache_page(123, my_view) self.assertEqual(my_view_cached(HttpRequest()), ""response"") class MethodDecoratorAdapterTests(TestCase):","class DecoratorsTest(TestCase): """""" def my_view(request): return ""response"" my_view_cached = cache_page(my_view, 123) self.assertEqual(my_view_cached(HttpRequest()), ""response"") class MethodDecoratorAdapterTests(TestCase):" 1068,https://:@github.com/iMerica/dj-models.git,7db68a888b633f2b65f753d50f21463b65a01edf,"@@ -399,7 +399,7 @@ def language(parser, token): """""" bits = token.split_contents() - if len(bits) < 2: + if len(bits) != 2: raise TemplateSyntaxError(""'%s' takes one argument (language)"" % bits[0]) language = parser.compile_filter(bits[1]) nodelist = parser.parse(('endlanguage',)) ",django/templatetags/i18n.py,"ReplaceText(target='!=' @(402,17)->(402,18))","def language(parser, token): """""" bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError(""'%s' takes one argument (language)"" % bits[0]) language = parser.compile_filter(bits[1]) nodelist = parser.parse(('endlanguage',))","def language(parser, token): """""" bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError(""'%s' takes one argument (language)"" % bits[0]) language = parser.compile_filter(bits[1]) nodelist = parser.parse(('endlanguage',))" 1069,https://:@github.com/iMerica/dj-models.git,b2050ff546da4164f90a795e55d7d8c55981783d,"@@ -169,7 +169,7 @@ class SQLCompiler(object): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] - if table in only_load and col not in only_load[table]: + if table in only_load and column not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases: ",django/db/models/sql/compiler.py,"ReplaceText(target='column' @(172,46)->(172,49))","class SQLCompiler(object): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and col not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases:","class SQLCompiler(object): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and column not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases:" 1070,https://:@github.com/iMerica/dj-models.git,cfba2460370a6d1808b78e2ba0709ea5c8b7e773,"@@ -42,7 +42,7 @@ def check_settings(base_url=None): Checks if the staticfiles settings have sane values. """""" - if base_url is not None: + if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured( ",django/contrib/staticfiles/utils.py,"ReplaceText(target=' is ' @(45,15)->(45,23))","def check_settings(base_url=None): Checks if the staticfiles settings have sane values. """""" if base_url is not None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured(","def check_settings(base_url=None): Checks if the staticfiles settings have sane values. """""" if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured(" 1071,https://:@github.com/iMerica/dj-models.git,5f2be4ecbb5df3760f4c6e49170478719d3026d7,"@@ -824,7 +824,7 @@ class SQLInsertCompiler(SQLCompiler): for val in values ] if self.return_id and self.connection.features.can_return_id_from_insert: - params = values[0] + params = params[0] col = ""%s.%s"" % (qn(opts.db_table), qn(opts.pk.column)) result.append(""VALUES (%s)"" % "", "".join(placeholders[0])) r_fmt, r_params = self.connection.ops.return_insert_id() ",django/db/models/sql/compiler.py,"ReplaceText(target='params' @(827,21)->(827,27))","class SQLInsertCompiler(SQLCompiler): for val in values ] if self.return_id and self.connection.features.can_return_id_from_insert: params = values[0] col = ""%s.%s"" % (qn(opts.db_table), qn(opts.pk.column)) result.append(""VALUES (%s)"" % "", "".join(placeholders[0])) r_fmt, r_params = self.connection.ops.return_insert_id()","class SQLInsertCompiler(SQLCompiler): for val in values ] if self.return_id and self.connection.features.can_return_id_from_insert: params = params[0] col = ""%s.%s"" % (qn(opts.db_table), qn(opts.pk.column)) result.append(""VALUES (%s)"" % "", "".join(placeholders[0])) r_fmt, r_params = self.connection.ops.return_insert_id()" 1072,https://:@github.com/iMerica/dj-models.git,d72d5ce8274992ce01e39f866a7a250bc459eefe,"@@ -37,7 +37,7 @@ class GeoSQLCompiler(compiler.SQLCompiler): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] - if table in only_load and col not in only_load[table]: + if table in only_load and column not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases: ",django/contrib/gis/db/models/sql/compiler.py,"ReplaceText(target='column' @(40,46)->(40,49))","class GeoSQLCompiler(compiler.SQLCompiler): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and col not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases:","class GeoSQLCompiler(compiler.SQLCompiler): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and column not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases:" 1073,https://:@github.com/iMerica/dj-models.git,6ecbac21a9017a53fe18ac81c9c1d2f28185a292,"@@ -111,5 +111,5 @@ class OSMWidget(BaseGeometryWidget): return 900913 def render(self, name, value, attrs=None): - return super(self, OSMWidget).render(name, value, + return super(OSMWidget, self).render(name, value, {'default_lon': self.default_lon, 'default_lat': self.default_lat}) ",django/contrib/gis/forms/widgets.py,"ArgSwap(idxs=0<->1 @(114,15)->(114,20))","class OSMWidget(BaseGeometryWidget): return 900913 def render(self, name, value, attrs=None): return super(self, OSMWidget).render(name, value, {'default_lon': self.default_lon, 'default_lat': self.default_lat})","class OSMWidget(BaseGeometryWidget): return 900913 def render(self, name, value, attrs=None): return super(OSMWidget, self).render(name, value, {'default_lon': self.default_lon, 'default_lat': self.default_lat})" 1074,https://:@github.com/iMerica/dj-models.git,86c248aa646183ef4a1cb407bb3e4cb597272f63,"@@ -575,7 +575,7 @@ class SQLCompiler(object): for order, order_params in ordering_group_by: # Even if we have seen the same SQL string, it might have # different params, so, we add same SQL in ""has params"" case. - if order not in seen or params: + if order not in seen or order_params: result.append(order) params.extend(order_params) seen.add(order) ",django/db/models/sql/compiler.py,"ReplaceText(target='order_params' @(578,44)->(578,50))","class SQLCompiler(object): for order, order_params in ordering_group_by: # Even if we have seen the same SQL string, it might have # different params, so, we add same SQL in ""has params"" case. if order not in seen or params: result.append(order) params.extend(order_params) seen.add(order)","class SQLCompiler(object): for order, order_params in ordering_group_by: # Even if we have seen the same SQL string, it might have # different params, so, we add same SQL in ""has params"" case. if order not in seen or order_params: result.append(order) params.extend(order_params) seen.add(order)" 1075,https://:@github.com/iMerica/dj-models.git,fddb0131d37109c809ec391e1a134ef1d9e442a7,"@@ -57,7 +57,7 @@ def check_password(password, encoded, setter=None, preferred='default'): must_update = hasher.algorithm != preferred.algorithm if not must_update: - must_update = hasher.must_update(encoded) + must_update = preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) if setter and is_correct and must_update: setter(password) ",django/contrib/auth/hashers.py,"ReplaceText(target='preferred' @(60,22)->(60,28))","def check_password(password, encoded, setter=None, preferred='default'): must_update = hasher.algorithm != preferred.algorithm if not must_update: must_update = hasher.must_update(encoded) is_correct = hasher.verify(password, encoded) if setter and is_correct and must_update: setter(password)","def check_password(password, encoded, setter=None, preferred='default'): must_update = hasher.algorithm != preferred.algorithm if not must_update: must_update = preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) if setter and is_correct and must_update: setter(password)" 1076,https://:@github.com/iMerica/dj-models.git,e8223b889aab3b5ac0c2312eb9ee2307ea635c97,"@@ -228,7 +228,7 @@ class GenericRelationTests(TestCase): # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) - self.assertEqual(qs[0].links__sum, l.id) + self.assertEqual(qs[0].links__sum, hs1.id) l.delete() # Now if we don't have proper left join, we will not produce any # results at all here. ",tests/generic_relations_regress/tests.py,"ReplaceText(target='hs1' @(231,43)->(231,44))","class GenericRelationTests(TestCase): # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].links__sum, l.id) l.delete() # Now if we don't have proper left join, we will not produce any # results at all here.","class GenericRelationTests(TestCase): # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].links__sum, hs1.id) l.delete() # Now if we don't have proper left join, we will not produce any # results at all here." 1077,https://:@github.com/iMerica/dj-models.git,3074c5b19e2da5f7a5359c3cf3c5308eb194cdf9,"@@ -112,7 +112,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): - super(cls, ClassDecoratedTestCase).setUpClass() + super(ClassDecoratedTestCase, cls).setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self): ",tests/settings_tests/tests.py,"ArgSwap(idxs=0<->1 @(115,8)->(115,13))","class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): super(cls, ClassDecoratedTestCase).setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self):","class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): super(ClassDecoratedTestCase, cls).setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self):" 1078,https://:@github.com/iMerica/dj-models.git,c2b4967e76fd671e6199e4dd54d2a2c1f096b8eb,"@@ -23,7 +23,7 @@ def import_string(dotted_path): return getattr(module, class_name) except AttributeError: msg = 'Module ""%s"" does not define a ""%s"" attribute/class' % ( - dotted_path, class_name) + module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) ",django/utils/module_loading.py,"ReplaceText(target='module_path' @(26,12)->(26,23))","def import_string(dotted_path): return getattr(module, class_name) except AttributeError: msg = 'Module ""%s"" does not define a ""%s"" attribute/class' % ( dotted_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) ","def import_string(dotted_path): return getattr(module, class_name) except AttributeError: msg = 'Module ""%s"" does not define a ""%s"" attribute/class' % ( module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) " 1079,https://:@github.com/iMerica/dj-models.git,a3fffdca2472885a99e1ea9159a685753cd45738,"@@ -99,7 +99,7 @@ class SessionStore(SessionBase): # Remove expired sessions. expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data)) - if expiry_age < 0: + if expiry_age <= 0: session_data = {} self.delete() self.create() ",django/contrib/sessions/backends/file.py,"ReplaceText(target='<=' @(102,30)->(102,31))","class SessionStore(SessionBase): # Remove expired sessions. expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data)) if expiry_age < 0: session_data = {} self.delete() self.create()","class SessionStore(SessionBase): # Remove expired sessions. expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data)) if expiry_age <= 0: session_data = {} self.delete() self.create()" 1080,https://:@github.com/iMerica/dj-models.git,abcdb237bb313d116ce2ac8e90f79f61429afc70,"@@ -31,7 +31,7 @@ class DatabaseCreation(BaseDatabaseCreation): try: if verbosity >= 1: print(""Destroying old test database for alias %s..."" % ( - self._get_database_display_str(target_database_name, verbosity), + self._get_database_display_str(verbosity, target_database_name), )) cursor.execute(""DROP DATABASE %s"" % qn(target_database_name)) cursor.execute(""CREATE DATABASE %s"" % qn(target_database_name)) ",django/db/backends/mysql/creation.py,"ArgSwap(idxs=0<->1 @(34,28)->(34,58))","class DatabaseCreation(BaseDatabaseCreation): try: if verbosity >= 1: print(""Destroying old test database for alias %s..."" % ( self._get_database_display_str(target_database_name, verbosity), )) cursor.execute(""DROP DATABASE %s"" % qn(target_database_name)) cursor.execute(""CREATE DATABASE %s"" % qn(target_database_name))","class DatabaseCreation(BaseDatabaseCreation): try: if verbosity >= 1: print(""Destroying old test database for alias %s..."" % ( self._get_database_display_str(verbosity, target_database_name), )) cursor.execute(""DROP DATABASE %s"" % qn(target_database_name)) cursor.execute(""CREATE DATABASE %s"" % qn(target_database_name))" 1081,https://:@github.com/iMerica/dj-models.git,542b7f6c50df18f2aa201cf1de81577c1bee643c,"@@ -50,7 +50,7 @@ class SeparateDatabaseAndState(Operation): to_state = base_state.clone() for dbop in self.database_operations[:-(pos + 1)]: dbop.state_forwards(app_label, to_state) - from_state = base_state.clone() + from_state = to_state.clone() database_operation.state_forwards(app_label, from_state) database_operation.database_backwards(app_label, schema_editor, from_state, to_state) ",django/db/migrations/operations/special.py,"ReplaceText(target='to_state' @(53,25)->(53,35))","class SeparateDatabaseAndState(Operation): to_state = base_state.clone() for dbop in self.database_operations[:-(pos + 1)]: dbop.state_forwards(app_label, to_state) from_state = base_state.clone() database_operation.state_forwards(app_label, from_state) database_operation.database_backwards(app_label, schema_editor, from_state, to_state) ","class SeparateDatabaseAndState(Operation): to_state = base_state.clone() for dbop in self.database_operations[:-(pos + 1)]: dbop.state_forwards(app_label, to_state) from_state = to_state.clone() database_operation.state_forwards(app_label, from_state) database_operation.database_backwards(app_label, schema_editor, from_state, to_state) " 1082,https://:@github.com/iMerica/dj-models.git,0d9ff873d9f93efbba875efbf582db88bb0e30ce,"@@ -147,7 +147,7 @@ class UserAttributeSimilarityValidator(object): continue value_parts = re.split(r'\W+', value) + [value] for value_part in value_parts: - if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity: + if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() >= self.max_similarity: try: verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name) except FieldDoesNotExist: ",django/contrib/auth/password_validation.py,"ReplaceText(target='>=' @(150,91)->(150,92))","class UserAttributeSimilarityValidator(object): continue value_parts = re.split(r'\W+', value) + [value] for value_part in value_parts: if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity: try: verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name) except FieldDoesNotExist:","class UserAttributeSimilarityValidator(object): continue value_parts = re.split(r'\W+', value) + [value] for value_part in value_parts: if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() >= self.max_similarity: try: verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name) except FieldDoesNotExist:" 1083,https://:@github.com/iMerica/dj-models.git,d5088f838d837fc9e3109c828f18511055f20bea,"@@ -383,7 +383,7 @@ class CombinedExpression(Expression): return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection) if (lhs_output and rhs_output and self.connector == self.SUB and lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and - lhs_output.get_internal_type() == lhs_output.get_internal_type()): + lhs_output.get_internal_type() == rhs_output.get_internal_type()): return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection) expressions = [] expression_params = [] ",django/db/models/expressions.py,"ReplaceText(target='rhs_output' @(386,50)->(386,60))","class CombinedExpression(Expression): return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection) if (lhs_output and rhs_output and self.connector == self.SUB and lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and lhs_output.get_internal_type() == lhs_output.get_internal_type()): return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection) expressions = [] expression_params = []","class CombinedExpression(Expression): return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection) if (lhs_output and rhs_output and self.connector == self.SUB and lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and lhs_output.get_internal_type() == rhs_output.get_internal_type()): return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection) expressions = [] expression_params = []" 1084,https://:@github.com/iMerica/dj-models.git,95993a89ce6ca5f5e26b1c22b65c57dcb8c005e9,"@@ -42,7 +42,7 @@ class PasswordResetTokenGenerator: return False # Check the timestamp is within limit - if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: + if (self._num_days(self._today()) - ts) >= settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True ",django/contrib/auth/tokens.py,"ReplaceText(target='>=' @(45,48)->(45,49))","class PasswordResetTokenGenerator: return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True","class PasswordResetTokenGenerator: return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) >= settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True" 1085,https://:@github.com/Cologler/lquery-python.git,2b2d5a249fd80693660433076d8c79ef119c89bb,"@@ -55,7 +55,7 @@ class DefaultExprVisitor(ExprVisitor): right = expr.right.accept(self) if left is expr.left and right is expr.right: return expr - return Make.binary_op(left, right, expr.op) + return Make.binary_op(left, expr.op, right) def visit_func_expr(self, expr): body = expr.body.accept(self) ",lquery/expr/visitor.py,"ArgSwap(idxs=1<->2 @(58,15)->(58,29))","class DefaultExprVisitor(ExprVisitor): right = expr.right.accept(self) if left is expr.left and right is expr.right: return expr return Make.binary_op(left, right, expr.op) def visit_func_expr(self, expr): body = expr.body.accept(self)","class DefaultExprVisitor(ExprVisitor): right = expr.right.accept(self) if left is expr.left and right is expr.right: return expr return Make.binary_op(left, expr.op, right) def visit_func_expr(self, expr): body = expr.body.accept(self)" 1086,https://:@github.com/rkhleics/police-api-client-python.git,2bedbab8eb7d2efb9ff8e39a821fd2796dd4ce3f,"@@ -28,7 +28,7 @@ class BaseService(object): def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} - if method == 'GET': + if verb == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs ",police_api/service.py,"ReplaceText(target='verb' @(31,11)->(31,17))","class BaseService(object): def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} if method == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs","class BaseService(object): def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} if verb == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs" 1087,https://:@github.com/dw/acid.git,7cdd45e62d60ea7e67a2a3d656f8cce8dd9f5571,"@@ -94,7 +94,7 @@ class RangeIterator(object): the iterator is still within the bounds of the collection prefix, otherwise False."""""" keys_raw, self.data = next(self.it, ('', '')) - keys = keylib.KeyList.from_raw(self.prefix, keys_raw) + keys = keylib.KeyList.from_raw(keys_raw, self.prefix) self.keys = keys return keys is not None ",acid/iterators.py,"ArgSwap(idxs=0<->1 @(97,15)->(97,38))","class RangeIterator(object): the iterator is still within the bounds of the collection prefix, otherwise False."""""" keys_raw, self.data = next(self.it, ('', '')) keys = keylib.KeyList.from_raw(self.prefix, keys_raw) self.keys = keys return keys is not None ","class RangeIterator(object): the iterator is still within the bounds of the collection prefix, otherwise False."""""" keys_raw, self.data = next(self.it, ('', '')) keys = keylib.KeyList.from_raw(keys_raw, self.prefix) self.keys = keys return keys is not None " 1088,https://:@github.com/dw/acid.git,7cdd45e62d60ea7e67a2a3d656f8cce8dd9f5571,"@@ -35,7 +35,7 @@ class IterTest: REVERSE = ITEMS[::-1] def _encode(self, s): - return keylib.packs(self.prefix, s) + return keylib.packs(s, self.prefix) def setUp(self): self.e = acid.engines.ListEngine() ",tests/core_test.py,"ArgSwap(idxs=0<->1 @(38,15)->(38,27))","class IterTest: REVERSE = ITEMS[::-1] def _encode(self, s): return keylib.packs(self.prefix, s) def setUp(self): self.e = acid.engines.ListEngine()","class IterTest: REVERSE = ITEMS[::-1] def _encode(self, s): return keylib.packs(s, self.prefix) def setUp(self): self.e = acid.engines.ListEngine()" 1089,https://:@github.com/akuendig/RxPython.git,f1a5d48b5c22cf5d39e592299a3760be72ba79f1,"@@ -50,7 +50,7 @@ class GroupBy(Producer): else: if not key in self.map: writer = Subject() - self.map[key] = value + self.map[key] = writer fireNewMapEntry = True except Exception as e: self.onError(e) ",linq/groupBy.py,"ReplaceText(target='writer' @(53,28)->(53,33))","class GroupBy(Producer): else: if not key in self.map: writer = Subject() self.map[key] = value fireNewMapEntry = True except Exception as e: self.onError(e)","class GroupBy(Producer): else: if not key in self.map: writer = Subject() self.map[key] = writer fireNewMapEntry = True except Exception as e: self.onError(e)" 1090,https://:@github.com/ANCIR/grano.git,0c1c013af342409e68adf8e50a80bd72f66cd9a4,"@@ -20,7 +20,7 @@ def save(data, project=None): """""" Create or update a project with a given slug. """""" validator = ProjectValidator() - data = validator.deserialize(validator) + data = validator.deserialize(data) if project is None: project = Project() ",grano/logic/projects.py,"ReplaceText(target='data' @(23,33)->(23,42))","def save(data, project=None): """""" Create or update a project with a given slug. """""" validator = ProjectValidator() data = validator.deserialize(validator) if project is None: project = Project()","def save(data, project=None): """""" Create or update a project with a given slug. """""" validator = ProjectValidator() data = validator.deserialize(data) if project is None: project = Project()" 1091,https://:@github.com/ANCIR/grano.git,051a6d6191ba975e6f741c19b354a9017c825de0,"@@ -50,7 +50,7 @@ def update(slug, name): authz.require(authz.project_manage(project)) schema = object_or_404(Schema.by_name(project, name)) data = request_data({'project': project}) - project = schemata.save(data, schema=schema) + schema = schemata.save(data, schema=schema) db.session.commit() return jsonify(schemata.to_rest(schema)) ",grano/views/schemata_api.py,"ReplaceText(target='schema' @(53,4)->(53,11))","def update(slug, name): authz.require(authz.project_manage(project)) schema = object_or_404(Schema.by_name(project, name)) data = request_data({'project': project}) project = schemata.save(data, schema=schema) db.session.commit() return jsonify(schemata.to_rest(schema)) ","def update(slug, name): authz.require(authz.project_manage(project)) schema = object_or_404(Schema.by_name(project, name)) data = request_data({'project': project}) schema = schemata.save(data, schema=schema) db.session.commit() return jsonify(schemata.to_rest(schema)) " 1092,https://:@github.com/eljost/pysisyphus.git,b5fd2ffdadc4b9d84a4b553b2e24a739509659be,"@@ -100,7 +100,7 @@ class NEB(ChainOfStates): if self._forces is None: # Parallel calculation - if self.parallel != 0: + if self.parallel > 0: with Pool(processes=self.parallel) as pool: image_number = len(self.images) par_images = pool.map(self.par_calc, range(image_number)) ",pysisyphus/cos/NEB.py,"ReplaceText(target='>' @(103,29)->(103,31))","class NEB(ChainOfStates): if self._forces is None: # Parallel calculation if self.parallel != 0: with Pool(processes=self.parallel) as pool: image_number = len(self.images) par_images = pool.map(self.par_calc, range(image_number))","class NEB(ChainOfStates): if self._forces is None: # Parallel calculation if self.parallel > 0: with Pool(processes=self.parallel) as pool: image_number = len(self.images) par_images = pool.map(self.par_calc, range(image_number))" 1093,https://:@github.com/eljost/pysisyphus.git,f2aa6358798813b4e77862d57a38ec3286f3a142,"@@ -425,7 +425,7 @@ class ORCA(Calculator): self.store_wfo_data(atoms, coords) # In the first iteration we have nothing to compare to old_root = self.root - if self.calc_counter >= 1: + if self.calc_counter > 1: last_two_coords = self.wfow.last_two_coords self.root = self.wfow.track(old_root=self.root) if self.root != old_root: ",pysisyphus/calculators/ORCA.py,"ReplaceText(target='>' @(428,29)->(428,31))","class ORCA(Calculator): self.store_wfo_data(atoms, coords) # In the first iteration we have nothing to compare to old_root = self.root if self.calc_counter >= 1: last_two_coords = self.wfow.last_two_coords self.root = self.wfow.track(old_root=self.root) if self.root != old_root:","class ORCA(Calculator): self.store_wfo_data(atoms, coords) # In the first iteration we have nothing to compare to old_root = self.root if self.calc_counter > 1: last_two_coords = self.wfow.last_two_coords self.root = self.wfow.track(old_root=self.root) if self.root != old_root:" 1094,https://:@github.com/eljost/pysisyphus.git,f00266de85fe1696b618f979711c52bafb2312be,"@@ -58,7 +58,7 @@ def get_geoms(xyz_fns, idpp=False, between=0, dump=False, multiple_geoms=False): # How is this different from above? elif isinstance(xyz_fns, str) and xyz_fns.endswith("".trj""): geoms = geoms_from_trj(xyz_fns) - elif multiple_geoms: + elif not multiple_geoms: geoms = geoms_from_trj(xyz_fns[0]) # Handle multiple .xyz files else: ",pysisyphus/trj.py,"ReplaceText(target='not ' @(61,9)->(61,9))","def get_geoms(xyz_fns, idpp=False, between=0, dump=False, multiple_geoms=False): # How is this different from above? elif isinstance(xyz_fns, str) and xyz_fns.endswith("".trj""): geoms = geoms_from_trj(xyz_fns) elif multiple_geoms: geoms = geoms_from_trj(xyz_fns[0]) # Handle multiple .xyz files else:","def get_geoms(xyz_fns, idpp=False, between=0, dump=False, multiple_geoms=False): # How is this different from above? elif isinstance(xyz_fns, str) and xyz_fns.endswith("".trj""): geoms = geoms_from_trj(xyz_fns) elif not multiple_geoms: geoms = geoms_from_trj(xyz_fns[0]) # Handle multiple .xyz files else:" 1095,https://:@github.com/eljost/pysisyphus.git,98f7e8f2e9a295c727cf57b2dd6bca90fd829b16,"@@ -837,7 +837,7 @@ def plot_opt(h5_fn=""optimization.h5"", group_name=""opt""): ax1.set_title(""max(forces)"") ax1.set_ylabel(""$E_h$ Bohr⁻¹ (rad)⁻¹"") - ax2.plot(max_forces, **ax_kwargs) + ax2.plot(rms_forces, **ax_kwargs) ax2.set_title(""rms(forces)"") ax2.set_xlabel(""Step"") ax2.set_ylabel(""$E_h$ Bohr⁻¹ (rad)⁻¹"") ",pysisyphus/plot.py,"ReplaceText(target='rms_forces' @(840,13)->(840,23))","def plot_opt(h5_fn=""optimization.h5"", group_name=""opt""): ax1.set_title(""max(forces)"") ax1.set_ylabel(""$E_h$ Bohr⁻¹ (rad)⁻¹"") ax2.plot(max_forces, **ax_kwargs) ax2.set_title(""rms(forces)"") ax2.set_xlabel(""Step"") ax2.set_ylabel(""$E_h$ Bohr⁻¹ (rad)⁻¹"")","def plot_opt(h5_fn=""optimization.h5"", group_name=""opt""): ax1.set_title(""max(forces)"") ax1.set_ylabel(""$E_h$ Bohr⁻¹ (rad)⁻¹"") ax2.plot(rms_forces, **ax_kwargs) ax2.set_title(""rms(forces)"") ax2.set_xlabel(""Step"") ax2.set_ylabel(""$E_h$ Bohr⁻¹ (rad)⁻¹"")" 1096,https://:@github.com/eljost/pysisyphus.git,2aaee0dec2e2c07da386ede88d22bd3c2b2baf5e,"@@ -131,7 +131,7 @@ def run(): inp = make_input(**inp_kwargs) inp_fn = ""packmol.inp"" with open(inp_fn, ""w"") as handle: - handle.write(inp_fn) + handle.write(inp) print(f""Wrote packmol input to '{inp_fn}'"") proc = call_packmol(inp) ",pysisyphus/pack.py,"ReplaceText(target='inp' @(134,21)->(134,27))","def run(): inp = make_input(**inp_kwargs) inp_fn = ""packmol.inp"" with open(inp_fn, ""w"") as handle: handle.write(inp_fn) print(f""Wrote packmol input to '{inp_fn}'"") proc = call_packmol(inp)","def run(): inp = make_input(**inp_kwargs) inp_fn = ""packmol.inp"" with open(inp_fn, ""w"") as handle: handle.write(inp) print(f""Wrote packmol input to '{inp_fn}'"") proc = call_packmol(inp)" 1097,https://:@github.com/pashango2/Image4Layer.git,24060ba346c534032314d6f28011d2edfceec1a2,"@@ -191,7 +191,7 @@ def separate_blend(cb, cs, func, eval_str=""func(float(a), float(b))""): # cs has alpha if cs_alpha: - base_img = img.copy() + base_img = cb.copy() base_img.paste(img, mask=cs_alpha) img = base_img ",image4layer/image4layer.py,"ReplaceText(target='cb' @(194,23)->(194,26))","def separate_blend(cb, cs, func, eval_str=""func(float(a), float(b))""): # cs has alpha if cs_alpha: base_img = img.copy() base_img.paste(img, mask=cs_alpha) img = base_img ","def separate_blend(cb, cs, func, eval_str=""func(float(a), float(b))""): # cs has alpha if cs_alpha: base_img = cb.copy() base_img.paste(img, mask=cs_alpha) img = base_img " 1098,https://:@github.com/BadrYoubiIdrissi/hydra-plugins.git,d690e35407ad42bbf99d99ced25e7f3f77dae25b,"@@ -46,7 +46,7 @@ class RangeSweeper(Sweeper): src_lists = [] for s in arguments: key, value = s.split(""="") - gl = re.match(r'glob\((.+)\)', s) + gl = re.match(r'glob\((.+)\)', value) if ',' in value: possible_values=value.split(',') elif ':' in value: ",badr_range_sweeper/hydra_plugins/range_sweeper_badr/range_sweeper_badr.py,"ReplaceText(target='value' @(49,43)->(49,44))","class RangeSweeper(Sweeper): src_lists = [] for s in arguments: key, value = s.split(""="") gl = re.match(r'glob\((.+)\)', s) if ',' in value: possible_values=value.split(',') elif ':' in value:","class RangeSweeper(Sweeper): src_lists = [] for s in arguments: key, value = s.split(""="") gl = re.match(r'glob\((.+)\)', value) if ',' in value: possible_values=value.split(',') elif ':' in value:" 1099,https://:@github.com/annoys-parrot/multi_view_network.git,df17d237d8e022cfa14fe76cce812b3914360e20,"@@ -340,7 +340,7 @@ def BuildMultiViewNetwork( [v1, v2, v3, v4], name='concatenation') fully_connected = keras.layers.Dense( units=hidden_units, name='fully_connected')(concatenation) - dropout = keras.layers.Dropout(rate=dropout_rate)(concatenation) + dropout = keras.layers.Dropout(rate=dropout_rate)(fully_connected) softmax = keras.layers.Dense( units=output_units, activation='softmax', name='softmax')(dropout) ",multi_view_network/models.py,"ReplaceText(target='fully_connected' @(343,54)->(343,67))","def BuildMultiViewNetwork( [v1, v2, v3, v4], name='concatenation') fully_connected = keras.layers.Dense( units=hidden_units, name='fully_connected')(concatenation) dropout = keras.layers.Dropout(rate=dropout_rate)(concatenation) softmax = keras.layers.Dense( units=output_units, activation='softmax', name='softmax')(dropout)","def BuildMultiViewNetwork( [v1, v2, v3, v4], name='concatenation') fully_connected = keras.layers.Dense( units=hidden_units, name='fully_connected')(concatenation) dropout = keras.layers.Dropout(rate=dropout_rate)(fully_connected) softmax = keras.layers.Dense( units=output_units, activation='softmax', name='softmax')(dropout)" 1100,https://:@github.com/jor-/measurements.git,7d2c45bf498b709aa6ff903f87122e24bf02ef06,"@@ -25,7 +25,7 @@ def npy_or_save_dop_and_po4(npy_file, dop_function, po4_function): po4 = po4.reshape((1,) + po4.shape) data = np.append(dop, po4, axis=0) - util.io.save_npy(npy_file, data, make_read_only=True, create_path_if_not_exists=True) + util.io.save_npy(data, npy_file, make_read_only=True, create_path_if_not_exists=True) return data ",all/woa/data.py,"ArgSwap(idxs=0<->1 @(28,8)->(28,24))","def npy_or_save_dop_and_po4(npy_file, dop_function, po4_function): po4 = po4.reshape((1,) + po4.shape) data = np.append(dop, po4, axis=0) util.io.save_npy(npy_file, data, make_read_only=True, create_path_if_not_exists=True) return data ","def npy_or_save_dop_and_po4(npy_file, dop_function, po4_function): po4 = po4.reshape((1,) + po4.shape) data = np.append(dop, po4, axis=0) util.io.save_npy(data, npy_file, make_read_only=True, create_path_if_not_exists=True) return data " 1101,https://:@github.com/jor-/measurements.git,a7a2d0f753fae4e81297af835aad164120937629,"@@ -73,7 +73,7 @@ class Cruise(): z = z_var.data assert po4_var.units == measurements.po4.wod.constants.PO4_UNIT - po4 = z_var.data + po4 = po4_var.data z_flag = z_flag_var.data po4_flag = po4_flag_var.data ",measurements/po4/wod/cruise.py,"ReplaceText(target='po4_var' @(76,22)->(76,27))","class Cruise(): z = z_var.data assert po4_var.units == measurements.po4.wod.constants.PO4_UNIT po4 = z_var.data z_flag = z_flag_var.data po4_flag = po4_flag_var.data","class Cruise(): z = z_var.data assert po4_var.units == measurements.po4.wod.constants.PO4_UNIT po4 = po4_var.data z_flag = z_flag_var.data po4_flag = po4_flag_var.data" 1102,https://:@github.com/jor-/measurements.git,859a296a6e70664de2e7ff4970b80f311735ef19,"@@ -678,7 +678,7 @@ class LandSeaMask(): # plot cm = matplotlib.pyplot.cm.winter_r - util.plot.data(data, file, land_value=0, power_limit=10, colormap=cm) + util.plot.data(file, data, land_value=0, power_limit=10, colormap=cm) # copy def copy(self): ",measurements/land_sea_mask/lsm.py,"ArgSwap(idxs=0<->1 @(681,8)->(681,22))","class LandSeaMask(): # plot cm = matplotlib.pyplot.cm.winter_r util.plot.data(data, file, land_value=0, power_limit=10, colormap=cm) # copy def copy(self):","class LandSeaMask(): # plot cm = matplotlib.pyplot.cm.winter_r util.plot.data(file, data, land_value=0, power_limit=10, colormap=cm) # copy def copy(self):" 1103,https://:@github.com/jor-/measurements.git,859a296a6e70664de2e7ff4970b80f311735ef19,"@@ -68,7 +68,7 @@ def _plot_map(data, lsm, file, layer=None, v_min=None, v_max=None, use_log_scale data = data[:, :, :, layer] data = data.reshape(data.shape + (1,)) file = _prepare_filename(file, lsm) - util.plot.data(data, file, no_data_value=np.inf, v_min=v_min, v_max=v_max, use_log_scale=use_log_scale, contours=False, colorbar=True, power_limit=0, colorbar_kwargs=colorbar_kwargs) + util.plot.data(file, data, no_data_value=np.inf, v_min=v_min, v_max=v_max, use_log_scale=use_log_scale, contours=False, colorbar=True, power_limit=0, colorbar_kwargs=colorbar_kwargs) def _plot_histogram(data, lsm, file, bins=None, step_size=None, v_min=None, v_max=None, use_log_scale=False, tick_power=None): file = _prepare_filename(file, lsm, 'histogram') ",measurements/util/plot.py,"ArgSwap(idxs=0<->1 @(71,4)->(71,18))","def _plot_map(data, lsm, file, layer=None, v_min=None, v_max=None, use_log_scale data = data[:, :, :, layer] data = data.reshape(data.shape + (1,)) file = _prepare_filename(file, lsm) util.plot.data(data, file, no_data_value=np.inf, v_min=v_min, v_max=v_max, use_log_scale=use_log_scale, contours=False, colorbar=True, power_limit=0, colorbar_kwargs=colorbar_kwargs) def _plot_histogram(data, lsm, file, bins=None, step_size=None, v_min=None, v_max=None, use_log_scale=False, tick_power=None): file = _prepare_filename(file, lsm, 'histogram')","def _plot_map(data, lsm, file, layer=None, v_min=None, v_max=None, use_log_scale data = data[:, :, :, layer] data = data.reshape(data.shape + (1,)) file = _prepare_filename(file, lsm) util.plot.data(file, data, no_data_value=np.inf, v_min=v_min, v_max=v_max, use_log_scale=use_log_scale, contours=False, colorbar=True, power_limit=0, colorbar_kwargs=colorbar_kwargs) def _plot_histogram(data, lsm, file, bins=None, step_size=None, v_min=None, v_max=None, use_log_scale=False, tick_power=None): file = _prepare_filename(file, lsm, 'histogram')" 1104,https://:@github.com/yeago/django-nonrel-enuff.git,77f985134934ef571ea04e9fe6629fffa0bc276d,"@@ -18,7 +18,7 @@ class EnuffManager(models.Manager): def push_to_list(self, queue, instance, trim=500, redis_conn=None, bump=True, site=None): backend = RedisBackend(conn=redis_conn) key = self.get_key(queue, site=site) - current_list = backend.get_ids(queue) + current_list = backend.get_ids(key) known_length = len(current_list) + 1 if bump: if instance.pk in current_list: ",enuff/managers.py,"ReplaceText(target='key' @(21,39)->(21,44))","class EnuffManager(models.Manager): def push_to_list(self, queue, instance, trim=500, redis_conn=None, bump=True, site=None): backend = RedisBackend(conn=redis_conn) key = self.get_key(queue, site=site) current_list = backend.get_ids(queue) known_length = len(current_list) + 1 if bump: if instance.pk in current_list:","class EnuffManager(models.Manager): def push_to_list(self, queue, instance, trim=500, redis_conn=None, bump=True, site=None): backend = RedisBackend(conn=redis_conn) key = self.get_key(queue, site=site) current_list = backend.get_ids(key) known_length = len(current_list) + 1 if bump: if instance.pk in current_list:" 1105,https://:@gitlab.com/ViDA-NYU/reproserver.git,4dea7214ea920d07375abefc9b6cafd6be72a418,"@@ -23,7 +23,7 @@ class OSF(BaseRepository): url = url[8:] else: raise RepositoryError(""Invalid URL"") - if url.lower().startswith('osf.io/'): + if not url.lower().startswith('osf.io/'): raise RepositoryError(""Not OSF URL"") path = url[7:] ",reproserver/repositories/osf.py,"ReplaceText(target='not ' @(26,11)->(26,11))","class OSF(BaseRepository): url = url[8:] else: raise RepositoryError(""Invalid URL"") if url.lower().startswith('osf.io/'): raise RepositoryError(""Not OSF URL"") path = url[7:]","class OSF(BaseRepository): url = url[8:] else: raise RepositoryError(""Invalid URL"") if not url.lower().startswith('osf.io/'): raise RepositoryError(""Not OSF URL"") path = url[7:]" 1106,https://:@github.com/bmeyers/StatisticalClearSky.git,34c593a9d8f1be450f20fe5d3bbd411cf5cef692,"@@ -399,7 +399,7 @@ class IterativeFitting(SerializationMixin, PlotMixin): Since it's used in constructor, TimeShift is injected through constructor. """""" - if time_shift is not None: + if time_shift is None: return ClusteringTimeShift(power_signals_d) else: return time_shift ",statistical_clear_sky/algorithm/iterative_fitting.py,"ReplaceText(target=' is ' @(402,21)->(402,29))","class IterativeFitting(SerializationMixin, PlotMixin): Since it's used in constructor, TimeShift is injected through constructor. """""" if time_shift is not None: return ClusteringTimeShift(power_signals_d) else: return time_shift","class IterativeFitting(SerializationMixin, PlotMixin): Since it's used in constructor, TimeShift is injected through constructor. """""" if time_shift is None: return ClusteringTimeShift(power_signals_d) else: return time_shift" 1107,https://:@github.com/dccs-tech/mcmi.git,64aa5041a581b2f11782f09dedae15a0d188e5cd,"@@ -176,7 +176,7 @@ class DataMixin(object, metaclass = MetaDataMixin): else: method_name = ""{}_name"".format(name) - relations[name] = getattr(self, method_name, None) + relations[field_name] = getattr(self, method_name, None) return relations ",app/systems/command/mixins/base.py,"ReplaceText(target='field_name' @(179,22)->(179,26))","class DataMixin(object, metaclass = MetaDataMixin): else: method_name = ""{}_name"".format(name) relations[name] = getattr(self, method_name, None) return relations ","class DataMixin(object, metaclass = MetaDataMixin): else: method_name = ""{}_name"".format(name) relations[field_name] = getattr(self, method_name, None) return relations " 1108,https://:@github.com/rbwinslow/hq.git,6417c2446670e67868162190254759a483b894ab,"@@ -69,7 +69,7 @@ def _cmp_nodes_to_value(base_op, first, second): def _cmp_value_to_nodes(base_op, first, second): node_values = set([number(node) for node in second]) first = number(first) - verbose_print('Comparing {0} nodes in node set to value ""{1}""'.format(len(node_values), second)) + verbose_print('Comparing {0} nodes in node set to value ""{1}""'.format(len(node_values), first)) for node_value in node_values: if base_op(first, node_value): ",hq/xpath/relational_operators.py,"ReplaceText(target='first' @(72,92)->(72,98))","def _cmp_nodes_to_value(base_op, first, second): def _cmp_value_to_nodes(base_op, first, second): node_values = set([number(node) for node in second]) first = number(first) verbose_print('Comparing {0} nodes in node set to value ""{1}""'.format(len(node_values), second)) for node_value in node_values: if base_op(first, node_value):","def _cmp_nodes_to_value(base_op, first, second): def _cmp_value_to_nodes(base_op, first, second): node_values = set([number(node) for node in second]) first = number(first) verbose_print('Comparing {0} nodes in node set to value ""{1}""'.format(len(node_values), first)) for node_value in node_values: if base_op(first, node_value):" 1109,https://:@github.com/PennWhartonBudgetModel/Utilities.git,dc85c81ce99f0290069d261bdacc675a40e67756,"@@ -114,7 +114,7 @@ class InterfaceReader(PWBMTask): if not exists(destination_folder): makedirs(destination_folder) - if self.filename == """": + if self.filename != """": file_location = join( server_location, ",pwbmutils/interface_reader.py,"ReplaceText(target='!=' @(117,29)->(117,31))","class InterfaceReader(PWBMTask): if not exists(destination_folder): makedirs(destination_folder) if self.filename == """": file_location = join( server_location,","class InterfaceReader(PWBMTask): if not exists(destination_folder): makedirs(destination_folder) if self.filename != """": file_location = join( server_location," 1110,https://:@github.com/wtrdrnkr/pyrecon.git,2055f9cddf60e78a7012ec7dbe9900cd59151e67,"@@ -288,7 +288,7 @@ def prepare_frontend_payload(session, section, grouped): # Add uniques to payload unique_ids_query = prepare_unique_query(session, section) for unique_id in unique_ids_query: - db_contour_unique = session.query(Contour).get(contour_A_id) + db_contour_unique = session.query(Contour).get(unique_id) unique_reconstruct_contour = section.contours[db_contour_unique.index] unique_dict = prepare_contour_dict_for_frontend( unique_reconstruct_contour, ",pyrecon/tools/mergetool/backend.py,"ReplaceText(target='unique_id' @(291,55)->(291,67))","def prepare_frontend_payload(session, section, grouped): # Add uniques to payload unique_ids_query = prepare_unique_query(session, section) for unique_id in unique_ids_query: db_contour_unique = session.query(Contour).get(contour_A_id) unique_reconstruct_contour = section.contours[db_contour_unique.index] unique_dict = prepare_contour_dict_for_frontend( unique_reconstruct_contour,","def prepare_frontend_payload(session, section, grouped): # Add uniques to payload unique_ids_query = prepare_unique_query(session, section) for unique_id in unique_ids_query: db_contour_unique = session.query(Contour).get(unique_id) unique_reconstruct_contour = section.contours[db_contour_unique.index] unique_dict = prepare_contour_dict_for_frontend( unique_reconstruct_contour," 1111,https://:@github.com/chili-epfl/pyrobots.git,146de875a3a4cdea20c0778bd454e7255d0ff78d,"@@ -57,7 +57,7 @@ with robots.PR2(knowledge = pyoro.Oro(), init = False) as pr2: for t in e: text = pr2.knowledge[""%s verbalisesTo *"" % t][0] logger.warning(""New verbalization from Dialogs: <%s>"" % text) - pr2.say(t) + pr2.say(text) if ""--init"" in sys.argv: ",scripts/handover.py,"ReplaceText(target='text' @(60,20)->(60,21))","with robots.PR2(knowledge = pyoro.Oro(), init = False) as pr2: for t in e: text = pr2.knowledge[""%s verbalisesTo *"" % t][0] logger.warning(""New verbalization from Dialogs: <%s>"" % text) pr2.say(t) if ""--init"" in sys.argv:","with robots.PR2(knowledge = pyoro.Oro(), init = False) as pr2: for t in e: text = pr2.knowledge[""%s verbalisesTo *"" % t][0] logger.warning(""New verbalization from Dialogs: <%s>"" % text) pr2.say(text) if ""--init"" in sys.argv:" 1112,https://:@github.com/raviqqe/tensorflow-extenteten.git,7d6a40a3bd15292c762e919d1411e8da06791329,"@@ -19,7 +19,7 @@ def get_attentions(): def add_metric(tensor, name=None): return tf.add_to_collection( METRICS, - tensor if name is None else util.rename(name, tensor)) + tensor if name is None else util.rename(tensor, name)) def get_metrics(): return tf.get_collection(METRICS) ",nn/collections.py,"ArgSwap(idxs=0<->1 @(22,34)->(22,45))","def get_attentions(): def add_metric(tensor, name=None): return tf.add_to_collection( METRICS, tensor if name is None else util.rename(name, tensor)) def get_metrics(): return tf.get_collection(METRICS)","def get_attentions(): def add_metric(tensor, name=None): return tf.add_to_collection( METRICS, tensor if name is None else util.rename(tensor, name)) def get_metrics(): return tf.get_collection(METRICS)" 1113,https://:@github.com/raviqqe/tensorflow-extenteten.git,f34e283077d1899902e276dff397defed16537f7,"@@ -60,7 +60,7 @@ def classify(logits, return (predictions, loss + l2_regularization_loss(regularization_scale), train.minimize(loss), - _evaluate(predictions, true_label)) + _evaluate(predicted_labels, true_label)) @func_scope() ",extenteten/classification.py,"ReplaceText(target='predicted_labels' @(63,22)->(63,33))","def classify(logits, return (predictions, loss + l2_regularization_loss(regularization_scale), train.minimize(loss), _evaluate(predictions, true_label)) @func_scope()","def classify(logits, return (predictions, loss + l2_regularization_loss(regularization_scale), train.minimize(loss), _evaluate(predicted_labels, true_label)) @func_scope()" 1114,https://:@github.com/Gulats/playmate.git,e7b2dc953d5117abdbf2d0821bb6991ed0fd26b1,"@@ -333,7 +333,7 @@ class PlayScraper(object): results = s.DEV_RESULTS if results is None else results page = 0 if page is None else page page_num = (results // 20) * page - if not 0 < page_num <= 12: + if not 0 <= page_num <= 12: raise ValueError('Page out of range. (results // 20) * page must be between 0 - 12') pagtok = self._pagtok[page_num] ",play_scraper/scraper.py,"ReplaceText(target='<=' @(336,17)->(336,18))","class PlayScraper(object): results = s.DEV_RESULTS if results is None else results page = 0 if page is None else page page_num = (results // 20) * page if not 0 < page_num <= 12: raise ValueError('Page out of range. (results // 20) * page must be between 0 - 12') pagtok = self._pagtok[page_num] ","class PlayScraper(object): results = s.DEV_RESULTS if results is None else results page = 0 if page is None else page page_num = (results // 20) * page if not 0 <= page_num <= 12: raise ValueError('Page out of range. (results // 20) * page must be between 0 - 12') pagtok = self._pagtok[page_num] " 1115,https://:@github.com/Acrisel/sshpipe.git,d87836437f14330751667874ae8ee4bbb257289c,"@@ -21,7 +21,7 @@ class MySSHPipeHandler(SSHPipeHandler): def atstart(self, received): file = ""{}{}"".format(__file__, "".remote.log"") - if hasattr(self, 'mlogger'): + if not hasattr(self, 'mlogger'): raise RuntimeError(""Self missing mlogger method."") self.mlogger.debug(""Opening file: {}."".format(file)) self.file = open(file, 'w') ",sshpipe/examples/ssh_remote_handler.py,"ReplaceText(target='not ' @(24,11)->(24,11))","class MySSHPipeHandler(SSHPipeHandler): def atstart(self, received): file = ""{}{}"".format(__file__, "".remote.log"") if hasattr(self, 'mlogger'): raise RuntimeError(""Self missing mlogger method."") self.mlogger.debug(""Opening file: {}."".format(file)) self.file = open(file, 'w')","class MySSHPipeHandler(SSHPipeHandler): def atstart(self, received): file = ""{}{}"".format(__file__, "".remote.log"") if not hasattr(self, 'mlogger'): raise RuntimeError(""Self missing mlogger method."") self.mlogger.debug(""Opening file: {}."".format(file)) self.file = open(file, 'w')" 1116,https://:@github.com/NREL/tracknodes.git,38a736a18b767b24a883698f15618bc160dceb5e,"@@ -124,7 +124,7 @@ class TrackNodes: for line in Popen([self.nodes_cmd, '--version'], stdout=PIPE, stderr=PIPE).communicate()[1].strip().split(""\n""): fields = line.split() - if len(fields) > 0: + if len(fields) < 0: raise Exception(""Unable to determine PBSpro or Torque"") if fields[0] == ""pbs_version"": ",lib/tracknodes/tracknodes.py,"ReplaceText(target='<' @(127,27)->(127,28))","class TrackNodes: for line in Popen([self.nodes_cmd, '--version'], stdout=PIPE, stderr=PIPE).communicate()[1].strip().split(""\n""): fields = line.split() if len(fields) > 0: raise Exception(""Unable to determine PBSpro or Torque"") if fields[0] == ""pbs_version"":","class TrackNodes: for line in Popen([self.nodes_cmd, '--version'], stdout=PIPE, stderr=PIPE).communicate()[1].strip().split(""\n""): fields = line.split() if len(fields) < 0: raise Exception(""Unable to determine PBSpro or Torque"") if fields[0] == ""pbs_version"":" 1117,https://:@github.com/podhmo/metafanstatic.git,3c8e226e19bc4d3e0ad0c41f0f09da0183a4fd0f,"@@ -67,7 +67,7 @@ def dependencies_iterator(xs): yield k, v else: for e in xs: - yield k, None + yield e, None class TotalComplement(object): ",metafanstatic/complement.py,"ReplaceText(target='e' @(70,18)->(70,19))","def dependencies_iterator(xs): yield k, v else: for e in xs: yield k, None class TotalComplement(object):","def dependencies_iterator(xs): yield k, v else: for e in xs: yield e, None class TotalComplement(object):" 1118,https://:@github.com/podhmo/metafanstatic.git,335a4deac8f721341e4983fab547082fb926b7e9,"@@ -58,7 +58,7 @@ def creation(args): if ""skip"" not in params[c]: sys.stderr.write(""create package: {}? (y or n)\n"".format(c)) sys.stderr.flush() - skip = ""y"" == sys.stdin.readline().strip().lower() + skip = ""y"" != sys.stdin.readline().strip().lower() else: skip = params[c][""skip""] if skip: ",metafanstatic/command.py,"ReplaceText(target='!=' @(61,23)->(61,25))","def creation(args): if ""skip"" not in params[c]: sys.stderr.write(""create package: {}? (y or n)\n"".format(c)) sys.stderr.flush() skip = ""y"" == sys.stdin.readline().strip().lower() else: skip = params[c][""skip""] if skip:","def creation(args): if ""skip"" not in params[c]: sys.stderr.write(""create package: {}? (y or n)\n"".format(c)) sys.stderr.flush() skip = ""y"" != sys.stdin.readline().strip().lower() else: skip = params[c][""skip""] if skip:" 1119,https://:@github.com/rte-france/Grid2Op.git,a5f67c567a5dda60a015e9c06802927eadd6f5df,"@@ -57,7 +57,7 @@ if __name__ == ""__main__"": old_version = re.sub(""version="", """", old_version) old_version = re.sub(""'"", """", old_version) old_version = re.sub('""', """", old_version) - if version <= old_version: + if version < old_version: raise RuntimeError(""You provided the \""new\"" version \""{}\"" which is older (or equal) to the current version "" ""found: \""{}\""."".format(version, old_version)) ",utils/make_release.py,"ReplaceText(target='<' @(60,15)->(60,17))","if __name__ == ""__main__"": old_version = re.sub(""version="", """", old_version) old_version = re.sub(""'"", """", old_version) old_version = re.sub('""', """", old_version) if version <= old_version: raise RuntimeError(""You provided the \""new\"" version \""{}\"" which is older (or equal) to the current version "" ""found: \""{}\""."".format(version, old_version)) ","if __name__ == ""__main__"": old_version = re.sub(""version="", """", old_version) old_version = re.sub(""'"", """", old_version) old_version = re.sub('""', """", old_version) if version < old_version: raise RuntimeError(""You provided the \""new\"" version \""{}\"" which is older (or equal) to the current version "" ""found: \""{}\""."".format(version, old_version)) " 1120,https://:@bitbucket.org/berkeleylab/als.milo.git,e60d005d389cb31b6e99f937e35adbe3fccb7aaf,"@@ -131,7 +131,7 @@ def get_versions(): pass return_key_values = _get_versions() - return_key_values[""authors""] = pieces[""authors""] + return_key_values[""authors""] = default_keys_values[""authors""] return return_key_values ",milo/version.py,"ReplaceText(target='default_keys_values' @(134,35)->(134,41))","def get_versions(): pass return_key_values = _get_versions() return_key_values[""authors""] = pieces[""authors""] return return_key_values ","def get_versions(): pass return_key_values = _get_versions() return_key_values[""authors""] = default_keys_values[""authors""] return return_key_values " 1121,https://:@github.com/astroJeff/dart_board.git,1e34f160c6865ba41d49a6261bd56b5ecdb3aa28,"@@ -42,7 +42,7 @@ def ln_prior(x, dart): if key == 'kick_sigma': kick_sigma = value if key == 'M1_alpha': M1_alpha = value if key == 'M1_min': M1_min = value - if key == 'M1_max': M1_min = value + if key == 'M1_max': M1_max = value if key == 'M2_min': M2_min = value if key == 'a_min': a_min = value if key == 'a_max': a_max = value ",dart_board/priors.py,"ReplaceText(target='M1_max' @(45,28)->(45,34))","def ln_prior(x, dart): if key == 'kick_sigma': kick_sigma = value if key == 'M1_alpha': M1_alpha = value if key == 'M1_min': M1_min = value if key == 'M1_max': M1_min = value if key == 'M2_min': M2_min = value if key == 'a_min': a_min = value if key == 'a_max': a_max = value","def ln_prior(x, dart): if key == 'kick_sigma': kick_sigma = value if key == 'M1_alpha': M1_alpha = value if key == 'M1_min': M1_min = value if key == 'M1_max': M1_max = value if key == 'M2_min': M2_min = value if key == 'a_min': a_min = value if key == 'a_max': a_max = value" 1122,https://:@github.com/astroJeff/dart_board.git,6362e24414b5056aea5b50b99e7a446b9e9a9625,"@@ -156,7 +156,7 @@ class DartBoard(): print(""You must include a binary evolution scheme, e.g. pybse.evolv_wrapper"") sys.exit(-1) - if ntemps != 1 or ntemps is not None: + if ntemps != 1 and ntemps is not None: if ln_likelihood_function is None: print(""You must include a likelihood function when using the parallel tempering MCMC method."") sys.exit(-1) ",dart_board/darts.py,"ReplaceText(target='and' @(159,23)->(159,25))","class DartBoard(): print(""You must include a binary evolution scheme, e.g. pybse.evolv_wrapper"") sys.exit(-1) if ntemps != 1 or ntemps is not None: if ln_likelihood_function is None: print(""You must include a likelihood function when using the parallel tempering MCMC method."") sys.exit(-1)","class DartBoard(): print(""You must include a binary evolution scheme, e.g. pybse.evolv_wrapper"") sys.exit(-1) if ntemps != 1 and ntemps is not None: if ln_likelihood_function is None: print(""You must include a likelihood function when using the parallel tempering MCMC method."") sys.exit(-1)" 1123,https://:@github.com/celskeggs/themis.git,7f075e9140cb32cd691ca4725fa6a1789226ad23,"@@ -19,7 +19,7 @@ def generate_prebuilt_files(build_lib): shutil.copyfile(os.path.join(builddir, SO_NAME), os.path.join(build_lib, ""themis"", SO_NAME)) - shutil.copyfile(os.path.join(builddir, HEADER_NAME), + shutil.copyfile(os.path.join(source_dir, HEADER_NAME), os.path.join(build_lib, ""themis"", os.path.basename(HEADER_NAME))) print(""finished compiling frc hal"") ",setup.py,"ReplaceText(target='source_dir' @(22,37)->(22,45))","def generate_prebuilt_files(build_lib): shutil.copyfile(os.path.join(builddir, SO_NAME), os.path.join(build_lib, ""themis"", SO_NAME)) shutil.copyfile(os.path.join(builddir, HEADER_NAME), os.path.join(build_lib, ""themis"", os.path.basename(HEADER_NAME))) print(""finished compiling frc hal"") ","def generate_prebuilt_files(build_lib): shutil.copyfile(os.path.join(builddir, SO_NAME), os.path.join(build_lib, ""themis"", SO_NAME)) shutil.copyfile(os.path.join(source_dir, HEADER_NAME), os.path.join(build_lib, ""themis"", os.path.basename(HEADER_NAME))) print(""finished compiling frc hal"") " 1124,https://:@github.com/LanjiaoGong/chinese_province_city_area_mapper.git,ef285ed737310b53eb8e44362f5239cd9e9414fe,"@@ -58,7 +58,7 @@ class Location: def __city_and_province(self): if self.city.isNotEmpty() and self.province.isNotEmpty(): if not self.city.isBlong(self.province.name): - if self.city.precision > self.province.precision: + if self.city.precision >= self.province.precision: self.province.name = self.city.belong else: self.city.reset() ",chinese_province_city_area_mapper/domain.py,"ReplaceText(target='>=' @(61,39)->(61,40))","class Location: def __city_and_province(self): if self.city.isNotEmpty() and self.province.isNotEmpty(): if not self.city.isBlong(self.province.name): if self.city.precision > self.province.precision: self.province.name = self.city.belong else: self.city.reset()","class Location: def __city_and_province(self): if self.city.isNotEmpty() and self.province.isNotEmpty(): if not self.city.isBlong(self.province.name): if self.city.precision >= self.province.precision: self.province.name = self.city.belong else: self.city.reset()" 1125,https://:@github.com/rkokkelk/python-athom-api.git,705215f6ce4bb02de2838e0298baeb70d51897ba,"@@ -56,7 +56,7 @@ class AthomSession(Session): text = response.text if status_code in range(200, 299): - return text + return response if status_code in (400, 401): error = AthomCloudAuthenticationError(text) ",athom/common/net.py,"ReplaceText(target='response' @(59,19)->(59,23))","class AthomSession(Session): text = response.text if status_code in range(200, 299): return text if status_code in (400, 401): error = AthomCloudAuthenticationError(text)","class AthomSession(Session): text = response.text if status_code in range(200, 299): return response if status_code in (400, 401): error = AthomCloudAuthenticationError(text)" 1126,https://:@github.com/lambdaloop/calligator.git,c427e036073748ec86466ecff89e10211567c7fe,"@@ -719,7 +719,7 @@ class CameraGroup: t2 = time.time() - if init_progress: + if verbose: print('optimization took {:.2f} seconds'.format(t2 - t1)) return p3ds_new2 ",calligator/cameras.py,"ReplaceText(target='verbose' @(722,11)->(722,24))","class CameraGroup: t2 = time.time() if init_progress: print('optimization took {:.2f} seconds'.format(t2 - t1)) return p3ds_new2","class CameraGroup: t2 = time.time() if verbose: print('optimization took {:.2f} seconds'.format(t2 - t1)) return p3ds_new2" 1127,https://:@github.com/lambdaloop/calligator.git,a6503f793a664d7687ed61ba2166ffe16bf47c87,"@@ -995,7 +995,7 @@ class CameraGroup: t1 = time.time() x0 = self._initialize_params_triangulation( - p3ds_med, constraints, constraints_weak) + p3ds_intp, constraints, constraints_weak) jac = self._jac_sparsity_triangulation( points, constraints, constraints_weak, n_deriv_smooth) ",calligator/cameras.py,"ReplaceText(target='p3ds_intp' @(998,12)->(998,20))","class CameraGroup: t1 = time.time() x0 = self._initialize_params_triangulation( p3ds_med, constraints, constraints_weak) jac = self._jac_sparsity_triangulation( points, constraints, constraints_weak, n_deriv_smooth)","class CameraGroup: t1 = time.time() x0 = self._initialize_params_triangulation( p3ds_intp, constraints, constraints_weak) jac = self._jac_sparsity_triangulation( points, constraints, constraints_weak, n_deriv_smooth)" 1128,https://:@github.com/European-XFEL/EXtra-data.git,732de23488baae986f89f9f1e6f63f38d160011e,"@@ -181,7 +181,7 @@ class VirtualStack: try: mod_data = self._data[modno] except KeyError: - if modno > self._nmodules: + if modno >= self._nmodules: raise IndexError(modno) mod_data = np.full(self._mod_shape, self._fillvalue, self.dtype) ",karabo_data/stacking.py,"ReplaceText(target='>=' @(184,21)->(184,22))","class VirtualStack: try: mod_data = self._data[modno] except KeyError: if modno > self._nmodules: raise IndexError(modno) mod_data = np.full(self._mod_shape, self._fillvalue, self.dtype) ","class VirtualStack: try: mod_data = self._data[modno] except KeyError: if modno >= self._nmodules: raise IndexError(modno) mod_data = np.full(self._mod_shape, self._fillvalue, self.dtype) " 1129,https://:@github.com/spohara79/estreamer.git,d5bdd807c9d421adb77111aad0d584c0dc26a68a,"@@ -37,7 +37,7 @@ class eStreamerConnection(object): except IOError: raise eStreamerKeyError(""Unable to locate key file {}"".format(pkey_path)) except crypto.Error: - raise eStreamerKeyError(""Invalid key file or bad passphrase {}"".format(cert_path)) + raise eStreamerKeyError(""Invalid key file or bad passphrase {}"".format(pkey_path)) try: self.cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(cert_path, 'rb').read()) except IOError: ",estreamer/streamer.py,"ReplaceText(target='pkey_path' @(40,83)->(40,92))","class eStreamerConnection(object): except IOError: raise eStreamerKeyError(""Unable to locate key file {}"".format(pkey_path)) except crypto.Error: raise eStreamerKeyError(""Invalid key file or bad passphrase {}"".format(cert_path)) try: self.cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(cert_path, 'rb').read()) except IOError:","class eStreamerConnection(object): except IOError: raise eStreamerKeyError(""Unable to locate key file {}"".format(pkey_path)) except crypto.Error: raise eStreamerKeyError(""Invalid key file or bad passphrase {}"".format(pkey_path)) try: self.cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(cert_path, 'rb').read()) except IOError:" 1130,https://:@gitlab.com/mihaicristianpirvu/neural-wrappers.git,ee31c3e9b05a3f5bedc923f7bdd5a3243b6d1450,"@@ -19,7 +19,7 @@ class CityScapesReader(DatasetReader): assert not data == ""rgb_first_frame"", ""RGB First frame is not available for sequential dataset"" # Only skipFrames=5 is supported now - if dataDimensions: + if sequentialData: dataDimensions = list(map(lambda x : ""seq_%s_5"" % (x), dataDimensions)) self.datasetPath = datasetPath ",neural_wrappers/readers/cityscapes_reader.py,"ReplaceText(target='sequentialData' @(22,5)->(22,19))","class CityScapesReader(DatasetReader): assert not data == ""rgb_first_frame"", ""RGB First frame is not available for sequential dataset"" # Only skipFrames=5 is supported now if dataDimensions: dataDimensions = list(map(lambda x : ""seq_%s_5"" % (x), dataDimensions)) self.datasetPath = datasetPath","class CityScapesReader(DatasetReader): assert not data == ""rgb_first_frame"", ""RGB First frame is not available for sequential dataset"" # Only skipFrames=5 is supported now if sequentialData: dataDimensions = list(map(lambda x : ""seq_%s_5"" % (x), dataDimensions)) self.datasetPath = datasetPath" 1131,https://:@gitlab.com/mihaicristianpirvu/neural-wrappers.git,79eeed7ae20989498e3377d4173a7fbca7501530,"@@ -115,7 +115,7 @@ class NetworkSerializer: Str += ""\t- %s in current, not in loaded""% (key) continue if current[key] != loaded[key]: - Str += ""\t- current[%s]=%s. loaded[%s]=%s"" % (key, current[key], key, current[key]) + Str += ""\t- current[%s]=%s. loaded[%s]=%s"" % (key, current[key], key, loaded[key]) raise Exception(Str) for key in stateKeys: ",neural_wrappers/pytorch/network_serializer.py,"ReplaceText(target='loaded' @(118,75)->(118,82))","class NetworkSerializer: Str += ""\t- %s in current, not in loaded""% (key) continue if current[key] != loaded[key]: Str += ""\t- current[%s]=%s. loaded[%s]=%s"" % (key, current[key], key, current[key]) raise Exception(Str) for key in stateKeys:","class NetworkSerializer: Str += ""\t- %s in current, not in loaded""% (key) continue if current[key] != loaded[key]: Str += ""\t- current[%s]=%s. loaded[%s]=%s"" % (key, current[key], key, loaded[key]) raise Exception(Str) for key in stateKeys:" 1132,https://:@bitbucket.org/fenics-project/ffc.git,f32ac6fb766df1abbb613d85e598953dc8122fa5,"@@ -186,7 +186,7 @@ class TensorRepresentation: ""Fancy printing of progress"" if facet0 == facet1 == None: debug(""Computing tensor representation for term %d..."" % i) - elif facet0 == None: + elif facet1 == None: debug(""Computing tensor representation for term %d, facet %d..."" % (i, facet0)) else: debug(""Computing tensor representation for term %d, facets (%d, %d)..."" % (i, facet0, facet1)) ",src/ffc/compiler/representation/tensor/tensorrepresentation.py,"ReplaceText(target='facet1' @(189,13)->(189,19))","class TensorRepresentation: ""Fancy printing of progress"" if facet0 == facet1 == None: debug(""Computing tensor representation for term %d..."" % i) elif facet0 == None: debug(""Computing tensor representation for term %d, facet %d..."" % (i, facet0)) else: debug(""Computing tensor representation for term %d, facets (%d, %d)..."" % (i, facet0, facet1))","class TensorRepresentation: ""Fancy printing of progress"" if facet0 == facet1 == None: debug(""Computing tensor representation for term %d..."" % i) elif facet1 == None: debug(""Computing tensor representation for term %d, facet %d..."" % (i, facet0)) else: debug(""Computing tensor representation for term %d, facets (%d, %d)..."" % (i, facet0, facet1))" 1133,https://:@bitbucket.org/fenics-project/ffc.git,68950e19d417ccaf80328da6afd1c52dda61856d,"@@ -151,7 +151,7 @@ def _generate_tensor_contraction(terms, options, g_set): a0 = A0.A0[tuple(i + a)] # Skip small values - if abs(a0) > epsilon: continue + if abs(a0) < epsilon: continue # Compute value if value and a0 < 0.0: ",ffc/tensor/tensorgenerator.py,"ReplaceText(target='<' @(154,27)->(154,28))","def _generate_tensor_contraction(terms, options, g_set): a0 = A0.A0[tuple(i + a)] # Skip small values if abs(a0) > epsilon: continue # Compute value if value and a0 < 0.0:","def _generate_tensor_contraction(terms, options, g_set): a0 = A0.A0[tuple(i + a)] # Skip small values if abs(a0) < epsilon: continue # Compute value if value and a0 < 0.0:" 1134,https://:@bitbucket.org/fenics-project/ffc.git,eda9a71a896b15096615e51c4567692e36672192,"@@ -77,7 +77,7 @@ def analyze_forms(forms, object_names, parameters, common_cell=None): element_numbers = _compute_element_numbers(unique_elements) # Get common cell - common_cell = form_data[0].cell + common_cell = form_datas[0].cell # Compute element cells and degrees (when cell or degree is undefined) element_cells = _auto_select_cells(unique_elements, common_cell) ",ffc/analysis.py,"ReplaceText(target='form_datas' @(80,18)->(80,27))","def analyze_forms(forms, object_names, parameters, common_cell=None): element_numbers = _compute_element_numbers(unique_elements) # Get common cell common_cell = form_data[0].cell # Compute element cells and degrees (when cell or degree is undefined) element_cells = _auto_select_cells(unique_elements, common_cell)","def analyze_forms(forms, object_names, parameters, common_cell=None): element_numbers = _compute_element_numbers(unique_elements) # Get common cell common_cell = form_datas[0].cell # Compute element cells and degrees (when cell or degree is undefined) element_cells = _auto_select_cells(unique_elements, common_cell)" 1135,https://:@bitbucket.org/fenics-project/ffc.git,834ccde04aa1d690b5cd293fcd2a83cad320d13d,"@@ -148,7 +148,7 @@ def _evaluate_basis(data): # coordinates from physical element to the FIAT reference element. # FIXME: KBO: Change this when supporting R^2 in R^3 elements. code += [format[""jacobian and inverse""](geometric_dimension, topological_dimension)] - code += ["""", format[""fiat coordinate map""](element_cell_domain, topological_dimension)] + code += ["""", format[""fiat coordinate map""](element_cell_domain, geometric_dimension)] # Get value shape and reset values. This should also work for TensorElement, # scalar are empty tuples, therefore (1,) in which case value_shape = 1. ",ffc/evaluatebasis.py,"ReplaceText(target='geometric_dimension' @(151,68)->(151,89))","def _evaluate_basis(data): # coordinates from physical element to the FIAT reference element. # FIXME: KBO: Change this when supporting R^2 in R^3 elements. code += [format[""jacobian and inverse""](geometric_dimension, topological_dimension)] code += ["""", format[""fiat coordinate map""](element_cell_domain, topological_dimension)] # Get value shape and reset values. This should also work for TensorElement, # scalar are empty tuples, therefore (1,) in which case value_shape = 1.","def _evaluate_basis(data): # coordinates from physical element to the FIAT reference element. # FIXME: KBO: Change this when supporting R^2 in R^3 elements. code += [format[""jacobian and inverse""](geometric_dimension, topological_dimension)] code += ["""", format[""fiat coordinate map""](element_cell_domain, geometric_dimension)] # Get value shape and reset values. This should also work for TensorElement, # scalar are empty tuples, therefore (1,) in which case value_shape = 1." 1136,https://:@bitbucket.org/fenics-project/ffc.git,dad40f5d3192ffe0fb614ecf0d4a9d443956dde5,"@@ -81,7 +81,7 @@ def generate_xi_from_x_snippets(cell, restriction): name_x = ""x%s"" % restriction name_y = ""vertex_coordinates%s"" % restriction name_z = ""xi%s"" % restriction - return generate_z_Axmy_snippets(name_z, name_A, name_x, name_y, gd, td) + return generate_z_Axmy_snippets(name_z, name_A, name_x, name_y, td, gd) class test_geometry_snippets(CodegenTestCase): ",tests/py/test_geometry_snippets.py,"ArgSwap(idxs=4<->5 @(84,11)->(84,35))","def generate_xi_from_x_snippets(cell, restriction): name_x = ""x%s"" % restriction name_y = ""vertex_coordinates%s"" % restriction name_z = ""xi%s"" % restriction return generate_z_Axmy_snippets(name_z, name_A, name_x, name_y, gd, td) class test_geometry_snippets(CodegenTestCase):","def generate_xi_from_x_snippets(cell, restriction): name_x = ""x%s"" % restriction name_y = ""vertex_coordinates%s"" % restriction name_z = ""xi%s"" % restriction return generate_z_Axmy_snippets(name_z, name_A, name_x, name_y, td, gd) class test_geometry_snippets(CodegenTestCase):" 1137,https://:@bitbucket.org/fenics-project/ffc.git,38550e99392b3c6bec52e45364351bd967baf714,"@@ -650,7 +650,7 @@ def _compute_reference_derivatives(data, dof_data): for k in range(tdim)], [f_transform(""JINV"", k, l, tdim, gdim, None) for k in range(tdim)])) - name = f_component(f_derivatives+_p, f_matrix_index(i, f_r, f_num_derivs(_t))) + name = f_component(f_derivatives+_p, f_matrix_index(p, f_r, f_num_derivs(_t))) lines += [f_assign(name, value)] else: error(""Unknown mapping: %s"" % mapping) ",ffc/evaluatebasisderivatives.py,"ReplaceText(target='p' @(653,64)->(653,65))","def _compute_reference_derivatives(data, dof_data): for k in range(tdim)], [f_transform(""JINV"", k, l, tdim, gdim, None) for k in range(tdim)])) name = f_component(f_derivatives+_p, f_matrix_index(i, f_r, f_num_derivs(_t))) lines += [f_assign(name, value)] else: error(""Unknown mapping: %s"" % mapping)","def _compute_reference_derivatives(data, dof_data): for k in range(tdim)], [f_transform(""JINV"", k, l, tdim, gdim, None) for k in range(tdim)])) name = f_component(f_derivatives+_p, f_matrix_index(p, f_r, f_num_derivs(_t))) lines += [f_assign(name, value)] else: error(""Unknown mapping: %s"" % mapping)" 1138,https://:@bitbucket.org/fenics-project/ffc.git,e6ee433c0854c86b4e38fedf725097c31d9744d5,"@@ -703,7 +703,7 @@ class IntegralGenerator(object): weights = self.backend.symbols.custom_weights_table() weight = weights[iq] else: - weight = self.backend.symbols.weights_table(num_points) + weights = self.backend.symbols.weights_table(num_points) weight = weights[iq] # Fetch code to access modified arguments ",ffc/uflacs/integralgenerator.py,"ReplaceText(target='weights' @(706,12)->(706,18))","class IntegralGenerator(object): weights = self.backend.symbols.custom_weights_table() weight = weights[iq] else: weight = self.backend.symbols.weights_table(num_points) weight = weights[iq] # Fetch code to access modified arguments","class IntegralGenerator(object): weights = self.backend.symbols.custom_weights_table() weight = weights[iq] else: weights = self.backend.symbols.weights_table(num_points) weight = weights[iq] # Fetch code to access modified arguments" 1139,https://:@github.com/Kitware/kwiver.git,19cfcc52be6863217fe227448b8dbfd19d6f63e9,"@@ -209,7 +209,7 @@ def test_datum(): test_error(""Could not initialize pipeline: '%s'"" % str(e)) continue - s = sreg.create_schedule(sched_type, c, p) + s = sreg.create_schedule(sched_type, p, c) try: s.start() ",tests/bindings/python/image/test-vil.py,"ArgSwap(idxs=1<->2 @(212,12)->(212,32))","def test_datum(): test_error(""Could not initialize pipeline: '%s'"" % str(e)) continue s = sreg.create_schedule(sched_type, c, p) try: s.start()","def test_datum(): test_error(""Could not initialize pipeline: '%s'"" % str(e)) continue s = sreg.create_schedule(sched_type, p, c) try: s.start()" 1140,https://:@github.com/Jincheng-Sun/Kylearn-pytorch.git,c4772f2db257170a0c6a456cd71896f6e393f7f5,"@@ -63,7 +63,7 @@ class TextualDataloader(): valid_sampler = SubsetRandomSampler(eval_indices) self.train_loader = DataLoader(train_set, batch_size, sampler=train_sampler, num_workers=4) - self.val_loader = DataLoader(train_set, batch_size, sampler=valid_sampler, num_workers=4) + self.val_loader = DataLoader(test_set, batch_size, sampler=valid_sampler, num_workers=4) self.test_loader = DataLoader(test_set, batch_size, num_workers=4) ",Implementation/nlp_smart_dispatching/dataloader.py,"ReplaceText(target='test_set' @(66,37)->(66,46))","class TextualDataloader(): valid_sampler = SubsetRandomSampler(eval_indices) self.train_loader = DataLoader(train_set, batch_size, sampler=train_sampler, num_workers=4) self.val_loader = DataLoader(train_set, batch_size, sampler=valid_sampler, num_workers=4) self.test_loader = DataLoader(test_set, batch_size, num_workers=4) ","class TextualDataloader(): valid_sampler = SubsetRandomSampler(eval_indices) self.train_loader = DataLoader(train_set, batch_size, sampler=train_sampler, num_workers=4) self.val_loader = DataLoader(test_set, batch_size, sampler=valid_sampler, num_workers=4) self.test_loader = DataLoader(test_set, batch_size, num_workers=4) " 1141,https://:@github.com/itxaka/pychef.git,ef4b72b7d13dab406b21c020a24fefe531f4b859,"@@ -153,7 +153,7 @@ class Key(object): size = RSA_size(self.key) output = create_string_buffer(size) ret = RSA_private_encrypt(len(buf), buf, output, self.key, padding) - if ret == 0: + if ret <= 0: raise SSLError('Unable to encrypt data') return output.raw[:ret] ",chef/rsa.py,"ReplaceText(target='<=' @(156,15)->(156,17))","class Key(object): size = RSA_size(self.key) output = create_string_buffer(size) ret = RSA_private_encrypt(len(buf), buf, output, self.key, padding) if ret == 0: raise SSLError('Unable to encrypt data') return output.raw[:ret] ","class Key(object): size = RSA_size(self.key) output = create_string_buffer(size) ret = RSA_private_encrypt(len(buf), buf, output, self.key, padding) if ret <= 0: raise SSLError('Unable to encrypt data') return output.raw[:ret] " 1142,https://:@github.com/hugobranq/ines.git,1d4af72308bfe0bbe63ec9292583805e26823f0f,"@@ -115,7 +115,7 @@ class PostmanCollection(object): response_key = camelcase(response_key) tests.append( 'if (answer.%s){ postman.setEnvironmentVariable(""%s"", answer.%s); }' - % (environment_key, environment_key, response_key)) + % (response_key, environment_key, response_key)) if tests: tests.insert(0, 'var answer = JSON.parse(responseBody);') ",ines/views/postman.py,"ReplaceText(target='response_key' @(118,39)->(118,54))","class PostmanCollection(object): response_key = camelcase(response_key) tests.append( 'if (answer.%s){ postman.setEnvironmentVariable(""%s"", answer.%s); }' % (environment_key, environment_key, response_key)) if tests: tests.insert(0, 'var answer = JSON.parse(responseBody);')","class PostmanCollection(object): response_key = camelcase(response_key) tests.append( 'if (answer.%s){ postman.setEnvironmentVariable(""%s"", answer.%s); }' % (response_key, environment_key, response_key)) if tests: tests.insert(0, 'var answer = JSON.parse(responseBody);')" 1143,https://:@github.com/hugobranq/ines.git,d0374fc9f5a5003d09c8137a14adb2eb66d3fd30,"@@ -58,7 +58,7 @@ class BaseCoreSessionManager(BaseSessionManager): def not_inactives_filter(column): return and_( or_(column.start_date <= func.now(), column.start_date.is_(None)), - or_(column.end_date >= func.now(), column.end_date.is_(None))) + or_(column.end_date > func.now(), column.end_date.is_(None))) def table_type(table): ",ines/api/core/__init__.py,"ReplaceText(target='>' @(61,28)->(61,30))","class BaseCoreSessionManager(BaseSessionManager): def not_inactives_filter(column): return and_( or_(column.start_date <= func.now(), column.start_date.is_(None)), or_(column.end_date >= func.now(), column.end_date.is_(None))) def table_type(table):","class BaseCoreSessionManager(BaseSessionManager): def not_inactives_filter(column): return and_( or_(column.start_date <= func.now(), column.start_date.is_(None)), or_(column.end_date > func.now(), column.end_date.is_(None))) def table_type(table):" 1144,https://:@github.com/brews/proxysiphon.git,f1acb73417edcbe4011f468ab66f6c53d6d02fcd,"@@ -413,7 +413,7 @@ def lmr_da_dfs(sitegrp=None, agemodel_iter=None, find_modern_seasonality=True): cut_deep = float(sitegrp['chronology'].cut_deep) cut_shallow = -np.inf if hasattr(sitegrp['chronology'], 'cut_shallow'): - cut_deep = float(sitegrp['chronology'].cut_shallow) + cut_shallow = float(sitegrp['chronology'].cut_shallow) depth = sitegrp['data'].variables['depth'][:] cutoff_msk = (depth >= cut_shallow) & (depth <= cut_deep) ",proxysiphon/lmr_hdf5/__init__.py,"ReplaceText(target='cut_shallow' @(416,12)->(416,20))","def lmr_da_dfs(sitegrp=None, agemodel_iter=None, find_modern_seasonality=True): cut_deep = float(sitegrp['chronology'].cut_deep) cut_shallow = -np.inf if hasattr(sitegrp['chronology'], 'cut_shallow'): cut_deep = float(sitegrp['chronology'].cut_shallow) depth = sitegrp['data'].variables['depth'][:] cutoff_msk = (depth >= cut_shallow) & (depth <= cut_deep) ","def lmr_da_dfs(sitegrp=None, agemodel_iter=None, find_modern_seasonality=True): cut_deep = float(sitegrp['chronology'].cut_deep) cut_shallow = -np.inf if hasattr(sitegrp['chronology'], 'cut_shallow'): cut_shallow = float(sitegrp['chronology'].cut_shallow) depth = sitegrp['data'].variables['depth'][:] cutoff_msk = (depth >= cut_shallow) & (depth <= cut_deep) " 1145,https://:@github.com/voytekresearch/bycycle.git,8b521e89226a75f9563a92395e1dfd280cda2e02,"@@ -75,7 +75,7 @@ def find_flank_zerox(sig, flank): """""" assert flank in ['rise', 'decay'] - pos = sig <= 0 if flank == 'rise' else sig >= 0 + pos = sig <= 0 if flank == 'rise' else sig > 0 zero_xs = (pos[:-1] & ~pos[1:]).nonzero()[0] ",bycycle/cyclepoints/zerox.py,"ReplaceText(target='>' @(78,47)->(78,49))","def find_flank_zerox(sig, flank): """""" assert flank in ['rise', 'decay'] pos = sig <= 0 if flank == 'rise' else sig >= 0 zero_xs = (pos[:-1] & ~pos[1:]).nonzero()[0] ","def find_flank_zerox(sig, flank): """""" assert flank in ['rise', 'decay'] pos = sig <= 0 if flank == 'rise' else sig > 0 zero_xs = (pos[:-1] & ~pos[1:]).nonzero()[0] " 1146,https://:@github.com/webcube/django-dockit.git,32c8adda7e11c6bc7e53cabea92e880cc291937f,"@@ -21,7 +21,7 @@ class PrimitiveListWidget(Widget): output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) - i = 0 + i = -1 for i, widget_value in enumerate(value): if id_: final_attrs = dict(final_attrs, id='%s_%s' % (id_, i)) ",dockit/forms/widgets.py,"ReplaceText(target='-1' @(24,12)->(24,13))","class PrimitiveListWidget(Widget): output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) i = 0 for i, widget_value in enumerate(value): if id_: final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))","class PrimitiveListWidget(Widget): output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) i = -1 for i, widget_value in enumerate(value): if id_: final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))" 1147,https://:@github.com/dimchat/sdk-py.git,e0752d614d145ba0a77f87ae06334b891f916c69,"@@ -295,7 +295,7 @@ class Facebook(Barrack): # decrypt key not found, use the same with sign key? key = self.private_key_for_signature(identifier) if key is not None: - keys = [keys] + keys = [key] return keys def contacts(self, identifier: ID) -> Optional[list]: ",dimsdk/facebook.py,"ReplaceText(target='key' @(298,24)->(298,28))","class Facebook(Barrack): # decrypt key not found, use the same with sign key? key = self.private_key_for_signature(identifier) if key is not None: keys = [keys] return keys def contacts(self, identifier: ID) -> Optional[list]:","class Facebook(Barrack): # decrypt key not found, use the same with sign key? key = self.private_key_for_signature(identifier) if key is not None: keys = [key] return keys def contacts(self, identifier: ID) -> Optional[list]:" 1148,https://:@github.com/tnewman/pat.git,ebc0ce494872d7f90e82ca2052d06252a3a0a952,"@@ -15,7 +15,7 @@ def play(audio_path: str): """""" pat_error = _libpat.pat_play(_pat, c_char_p(audio_path.encode('ascii'))) - if pat_error != _PATError.PAT_SUCCESS: + if pat_error == _PATError.PAT_SUCCESS: return elif pat_error == _PATError.PAT_INTERRUPTED_ERROR: os.kill(os.getpid(), signal.SIGINT) ",pypat/pypat/__init__.py,"ReplaceText(target='==' @(18,17)->(18,19))","def play(audio_path: str): """""" pat_error = _libpat.pat_play(_pat, c_char_p(audio_path.encode('ascii'))) if pat_error != _PATError.PAT_SUCCESS: return elif pat_error == _PATError.PAT_INTERRUPTED_ERROR: os.kill(os.getpid(), signal.SIGINT)","def play(audio_path: str): """""" pat_error = _libpat.pat_play(_pat, c_char_p(audio_path.encode('ascii'))) if pat_error == _PATError.PAT_SUCCESS: return elif pat_error == _PATError.PAT_INTERRUPTED_ERROR: os.kill(os.getpid(), signal.SIGINT)" 1149,https://:@github.com/openp2pdesign/platform_analysis.git,526eb0afcc35b076c1860aad48b9a733681e13c7,"@@ -52,7 +52,7 @@ def graph_to_pandas_time_series(graph): ]) # Iterate over edges to create a DataFrame of actions - for i in time_dataframe.edges_iter(data=True): + for i in graph.edges_iter(data=True): if ""node"" in i[2]: node = i[2][""node""] else: ",platform_analysis/sna.py,"ReplaceText(target='graph' @(55,13)->(55,27))","def graph_to_pandas_time_series(graph): ]) # Iterate over edges to create a DataFrame of actions for i in time_dataframe.edges_iter(data=True): if ""node"" in i[2]: node = i[2][""node""] else:","def graph_to_pandas_time_series(graph): ]) # Iterate over edges to create a DataFrame of actions for i in graph.edges_iter(data=True): if ""node"" in i[2]: node = i[2][""node""] else:" 1150,https://:@github.com/jun-harashima/pott.git,31942b58f1aad8a32969c7a1e6ea4184a4f52d4b,"@@ -28,7 +28,7 @@ class Assistant: original_start = self.option.start self.option.start += increment papers = self._search() - if papers: + if not papers: self.option.start = original_start return papers ",pott/assistants/assistant.py,"ReplaceText(target='not ' @(31,11)->(31,11))","class Assistant: original_start = self.option.start self.option.start += increment papers = self._search() if papers: self.option.start = original_start return papers ","class Assistant: original_start = self.option.start self.option.start += increment papers = self._search() if not papers: self.option.start = original_start return papers " 1151,https://:@github.com/Zerostack-open/zs-preflight.git,1a0cc81f539606040222ceb11b7974cd48a30cd7,"@@ -45,7 +45,7 @@ class network_check(): nic_speed = int(speed.read().strip()) if(nic_speed == 1000): nic.append({'nic_name':o,'nic_speed':nic_speed,'nic_brand':nic_brand,'text':'NIC minimum config'}) - elif(nic_speed == 10000): + elif(nic_speed >= 10000): nic.append({'nic_name':o,'nic_speed':nic_speed,'nic_brand':nic_brand,'text':'NIC recommended config'}) except Exception as e: nic.append({'nic_name':o,'nic_speed':'Unknown','nic_brand':nic_brand,'text':'NIC Unknown'}) ",zspreflight/network.py,"ReplaceText(target='>=' @(48,39)->(48,41))","class network_check(): nic_speed = int(speed.read().strip()) if(nic_speed == 1000): nic.append({'nic_name':o,'nic_speed':nic_speed,'nic_brand':nic_brand,'text':'NIC minimum config'}) elif(nic_speed == 10000): nic.append({'nic_name':o,'nic_speed':nic_speed,'nic_brand':nic_brand,'text':'NIC recommended config'}) except Exception as e: nic.append({'nic_name':o,'nic_speed':'Unknown','nic_brand':nic_brand,'text':'NIC Unknown'})","class network_check(): nic_speed = int(speed.read().strip()) if(nic_speed == 1000): nic.append({'nic_name':o,'nic_speed':nic_speed,'nic_brand':nic_brand,'text':'NIC minimum config'}) elif(nic_speed >= 10000): nic.append({'nic_name':o,'nic_speed':nic_speed,'nic_brand':nic_brand,'text':'NIC recommended config'}) except Exception as e: nic.append({'nic_name':o,'nic_speed':'Unknown','nic_brand':nic_brand,'text':'NIC Unknown'})" 1152,https://:@github.com/inkstitch/pyembroidery.git,03f6fded69fc431b28cade51f008de235b09390e,"@@ -9,7 +9,7 @@ MAX_STITCH_DISTANCE = float('inf') def write(pattern, f, settings=None): - if settings is not None: + if settings is None: settings = {} flip_x = settings.get('flip_x', True) ",pyembroidery/GcodeWriter.py,"ReplaceText(target=' is ' @(12,15)->(12,23))","MAX_STITCH_DISTANCE = float('inf') def write(pattern, f, settings=None): if settings is not None: settings = {} flip_x = settings.get('flip_x', True)","MAX_STITCH_DISTANCE = float('inf') def write(pattern, f, settings=None): if settings is None: settings = {} flip_x = settings.get('flip_x', True)" 1153,https://:@github.com/mass-project/mass_api_client.git,aca9dd7184b27be9c14df9d361b8120fd00f40b0,"@@ -34,7 +34,7 @@ class SwitchConnection: @classmethod def _create_instance_from_data(cls, data): subcls = cls._unmodified_cls._search_subclass(data['_cls']) - return subcls(subcls.connection_alias, **data) + return subcls(cls.connection_alias, **data) @classmethod def _deserialize(cls, data, many=False): ",mass_api_client/switch_connection.py,"ReplaceText(target='cls' @(37,30)->(37,36))","class SwitchConnection: @classmethod def _create_instance_from_data(cls, data): subcls = cls._unmodified_cls._search_subclass(data['_cls']) return subcls(subcls.connection_alias, **data) @classmethod def _deserialize(cls, data, many=False):","class SwitchConnection: @classmethod def _create_instance_from_data(cls, data): subcls = cls._unmodified_cls._search_subclass(data['_cls']) return subcls(cls.connection_alias, **data) @classmethod def _deserialize(cls, data, many=False):" 1154,https://:@github.com/pwitab/dlms-cosem.git,6d5eec88b05e0020b437aa13f11f5f807334356a,"@@ -81,4 +81,4 @@ class DlmsUdpMessage: raise ValueError(( f'Length of data in UDP message ({body_length}) does not match ' f'the length parameter in the UDP Wrapper Header ({length})')) - return cls(source_wport, destination_wport, in_data, version) + return cls(source_wport, destination_wport, body, version) ",dlms_cosem/wrappers.py,"ReplaceText(target='body' @(84,52)->(84,59))","class DlmsUdpMessage: raise ValueError(( f'Length of data in UDP message ({body_length}) does not match ' f'the length parameter in the UDP Wrapper Header ({length})')) return cls(source_wport, destination_wport, in_data, version)","class DlmsUdpMessage: raise ValueError(( f'Length of data in UDP message ({body_length}) does not match ' f'the length parameter in the UDP Wrapper Header ({length})')) return cls(source_wport, destination_wport, body, version)" 1155,https://:@github.com/Heiss/connexion-plus.git,df1489bdff879ba6cee2ea7456d503c55e545599,"@@ -26,7 +26,7 @@ class MultipleResourceResolver(RestyResolver): for s in split: # find the parameter, where a variable was defined to exlude it in resource_name pattern = re.compile(r""\{[a-zA-Z-_]+\}"") - if not s and pattern.search(s) is None: + if s and pattern.search(s) is None: resource_name += s.title() if x_router_controller: ",connexion_plus/MultipleResourceResolver.py,"ReplaceText(target='' @(29,19)->(29,23))","class MultipleResourceResolver(RestyResolver): for s in split: # find the parameter, where a variable was defined to exlude it in resource_name pattern = re.compile(r""\{[a-zA-Z-_]+\}"") if not s and pattern.search(s) is None: resource_name += s.title() if x_router_controller:","class MultipleResourceResolver(RestyResolver): for s in split: # find the parameter, where a variable was defined to exlude it in resource_name pattern = re.compile(r""\{[a-zA-Z-_]+\}"") if s and pattern.search(s) is None: resource_name += s.title() if x_router_controller:" 1156,https://:@github.com/kgaughan/imageproxy.git,bfab82a641baf3ecfe4f616a9acad6b05178ff41,"@@ -79,7 +79,7 @@ def is_subpath(base, path, sep=os.path.sep): """""" Check if the given path is a proper subpath of a base path. """""" - if path.startswith(path): + if path.startswith(base): trailing = base[len(base):] return trailing == '' or trailing[0] == sep return False ",imageproxy.py,"ReplaceText(target='base' @(82,23)->(82,27))","def is_subpath(base, path, sep=os.path.sep): """""" Check if the given path is a proper subpath of a base path. """""" if path.startswith(path): trailing = base[len(base):] return trailing == '' or trailing[0] == sep return False","def is_subpath(base, path, sep=os.path.sep): """""" Check if the given path is a proper subpath of a base path. """""" if path.startswith(base): trailing = base[len(base):] return trailing == '' or trailing[0] == sep return False" 1157,https://:@github.com/johnlees/glmnet_python.git,c9b08ed3713f2448017bc041e78324add75196b7,"@@ -117,7 +117,7 @@ def plotCoef(beta, norm, lambdau, df, dev, label, xvar, xlab, ylab, **options): ax2.xaxis.tick_top() xlim1 = ax1.get_xlim() - ylim1 = ax2.get_ylim() + ylim1 = ax1.get_ylim() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer) ",lib/glmnetPlot.py,"ReplaceText(target='ax1' @(120,12)->(120,15))","def plotCoef(beta, norm, lambdau, df, dev, label, xvar, xlab, ylab, **options): ax2.xaxis.tick_top() xlim1 = ax1.get_xlim() ylim1 = ax2.get_ylim() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer)","def plotCoef(beta, norm, lambdau, df, dev, label, xvar, xlab, ylab, **options): ax2.xaxis.tick_top() xlim1 = ax1.get_xlim() ylim1 = ax1.get_ylim() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer)" 1158,https://:@github.com/matheusmoreira/multihash.py.git,57a6c7b3f6fb79e72fac08e39d32202cfd7b5b35,"@@ -24,7 +24,7 @@ class LengthMismatchError(Exception): def __init__(self, multihash_length: int, digest_length: int) -> None: template = ""length from data ({}) and metadata ({}) don't match"" - super().__init__(template.format(multihash_length, digest_length)) + super().__init__(template.format(digest_length, multihash_length)) self.multihash_length = multihash_length self.digest_length = digest_length ",multihash/__init__.py,"ArgSwap(idxs=0<->1 @(27,25)->(27,40))","class LengthMismatchError(Exception): def __init__(self, multihash_length: int, digest_length: int) -> None: template = ""length from data ({}) and metadata ({}) don't match"" super().__init__(template.format(multihash_length, digest_length)) self.multihash_length = multihash_length self.digest_length = digest_length","class LengthMismatchError(Exception): def __init__(self, multihash_length: int, digest_length: int) -> None: template = ""length from data ({}) and metadata ({}) don't match"" super().__init__(template.format(digest_length, multihash_length)) self.multihash_length = multihash_length self.digest_length = digest_length" 1159,https://:@github.com/pytest-buildkite/pipefish.git,4ba4918fbd000b6c8f8c7d266d79b0e09b85dd11,"@@ -39,7 +39,7 @@ def read_version(): for line in fobj: mobj = regex.match(line) if mobj: - return regex.group(1) + return mobj.group(1) raise Exception('Failed to read version') ",app/setup.py,"ReplaceText(target='mobj' @(42,23)->(42,28))","def read_version(): for line in fobj: mobj = regex.match(line) if mobj: return regex.group(1) raise Exception('Failed to read version') ","def read_version(): for line in fobj: mobj = regex.match(line) if mobj: return mobj.group(1) raise Exception('Failed to read version') " 1160,https://:@github.com/kmarilleau/pytest-django-model.git,31fa2011c76bd1581d24bef19f422cebf644b03d,"@@ -237,7 +237,7 @@ class ModelGenerator: # Ignore Special Methods. or is_dunder(attr) # Ignore Functions. - or inspect.isfunction(attr) + or inspect.isfunction(value) # Ignore Django Model Attributes. or attr in (""objects"", ""id"", ""_meta"") # Ignore Fields. ",pytest_django_model/objects.py,"ReplaceText(target='value' @(240,34)->(240,38))","class ModelGenerator: # Ignore Special Methods. or is_dunder(attr) # Ignore Functions. or inspect.isfunction(attr) # Ignore Django Model Attributes. or attr in (""objects"", ""id"", ""_meta"") # Ignore Fields.","class ModelGenerator: # Ignore Special Methods. or is_dunder(attr) # Ignore Functions. or inspect.isfunction(value) # Ignore Django Model Attributes. or attr in (""objects"", ""id"", ""_meta"") # Ignore Fields." 1161,https://:@github.com/innolitics/hdat.git,536b4c0b60a57b2a0d7aa95bf3a8e0a484a2a0c2,"@@ -31,7 +31,7 @@ class Archive: results_sorted = sorted(results, key=lambda r: r['ran_on']) - return results + return results_sorted def insert(self, result): suite_id = result['suite_id'] ",store.py,"ReplaceText(target='results_sorted' @(34,15)->(34,22))","class Archive: results_sorted = sorted(results, key=lambda r: r['ran_on']) return results def insert(self, result): suite_id = result['suite_id']","class Archive: results_sorted = sorted(results, key=lambda r: r['ran_on']) return results_sorted def insert(self, result): suite_id = result['suite_id']" 1162,https://:@github.com/innolitics/hdat.git,37beec7e4e98b5787f87cb083d512c872a9a2ae6,"@@ -26,7 +26,7 @@ def main(): golden_store_location = os.path.join(repo_directory, 'golden_results') golden_store = GoldenStore(golden_store_location) - suites = collect_suites(cwd) + suites = collect_suites(repo_directory) hdat_cli(sys.argv[1:], suites, golden_store, archive, git_info) ",hdat/main.py,"ReplaceText(target='repo_directory' @(29,32)->(29,35))","def main(): golden_store_location = os.path.join(repo_directory, 'golden_results') golden_store = GoldenStore(golden_store_location) suites = collect_suites(cwd) hdat_cli(sys.argv[1:], suites, golden_store, archive, git_info) ","def main(): golden_store_location = os.path.join(repo_directory, 'golden_results') golden_store = GoldenStore(golden_store_location) suites = collect_suites(repo_directory) hdat_cli(sys.argv[1:], suites, golden_store, archive, git_info) " 1163,https://:@github.com/innolitics/hdat.git,1756c0c9966de2746b1775521771d820004ae859,"@@ -26,7 +26,7 @@ def main(): golden_store_location = os.path.join(repo_directory, 'golden_results') golden_store = GoldenStore(golden_store_location) - suites = collect_suites(cwd) + suites = collect_suites(repo_directory) hdat_cli(sys.argv[1:], suites, golden_store, archive, git_info) ",hdat/main.py,"ReplaceText(target='repo_directory' @(29,32)->(29,35))","def main(): golden_store_location = os.path.join(repo_directory, 'golden_results') golden_store = GoldenStore(golden_store_location) suites = collect_suites(cwd) hdat_cli(sys.argv[1:], suites, golden_store, archive, git_info) ","def main(): golden_store_location = os.path.join(repo_directory, 'golden_results') golden_store = GoldenStore(golden_store_location) suites = collect_suites(repo_directory) hdat_cli(sys.argv[1:], suites, golden_store, archive, git_info) " 1164,https://:@github.com/reversefold/celery.git,e16932c6b10a0c3fa1b8eda202d857b7e8157f4a,"@@ -71,7 +71,7 @@ def _get(name, default=None, compat=None): compat = [name] + compat for i, alias in enumerate(compat): try: - value = getattr(settings, name) + value = getattr(settings, alias) i > 0 and warnings.warn(DeprecationWarning(_DEPRECATION_FMT % ( alias, name))) return value ",celery/conf.py,"ReplaceText(target='alias' @(74,38)->(74,42))","def _get(name, default=None, compat=None): compat = [name] + compat for i, alias in enumerate(compat): try: value = getattr(settings, name) i > 0 and warnings.warn(DeprecationWarning(_DEPRECATION_FMT % ( alias, name))) return value","def _get(name, default=None, compat=None): compat = [name] + compat for i, alias in enumerate(compat): try: value = getattr(settings, alias) i > 0 and warnings.warn(DeprecationWarning(_DEPRECATION_FMT % ( alias, name))) return value" 1165,https://:@github.com/reversefold/celery.git,b0f42919f173005265e9880d30d166db734ff9c7,"@@ -43,7 +43,7 @@ class Router(object): route = self.lookup_route(task, args, kwargs) if route: # Also expand ""queue"" keys in route. - return merge(options, self.expand_destination(route)) + return merge(self.expand_destination(route), options) return options def expand_destination(self, route): ",celery/routes.py,"ArgSwap(idxs=0<->1 @(46,23)->(46,28))","class Router(object): route = self.lookup_route(task, args, kwargs) if route: # Also expand ""queue"" keys in route. return merge(options, self.expand_destination(route)) return options def expand_destination(self, route):","class Router(object): route = self.lookup_route(task, args, kwargs) if route: # Also expand ""queue"" keys in route. return merge(self.expand_destination(route), options) return options def expand_destination(self, route):" 1166,https://:@github.com/reversefold/celery.git,d47ae1389c4cb679a13057e24c82ede7581b4ab1,"@@ -155,7 +155,7 @@ class Namespace(object): return self.close(parent) self.state = CLOSE - self.restart(parent, what, 'terminate' if terminate else 'stop') + self.restart(parent, 'terminate' if terminate else 'stop', what) if self.on_stopped: self.on_stopped() ",celery/bootsteps.py,"ArgSwap(idxs=1<->2 @(158,8)->(158,20))","class Namespace(object): return self.close(parent) self.state = CLOSE self.restart(parent, what, 'terminate' if terminate else 'stop') if self.on_stopped: self.on_stopped()","class Namespace(object): return self.close(parent) self.state = CLOSE self.restart(parent, 'terminate' if terminate else 'stop', what) if self.on_stopped: self.on_stopped()" 1167,https://:@github.com/reversefold/celery.git,551546ceaecb5afdf3a848604faa57117e0a2c1a,"@@ -182,7 +182,7 @@ class test_Tasks(AppCase): tasks = Tasks(c) self.assertIsNone(c.task_consumer) self.assertIsNone(c.qos) - self.assertEqual(tasks.initial_prefetch_count, 2) + self.assertEqual(c.initial_prefetch_count, 2) c.task_consumer = Mock() tasks.stop(c) ",celery/tests/worker/test_consumer.py,"ReplaceText(target='c' @(185,25)->(185,30))","class test_Tasks(AppCase): tasks = Tasks(c) self.assertIsNone(c.task_consumer) self.assertIsNone(c.qos) self.assertEqual(tasks.initial_prefetch_count, 2) c.task_consumer = Mock() tasks.stop(c)","class test_Tasks(AppCase): tasks = Tasks(c) self.assertIsNone(c.task_consumer) self.assertIsNone(c.qos) self.assertEqual(c.initial_prefetch_count, 2) c.task_consumer = Mock() tasks.stop(c)" 1168,https://:@github.com/reversefold/celery.git,1ac10f3b8f2bc0a21b7e418ee6c967df614bd106,"@@ -91,7 +91,7 @@ class RiakBackend(KeyValueStoreBackend): self.host = uhost or config.get('host', self.host) self.port = int(uport or config.get('port', self.port)) self.bucket_name = ubucket or config.get('bucket', self.bucket_name) - self.protocol = uprot or config.get('protocol', self.protocol) + self.protocol = protocol or config.get('protocol', self.protocol) # riak bucket must be ascii letters or numbers only if not Validators.validate_riak_bucket_name(self.bucket_name): ",celery/backends/riak.py,"ReplaceText(target='protocol' @(94,24)->(94,29))","class RiakBackend(KeyValueStoreBackend): self.host = uhost or config.get('host', self.host) self.port = int(uport or config.get('port', self.port)) self.bucket_name = ubucket or config.get('bucket', self.bucket_name) self.protocol = uprot or config.get('protocol', self.protocol) # riak bucket must be ascii letters or numbers only if not Validators.validate_riak_bucket_name(self.bucket_name):","class RiakBackend(KeyValueStoreBackend): self.host = uhost or config.get('host', self.host) self.port = int(uport or config.get('port', self.port)) self.bucket_name = ubucket or config.get('bucket', self.bucket_name) self.protocol = protocol or config.get('protocol', self.protocol) # riak bucket must be ascii letters or numbers only if not Validators.validate_riak_bucket_name(self.bucket_name):" 1169,https://:@github.com/reversefold/celery.git,51592a86a35998d40098db72524ba70299c5c489,"@@ -273,7 +273,7 @@ class Celery(object): if not module_name: if silent: return False - raise ImproperlyConfigured(ERR_ENVVAR_NOT_SET.format(module_name)) + raise ImproperlyConfigured(ERR_ENVVAR_NOT_SET.format(variable_name)) return self.config_from_object(module_name, silent=silent, force=force) def config_from_cmdline(self, argv, namespace='celery'): ",celery/app/base.py,"ReplaceText(target='variable_name' @(276,65)->(276,76))","class Celery(object): if not module_name: if silent: return False raise ImproperlyConfigured(ERR_ENVVAR_NOT_SET.format(module_name)) return self.config_from_object(module_name, silent=silent, force=force) def config_from_cmdline(self, argv, namespace='celery'):","class Celery(object): if not module_name: if silent: return False raise ImproperlyConfigured(ERR_ENVVAR_NOT_SET.format(variable_name)) return self.config_from_object(module_name, silent=silent, force=force) def config_from_cmdline(self, argv, namespace='celery'):" 1170,https://:@github.com/reversefold/celery.git,d5029501ab762c4fb6b7baab7af4ecf96b106fbe,"@@ -174,7 +174,7 @@ def create_module(name, attrs, cls_attrs=None, pkg=None, attr_name: (prepare_attr(attr) if prepare_attr else attr) for attr_name, attr in items(attrs) } - module = sys.modules[fqdn] = type(modname, (base, ), cls_attrs)(fqdn) + module = sys.modules[fqdn] = type(modname, (base, ), cls_attrs)(name) module.__dict__.update(attrs) return module ",celery/five.py,"ReplaceText(target='name' @(177,68)->(177,72))","def create_module(name, attrs, cls_attrs=None, pkg=None, attr_name: (prepare_attr(attr) if prepare_attr else attr) for attr_name, attr in items(attrs) } module = sys.modules[fqdn] = type(modname, (base, ), cls_attrs)(fqdn) module.__dict__.update(attrs) return module ","def create_module(name, attrs, cls_attrs=None, pkg=None, attr_name: (prepare_attr(attr) if prepare_attr else attr) for attr_name, attr in items(attrs) } module = sys.modules[fqdn] = type(modname, (base, ), cls_attrs)(name) module.__dict__.update(attrs) return module " 1171,https://:@github.com/reversefold/celery.git,86e7eed314a167ec0f2fa377f36f0f373a334d77,"@@ -303,7 +303,7 @@ class Request(object): task_ready(self) if soft: warn('Soft time limit (%ss) exceeded for %s[%s]', - soft, self.name, self.id) + timeout, self.name, self.id) exc = SoftTimeLimitExceeded(soft) else: error('Hard time limit (%ss) exceeded for %s[%s]', ",celery/worker/request.py,"ReplaceText(target='timeout' @(306,17)->(306,21))","class Request(object): task_ready(self) if soft: warn('Soft time limit (%ss) exceeded for %s[%s]', soft, self.name, self.id) exc = SoftTimeLimitExceeded(soft) else: error('Hard time limit (%ss) exceeded for %s[%s]',","class Request(object): task_ready(self) if soft: warn('Soft time limit (%ss) exceeded for %s[%s]', timeout, self.name, self.id) exc = SoftTimeLimitExceeded(soft) else: error('Hard time limit (%ss) exceeded for %s[%s]'," 1172,https://:@gitlab.com/elad.noor/optslope.git,c810fd18febb83e0212b5a5404dcc82758322541,"@@ -79,7 +79,7 @@ def create_extended_core_model( for ki in knockins: add_cytoplasmic_reaction(model, ki, 0, 1000) - if knockins is not None: + if carbon_sources is not None: for cs in carbon_sources: add_metabolite_exchange(model, cs) ",optslope/models.py,"ReplaceText(target='carbon_sources' @(82,7)->(82,15))","def create_extended_core_model( for ki in knockins: add_cytoplasmic_reaction(model, ki, 0, 1000) if knockins is not None: for cs in carbon_sources: add_metabolite_exchange(model, cs) ","def create_extended_core_model( for ki in knockins: add_cytoplasmic_reaction(model, ki, 0, 1000) if carbon_sources is not None: for cs in carbon_sources: add_metabolite_exchange(model, cs) " 1173,https://:@github.com/jamesjiang52/Bitwise.git,796301ae466d418612c6ac291ea9838d7a51ce70,"@@ -7,7 +7,7 @@ class TestTristateBuffer: switch = bw.wire.Wire() output = bw.wire.Wire() - bw.wire.TristateBuffer(input_1, switch, output) + bw.wire.TristateBuffer(switch, input_1, output) switch.value = 0 input_1.value = 0 ",tests/wire/test_TristateBuffer.py,"ArgSwap(idxs=0<->1 @(10,8)->(10,30))","class TestTristateBuffer: switch = bw.wire.Wire() output = bw.wire.Wire() bw.wire.TristateBuffer(input_1, switch, output) switch.value = 0 input_1.value = 0","class TestTristateBuffer: switch = bw.wire.Wire() output = bw.wire.Wire() bw.wire.TristateBuffer(switch, input_1, output) switch.value = 0 input_1.value = 0" 1174,https://:@github.com/jamesjiang52/Bitwise.git,e7fb994abf6b7e9d85cf5b8f3d2b199a717d281b,"@@ -82,7 +82,7 @@ class FullAdder: self.carry_in = carry_in self.a = a - self.b = a + self.b = b self.carry_out = carry_out self.sum = sum ",bitwise/arithmetic/ADD.py,"ReplaceText(target='b' @(85,17)->(85,18))","class FullAdder: self.carry_in = carry_in self.a = a self.b = a self.carry_out = carry_out self.sum = sum ","class FullAdder: self.carry_in = carry_in self.a = a self.b = b self.carry_out = carry_out self.sum = sum " 1175,https://:@github.com/sethmurphy/BrubeckOAuth.git,62f218940e723171c3d32115389d3c07c86effb5,"@@ -269,7 +269,7 @@ class OAuthMixin(object): initial_args = json.loads(self.oauth_request_model.initial_request_args) self.message.arguments.update(initial_args) logging.debug('Merged arguments: %s' % json.dumps(self.message.arguments)); - if self.oauth_error != None and self.oauth_token != None or self.state != None: + if self.oauth_error == None and self.oauth_token != None or self.state != None: self._oauth_request_model = oauth_object.callback( provider_settings, self.oauth_request_model, ",brubeckoauth/handlers.py,"ReplaceText(target='==' @(272,36)->(272,38))","class OAuthMixin(object): initial_args = json.loads(self.oauth_request_model.initial_request_args) self.message.arguments.update(initial_args) logging.debug('Merged arguments: %s' % json.dumps(self.message.arguments)); if self.oauth_error != None and self.oauth_token != None or self.state != None: self._oauth_request_model = oauth_object.callback( provider_settings, self.oauth_request_model, ","class OAuthMixin(object): initial_args = json.loads(self.oauth_request_model.initial_request_args) self.message.arguments.update(initial_args) logging.debug('Merged arguments: %s' % json.dumps(self.message.arguments)); if self.oauth_error == None and self.oauth_token != None or self.state != None: self._oauth_request_model = oauth_object.callback( provider_settings, self.oauth_request_model, " 1176,https://:@bitbucket.org/mosaik/mosaik-pypower.git,d05f00ae723c45cccabf1ffc75317f96f74176c5,"@@ -185,7 +185,7 @@ def _get_branches(loader, raw_case, entity_map, grid_idx): tbus = make_eid(tbus, grid_idx) assert fbus in entity_map, fbus - assert tbus in entity_map, fbus + assert tbus in entity_map, tbus f_idx = entity_map[fbus]['idx'] t_idx = entity_map[tbus]['idx'] ",mosaik_pypower/model.py,"ReplaceText(target='tbus' @(188,35)->(188,39))","def _get_branches(loader, raw_case, entity_map, grid_idx): tbus = make_eid(tbus, grid_idx) assert fbus in entity_map, fbus assert tbus in entity_map, fbus f_idx = entity_map[fbus]['idx'] t_idx = entity_map[tbus]['idx']","def _get_branches(loader, raw_case, entity_map, grid_idx): tbus = make_eid(tbus, grid_idx) assert fbus in entity_map, fbus assert tbus in entity_map, tbus f_idx = entity_map[fbus]['idx'] t_idx = entity_map[tbus]['idx']" 1177,https://:@bitbucket.org/mosaik/mosaik-pypower.git,8440caae0cc2ac9f18087171866abcf2ee1783b6,"@@ -131,7 +131,7 @@ def get_cache_entries(cases, entity_map): # Use side with higher voltage to calculate I if fbus_v >= tbus_v: ir = branch[idx_brch.PF] / fbus_v - ii = branch[idx_brch.QF] / tbus_v + ii = branch[idx_brch.QF] / fbus_v else: ir = branch[idx_brch.PT] / tbus_v ii = branch[idx_brch.QT] / tbus_v ",mosaik_pypower/model.py,"ReplaceText(target='fbus_v' @(134,51)->(134,57))","def get_cache_entries(cases, entity_map): # Use side with higher voltage to calculate I if fbus_v >= tbus_v: ir = branch[idx_brch.PF] / fbus_v ii = branch[idx_brch.QF] / tbus_v else: ir = branch[idx_brch.PT] / tbus_v ii = branch[idx_brch.QT] / tbus_v","def get_cache_entries(cases, entity_map): # Use side with higher voltage to calculate I if fbus_v >= tbus_v: ir = branch[idx_brch.PF] / fbus_v ii = branch[idx_brch.QF] / fbus_v else: ir = branch[idx_brch.PT] / tbus_v ii = branch[idx_brch.QT] / tbus_v" 1178,https://:@github.com/moble/sxs.git,4b224cf7771980d6817413d8d218858ea972a94e,"@@ -34,7 +34,7 @@ def test_xmb_format(): with tempfile.TemporaryDirectory() as temp_dir: file = pathlib.Path(temp_dir) / 'horizons.h5' - sxs.horizons.xor_multishuffle_bzip2.save(file, horizons_spec) + sxs.horizons.xor_multishuffle_bzip2.save(horizons_spec, file) with pytest.raises(ValueError): horizons_error = sxs.horizons.spec_horizons_h5.load(file) horizons_xmb = sxs.horizons.xor_multishuffle_bzip2.load(file) ",tests/test_horizons.py,"ArgSwap(idxs=0<->1 @(37,8)->(37,48))","def test_xmb_format(): with tempfile.TemporaryDirectory() as temp_dir: file = pathlib.Path(temp_dir) / 'horizons.h5' sxs.horizons.xor_multishuffle_bzip2.save(file, horizons_spec) with pytest.raises(ValueError): horizons_error = sxs.horizons.spec_horizons_h5.load(file) horizons_xmb = sxs.horizons.xor_multishuffle_bzip2.load(file)","def test_xmb_format(): with tempfile.TemporaryDirectory() as temp_dir: file = pathlib.Path(temp_dir) / 'horizons.h5' sxs.horizons.xor_multishuffle_bzip2.save(horizons_spec, file) with pytest.raises(ValueError): horizons_error = sxs.horizons.spec_horizons_h5.load(file) horizons_xmb = sxs.horizons.xor_multishuffle_bzip2.load(file)" 1179,https://:@github.com/inkenbrandt/loggerloader.git,4a64ce022708c6e5c93124cf250d59bded529624,"@@ -80,7 +80,7 @@ def fix_drift(well, manualfile, meas='Level', manmeas='MeasuredDTW', outcolname= wellbarofixed.set_index(dtnm, inplace=True) drift_info = pd.DataFrame(drift_features).T - return wellbarofixed, drift_info + return wellbarofixed, drift def correct_be(site_number, well_table, welldata, be = None, meas = 'corrwl', baro = 'barometer'): ",loggerloader/data_fixers.py,"ReplaceText(target='drift' @(83,26)->(83,36))","def fix_drift(well, manualfile, meas='Level', manmeas='MeasuredDTW', outcolname= wellbarofixed.set_index(dtnm, inplace=True) drift_info = pd.DataFrame(drift_features).T return wellbarofixed, drift_info def correct_be(site_number, well_table, welldata, be = None, meas = 'corrwl', baro = 'barometer'): ","def fix_drift(well, manualfile, meas='Level', manmeas='MeasuredDTW', outcolname= wellbarofixed.set_index(dtnm, inplace=True) drift_info = pd.DataFrame(drift_features).T return wellbarofixed, drift def correct_be(site_number, well_table, welldata, be = None, meas = 'corrwl', baro = 'barometer'): " 1180,https://:@gitlab.com/Plasticity/supersqlite.git,e6dbaa2a00df2020b62ce72329b5b294762c23a4,"@@ -119,7 +119,7 @@ def get_modules(THIRD_PARTY, INTERNAL, PROJ_PATH, else: libraries.append(ICU_UNIX) includes.append(ICU_UNIX) - link_args.append('-L' + ICU_WIN32) + link_args.append('-L' + ICU_UNIX) SQLITE_PRE = os.path.relpath( os.path.join(SQLITE3, 'sqlite3.c.pre.c'), PROJ_PATH) ",setup.py,"ReplaceText(target='ICU_UNIX' @(122,32)->(122,41))","def get_modules(THIRD_PARTY, INTERNAL, PROJ_PATH, else: libraries.append(ICU_UNIX) includes.append(ICU_UNIX) link_args.append('-L' + ICU_WIN32) SQLITE_PRE = os.path.relpath( os.path.join(SQLITE3, 'sqlite3.c.pre.c'), PROJ_PATH)","def get_modules(THIRD_PARTY, INTERNAL, PROJ_PATH, else: libraries.append(ICU_UNIX) includes.append(ICU_UNIX) link_args.append('-L' + ICU_UNIX) SQLITE_PRE = os.path.relpath( os.path.join(SQLITE3, 'sqlite3.c.pre.c'), PROJ_PATH)" 1181,https://:@github.com/jboes/decaf-espresso.git,807549a48404ee3028f5935b8ddfa665378add29,"@@ -384,7 +384,7 @@ class SiteConfig(): state = subprocess.call(command, stdout=f) if state != 0: - if grepy(outfile, 'JOB DONE.'): + if grepy('JOB DONE.', outfile): pass else: raise RuntimeError( ",espresso/siteconfig.py,"ArgSwap(idxs=0<->1 @(387,15)->(387,20))","class SiteConfig(): state = subprocess.call(command, stdout=f) if state != 0: if grepy(outfile, 'JOB DONE.'): pass else: raise RuntimeError(","class SiteConfig(): state = subprocess.call(command, stdout=f) if state != 0: if grepy('JOB DONE.', outfile): pass else: raise RuntimeError(" 1182,https://:@github.com/Aareon/rtv.git,3e6b7c98d529668d5cab946485bd7c3be843574c,"@@ -126,7 +126,7 @@ class SubredditPage(BasePage): return # Open the submission window - submission_info = SUBMISSION_FILE.format(name=sub, content='') + submission_info = SUBMISSION_FILE.format(name=subreddit, content='') curses.endwin() submission_text = open_editor(submission_info) curses.doupdate() ",rtv/subreddit.py,"ReplaceText(target='subreddit' @(129,54)->(129,57))","class SubredditPage(BasePage): return # Open the submission window submission_info = SUBMISSION_FILE.format(name=sub, content='') curses.endwin() submission_text = open_editor(submission_info) curses.doupdate()","class SubredditPage(BasePage): return # Open the submission window submission_info = SUBMISSION_FILE.format(name=subreddit, content='') curses.endwin() submission_text = open_editor(submission_info) curses.doupdate()" 1183,https://:@github.com/Aareon/rtv.git,f5dab8dd560dc319cf23724653de376bdc850e10,"@@ -813,7 +813,7 @@ class Terminal(object): # Prune empty lines at the bottom of the textbox. for item in stack[::-1]: - if item: + if not item: stack.pop() else: break ",rtv/terminal.py,"ReplaceText(target='not ' @(816,15)->(816,15))","class Terminal(object): # Prune empty lines at the bottom of the textbox. for item in stack[::-1]: if item: stack.pop() else: break","class Terminal(object): # Prune empty lines at the bottom of the textbox. for item in stack[::-1]: if not item: stack.pop() else: break" 1184,https://:@github.com/kgdunn/process_improve.git,098e24ca8653f3b94be6f8efcc584f149bb9d8db,"@@ -143,7 +143,7 @@ def pareto_plot(model, (""Full name"", ""@full_names""), (""Magnitude and sign"", ""@original_magnitude_with_sign""), ] - if len(alias_strings) == 0: + if len(alias_strings) != 0: TOOLTIPS.append((""Aliasing"", ""@alias_strings""),) p = figure(plot_width=plot_width, ",process_improve/plotting.py,"ReplaceText(target='!=' @(146,26)->(146,28))","def pareto_plot(model, (""Full name"", ""@full_names""), (""Magnitude and sign"", ""@original_magnitude_with_sign""), ] if len(alias_strings) == 0: TOOLTIPS.append((""Aliasing"", ""@alias_strings""),) p = figure(plot_width=plot_width,","def pareto_plot(model, (""Full name"", ""@full_names""), (""Magnitude and sign"", ""@original_magnitude_with_sign""), ] if len(alias_strings) != 0: TOOLTIPS.append((""Aliasing"", ""@alias_strings""),) p = figure(plot_width=plot_width," 1185,https://:@github.com/gforcada/flake8-plone-api.git,dd24cd9846350da8e176296f0c5e51d285c101b6,"@@ -35,7 +35,7 @@ class PloneAPIChecker(object): return found next_character_position = found + len(old_approach) + 1 - if next_character_position > len(line): + if next_character_position >= len(line): return found # check that the method is not a substring of another ",flake8_plone_api.py,"ReplaceText(target='>=' @(38,35)->(38,36))","class PloneAPIChecker(object): return found next_character_position = found + len(old_approach) + 1 if next_character_position > len(line): return found # check that the method is not a substring of another","class PloneAPIChecker(object): return found next_character_position = found + len(old_approach) + 1 if next_character_position >= len(line): return found # check that the method is not a substring of another" 1186,https://:@github.com/prymatex/prymatex.git,1b830e8afa9b956c4a603f2f44c20d7ce87f2fb9,"@@ -779,7 +779,7 @@ class PMXSnippet(PMXBundleItem): return hash def __deepcopy__(self, memo): - snippet = PMXSnippet(self.hash, self.namespace) + snippet = PMXSnippet(self.namespace, self.hash) memo[""snippet""] = deepcopy(self.snippet, memo) snippet.bundle = self.bundle return snippet ",src/prymatex/bundles/snippet.py,"ArgSwap(idxs=0<->1 @(782,18)->(782,28))","class PMXSnippet(PMXBundleItem): return hash def __deepcopy__(self, memo): snippet = PMXSnippet(self.hash, self.namespace) memo[""snippet""] = deepcopy(self.snippet, memo) snippet.bundle = self.bundle return snippet","class PMXSnippet(PMXBundleItem): return hash def __deepcopy__(self, memo): snippet = PMXSnippet(self.namespace, self.hash) memo[""snippet""] = deepcopy(self.snippet, memo) snippet.bundle = self.bundle return snippet" 1187,https://:@github.com/prymatex/prymatex.git,1595b520a888b1d6635d2bb64c99024ef06d0d7e,"@@ -43,7 +43,7 @@ class PMXBundleTreeProxyModel(QtGui.QSortFilterProxyModel): return self.sourceModel().node(sIndex) def setFilterNamespace(self, namespace): - if namespace: + if not namespace: self.namespacesFilter = [ ""prymatex"", ""user"" ] else: self.namespacesFilter = namespace.split() ",prymatex/gui/support/proxies.py,"ReplaceText(target='not ' @(46,11)->(46,11))","class PMXBundleTreeProxyModel(QtGui.QSortFilterProxyModel): return self.sourceModel().node(sIndex) def setFilterNamespace(self, namespace): if namespace: self.namespacesFilter = [ ""prymatex"", ""user"" ] else: self.namespacesFilter = namespace.split()","class PMXBundleTreeProxyModel(QtGui.QSortFilterProxyModel): return self.sourceModel().node(sIndex) def setFilterNamespace(self, namespace): if not namespace: self.namespacesFilter = [ ""prymatex"", ""user"" ] else: self.namespacesFilter = namespace.split()" 1188,https://:@github.com/prymatex/prymatex.git,8bc4aeccf489096d05f1b8fb2a6ad57d75a3f7fd,"@@ -359,7 +359,7 @@ class CodeEditor(TextEditWidget, PMXBaseEditor): cls.SCOPES[scopeHash] = CodeEditorScope( name = scopeName, path = scopeStack, - settings = cls.application.supportManager.getPreferenceSettings(scopeName), + settings = cls.application.supportManager.getPreferenceSettings(scopeStack), group = PMXSyntax.findGroup(scopeStack[::-1]) ) return scopeHash ",prymatex/gui/codeeditor/editor.py,"ReplaceText(target='scopeStack' @(362,80)->(362,89))","class CodeEditor(TextEditWidget, PMXBaseEditor): cls.SCOPES[scopeHash] = CodeEditorScope( name = scopeName, path = scopeStack, settings = cls.application.supportManager.getPreferenceSettings(scopeName), group = PMXSyntax.findGroup(scopeStack[::-1]) ) return scopeHash","class CodeEditor(TextEditWidget, PMXBaseEditor): cls.SCOPES[scopeHash] = CodeEditorScope( name = scopeName, path = scopeStack, settings = cls.application.supportManager.getPreferenceSettings(scopeStack), group = PMXSyntax.findGroup(scopeStack[::-1]) ) return scopeHash" 1189,https://:@github.com/prymatex/prymatex.git,5e2aeb256ab658a0ef392096ae4c6cea383e4fff,"@@ -61,7 +61,7 @@ class CodeEditorBlockUserData(QtGui.QTextBlockUserData): def tokenAtPosition(self, pos): for token in self.__tokens[::-1]: - if token.start <= pos <= token.end: + if token.start <= pos < token.end: return token # ------------------- Cache Handle ",prymatex/gui/codeeditor/userdata.py,"ReplaceText(target='<' @(64,34)->(64,36))","class CodeEditorBlockUserData(QtGui.QTextBlockUserData): def tokenAtPosition(self, pos): for token in self.__tokens[::-1]: if token.start <= pos <= token.end: return token # ------------------- Cache Handle","class CodeEditorBlockUserData(QtGui.QTextBlockUserData): def tokenAtPosition(self, pos): for token in self.__tokens[::-1]: if token.start <= pos < token.end: return token # ------------------- Cache Handle" 1190,https://:@github.com/prymatex/prymatex.git,4aaa53c919b90ec7d094d6861b9c229fd282c26d,"@@ -72,7 +72,7 @@ class CodeEditorSyntaxProcessor(CodeEditorBaseProcessor, SyntaxProcessorMixin): self.stacks[user_data.revision] = (self.stack[:], self.scope.clone()) def blockRevision(self, block): - return _revision(block.text() + ""\n"", self.scope_name, block.previous().userState()) + return _revision(self.scope_name, block.text() + ""\n"", block.previous().userState()) def testRevision(self, block): return block.userData() is not None and block.userData().revision == self.blockRevision(block) ",prymatex/gui/codeeditor/processors/syntax.py,"ArgSwap(idxs=0<->1 @(75,15)->(75,24))","class CodeEditorSyntaxProcessor(CodeEditorBaseProcessor, SyntaxProcessorMixin): self.stacks[user_data.revision] = (self.stack[:], self.scope.clone()) def blockRevision(self, block): return _revision(block.text() + ""\n"", self.scope_name, block.previous().userState()) def testRevision(self, block): return block.userData() is not None and block.userData().revision == self.blockRevision(block)","class CodeEditorSyntaxProcessor(CodeEditorBaseProcessor, SyntaxProcessorMixin): self.stacks[user_data.revision] = (self.stack[:], self.scope.clone()) def blockRevision(self, block): return _revision(self.scope_name, block.text() + ""\n"", block.previous().userState()) def testRevision(self, block): return block.userData() is not None and block.userData().revision == self.blockRevision(block)" 1191,https://:@github.com/cdeitrick/muller_diagrams.git,fd5e9df63b9a5c558c6d88f646a5003e3d959402,"@@ -58,7 +58,7 @@ DF = pandas.DataFrame def workflow(trajectories_filename: Path, goptions:calculate_genotypes.GenotypeOptions) -> Tuple[DF, DF, Any]: trajectory_table, _ = import_trajectory_table(trajectories_filename) - genotype_table = calculate_genotypes.workflow(trajectories_filename, options = goptions) + genotype_table = calculate_genotypes.workflow(trajectory_table, options = goptions) # return trajectory_table, genotype_table cache:List[Tuple[DF, DF]] = [(trajectory_table.copy(), genotype_table.copy())] ",muller/genotype_filters.py,"ReplaceText(target='trajectory_table' @(61,47)->(61,68))","DF = pandas.DataFrame def workflow(trajectories_filename: Path, goptions:calculate_genotypes.GenotypeOptions) -> Tuple[DF, DF, Any]: trajectory_table, _ = import_trajectory_table(trajectories_filename) genotype_table = calculate_genotypes.workflow(trajectories_filename, options = goptions) # return trajectory_table, genotype_table cache:List[Tuple[DF, DF]] = [(trajectory_table.copy(), genotype_table.copy())]","DF = pandas.DataFrame def workflow(trajectories_filename: Path, goptions:calculate_genotypes.GenotypeOptions) -> Tuple[DF, DF, Any]: trajectory_table, _ = import_trajectory_table(trajectories_filename) genotype_table = calculate_genotypes.workflow(trajectory_table, options = goptions) # return trajectory_table, genotype_table cache:List[Tuple[DF, DF]] = [(trajectory_table.copy(), genotype_table.copy())]" 1192,https://:@github.com/MacKey-255/GoodByeCatpcha.git,39bd93f737d90c82906fdd388a9f8d2e5939bfa5,"@@ -64,7 +64,7 @@ class Launcher(launcher.Launcher): def waitForChromeToClose(self): """"""Terminate chrome."""""" - if self.proc.returncode is not None and not self.chromeClosed: + if self.proc.returncode is None and not self.chromeClosed: self.chromeClosed = True if psutil.pid_exists(self.proc.pid): self.proc.terminate() ",nonocaptcha/solver.py,"ReplaceText(target=' is ' @(67,31)->(67,39))","class Launcher(launcher.Launcher): def waitForChromeToClose(self): """"""Terminate chrome."""""" if self.proc.returncode is not None and not self.chromeClosed: self.chromeClosed = True if psutil.pid_exists(self.proc.pid): self.proc.terminate()","class Launcher(launcher.Launcher): def waitForChromeToClose(self): """"""Terminate chrome."""""" if self.proc.returncode is None and not self.chromeClosed: self.chromeClosed = True if psutil.pid_exists(self.proc.pid): self.proc.terminate()" 1193,https://:@gitlab.com/bz1/peempy.git,7cbb4d659093bab5848fd3796f059e8ae759466f,"@@ -54,7 +54,7 @@ def drift(ctx, folder_id, verbose, norm_id, save_xmcd, save_drift, ppath = ctx.obj[""ppath""] if norm_id is not None: - normfolder = ppath.basedir + ""{}_{}"".format(norm_id, folder_suffix) + normfolder = ppath.basedir / ""{}_{}"".format(norm_id, folder_suffix) norm = get_normalisation(fdname=normfolder, name=norm_name) else: import numpy as np ",peempy/cmdline/cmd_batch.py,"ReplaceText(target='/' @(57,35)->(57,36))","def drift(ctx, folder_id, verbose, norm_id, save_xmcd, save_drift, ppath = ctx.obj[""ppath""] if norm_id is not None: normfolder = ppath.basedir + ""{}_{}"".format(norm_id, folder_suffix) norm = get_normalisation(fdname=normfolder, name=norm_name) else: import numpy as np","def drift(ctx, folder_id, verbose, norm_id, save_xmcd, save_drift, ppath = ctx.obj[""ppath""] if norm_id is not None: normfolder = ppath.basedir / ""{}_{}"".format(norm_id, folder_suffix) norm = get_normalisation(fdname=normfolder, name=norm_name) else: import numpy as np" 1194,https://:@github.com/termie/farmboy.git,35950d1e384b4ea70d2698544aec6652521a1dc1,"@@ -63,7 +63,7 @@ def update(d, path='farmboy.yaml'): doc = {} doc.update(d) - yaml.dump(d, + yaml.dump(doc, stream=open(path, 'w'), default_flow_style=False, indent=2, ",farmboy/util.py,"ReplaceText(target='doc' @(66,14)->(66,15))","def update(d, path='farmboy.yaml'): doc = {} doc.update(d) yaml.dump(d, stream=open(path, 'w'), default_flow_style=False, indent=2,","def update(d, path='farmboy.yaml'): doc = {} doc.update(d) yaml.dump(doc, stream=open(path, 'w'), default_flow_style=False, indent=2," 1195,https://:@github.com/Mariocj89/hubsync.git,47076ad24664e140ce104a11a2845395ae40da27,"@@ -41,7 +41,7 @@ def zip_pairs(xs, ys, key=lambda x: x): yield None, ys.pop() elif key(xs[-1]) == key(ys[-1]): yield xs.pop(), ys.pop() - elif key(xs[-1]) > key(ys[-1]): + elif key(xs[-1]) < key(ys[-1]): yield xs.pop(), None else: yield None, ys.pop() ",hubsync/sync.py,"ReplaceText(target='<' @(44,25)->(44,26))","def zip_pairs(xs, ys, key=lambda x: x): yield None, ys.pop() elif key(xs[-1]) == key(ys[-1]): yield xs.pop(), ys.pop() elif key(xs[-1]) > key(ys[-1]): yield xs.pop(), None else: yield None, ys.pop()","def zip_pairs(xs, ys, key=lambda x: x): yield None, ys.pop() elif key(xs[-1]) == key(ys[-1]): yield xs.pop(), ys.pop() elif key(xs[-1]) < key(ys[-1]): yield xs.pop(), None else: yield None, ys.pop()" 1196,https://:@github.com/andrewsanchez/NCBITK.git,233aa289b2674bf0d2880acb45f7b1f832eceee7,"@@ -41,7 +41,7 @@ def update(genbank_mirror, genbank_status, path_vars, assembly_summary, species_ curate.create_species_dirs(genbank_mirror, assembly_summary, logger, species_list) local_genomes, new_genomes, old_genomes, sketch_files, missing_sketch_files = genbank_status - curate.remove_old_genomes(genbank_mirror, assembly_summary, local_genomes, logger) + curate.remove_old_genomes(genbank_mirror, assembly_summary, old_genomes, logger) sync.sync_latest_genomes(genbank_mirror, assembly_summary, new_genomes, logger) curate.unzip_genbank_mirror(genbank_mirror) rename.rename(genbank_mirror, assembly_summary) ",run.py,"ReplaceText(target='old_genomes' @(44,64)->(44,77))","def update(genbank_mirror, genbank_status, path_vars, assembly_summary, species_ curate.create_species_dirs(genbank_mirror, assembly_summary, logger, species_list) local_genomes, new_genomes, old_genomes, sketch_files, missing_sketch_files = genbank_status curate.remove_old_genomes(genbank_mirror, assembly_summary, local_genomes, logger) sync.sync_latest_genomes(genbank_mirror, assembly_summary, new_genomes, logger) curate.unzip_genbank_mirror(genbank_mirror) rename.rename(genbank_mirror, assembly_summary)","def update(genbank_mirror, genbank_status, path_vars, assembly_summary, species_ curate.create_species_dirs(genbank_mirror, assembly_summary, logger, species_list) local_genomes, new_genomes, old_genomes, sketch_files, missing_sketch_files = genbank_status curate.remove_old_genomes(genbank_mirror, assembly_summary, old_genomes, logger) sync.sync_latest_genomes(genbank_mirror, assembly_summary, new_genomes, logger) curate.unzip_genbank_mirror(genbank_mirror) rename.rename(genbank_mirror, assembly_summary)" 1197,https://:@github.com/williamjameshandley/spherical_kde.git,690bedc85f0d7c0fcf419609fbf05f34fe3cd419,"@@ -68,7 +68,7 @@ class SphericalKDE(object): ""shape as weights ({}!={})"".format( len(self.phi), len(self.weights))) - sigmahat = VonMises_std(self.theta, self.phi) + sigmahat = VonMises_std(self.phi, self.theta) self.suggested_bandwidth = 1.06*sigmahat*len(weights)**-0.2 def __call__(self, phi, theta): ",spherical_kde/__init__.py,"ArgSwap(idxs=0<->1 @(71,19)->(71,31))","class SphericalKDE(object): ""shape as weights ({}!={})"".format( len(self.phi), len(self.weights))) sigmahat = VonMises_std(self.theta, self.phi) self.suggested_bandwidth = 1.06*sigmahat*len(weights)**-0.2 def __call__(self, phi, theta):","class SphericalKDE(object): ""shape as weights ({}!={})"".format( len(self.phi), len(self.weights))) sigmahat = VonMises_std(self.phi, self.theta) self.suggested_bandwidth = 1.06*sigmahat*len(weights)**-0.2 def __call__(self, phi, theta):" 1198,https://:@github.com/mmcdermo/pressurize.git,a5373cd338db37c225d15c61e3531fae1dc3b8ef,"@@ -33,7 +33,7 @@ class ModelServer(object): self._pipe = pipe self._resources = ModelServer.acquire_resources(config, model_conf, resource_path) self._model_class = ModelServer.import_model(model_conf['path'], source_path) - self._model = self._model_class(self._resources, config=config) + self._model = self._model_class(self._resources, config=model_conf) def run(self): handler = logging.handlers.WatchedFileHandler( ",pressurize/model/model_server.py,"ReplaceText(target='model_conf' @(36,64)->(36,70))","class ModelServer(object): self._pipe = pipe self._resources = ModelServer.acquire_resources(config, model_conf, resource_path) self._model_class = ModelServer.import_model(model_conf['path'], source_path) self._model = self._model_class(self._resources, config=config) def run(self): handler = logging.handlers.WatchedFileHandler(","class ModelServer(object): self._pipe = pipe self._resources = ModelServer.acquire_resources(config, model_conf, resource_path) self._model_class = ModelServer.import_model(model_conf['path'], source_path) self._model = self._model_class(self._resources, config=model_conf) def run(self): handler = logging.handlers.WatchedFileHandler(" 1199,https://:@github.com/ladybug-tools/dragonfly.git,8c336e3b05084859242d393c51ceab66e56491cf,"@@ -929,7 +929,7 @@ class Room2D(_BaseGeometry): seg_1.distance_to_point(seg_2.p2) <= tolerance: # set the boundary conditions of the segments room_1.set_adjacency(room_2, j, k) - adj_info.append(((room_1, k), (room_2, k))) + adj_info.append(((room_1, j), (room_2, k))) break except IndexError: pass # we have reached the end of the list of zones ",dragonfly/room2d.py,"ReplaceText(target='j' @(932,62)->(932,63))","class Room2D(_BaseGeometry): seg_1.distance_to_point(seg_2.p2) <= tolerance: # set the boundary conditions of the segments room_1.set_adjacency(room_2, j, k) adj_info.append(((room_1, k), (room_2, k))) break except IndexError: pass # we have reached the end of the list of zones","class Room2D(_BaseGeometry): seg_1.distance_to_point(seg_2.p2) <= tolerance: # set the boundary conditions of the segments room_1.set_adjacency(room_2, j, k) adj_info.append(((room_1, j), (room_2, k))) break except IndexError: pass # we have reached the end of the list of zones" 1200,https://:@github.com/mworion/MountWizzard4.git,f242a72c11cd1a6e904daf11afdfdee81c2aeb20,"@@ -109,7 +109,7 @@ class SiteStatus(object): if self.ui.checkRefracNone.isChecked(): return False if self.ui.checkRefracNoTrack.isChecked(): - if self.app.mount.obsSite.status != 0: + if self.app.mount.obsSite.status == 0: return False temp, press = self.app.environment.getFilteredRefracParams() if temp is None or press is None: ",mw4/gui/mainWmixin/tabSiteStatus.py,"ReplaceText(target='==' @(112,45)->(112,47))","class SiteStatus(object): if self.ui.checkRefracNone.isChecked(): return False if self.ui.checkRefracNoTrack.isChecked(): if self.app.mount.obsSite.status != 0: return False temp, press = self.app.environment.getFilteredRefracParams() if temp is None or press is None:","class SiteStatus(object): if self.ui.checkRefracNone.isChecked(): return False if self.ui.checkRefracNoTrack.isChecked(): if self.app.mount.obsSite.status == 0: return False temp, press = self.app.environment.getFilteredRefracParams() if temp is None or press is None:" 1201,https://:@github.com/mworion/MountWizzard4.git,a1d62cbed9ed70e9caebb9f3b66c9367ce584216,"@@ -128,7 +128,7 @@ class Weather(indiClass.IndiClass): else: key = element - self.data[element] = value + self.data[key] = value if 'WEATHER_DEWPOINT' in self.data: return True ",mw4/environment/weather.py,"ReplaceText(target='key' @(131,22)->(131,29))","class Weather(indiClass.IndiClass): else: key = element self.data[element] = value if 'WEATHER_DEWPOINT' in self.data: return True","class Weather(indiClass.IndiClass): else: key = element self.data[key] = value if 'WEATHER_DEWPOINT' in self.data: return True" 1202,https://:@github.com/mworion/MountWizzard4.git,cf891426dffe2a018621bf2c836ff19bfb086835,"@@ -460,7 +460,7 @@ class SettMisc(object): :return: True for test purpose """""" - if platform.machine() not in Config.excludedPlatforms: + if platform.machine() in Config.excludedPlatforms: return False self.audioSignalsSet['Beep'] = ':/sound/beep.wav' ",mw4/gui/mainWmixin/tabSettMisc.py,"ReplaceText(target=' in ' @(463,29)->(463,37))","class SettMisc(object): :return: True for test purpose """""" if platform.machine() not in Config.excludedPlatforms: return False self.audioSignalsSet['Beep'] = ':/sound/beep.wav'","class SettMisc(object): :return: True for test purpose """""" if platform.machine() in Config.excludedPlatforms: return False self.audioSignalsSet['Beep'] = ':/sound/beep.wav'" 1203,https://:@github.com/mworion/MountWizzard4.git,03adbd9668d10e81e3a9342c6dc5053442394559,"@@ -376,7 +376,7 @@ class DataPoint(object): track = self.app.mount.setting.meridianLimitTrack if slew is None or track is None: - return True + return False value = max(slew, track) ",mw4/logic/modeldata/buildpoints.py,"ReplaceText(target='False' @(379,19)->(379,23))","class DataPoint(object): track = self.app.mount.setting.meridianLimitTrack if slew is None or track is None: return True value = max(slew, track) ","class DataPoint(object): track = self.app.mount.setting.meridianLimitTrack if slew is None or track is None: return False value = max(slew, track) " 1204,https://:@github.com/beincy/utils-mini.git,989c19fa9755236023d28748724a64e8a379de07,"@@ -98,7 +98,7 @@ def isNoneOrEmpty(obj): 判断列表或者字符串是否为空 ''' if obj is None: - return False + return True if isinstance(obj, list): return len(obj) <= 0 if isinstance(obj, str): ",utilsMini/uitiy.py,"ReplaceText(target='True' @(101,15)->(101,20))","def isNoneOrEmpty(obj): 判断列表或者字符串是否为空 ''' if obj is None: return False if isinstance(obj, list): return len(obj) <= 0 if isinstance(obj, str):","def isNoneOrEmpty(obj): 判断列表或者字符串是否为空 ''' if obj is None: return True if isinstance(obj, list): return len(obj) <= 0 if isinstance(obj, str):" 1205,https://:@github.com/philipdexter/pear.git,41a38e1c951ce4939b28654c0b3269bc7a3afa38,"@@ -47,7 +47,7 @@ def upgrade(ctx): print('failed to find {} on server'.format(n)) continue elif lv != rv: - print('found new version {} (old: {}) for {}, do you want to upgrade? [Y/n] '.format(lv, rv, n), end='') + print('found new version {} (old: {}) for {}, do you want to upgrade? [Y/n] '.format(rv, lv, n), end='') sys.stdout.flush() answer = sys.stdin.readline().strip() if answer in ('', ' ', 'Y', 'y'): ",pear/__init__.py,"ArgSwap(idxs=0<->1 @(50,18)->(50,96))","def upgrade(ctx): print('failed to find {} on server'.format(n)) continue elif lv != rv: print('found new version {} (old: {}) for {}, do you want to upgrade? [Y/n] '.format(lv, rv, n), end='') sys.stdout.flush() answer = sys.stdin.readline().strip() if answer in ('', ' ', 'Y', 'y'):","def upgrade(ctx): print('failed to find {} on server'.format(n)) continue elif lv != rv: print('found new version {} (old: {}) for {}, do you want to upgrade? [Y/n] '.format(rv, lv, n), end='') sys.stdout.flush() answer = sys.stdin.readline().strip() if answer in ('', ' ', 'Y', 'y'):" 1206,https://:@github.com/wesselb/matrix.git,e0cc62b07fcfe89d4adf592e4ab16d1a4865c71d,"@@ -93,7 +93,7 @@ def matmul(a, b, tr_a=False, tr_b=False): b = _tr(b, tr_b) middle = B.matmul(a.right, b.left, tr_a=True) rows, cols = B.shape(middle) - if rows < cols: + if rows > cols: return LowRank(B.matmul(a.left, middle), b.right) else: return LowRank(a.left, B.matmul(b.right, middle, tr_b=True)) ",matrix/ops/matmul.py,"ReplaceText(target='>' @(96,12)->(96,13))","def matmul(a, b, tr_a=False, tr_b=False): b = _tr(b, tr_b) middle = B.matmul(a.right, b.left, tr_a=True) rows, cols = B.shape(middle) if rows < cols: return LowRank(B.matmul(a.left, middle), b.right) else: return LowRank(a.left, B.matmul(b.right, middle, tr_b=True))","def matmul(a, b, tr_a=False, tr_b=False): b = _tr(b, tr_b) middle = B.matmul(a.right, b.left, tr_a=True) rows, cols = B.shape(middle) if rows > cols: return LowRank(B.matmul(a.left, middle), b.right) else: return LowRank(a.left, B.matmul(b.right, middle, tr_b=True))" 1207,https://:@github.com/cuenca-mx/ivoy-python.git,4bc75f0341179efdbf63ddba96e9de8e651adae4,"@@ -33,7 +33,7 @@ class Waybill(Resource): resp = cls._client.post(cls._endpoint, json=json_data) return cls( id_package_list=id_package_list, - guide_list=ivoy_guide_list, + guide_list=guide_list, ivoy_guide_list=ivoy_guide_list, byte_content=resp.content, ) ",ivoy/resources/waybill.py,"ReplaceText(target='guide_list' @(36,23)->(36,38))","class Waybill(Resource): resp = cls._client.post(cls._endpoint, json=json_data) return cls( id_package_list=id_package_list, guide_list=ivoy_guide_list, ivoy_guide_list=ivoy_guide_list, byte_content=resp.content, )","class Waybill(Resource): resp = cls._client.post(cls._endpoint, json=json_data) return cls( id_package_list=id_package_list, guide_list=guide_list, ivoy_guide_list=ivoy_guide_list, byte_content=resp.content, )" 1208,https://:@github.com/twmacro/pyyeti.git,0b1aa385a36ed58d82895e91cbb23bb59823f7ba,"@@ -733,7 +733,7 @@ def _get_Tlv2sc(sccoord): T = np.zeros((6, 6)) T[:3, :3] = sccoord T[3:, 3:] = sccoord - return sccoord + return T # get transform from l/v basic to s/c: uset = n2p.addgrid(None, 1, 'b', sccoord, [0, 0, 0], sccoord) ",pyyeti/cb.py,"ReplaceText(target='T' @(736,15)->(736,22))","def _get_Tlv2sc(sccoord): T = np.zeros((6, 6)) T[:3, :3] = sccoord T[3:, 3:] = sccoord return sccoord # get transform from l/v basic to s/c: uset = n2p.addgrid(None, 1, 'b', sccoord, [0, 0, 0], sccoord)","def _get_Tlv2sc(sccoord): T = np.zeros((6, 6)) T[:3, :3] = sccoord T[3:, 3:] = sccoord return T # get transform from l/v basic to s/c: uset = n2p.addgrid(None, 1, 'b', sccoord, [0, 0, 0], sccoord)" 1209,https://:@github.com/civodlu/trw.git,a2e824a5ae886c95af4e2cecd29331401aa61f76,"@@ -158,7 +158,7 @@ class CallbackExplainDecision(callback.Callback): self.dataset_name = next(iter(datasets)) if datasets[self.dataset_name].get(self.split_name) is None: - logger.error('can\'t find split={} for dataset={}'.format(self.dataset_name, self.split_name)) + logger.error('can\'t find split={} for dataset={}'.format(self.split_name, self.dataset_name)) self.dataset_name = None return ",src/trw/train/callback_explain_decision.py,"ArgSwap(idxs=0<->1 @(161,25)->(161,69))","class CallbackExplainDecision(callback.Callback): self.dataset_name = next(iter(datasets)) if datasets[self.dataset_name].get(self.split_name) is None: logger.error('can\'t find split={} for dataset={}'.format(self.dataset_name, self.split_name)) self.dataset_name = None return ","class CallbackExplainDecision(callback.Callback): self.dataset_name = next(iter(datasets)) if datasets[self.dataset_name].get(self.split_name) is None: logger.error('can\'t find split={} for dataset={}'.format(self.split_name, self.dataset_name)) self.dataset_name = None return " 1210,https://:@github.com/lycantropos/gon.git,ff1fe6cc1054b70682a5c3ecf41ba9c0b4e14137,"@@ -88,7 +88,7 @@ class Interval: and _in_interval(other.end, self)) def orientation_with(self, point: Point) -> int: - return Angle(self.start, self.end, point).orientation + return Angle(self.end, self.start, point).orientation class Segment(Interval): ",gon/linear.py,"ArgSwap(idxs=0<->1 @(91,15)->(91,20))","class Interval: and _in_interval(other.end, self)) def orientation_with(self, point: Point) -> int: return Angle(self.start, self.end, point).orientation class Segment(Interval):","class Interval: and _in_interval(other.end, self)) def orientation_with(self, point: Point) -> int: return Angle(self.end, self.start, point).orientation class Segment(Interval):" 1211,https://:@github.com/lycantropos/gon.git,ff1fe6cc1054b70682a5c3ecf41ba9c0b4e14137,"@@ -9,7 +9,7 @@ from . import strategies def test_basic(vertex: Point, first_ray_point: Point, second_ray_point: Point) -> None: - angle = Angle(vertex, first_ray_point, second_ray_point) + angle = Angle(first_ray_point, vertex, second_ray_point) assert angle.vertex == vertex assert angle.first_ray_point == first_ray_point ",tests/angular_tests/angle_tests/test_creation.py,"ArgSwap(idxs=0<->1 @(12,12)->(12,17))","from . import strategies def test_basic(vertex: Point, first_ray_point: Point, second_ray_point: Point) -> None: angle = Angle(vertex, first_ray_point, second_ray_point) assert angle.vertex == vertex assert angle.first_ray_point == first_ray_point","from . import strategies def test_basic(vertex: Point, first_ray_point: Point, second_ray_point: Point) -> None: angle = Angle(first_ray_point, vertex, second_ray_point) assert angle.vertex == vertex assert angle.first_ray_point == first_ray_point" 1212,https://:@github.com/lycantropos/gon.git,31bfd6196e50ef10a020b3adee21e87705ba5abf,"@@ -68,7 +68,7 @@ class Vector: >>> not zero_vector True """""" - return bool(self._x and self._y) + return bool(self._x or self._y) @property def x(self) -> Scalar: ",gon/base.py,"ReplaceText(target='or' @(71,28)->(71,31))","class Vector: >>> not zero_vector True """""" return bool(self._x and self._y) @property def x(self) -> Scalar:","class Vector: >>> not zero_vector True """""" return bool(self._x or self._y) @property def x(self) -> Scalar:" 1213,https://:@github.com/lycantropos/gon.git,948c5adbfc855d0fcd1fd92d5442fc24ac3986ca,"@@ -105,7 +105,7 @@ def replace_segment(segments: Set[Segment], def is_non_origin_point(point: Point) -> bool: - return bool(point.x and point.y) + return bool(point.x or point.y) def reflect_point(point: Point) -> Point: ",tests/utils.py,"ReplaceText(target='or' @(108,24)->(108,27))","def replace_segment(segments: Set[Segment], def is_non_origin_point(point: Point) -> bool: return bool(point.x and point.y) def reflect_point(point: Point) -> Point:","def replace_segment(segments: Set[Segment], def is_non_origin_point(point: Point) -> bool: return bool(point.x or point.y) def reflect_point(point: Point) -> Point:" 1214,https://:@github.com/lycantropos/gon.git,e8e6c3d4505c540b8dfb5ca1f5fb29fefad25ee6,"@@ -49,8 +49,8 @@ class Angle: @property def kind(self) -> AngleKind: return AngleKind(to_sign( - projection.signed_length(self._vertex, - self._first_ray_point, + projection.signed_length(self._first_ray_point, + self._vertex, self._second_ray_point))) @property ",gon/angular.py,"ArgSwap(idxs=0<->1 @(52,16)->(52,40))","class Angle: @property def kind(self) -> AngleKind: return AngleKind(to_sign( projection.signed_length(self._vertex, self._first_ray_point, self._second_ray_point))) @property","class Angle: @property def kind(self) -> AngleKind: return AngleKind(to_sign( projection.signed_length(self._first_ray_point, self._vertex, self._second_ray_point))) @property" 1215,https://:@github.com/lycantropos/gon.git,36f206f6debde8166907e917b5a96e08a1dbe256,"@@ -185,7 +185,7 @@ class Polygon(Geometry): >>> polygon > polygon.convex_hull False """""" - return self != other and self <= other + return self != other and self >= other def __hash__(self) -> int: """""" ",gon/shaped.py,"ReplaceText(target='>=' @(188,38)->(188,40))","class Polygon(Geometry): >>> polygon > polygon.convex_hull False """""" return self != other and self <= other def __hash__(self) -> int: """"""","class Polygon(Geometry): >>> polygon > polygon.convex_hull False """""" return self != other and self >= other def __hash__(self) -> int: """"""" 1216,https://:@github.com/energy-analytics-project/energy-dashboard-lib.git,7f6979e46e7d4c015302ac3e826ee317325bf216,"@@ -161,7 +161,7 @@ def insert_file(logger, resource_name, dbmgr, sql_dir, db_dir, sql_file_name, id ""dbmgr"" : str(dbmgr), ""message"" : ""completed"", }) - return sql_file + return sql_file_name except Exception as e: log.error(chlogger, { ""name"" : __name__, ",edl/resources/db.py,"ReplaceText(target='sql_file_name' @(164,15)->(164,23))","def insert_file(logger, resource_name, dbmgr, sql_dir, db_dir, sql_file_name, id ""dbmgr"" : str(dbmgr), ""message"" : ""completed"", }) return sql_file except Exception as e: log.error(chlogger, { ""name"" : __name__,","def insert_file(logger, resource_name, dbmgr, sql_dir, db_dir, sql_file_name, id ""dbmgr"" : str(dbmgr), ""message"" : ""completed"", }) return sql_file_name except Exception as e: log.error(chlogger, { ""name"" : __name__," 1217,https://:@github.com/quipucords/camayoc.git,5d52f47ce5f7085773edfba8ac3cb0a7016b9500,"@@ -39,7 +39,7 @@ def browser(request): debug_mode = (os.environ.get('SELENIUM_DEBUG', 'false').lower() == 'true') if driver_type == 'chrome': chrome_options = webdriver.ChromeOptions() - if debug_mode: + if not debug_mode: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') ",camayoc/tests/qpc/ui/conftest.py,"ReplaceText(target='not ' @(42,11)->(42,11))","def browser(request): debug_mode = (os.environ.get('SELENIUM_DEBUG', 'false').lower() == 'true') if driver_type == 'chrome': chrome_options = webdriver.ChromeOptions() if debug_mode: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox')","def browser(request): debug_mode = (os.environ.get('SELENIUM_DEBUG', 'false').lower() == 'true') if driver_type == 'chrome': chrome_options = webdriver.ChromeOptions() if not debug_mode: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox')" 1218,https://:@github.com/AnemoneLabs/unmessage.git,cdbdf31e6db0a03b7521240aab8ef7e78f259027,"@@ -33,7 +33,7 @@ def test_build_regular_packet(iv, len(iv_hash) == packets.HASH_LEN and len(payload_hash) == packets.HASH_LEN and not len(handshake_key) and - len(payload_hash)): + len(payload)): assert isinstance(packets.build_regular_packet(data), packets.RegularPacket) else: ",tests/test_packets.py,"ReplaceText(target='payload' @(36,16)->(36,28))","def test_build_regular_packet(iv, len(iv_hash) == packets.HASH_LEN and len(payload_hash) == packets.HASH_LEN and not len(handshake_key) and len(payload_hash)): assert isinstance(packets.build_regular_packet(data), packets.RegularPacket) else:","def test_build_regular_packet(iv, len(iv_hash) == packets.HASH_LEN and len(payload_hash) == packets.HASH_LEN and not len(handshake_key) and len(payload)): assert isinstance(packets.build_regular_packet(data), packets.RegularPacket) else:" 1219,https://:@github.com/datacamp/shellwhat_ext.git,a8cf5633b36c6f11da7cb32b604b2cb1dbf246ad,"@@ -83,7 +83,7 @@ def test_output_does_not_contain(state, text, fixed=True, msg='Submission output else: pat = re.compile(text) - if text.search(state.student_result): + if pat.search(state.student_result): state.do_test(msg.format(text)) return state ",shellwhat_ext/__init__.py,"ReplaceText(target='pat' @(86,11)->(86,15))","def test_output_does_not_contain(state, text, fixed=True, msg='Submission output else: pat = re.compile(text) if text.search(state.student_result): state.do_test(msg.format(text)) return state","def test_output_does_not_contain(state, text, fixed=True, msg='Submission output else: pat = re.compile(text) if pat.search(state.student_result): state.do_test(msg.format(text)) return state" 1220,https://:@github.com/fdcl-nrf/fym.git,ac48fb4c314929f215ce7a7fa86c245cd9c84261,"@@ -223,7 +223,7 @@ class Delay: return self.clock.get() >= self.T def set_states(self, time): - if time > self.memory_dump.x[-1] - self.T: + if time > self.memory_dump.x[-1] + self.T: fit = self.memory[0] else: fit = self.memory_dump ",fym/core.py,"ReplaceText(target='+' @(226,41)->(226,42))","class Delay: return self.clock.get() >= self.T def set_states(self, time): if time > self.memory_dump.x[-1] - self.T: fit = self.memory[0] else: fit = self.memory_dump","class Delay: return self.clock.get() >= self.T def set_states(self, time): if time > self.memory_dump.x[-1] + self.T: fit = self.memory[0] else: fit = self.memory_dump" 1221,https://:@github.com/tjbanks/bmtools.git,6c3bec26dc0e7338760233359c320ebfd94c4c8d,"@@ -339,7 +339,7 @@ def connection_divergence_average(config=None,nodes=None,edges=None,sources=[],t vc = vc[target_id_type].dropna().sort_index() count = vc.ix[target_id]#t_list[t_list[target_id_type]==target_id] else: - vc = t_list.apply(pd.Series.value_counts) + vc = s_list.apply(pd.Series.value_counts) vc = vc[source_id_type].dropna().sort_index() count = vc.ix[source_id]#count = s_list[s_list[source_id_type]==source_id] ",bmtools/util.py,"ReplaceText(target='s_list' @(342,17)->(342,23))","def connection_divergence_average(config=None,nodes=None,edges=None,sources=[],t vc = vc[target_id_type].dropna().sort_index() count = vc.ix[target_id]#t_list[t_list[target_id_type]==target_id] else: vc = t_list.apply(pd.Series.value_counts) vc = vc[source_id_type].dropna().sort_index() count = vc.ix[source_id]#count = s_list[s_list[source_id_type]==source_id] ","def connection_divergence_average(config=None,nodes=None,edges=None,sources=[],t vc = vc[target_id_type].dropna().sort_index() count = vc.ix[target_id]#t_list[t_list[target_id_type]==target_id] else: vc = s_list.apply(pd.Series.value_counts) vc = vc[source_id_type].dropna().sort_index() count = vc.ix[source_id]#count = s_list[s_list[source_id_type]==source_id] " 1222,https://:@github.com/tjbanks/bmtools.git,d8cb66f7299499176a5391effe12f55213115f15,"@@ -1379,7 +1379,7 @@ https://github.com/tjbanks/bmtool ctg.add_widget(window_index,column_index,widget) segpassivewidget = SegregationPassiveWidget(fir_widget,ctg.root_sec.cell(), other_cells,section_selected,ctg.mechanism_dict,gleak_var=gleak,eleak_var=eleak) - ctg.add_widget(window_index,column_index,widget) + ctg.add_widget(window_index,column_index,segpassivewidget) widget = SegregationFIRFitWidget(fir_widget) ctg.add_widget(window_index,column_index,widget) ",bmtools/cli/plugins/util/commands.py,"ReplaceText(target='segpassivewidget' @(1382,45)->(1382,51))","https://github.com/tjbanks/bmtool ctg.add_widget(window_index,column_index,widget) segpassivewidget = SegregationPassiveWidget(fir_widget,ctg.root_sec.cell(), other_cells,section_selected,ctg.mechanism_dict,gleak_var=gleak,eleak_var=eleak) ctg.add_widget(window_index,column_index,widget) widget = SegregationFIRFitWidget(fir_widget) ctg.add_widget(window_index,column_index,widget)","https://github.com/tjbanks/bmtool ctg.add_widget(window_index,column_index,widget) segpassivewidget = SegregationPassiveWidget(fir_widget,ctg.root_sec.cell(), other_cells,section_selected,ctg.mechanism_dict,gleak_var=gleak,eleak_var=eleak) ctg.add_widget(window_index,column_index,segpassivewidget) widget = SegregationFIRFitWidget(fir_widget) ctg.add_widget(window_index,column_index,widget)" 1223,https://:@github.com/tslight/ppick.git,d610a851b37e3b280fe22c704e5845194420fc86,"@@ -65,7 +65,7 @@ def process(parent, action, curline): curline += 1 elif action == 'get_size_all': for c, d in parent.traverse(): - child.sized[os.path.abspath(child.name)] = None + child.sized[os.path.abspath(c.name)] = None action = None # reset action line += 1 # keep scrolling! return curline, line ",treepick/pick.py,"ReplaceText(target='c' @(68,48)->(68,53))","def process(parent, action, curline): curline += 1 elif action == 'get_size_all': for c, d in parent.traverse(): child.sized[os.path.abspath(child.name)] = None action = None # reset action line += 1 # keep scrolling! return curline, line","def process(parent, action, curline): curline += 1 elif action == 'get_size_all': for c, d in parent.traverse(): child.sized[os.path.abspath(c.name)] = None action = None # reset action line += 1 # keep scrolling! return curline, line" 1224,https://:@github.com/tslight/ppick.git,df4927a8e15cd6ebce72e989da9b12999158d951,"@@ -58,7 +58,7 @@ def process(parent, action, curline): child.picked.add(child.name) curline += 1 elif action == 'next_parent': - curline += child.nextparent(parent, curline, depth) + curline = child.nextparent(parent, curline, depth) elif action == 'prev_parent': curline = child.prevparent(parent, curline, depth)[0] elif action == 'get_size': ",treepick/pick.py,"ReplaceText(target='=' @(61,24)->(61,26))","def process(parent, action, curline): child.picked.add(child.name) curline += 1 elif action == 'next_parent': curline += child.nextparent(parent, curline, depth) elif action == 'prev_parent': curline = child.prevparent(parent, curline, depth)[0] elif action == 'get_size':","def process(parent, action, curline): child.picked.add(child.name) curline += 1 elif action == 'next_parent': curline = child.nextparent(parent, curline, depth) elif action == 'prev_parent': curline = child.prevparent(parent, curline, depth)[0] elif action == 'get_size':" 1225,https://:@github.com/tslight/ppick.git,0e6b3b8077f15ae49045d1aef5e4b597ec1f7ada,"@@ -76,7 +76,7 @@ def pick(stdscr, root, hidden=True, relative=False, picked=[]): if action == 'reset': parent, action, curline = reset(stdscr, root, hidden, picked=[]) elif action == 'toggle_hidden': - curline = scr.toggle_hidden(curline, scr) + curline = parent.toggle_hidden(curline, scr) elif action == 'find': string = scr.txtbox(""Find: "").strip() if string: ",treepick/pick.py,"ReplaceText(target='parent' @(79,22)->(79,25))","def pick(stdscr, root, hidden=True, relative=False, picked=[]): if action == 'reset': parent, action, curline = reset(stdscr, root, hidden, picked=[]) elif action == 'toggle_hidden': curline = scr.toggle_hidden(curline, scr) elif action == 'find': string = scr.txtbox(""Find: "").strip() if string:","def pick(stdscr, root, hidden=True, relative=False, picked=[]): if action == 'reset': parent, action, curline = reset(stdscr, root, hidden, picked=[]) elif action == 'toggle_hidden': curline = parent.toggle_hidden(curline, scr) elif action == 'find': string = scr.txtbox(""Find: "").strip() if string:" 1226,https://:@github.com/cloudve/djcloudbridge.git,3a4862c261a0e3457358cd71842d7e0d7b62b11a,"@@ -194,7 +194,7 @@ class GCECredentials(Credentials): gce_creds = json.loads(self.credentials) # Overwrite with super values in case gce_creds also has an id property gce_creds.update(d) - return d + return gce_creds class AzureCredentials(Credentials): ",djcloudbridge/models.py,"ReplaceText(target='gce_creds' @(197,15)->(197,16))","class GCECredentials(Credentials): gce_creds = json.loads(self.credentials) # Overwrite with super values in case gce_creds also has an id property gce_creds.update(d) return d class AzureCredentials(Credentials):","class GCECredentials(Credentials): gce_creds = json.loads(self.credentials) # Overwrite with super values in case gce_creds also has an id property gce_creds.update(d) return gce_creds class AzureCredentials(Credentials):" 1227,https://:@github.com/suizokukan/katal.git,08b3edeb2142136a0f857a185d483ccc75ae2591,"@@ -1053,7 +1053,7 @@ def fill_select(_debug_datatime=None): "": incompatibility with the sieves"".format(prefix, fullname), _important_msg=False) else: - tobeadded, partialhashid, hashid = thefilehastobeadded__db(filename, size, time) + tobeadded, partialhashid, hashid = thefilehastobeadded__db(fullname, size, time) if tobeadded: # ok, let's add to SELECT... ",katal/katal.py,"ReplaceText(target='fullname' @(1056,75)->(1056,83))","def fill_select(_debug_datatime=None): "": incompatibility with the sieves"".format(prefix, fullname), _important_msg=False) else: tobeadded, partialhashid, hashid = thefilehastobeadded__db(filename, size, time) if tobeadded: # ok, let's add to SELECT...","def fill_select(_debug_datatime=None): "": incompatibility with the sieves"".format(prefix, fullname), _important_msg=False) else: tobeadded, partialhashid, hashid = thefilehastobeadded__db(fullname, size, time) if tobeadded: # ok, let's add to SELECT..." 1228,https://:@github.com/jrabbit/pyborg-1up.git,0552700be4229d7b06c3264bb2e9d1c59c20ecfa,"@@ -125,7 +125,7 @@ class PyborgDiscord(discord.Client): try: if self.settings[""discord""][""plaintext_ping""]: exp = re.compile(message.guild.me.display_name, re.IGNORECASE) - line = exp.sub(line, ""#nick"") + line = exp.sub(""#nick"", line) except KeyError: pass ",pyborg/pyborg/mod/mod_discord.py,"ArgSwap(idxs=0<->1 @(128,23)->(128,30))","class PyborgDiscord(discord.Client): try: if self.settings[""discord""][""plaintext_ping""]: exp = re.compile(message.guild.me.display_name, re.IGNORECASE) line = exp.sub(line, ""#nick"") except KeyError: pass ","class PyborgDiscord(discord.Client): try: if self.settings[""discord""][""plaintext_ping""]: exp = re.compile(message.guild.me.display_name, re.IGNORECASE) line = exp.sub(""#nick"", line) except KeyError: pass " 1229,https://:@github.com/gallantlab/tikreg.git,4241a935801cdef4b85a79e361eb365e65385f04,"@@ -1103,7 +1103,7 @@ def estimate_stem_wmvnp(features_train, feature_priors=feature_priors, feature_hyparams=spatial_opt, weights=weights, - performance=weights, + performance=performance, predictions=predictions, ridge_scale=ridge_opt, verbosity=verbosity, ",tikypy/models.py,"ReplaceText(target='performance' @(1106,67)->(1106,74))","def estimate_stem_wmvnp(features_train, feature_priors=feature_priors, feature_hyparams=spatial_opt, weights=weights, performance=weights, predictions=predictions, ridge_scale=ridge_opt, verbosity=verbosity,","def estimate_stem_wmvnp(features_train, feature_priors=feature_priors, feature_hyparams=spatial_opt, weights=weights, performance=performance, predictions=predictions, ridge_scale=ridge_opt, verbosity=verbosity," 1230,https://:@github.com/SpotlightKid/picoredis.git,f7996b19a47b6372bd3d29c081320d38ce2f566c,"@@ -53,7 +53,7 @@ class Redis: self.connect(host, port) def connect(self, host=None, port=None): - if port is not None: + if host is not None: self._host = host if port is not None: ",picoredis/picoredis.py,"ReplaceText(target='host' @(56,11)->(56,15))","class Redis: self.connect(host, port) def connect(self, host=None, port=None): if port is not None: self._host = host if port is not None:","class Redis: self.connect(host, port) def connect(self, host=None, port=None): if host is not None: self._host = host if port is not None:" 1231,https://:@github.com/igordejanovic/pyFlies.git,915aaec319a22c7e312a45ecded6d2d2a2372321,"@@ -127,7 +127,7 @@ class ExpTableRow(ModelElement, ScopeProvider): for comp_time in cond_comp.comp_times: comp_time_inst = comp_time.eval(context, last_comp) comp_insts.append(comp_time_inst) - last_comp = comp_time_inst + last_comp = comp_time setattr(self, f'ph_{phase}', comp_insts) break ",src/textx-lang-pyflies/pyflies/table.py,"ReplaceText(target='comp_time' @(130,36)->(130,50))","class ExpTableRow(ModelElement, ScopeProvider): for comp_time in cond_comp.comp_times: comp_time_inst = comp_time.eval(context, last_comp) comp_insts.append(comp_time_inst) last_comp = comp_time_inst setattr(self, f'ph_{phase}', comp_insts) break ","class ExpTableRow(ModelElement, ScopeProvider): for comp_time in cond_comp.comp_times: comp_time_inst = comp_time.eval(context, last_comp) comp_insts.append(comp_time_inst) last_comp = comp_time setattr(self, f'ph_{phase}', comp_insts) break " 1232,https://:@github.com/igordejanovic/pyFlies.git,c1437ff636c345265b020ddbfae245a266372833,"@@ -151,7 +151,7 @@ class ConditionsTable(ModelElement): else: cond_template.append(iter(var_exp_resolved)) else: - if has_sequences: + if should_repeat: cond_template.append(repeat(var_exp)) else: cond_template.append(iter([var_exp])) ",src/textx-lang-pyflies/pyflies/lang/pyflies.py,"ReplaceText(target='should_repeat' @(154,27)->(154,40))","class ConditionsTable(ModelElement): else: cond_template.append(iter(var_exp_resolved)) else: if has_sequences: cond_template.append(repeat(var_exp)) else: cond_template.append(iter([var_exp]))","class ConditionsTable(ModelElement): else: cond_template.append(iter(var_exp_resolved)) else: if should_repeat: cond_template.append(repeat(var_exp)) else: cond_template.append(iter([var_exp]))" 1233,https://:@github.com/Deeplodocus/deeplodocus.git,2c3e93e9faa91aa4b0c992409d3423300402e039,"@@ -138,7 +138,7 @@ class GenericEvaluator(GenericInferer): if DEEP_ENTRY_ADDITIONAL_DATA in metric_args: temp_metric_result = metric_method(inputs, outputs, labels, additional_data) else: - temp_metric_result = metric_method(outputs, labels) + temp_metric_result = metric_method(inputs, labels) else: if DEEP_ENTRY_ADDITIONAL_DATA in metric_args: temp_metric_result = metric_method(inputs, outputs, additional_data) ",deeplodocus/core/inference/generic_evaluator.py,"ReplaceText(target='inputs' @(141,59)->(141,66))","class GenericEvaluator(GenericInferer): if DEEP_ENTRY_ADDITIONAL_DATA in metric_args: temp_metric_result = metric_method(inputs, outputs, labels, additional_data) else: temp_metric_result = metric_method(outputs, labels) else: if DEEP_ENTRY_ADDITIONAL_DATA in metric_args: temp_metric_result = metric_method(inputs, outputs, additional_data)","class GenericEvaluator(GenericInferer): if DEEP_ENTRY_ADDITIONAL_DATA in metric_args: temp_metric_result = metric_method(inputs, outputs, labels, additional_data) else: temp_metric_result = metric_method(inputs, labels) else: if DEEP_ENTRY_ADDITIONAL_DATA in metric_args: temp_metric_result = metric_method(inputs, outputs, additional_data)" 1234,https://:@github.com/mimba/scikit-optimize.git,f760e9c43423753fa1912c9ad7db0b4d74c36a7d,"@@ -215,7 +215,7 @@ class Real(Dimension): return (self.low, self.high) def __contains__(self, point): - return self.low <= point <= self.high + return self.low <= point < self.high @property def transformed_bounds(self): ",skopt/space/space.py,"ReplaceText(target='<' @(218,33)->(218,35))","class Real(Dimension): return (self.low, self.high) def __contains__(self, point): return self.low <= point <= self.high @property def transformed_bounds(self):","class Real(Dimension): return (self.low, self.high) def __contains__(self, point): return self.low <= point < self.high @property def transformed_bounds(self):" 1235,https://:@github.com/mimba/scikit-optimize.git,198ddde419c281d5ed698eee0a8f5874cd30e444,"@@ -227,7 +227,7 @@ class Sobol(InitialPointGenerator): for j in range(n_samples): r[j, 0:n_dim], seed = self._sobol(n_dim, seed) if self.randomize: - r = space.inverse_transform(_random_shift(r, random_state)) + r = space.inverse_transform(_random_shift(r, rng)) r = space.inverse_transform(r) space.set_transformer(transformer) return r ",skopt/samples/sobol.py,"ReplaceText(target='rng' @(230,57)->(230,69))","class Sobol(InitialPointGenerator): for j in range(n_samples): r[j, 0:n_dim], seed = self._sobol(n_dim, seed) if self.randomize: r = space.inverse_transform(_random_shift(r, random_state)) r = space.inverse_transform(r) space.set_transformer(transformer) return r","class Sobol(InitialPointGenerator): for j in range(n_samples): r[j, 0:n_dim], seed = self._sobol(n_dim, seed) if self.randomize: r = space.inverse_transform(_random_shift(r, rng)) r = space.inverse_transform(r) space.set_transformer(transformer) return r" 1236,https://:@github.com/biosustain/sanger-sequencing.git,5c730c6b687e3436bb2a0f3dad5d54d326de4021,"@@ -110,5 +110,5 @@ def drop_missing_records( if (~sample_mask).any(): LOGGER.error( ""The following sample(s) have no corresponding sequence record: "" - ""%s."", "", "".join(template.loc[plasmid_mask, ""sample""])) + ""%s."", "", "".join(template.loc[sample_mask, ""sample""])) return template.loc[plasmid_mask & sample_mask, :] ",src/sanger_sequencing/validation/template.py,"ReplaceText(target='sample_mask' @(113,42)->(113,54))","def drop_missing_records( if (~sample_mask).any(): LOGGER.error( ""The following sample(s) have no corresponding sequence record: "" ""%s."", "", "".join(template.loc[plasmid_mask, ""sample""])) return template.loc[plasmid_mask & sample_mask, :]","def drop_missing_records( if (~sample_mask).any(): LOGGER.error( ""The following sample(s) have no corresponding sequence record: "" ""%s."", "", "".join(template.loc[sample_mask, ""sample""])) return template.loc[plasmid_mask & sample_mask, :]" 1237,https://:@github.com/KrishnaswamyLab/MAGIC.git,a9ff9b948fdb3f9754cd9b12c271b56a0deb1476,"@@ -464,7 +464,7 @@ class MAGIC(BaseEstimator): if not np.all(np.isin(genes, X.columns)): warnings.warn(""genes {} missing from input data"".format( genes[~np.isin(genes, X.columns)])) - genes = np.argwhere(np.isin(genes, X.columns)).reshape(-1) + genes = np.argwhere(np.isin(X.columns, genes)).reshape(-1) if store_result and self.X_magic is not None: X_magic = self.X_magic ",python/magic/magic.py,"ArgSwap(idxs=0<->1 @(467,36)->(467,43))","class MAGIC(BaseEstimator): if not np.all(np.isin(genes, X.columns)): warnings.warn(""genes {} missing from input data"".format( genes[~np.isin(genes, X.columns)])) genes = np.argwhere(np.isin(genes, X.columns)).reshape(-1) if store_result and self.X_magic is not None: X_magic = self.X_magic","class MAGIC(BaseEstimator): if not np.all(np.isin(genes, X.columns)): warnings.warn(""genes {} missing from input data"".format( genes[~np.isin(genes, X.columns)])) genes = np.argwhere(np.isin(X.columns, genes)).reshape(-1) if store_result and self.X_magic is not None: X_magic = self.X_magic" 1238,https://:@github.com/ihgazni2/edict.git,86474307d077d0a0b19ed9e26850bddb7a8fcc14,"@@ -1198,7 +1198,7 @@ def _get_rvmat(d): def map_func(ele,indexc,indexr): return(_getitem_via_pathlist(d,ele)) rvmat = elel.matrix_map(km,map_func) - rvmat = elel.prepend([],rvmat) + rvmat = elel.prepend(rvmat,[]) return(rvmat) ",edict/edict.py,"ArgSwap(idxs=0<->1 @(1201,12)->(1201,24))","def _get_rvmat(d): def map_func(ele,indexc,indexr): return(_getitem_via_pathlist(d,ele)) rvmat = elel.matrix_map(km,map_func) rvmat = elel.prepend([],rvmat) return(rvmat) ","def _get_rvmat(d): def map_func(ele,indexc,indexr): return(_getitem_via_pathlist(d,ele)) rvmat = elel.matrix_map(km,map_func) rvmat = elel.prepend(rvmat,[]) return(rvmat) " 1239,https://:@github.com/ihgazni2/edict.git,c33c711d302b920b2534d253018e2afa38481e57,"@@ -1405,7 +1405,7 @@ def _descmat_non_leaf_handler(desc,pdesc): pdesc['non_leaf_descendant_paths'] = cpnldpl pdesc['non_leaf_descendant_paths'].append(cpkpl) else: - pdesc['non_leaf_descendant_paths'].extend(cpldpl) + pdesc['non_leaf_descendant_paths'].extend(cpnldpl) pdesc['non_leaf_descendant_paths'].append(cpkpl) def _acc_sons_count(desc): ",edict/edict.py,"ReplaceText(target='cpnldpl' @(1408,50)->(1408,56))","def _descmat_non_leaf_handler(desc,pdesc): pdesc['non_leaf_descendant_paths'] = cpnldpl pdesc['non_leaf_descendant_paths'].append(cpkpl) else: pdesc['non_leaf_descendant_paths'].extend(cpldpl) pdesc['non_leaf_descendant_paths'].append(cpkpl) def _acc_sons_count(desc):","def _descmat_non_leaf_handler(desc,pdesc): pdesc['non_leaf_descendant_paths'] = cpnldpl pdesc['non_leaf_descendant_paths'].append(cpkpl) else: pdesc['non_leaf_descendant_paths'].extend(cpnldpl) pdesc['non_leaf_descendant_paths'].append(cpkpl) def _acc_sons_count(desc):" 1240,https://:@github.com/ihgazni2/edict.git,b27369ea4e770818dbc19f04b744b4f5db0e5185,"@@ -1799,7 +1799,7 @@ def get_vndmat_attr(d,keypath,attr,**kwargs): nlocs = elel.array_map(rslt,ltree.path2loc) def cond_func(ele,kdmat): return(kdmat[ele[0]][ele[1]]['path']) - rslt = elel.array_map(rslt,cond_func,kdmat) + rslt = elel.array_map(nlocs,cond_func,kdmat) else: pass else: ",edict/edict.py,"ReplaceText(target='nlocs' @(1802,34)->(1802,38))","def get_vndmat_attr(d,keypath,attr,**kwargs): nlocs = elel.array_map(rslt,ltree.path2loc) def cond_func(ele,kdmat): return(kdmat[ele[0]][ele[1]]['path']) rslt = elel.array_map(rslt,cond_func,kdmat) else: pass else:","def get_vndmat_attr(d,keypath,attr,**kwargs): nlocs = elel.array_map(rslt,ltree.path2loc) def cond_func(ele,kdmat): return(kdmat[ele[0]][ele[1]]['path']) rslt = elel.array_map(nlocs,cond_func,kdmat) else: pass else:" 1241,https://:@github.com/ihgazni2/edict.git,f392badd01323d2cef4124158581b1e51eaac168,"@@ -97,7 +97,7 @@ def _cond_sort(d,**kwargs): else: return(1) ntl = sorted(tl,key=functools.cmp_to_key(cmp_func),reverse=reverse) - nd = tlist2dict(tl) + nd = tlist2dict(ntl) return(nd) def _reorder_via_klist(d,nkl,**kwargs): ",edict/edict.py,"ReplaceText(target='ntl' @(100,20)->(100,22))","def _cond_sort(d,**kwargs): else: return(1) ntl = sorted(tl,key=functools.cmp_to_key(cmp_func),reverse=reverse) nd = tlist2dict(tl) return(nd) def _reorder_via_klist(d,nkl,**kwargs):","def _cond_sort(d,**kwargs): else: return(1) ntl = sorted(tl,key=functools.cmp_to_key(cmp_func),reverse=reverse) nd = tlist2dict(ntl) return(nd) def _reorder_via_klist(d,nkl,**kwargs):" 1242,https://:@github.com/ihgazni2/edict.git,92c0b13f1cd0db9ec146f26dbb96276d2335e2b5,"@@ -2771,7 +2771,7 @@ def sub_not_algo(d,kl,**kwargs): full_kl = list(d.keys()) nnd = {} for k in full_kl: - if(not(k in nd)): + if(not(k in kl)): nnd[k] = nd[k] else: pass ",edict/edict.py,"ReplaceText(target='kl' @(2774,20)->(2774,22))","def sub_not_algo(d,kl,**kwargs): full_kl = list(d.keys()) nnd = {} for k in full_kl: if(not(k in nd)): nnd[k] = nd[k] else: pass","def sub_not_algo(d,kl,**kwargs): full_kl = list(d.keys()) nnd = {} for k in full_kl: if(not(k in kl)): nnd[k] = nd[k] else: pass" 1243,https://:@github.com/playpauseandstop/setman.git,daf7a569ca07add82f3fabc4575b73349532eff7,"@@ -332,7 +332,7 @@ class TestUI(TestCase): ) self.assertNotContains(response, '
Value:
') - if not getattr(django_settings, name): + if getattr(django_settings, name): self.assertNotContains( response, '%s' % getattr(django_settings, name) ) ",testproject-django/testapp/tests/test_ui.py,"ReplaceText(target='' @(335,15)->(335,19))","class TestUI(TestCase): ) self.assertNotContains(response, '
Value:
') if not getattr(django_settings, name): self.assertNotContains( response, '%s' % getattr(django_settings, name) )","class TestUI(TestCase): ) self.assertNotContains(response, '
Value:
') if getattr(django_settings, name): self.assertNotContains( response, '%s' % getattr(django_settings, name) )" 1244,https://:@github.com/hvidy/halophot.git,c6ad80221bded8b417be0c52a62229ebf7b9fea9,"@@ -440,7 +440,7 @@ def do_lc(tpf,ts,splits,sub,order,maxiter=101,split_times=None,w_init=None,rando else: cad1.append(ts['cadence'][low]) if high is None: - cad1.append(ts['cadence'][-1]) + cad2.append(ts['cadence'][-1]) else: cad2.append(ts['cadence'][high]) sat.append(pmap[""sat_pixels""]) ",src/halo_tools.py,"ReplaceText(target='cad2' @(443,16)->(443,20))","def do_lc(tpf,ts,splits,sub,order,maxiter=101,split_times=None,w_init=None,rando else: cad1.append(ts['cadence'][low]) if high is None: cad1.append(ts['cadence'][-1]) else: cad2.append(ts['cadence'][high]) sat.append(pmap[""sat_pixels""])","def do_lc(tpf,ts,splits,sub,order,maxiter=101,split_times=None,w_init=None,rando else: cad1.append(ts['cadence'][low]) if high is None: cad2.append(ts['cadence'][-1]) else: cad2.append(ts['cadence'][high]) sat.append(pmap[""sat_pixels""])" 1245,https://:@gitlab.com/nicolas.hainaux/mathmakerlib.git,1995fab6610ba450545cc21879259415710e0255,"@@ -102,7 +102,7 @@ class LineSegment(Drawable, HasThickness, PointsPair): else: self.label_position = 'above' elif label_position == 'clockwise': - if self.deltax > 0: + if self.deltax >= 0: self.label_position = 'above' else: self.label_position = 'below' ",mathmakerlib/geometry/linesegment.py,"ReplaceText(target='>=' @(105,27)->(105,28))","class LineSegment(Drawable, HasThickness, PointsPair): else: self.label_position = 'above' elif label_position == 'clockwise': if self.deltax > 0: self.label_position = 'above' else: self.label_position = 'below'","class LineSegment(Drawable, HasThickness, PointsPair): else: self.label_position = 'above' elif label_position == 'clockwise': if self.deltax >= 0: self.label_position = 'above' else: self.label_position = 'below'" 1246,https://:@github.com/ecohydro/CropMask_RCNN.git,8a09a75073fd96df996f62bef98f8af9380e2aea,"@@ -694,7 +694,7 @@ def compute_matches(gt_boxes, gt_class_ids, gt_masks, # 3. Find the match for j in sorted_ixs: # If ground truth box is already matched, go to next one - if gt_match[j] > 0: + if gt_match[j] > -1: continue # If we reach IoU smaller than the threshold, end the loop iou = overlaps[i, j] ",mrcnn/utils.py,"ReplaceText(target='-1' @(697,29)->(697,30))","def compute_matches(gt_boxes, gt_class_ids, gt_masks, # 3. Find the match for j in sorted_ixs: # If ground truth box is already matched, go to next one if gt_match[j] > 0: continue # If we reach IoU smaller than the threshold, end the loop iou = overlaps[i, j]","def compute_matches(gt_boxes, gt_class_ids, gt_masks, # 3. Find the match for j in sorted_ixs: # If ground truth box is already matched, go to next one if gt_match[j] > -1: continue # If we reach IoU smaller than the threshold, end the loop iou = overlaps[i, j]" 1247,https://:@github.com/matteomattei/PySquashfsImage.git,7ca480b91e2f1056d14ddc59e5d30d9f94ef4a80,"@@ -923,7 +923,7 @@ class SquashFsImage(_Squashfs_commons): index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids) indexes = SQUASHFS_XATTR_BLOCKS(ids) index = [] - for r in range(0,ids): + for r in range(0,indexes): index.append( self.makeInteger(myfile,SQUASHFS_XATTR_BLOCK_BYTES(1)) ) bytes = SQUASHFS_XATTR_BYTES(ids) xattr_ids = {} ",PySquashfsImage/PySquashfsImage.py,"ReplaceText(target='indexes' @(926,19)->(926,22))","class SquashFsImage(_Squashfs_commons): index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids) indexes = SQUASHFS_XATTR_BLOCKS(ids) index = [] for r in range(0,ids): index.append( self.makeInteger(myfile,SQUASHFS_XATTR_BLOCK_BYTES(1)) ) bytes = SQUASHFS_XATTR_BYTES(ids) xattr_ids = {}","class SquashFsImage(_Squashfs_commons): index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids) indexes = SQUASHFS_XATTR_BLOCKS(ids) index = [] for r in range(0,indexes): index.append( self.makeInteger(myfile,SQUASHFS_XATTR_BLOCK_BYTES(1)) ) bytes = SQUASHFS_XATTR_BYTES(ids) xattr_ids = {}" 1248,https://:@github.com/CFPB/django-nudge.git,4c69de668bd9a2ba96c639c252f555bea9ec2d34,"@@ -55,7 +55,7 @@ def process_batch(key, batch_info, iv): success = True for item in items: item.save() - if isinstance(Version, item.object): + if isinstance(item.object, Version): version = item.object if version.type == VERSION_DELETE: if version.object: ",src/nudge/server.py,"ArgSwap(idxs=0<->1 @(58,15)->(58,25))","def process_batch(key, batch_info, iv): success = True for item in items: item.save() if isinstance(Version, item.object): version = item.object if version.type == VERSION_DELETE: if version.object:","def process_batch(key, batch_info, iv): success = True for item in items: item.save() if isinstance(item.object, Version): version = item.object if version.type == VERSION_DELETE: if version.object:" 1249,https://:@github.com/terminusdb/terminus-client-python.git,4e688ba70754dbe47b72232c720cf1100e6abea6,"@@ -422,7 +422,7 @@ class WOQLCore: def _clean_class(self, user_class, string_only=None): if type(user_class) != str: return """" - if "":"" in user_class: + if "":"" not in user_class: if self._vocab and (user_class in self._vocab): user_class = self._vocab[user_class] else: ",terminusdb_client/woqlquery/woql_core.py,"ReplaceText(target=' not in ' @(425,14)->(425,18))","class WOQLCore: def _clean_class(self, user_class, string_only=None): if type(user_class) != str: return """" if "":"" in user_class: if self._vocab and (user_class in self._vocab): user_class = self._vocab[user_class] else:","class WOQLCore: def _clean_class(self, user_class, string_only=None): if type(user_class) != str: return """" if "":"" not in user_class: if self._vocab and (user_class in self._vocab): user_class = self._vocab[user_class] else:" 1250,https://:@github.com/terminusdb/terminus-client-python.git,a8cb21f0481e248f02f895a7d0c16917f82fcd5d,"@@ -688,7 +688,7 @@ class WOQLClient: request_file_dict[name] = (name, open(path, ""rb""), ""application/binary"") payload = None else: - file_dict = None + request_file_dict = None payload = query_obj return self.dispatch( ",terminusdb_client/woqlclient/woqlClient.py,"ReplaceText(target='request_file_dict' @(691,12)->(691,21))","class WOQLClient: request_file_dict[name] = (name, open(path, ""rb""), ""application/binary"") payload = None else: file_dict = None payload = query_obj return self.dispatch(","class WOQLClient: request_file_dict[name] = (name, open(path, ""rb""), ""application/binary"") payload = None else: request_file_dict = None payload = query_obj return self.dispatch(" 1251,https://:@github.com/dnarvaez/osbuild.git,bd6517e635b15c77fa5c158e199cdb99139bf41e,"@@ -70,7 +70,7 @@ def system_check_touch(): def full_build_is_required(): full_build = _load_state(_FULL_BUILD) if not full_build: - return True + return False return not (full_build[""last""] == config.get_full_build()) ",osbuild/state.py,"ReplaceText(target='False' @(73,15)->(73,19))","def system_check_touch(): def full_build_is_required(): full_build = _load_state(_FULL_BUILD) if not full_build: return True return not (full_build[""last""] == config.get_full_build()) ","def system_check_touch(): def full_build_is_required(): full_build = _load_state(_FULL_BUILD) if not full_build: return False return not (full_build[""last""] == config.get_full_build()) " 1252,https://:@github.com/mwouts/easyplotly.git,687645cc6bb61a16c63259a696fe535059f91665,"@@ -35,7 +35,7 @@ def sunburst_or_treemap(values, root_label=None, branchvalues='total', **kwargs) for item in org_tree: if isinstance(item, tuple): - value = values[item] + value = org_tree[item] if value < 0: raise ValueError('Negative value {} for {}'.format(value, item)) ",easyplotly/internals.py,"ReplaceText(target='org_tree' @(38,20)->(38,26))","def sunburst_or_treemap(values, root_label=None, branchvalues='total', **kwargs) for item in org_tree: if isinstance(item, tuple): value = values[item] if value < 0: raise ValueError('Negative value {} for {}'.format(value, item)) ","def sunburst_or_treemap(values, root_label=None, branchvalues='total', **kwargs) for item in org_tree: if isinstance(item, tuple): value = org_tree[item] if value < 0: raise ValueError('Negative value {} for {}'.format(value, item)) " 1253,https://:@github.com/affinitic/collective.registration.git,9f740984c7d0206ea21321a37b1ba233003b7423,"@@ -31,6 +31,6 @@ class SubscriberView(BrowserView): def available_places_validator(self, context, request, value): registration = context.getParentNode().getParentNode() period = registration.get(request.form.get('period')) - if int(value) < period.available_places: + if int(value) <= period.available_places: return False return _('Not enough places left in the selected period') ",src/collective/registration/browser/subscriber.py,"ReplaceText(target='<=' @(34,22)->(34,23))","class SubscriberView(BrowserView): def available_places_validator(self, context, request, value): registration = context.getParentNode().getParentNode() period = registration.get(request.form.get('period')) if int(value) < period.available_places: return False return _('Not enough places left in the selected period')","class SubscriberView(BrowserView): def available_places_validator(self, context, request, value): registration = context.getParentNode().getParentNode() period = registration.get(request.form.get('period')) if int(value) <= period.available_places: return False return _('Not enough places left in the selected period')" 1254,https://:@github.com/alisaifee/pyutrack.git,620d59b82e8a5c98fd4568217c74b485f802ac94,"@@ -17,4 +17,4 @@ class AuthenticationTests(IntegrationTest): credentials=Credentials(username='root', password='rooted'), base_url='http://localhost:9876' ) - self.assertRaises(connection.login, LoginError) + self.assertRaises(LoginError, connection.login) ",tests/integration/test_authentication.py,"ArgSwap(idxs=0<->1 @(20,8)->(20,25))","class AuthenticationTests(IntegrationTest): credentials=Credentials(username='root', password='rooted'), base_url='http://localhost:9876' ) self.assertRaises(connection.login, LoginError)","class AuthenticationTests(IntegrationTest): credentials=Credentials(username='root', password='rooted'), base_url='http://localhost:9876' ) self.assertRaises(LoginError, connection.login)" 1255,https://:@github.com/angelolovatto/gym-cartpole-swingup.git,d31a62df97b07609f86358d3e25e70e623797995,"@@ -33,7 +33,7 @@ class TorchCartPoleSwingUpEnv(CartPoleSwingUpEnv): def terminal(self, state): """"""Return a batched tensor indicating which states are terminal."""""" - return (state[..., 0] < -self.params.x_threshold) & ( + return (state[..., 0] < -self.params.x_threshold) | ( state[..., 0] > self.params.x_threshold ) ",gym_cartpole_swingup/envs/torch_cartpole_swingup.py,"ReplaceText(target='|' @(36,58)->(36,59))","class TorchCartPoleSwingUpEnv(CartPoleSwingUpEnv): def terminal(self, state): """"""Return a batched tensor indicating which states are terminal."""""" return (state[..., 0] < -self.params.x_threshold) & ( state[..., 0] > self.params.x_threshold ) ","class TorchCartPoleSwingUpEnv(CartPoleSwingUpEnv): def terminal(self, state): """"""Return a batched tensor indicating which states are terminal."""""" return (state[..., 0] < -self.params.x_threshold) | ( state[..., 0] > self.params.x_threshold ) " 1256,https://:@github.com/shubhamjain0594/opalalgorithms.git,42258ea2348e9a624ab5deac7a334bab7656f565,"@@ -29,7 +29,7 @@ class PrivacyAlgorithmRunner(object): Return: dict: Privacy ensured dictionary """""" - result = self.algorithm(result, self.params, self.salt) + result = self.algorithm(self.params, result, self.salt) if self._validate_result(result): return result return {} ",opalalgorithms/utils/privacyrunner.py,"ArgSwap(idxs=0<->1 @(32,17)->(32,31))","class PrivacyAlgorithmRunner(object): Return: dict: Privacy ensured dictionary """""" result = self.algorithm(result, self.params, self.salt) if self._validate_result(result): return result return {}","class PrivacyAlgorithmRunner(object): Return: dict: Privacy ensured dictionary """""" result = self.algorithm(self.params, result, self.salt) if self._validate_result(result): return result return {}" 1257,https://:@github.com/rcook/ibt.git,f32b4fadfb4b9a1416864d7cc05ec867128a32d4,"@@ -54,7 +54,7 @@ class UpCommand(Command): subprocess.check_call([""/bin/sh"", temp_path]) if args.destroy: - docker_image_remove(ctx.image_id) + docker_image_remove(project.image_id) with temp_dir() as dir: if docker_image is None: ",ibtimpl/up_command.py,"ReplaceText(target='project' @(57,32)->(57,35))","class UpCommand(Command): subprocess.check_call([""/bin/sh"", temp_path]) if args.destroy: docker_image_remove(ctx.image_id) with temp_dir() as dir: if docker_image is None:","class UpCommand(Command): subprocess.check_call([""/bin/sh"", temp_path]) if args.destroy: docker_image_remove(project.image_id) with temp_dir() as dir: if docker_image is None:" 1258,https://:@github.com/MasterOdin/nullsmtp.git,f945b842e6f849834a020af87ad8293de7124451,"@@ -38,7 +38,7 @@ class NullSMTP(smtpd.SMTPServer): smtpd.SMTPServer.__init__(self, localaddr, None) self.logger = get_logger() - if mail_dir is None or isinstance(mail_dir, str): + if mail_dir is None or not isinstance(mail_dir, str): msg = ""Invalid mail_dir variable: {}"".format(mail_dir) self.logger.error(msg) raise SystemExit(msg) ",nullsmtp/nullsmtp.py,"ReplaceText(target='not ' @(41,31)->(41,31))","class NullSMTP(smtpd.SMTPServer): smtpd.SMTPServer.__init__(self, localaddr, None) self.logger = get_logger() if mail_dir is None or isinstance(mail_dir, str): msg = ""Invalid mail_dir variable: {}"".format(mail_dir) self.logger.error(msg) raise SystemExit(msg)","class NullSMTP(smtpd.SMTPServer): smtpd.SMTPServer.__init__(self, localaddr, None) self.logger = get_logger() if mail_dir is None or not isinstance(mail_dir, str): msg = ""Invalid mail_dir variable: {}"".format(mail_dir) self.logger.error(msg) raise SystemExit(msg)" 1259,https://:@github.com/ddbeck/oraide.git,2139a3d8eb3de615d3eea3435f9e715b15b82e93,"@@ -27,7 +27,7 @@ def assert_after_timeout(fn, timeout_duration=2.0): try: return fn() except AssertionError: - if time.time() < timeout: + if time.time() > timeout: raise return wrapper ",oraide/tests.py,"ReplaceText(target='>' @(30,31)->(30,32))","def assert_after_timeout(fn, timeout_duration=2.0): try: return fn() except AssertionError: if time.time() < timeout: raise return wrapper ","def assert_after_timeout(fn, timeout_duration=2.0): try: return fn() except AssertionError: if time.time() > timeout: raise return wrapper " 1260,https://:@github.com/thespacedoctor/marshallEngine.git,c2aa68840d770ad66caaa775d4497bc72dd6b3c5,"@@ -101,7 +101,7 @@ class data(object): print('HTTP Request failed') sys.exit(0) - if status_code != 502: + if status_code == 502: print('HTTP Request failed - status %(status_code)s' % locals()) print(url) self.csvDicts = [] ",marshallEngine/feeders/data.py,"ReplaceText(target='==' @(104,23)->(104,25))","class data(object): print('HTTP Request failed') sys.exit(0) if status_code != 502: print('HTTP Request failed - status %(status_code)s' % locals()) print(url) self.csvDicts = []","class data(object): print('HTTP Request failed') sys.exit(0) if status_code == 502: print('HTTP Request failed - status %(status_code)s' % locals()) print(url) self.csvDicts = []" 1261,https://:@github.com/JoshLee0915/youtrack-rest-python-library.git,0695b2e31750184cf7fa301821f3d4d050a90820,"@@ -154,7 +154,7 @@ class Issue(YouTrackObject): if getattr(self, 'links', None) is None: return self.youtrack.getLinks(self.id, outwardOnly) else: - return [l for l in self.links if l.source != self.id or not outwardOnly] + return [l for l in self.links if l.source == self.id or not outwardOnly] class Comment(YouTrackObject): ",python/youtrack/__init__.py,"ReplaceText(target='==' @(157,54)->(157,56))","class Issue(YouTrackObject): if getattr(self, 'links', None) is None: return self.youtrack.getLinks(self.id, outwardOnly) else: return [l for l in self.links if l.source != self.id or not outwardOnly] class Comment(YouTrackObject):","class Issue(YouTrackObject): if getattr(self, 'links', None) is None: return self.youtrack.getLinks(self.id, outwardOnly) else: return [l for l in self.links if l.source == self.id or not outwardOnly] class Comment(YouTrackObject):" 1262,https://:@github.com/JoshLee0915/youtrack-rest-python-library.git,7e5d1b3d6ad8e12ae2ef0791e4afcff9b3865fd3,"@@ -77,7 +77,7 @@ class YouTrackImporter(object): [self._to_yt_issue(issue, project_id) for issue in issues]) for issue in issues: issue_id = self._get_issue_id(issue) - issue_attachments = self._get_attachments(issue_id) + issue_attachments = self._get_attachments(issue) yt_issue_id = u'%s-%s' % (project_id, issue_id) self._import_attachments(yt_issue_id, issue_attachments) ",python/youtrackImporter.py,"ReplaceText(target='issue' @(80,58)->(80,66))","class YouTrackImporter(object): [self._to_yt_issue(issue, project_id) for issue in issues]) for issue in issues: issue_id = self._get_issue_id(issue) issue_attachments = self._get_attachments(issue_id) yt_issue_id = u'%s-%s' % (project_id, issue_id) self._import_attachments(yt_issue_id, issue_attachments) ","class YouTrackImporter(object): [self._to_yt_issue(issue, project_id) for issue in issues]) for issue in issues: issue_id = self._get_issue_id(issue) issue_attachments = self._get_attachments(issue) yt_issue_id = u'%s-%s' % (project_id, issue_id) self._import_attachments(yt_issue_id, issue_attachments) " 1263,https://:@github.com/bird-house/malleefowl.git,279479a4cba930e14803ea4a748faa57d884399f,"@@ -52,5 +52,5 @@ class ThreddsDownload(Process): with open('out.json', 'w') as fp: json.dump(obj=files, fp=fp, indent=4, sort_keys=True) - request.outputs['outputs'].file = fp.name + response.outputs['outputs'].file = fp.name return response ",malleefowl/processes/wps_thredds.py,"ReplaceText(target='response' @(55,12)->(55,19))","class ThreddsDownload(Process): with open('out.json', 'w') as fp: json.dump(obj=files, fp=fp, indent=4, sort_keys=True) request.outputs['outputs'].file = fp.name return response","class ThreddsDownload(Process): with open('out.json', 'w') as fp: json.dump(obj=files, fp=fp, indent=4, sort_keys=True) response.outputs['outputs'].file = fp.name return response" 1264,https://:@github.com/jeremiedecock/mrif.git,51ea19f5d8cec9f4759eb8079dc4c01295719577,"@@ -228,7 +228,7 @@ class AbstractCleaningAlgorithm(object): image_dict[""img_cleaned_max_pe""] = float(np.nanmax(cleaned_img)) image_dict[""img_cleaned_num_pix""] = int( (cleaned_img[np.isfinite(cleaned_img)] > 0).sum() ) - cleaned_img1d = geometry_converter.image_2d_to_1d(reference_img, fits_metadata_dict['cam_id']) + cleaned_img1d = geometry_converter.image_2d_to_1d(cleaned_img, fits_metadata_dict['cam_id']) hillas_params_2_cleaned_img = get_hillas_parameters(geom1d, cleaned_img1d, HILLAS_IMPLEMENTATION) # GEOM image_dict[""img_cleaned_hillas_2_size""] = float(hillas_params_2_cleaned_img.size) ",datapipe/denoising/abstract_cleaning_algorithm.py,"ReplaceText(target='cleaned_img' @(231,74)->(231,87))","class AbstractCleaningAlgorithm(object): image_dict[""img_cleaned_max_pe""] = float(np.nanmax(cleaned_img)) image_dict[""img_cleaned_num_pix""] = int( (cleaned_img[np.isfinite(cleaned_img)] > 0).sum() ) cleaned_img1d = geometry_converter.image_2d_to_1d(reference_img, fits_metadata_dict['cam_id']) hillas_params_2_cleaned_img = get_hillas_parameters(geom1d, cleaned_img1d, HILLAS_IMPLEMENTATION) # GEOM image_dict[""img_cleaned_hillas_2_size""] = float(hillas_params_2_cleaned_img.size)","class AbstractCleaningAlgorithm(object): image_dict[""img_cleaned_max_pe""] = float(np.nanmax(cleaned_img)) image_dict[""img_cleaned_num_pix""] = int( (cleaned_img[np.isfinite(cleaned_img)] > 0).sum() ) cleaned_img1d = geometry_converter.image_2d_to_1d(cleaned_img, fits_metadata_dict['cam_id']) hillas_params_2_cleaned_img = get_hillas_parameters(geom1d, cleaned_img1d, HILLAS_IMPLEMENTATION) # GEOM image_dict[""img_cleaned_hillas_2_size""] = float(hillas_params_2_cleaned_img.size)" 1265,https://:@github.com/dsbowen/hemlock.git,4fb5980272b7827170bf66d1a405354e50b5deab,"@@ -35,7 +35,7 @@ def Start(): Choice(q, '2', value=2) p = Page(b) - q = Question(b, 'Where do you shop?', qtype='free', var='shop') + q = Question(p, 'Where do you shop?', qtype='free', var='shop') p = Page(b, terminal=True) q = Question(p, ""

Thank you for participating!

"") ",survey.py,"ReplaceText(target='p' @(38,17)->(38,18))","def Start(): Choice(q, '2', value=2) p = Page(b) q = Question(b, 'Where do you shop?', qtype='free', var='shop') p = Page(b, terminal=True) q = Question(p, ""

Thank you for participating!

"")","def Start(): Choice(q, '2', value=2) p = Page(b) q = Question(p, 'Where do you shop?', qtype='free', var='shop') p = Page(b, terminal=True) q = Question(p, ""

Thank you for participating!

"")" 1266,https://:@github.com/dsbowen/hemlock.git,314a07abb5445aaf7433ef26bfd0cbe7e576018d,"@@ -128,7 +128,7 @@ def _verify_data(check, last_instr_page, curr_attempt, attempts): attempts : int or None Maximum number of attempts. """""" - if all(q.data for q in check.questions) or curr_attempt == attempts: + if all(q.data for q in check.questions) or curr_attempt >= attempts: if check != check.branch.pages[-1]: # this check does not have to be repeated last_instr_page.forward_to = check.branch.pages[check.index+1] ",hemlock/tools/comprehension.py,"ReplaceText(target='>=' @(131,60)->(131,62))","def _verify_data(check, last_instr_page, curr_attempt, attempts): attempts : int or None Maximum number of attempts. """""" if all(q.data for q in check.questions) or curr_attempt == attempts: if check != check.branch.pages[-1]: # this check does not have to be repeated last_instr_page.forward_to = check.branch.pages[check.index+1]","def _verify_data(check, last_instr_page, curr_attempt, attempts): attempts : int or None Maximum number of attempts. """""" if all(q.data for q in check.questions) or curr_attempt >= attempts: if check != check.branch.pages[-1]: # this check does not have to be repeated last_instr_page.forward_to = check.branch.pages[check.index+1]" 1267,https://:@github.com/cartlogic/manhattan.git,4be7aa9c741a051e82e2c11a16af9ddc8758554f,"@@ -49,5 +49,5 @@ def truncate_recent(max_records): offset(max_records) delete_before = q.scalar() if delete_before: - q = t.delete().where(t.c.last_timestamp >= delete_before) + q = t.delete().where(t.c.last_timestamp < delete_before) meta.Session.execute(q) ",manhattan/backends/sql/model/recent.py,"ReplaceText(target='<' @(52,48)->(52,50))","def truncate_recent(max_records): offset(max_records) delete_before = q.scalar() if delete_before: q = t.delete().where(t.c.last_timestamp >= delete_before) meta.Session.execute(q)","def truncate_recent(max_records): offset(max_records) delete_before = q.scalar() if delete_before: q = t.delete().where(t.c.last_timestamp < delete_before) meta.Session.execute(q)" 1268,https://:@github.com/patryk4815/PySteamWeb.git,77176388a1673364d9a2b11018b6508db603d445,"@@ -52,7 +52,7 @@ class SteamTrade(SteamWebBase): def get_parse_trade_url(cls, trade_url): regex = re.compile(r'^https?://steamcommunity\.com/tradeoffer/new/\?partner=(\d+)&token=([a-zA-Z0-9_-]+)$') match = regex.match(trade_url) - if match: + if not match: return None return { ",pysteamweb/plugins/trade.py,"ReplaceText(target='not ' @(55,11)->(55,11))","class SteamTrade(SteamWebBase): def get_parse_trade_url(cls, trade_url): regex = re.compile(r'^https?://steamcommunity\.com/tradeoffer/new/\?partner=(\d+)&token=([a-zA-Z0-9_-]+)$') match = regex.match(trade_url) if match: return None return {","class SteamTrade(SteamWebBase): def get_parse_trade_url(cls, trade_url): regex = re.compile(r'^https?://steamcommunity\.com/tradeoffer/new/\?partner=(\d+)&token=([a-zA-Z0-9_-]+)$') match = regex.match(trade_url) if not match: return None return {" 1269,https://:@github.com/reidmcy/uchicago-pyanno.git,f23229e9f63648d04ba10b6fea310742f0fc52b3,"@@ -11,5 +11,5 @@ def is_display_small(): size = wx.GetDisplaySize() if size is not None: w, h = size - return w < 1300 and h < 850 + return w < 1300 or h < 850 return False ",pyanno/ui/appbase/wx_utils.py,"ReplaceText(target='or' @(14,24)->(14,27))","def is_display_small(): size = wx.GetDisplaySize() if size is not None: w, h = size return w < 1300 and h < 850 return False","def is_display_small(): size = wx.GetDisplaySize() if size is not None: w, h = size return w < 1300 or h < 850 return False" 1270,https://:@github.com/hbradleyiii/nwid.git,86c3d7b9c0b6f35f3310250c0ddc690d3280e023,"@@ -55,7 +55,7 @@ class TerminalString(object): self.escape_markers = [] for index, char in enumerate(self.string): # Mark the stop of an escape sequence - if sequence_start is None and char in string.letters: + if sequence_start is not None and char in string.letters: self.escape_markers.append(EscapeMarker(sequence_start, index)) sequence_start = None # Reset start sequence ",nwid/terminal/terminal_string.py,"ReplaceText(target=' is not ' @(58,29)->(58,33))","class TerminalString(object): self.escape_markers = [] for index, char in enumerate(self.string): # Mark the stop of an escape sequence if sequence_start is None and char in string.letters: self.escape_markers.append(EscapeMarker(sequence_start, index)) sequence_start = None # Reset start sequence ","class TerminalString(object): self.escape_markers = [] for index, char in enumerate(self.string): # Mark the stop of an escape sequence if sequence_start is not None and char in string.letters: self.escape_markers.append(EscapeMarker(sequence_start, index)) sequence_start = None # Reset start sequence " 1271,https://:@gitlab.com/metapensiero/metapensiero.sqlalchemy.asyncpg.git,107f9fec1716ab99d5deee8deec1e6c92f9ed40c,"@@ -34,7 +34,7 @@ def compile(stmt, pos_args=None, named_args=None, _d=PGDialect_asyncpg()): """""" if isinstance(stmt, str): - return stmt, tuple(pos_args) if pos_args is None else () + return stmt, tuple(pos_args) if pos_args is not None else () else: compiled = stmt.compile(dialect=_d) params = compiled.construct_params(named_args) ",src/arstecnica/ytefas/asyncpg/__init__.py,"ReplaceText(target=' is not ' @(37,48)->(37,52))","def compile(stmt, pos_args=None, named_args=None, _d=PGDialect_asyncpg()): """""" if isinstance(stmt, str): return stmt, tuple(pos_args) if pos_args is None else () else: compiled = stmt.compile(dialect=_d) params = compiled.construct_params(named_args)","def compile(stmt, pos_args=None, named_args=None, _d=PGDialect_asyncpg()): """""" if isinstance(stmt, str): return stmt, tuple(pos_args) if pos_args is not None else () else: compiled = stmt.compile(dialect=_d) params = compiled.construct_params(named_args)" 1272,https://:@github.com/CMU-ARM/alloy.git,04200226608ac01de2e5fa0778da0b6ec2a34f79,"@@ -52,7 +52,7 @@ class PrioritySearchQueue(SearchQueue): def update(self, obj, **kwargs): for h in self._pheap: if h[1] == obj: - self._pheap.remove(obj) + self._pheap.remove(h) break heapq.heappush(self._pheap, (kwargs['cost'], obj)) ",alloy/algo/graph_search.py,"ReplaceText(target='h' @(55,35)->(55,38))","class PrioritySearchQueue(SearchQueue): def update(self, obj, **kwargs): for h in self._pheap: if h[1] == obj: self._pheap.remove(obj) break heapq.heappush(self._pheap, (kwargs['cost'], obj)) ","class PrioritySearchQueue(SearchQueue): def update(self, obj, **kwargs): for h in self._pheap: if h[1] == obj: self._pheap.remove(h) break heapq.heappush(self._pheap, (kwargs['cost'], obj)) " 1273,https://:@github.com/pombredanne/schematics.git,8fad1ee655244b3e6cf24a4b4236d414075498ca,"@@ -47,7 +47,7 @@ def apply_shape(cls, model_or_dict, field_converter, model_converter, model_dict[serialized_name] = model_converter(field_value) ### Convert field as list of models - elif isinstance(field_name, list) and len(field_value) > 0: + elif isinstance(field_value, list) and len(field_value) > 0: if isinstance(field_value[0], Model): model_dict[serialized_name] = [model_converter(vi) for vi in field_value] ",schematics/serialize.py,"ReplaceText(target='field_value' @(50,24)->(50,34))","def apply_shape(cls, model_or_dict, field_converter, model_converter, model_dict[serialized_name] = model_converter(field_value) ### Convert field as list of models elif isinstance(field_name, list) and len(field_value) > 0: if isinstance(field_value[0], Model): model_dict[serialized_name] = [model_converter(vi) for vi in field_value]","def apply_shape(cls, model_or_dict, field_converter, model_converter, model_dict[serialized_name] = model_converter(field_value) ### Convert field as list of models elif isinstance(field_value, list) and len(field_value) > 0: if isinstance(field_value[0], Model): model_dict[serialized_name] = [model_converter(vi) for vi in field_value]" 1274,https://:@github.com/Hedgehogues/python-clients.git,e4e905beb5cc095f6c2a3d0d0ffec5dda5c6fd68,"@@ -68,7 +68,7 @@ class Client: else: r = requests.get(url=url, params=method.params, headers=method.headers, proxies=self.proxies, auth=auth_) elif m_type == 'FILE': - assert method.files is None, 'For FILE attribute file must not be empty' + assert method.files is not None, 'For FILE attribute file must not be empty' if self.proxies is not None: r = requests.post(url=url, params=method.params, data=method.body, headers=method.headers, auth=auth_, files=method.files) ",clients/http.py,"ReplaceText(target=' is not ' @(71,31)->(71,35))","class Client: else: r = requests.get(url=url, params=method.params, headers=method.headers, proxies=self.proxies, auth=auth_) elif m_type == 'FILE': assert method.files is None, 'For FILE attribute file must not be empty' if self.proxies is not None: r = requests.post(url=url, params=method.params, data=method.body, headers=method.headers, auth=auth_, files=method.files)","class Client: else: r = requests.get(url=url, params=method.params, headers=method.headers, proxies=self.proxies, auth=auth_) elif m_type == 'FILE': assert method.files is not None, 'For FILE attribute file must not be empty' if self.proxies is not None: r = requests.post(url=url, params=method.params, data=method.body, headers=method.headers, auth=auth_, files=method.files)" 1275,https://:@github.com/pbrisk/businessdate.git,c5359efe862021fe445ef048ac52a30b527cce83,"@@ -116,7 +116,7 @@ class BusinessPeriod(object): def _parse_ymd(cls, period): # can even parse strings like '-1B-2Y-4Q+5M' but also '0B', '-1Y2M3D' as well. def _parse(p, letter): - if p.find(letter) > 0: + if p.find(letter) >= 0: s, p = p.split(letter, 1) s = s[1:] if s.startswith('+') else s sgn, s = (-1, s[1:]) if s.startswith('-') else (1, s) ",businessdate/businessperiod.py,"ReplaceText(target='>=' @(119,30)->(119,31))","class BusinessPeriod(object): def _parse_ymd(cls, period): # can even parse strings like '-1B-2Y-4Q+5M' but also '0B', '-1Y2M3D' as well. def _parse(p, letter): if p.find(letter) > 0: s, p = p.split(letter, 1) s = s[1:] if s.startswith('+') else s sgn, s = (-1, s[1:]) if s.startswith('-') else (1, s)","class BusinessPeriod(object): def _parse_ymd(cls, period): # can even parse strings like '-1B-2Y-4Q+5M' but also '0B', '-1Y2M3D' as well. def _parse(p, letter): if p.find(letter) >= 0: s, p = p.split(letter, 1) s = s[1:] if s.startswith('+') else s sgn, s = (-1, s[1:]) if s.startswith('-') else (1, s)" 1276,https://:@github.com/GenesisCoast/conditions-py.git,c6326f3fc1805eddc80f4556e786523bf6725ffd,"@@ -306,7 +306,7 @@ class StringValidator(Validator): """""" Checks whether the given value does not match the supplied `pattern`. An exception is thrown otherwise. """""" - if not RegexHelper.is_match(pattern, self.value): + if RegexHelper.is_match(pattern, self.value): raise ArgumentPatternError( f'The argument `{self.argument_name}` should match the pattern `{pattern}`', self.value, ",src/validators/string_validator.py,"ReplaceText(target='' @(309,11)->(309,15))","class StringValidator(Validator): """""" Checks whether the given value does not match the supplied `pattern`. An exception is thrown otherwise. """""" if not RegexHelper.is_match(pattern, self.value): raise ArgumentPatternError( f'The argument `{self.argument_name}` should match the pattern `{pattern}`', self.value,","class StringValidator(Validator): """""" Checks whether the given value does not match the supplied `pattern`. An exception is thrown otherwise. """""" if RegexHelper.is_match(pattern, self.value): raise ArgumentPatternError( f'The argument `{self.argument_name}` should match the pattern `{pattern}`', self.value," 1277,https://:@github.com/aperezdc/omni.git,5755dd751e818fcb78235a0c1a17a4d654d0cb6e,"@@ -304,7 +304,7 @@ def authenticate(get_realm, realm_param=""realm""): if request.authorization: password = b64decode(request.authorization[1]) username, password = password.decode(""utf-8"").split("":"", 1) - if username is None or realm.authenticate(username, password): + if username is None or not realm.authenticate(username, password): raise HTTPUnauthorized(headers=[ (""WWW-Authenticate"", ""Basic realm=\""{}\"""".format(realm.description)), ",omni/web/routing.py,"ReplaceText(target='not ' @(307,35)->(307,35))","def authenticate(get_realm, realm_param=""realm""): if request.authorization: password = b64decode(request.authorization[1]) username, password = password.decode(""utf-8"").split("":"", 1) if username is None or realm.authenticate(username, password): raise HTTPUnauthorized(headers=[ (""WWW-Authenticate"", ""Basic realm=\""{}\"""".format(realm.description)),","def authenticate(get_realm, realm_param=""realm""): if request.authorization: password = b64decode(request.authorization[1]) username, password = password.decode(""utf-8"").split("":"", 1) if username is None or not realm.authenticate(username, password): raise HTTPUnauthorized(headers=[ (""WWW-Authenticate"", ""Basic realm=\""{}\"""".format(realm.description))," 1278,https://:@github.com/nectar-cs/k8-kat.git,5dceaae2ba32d6053cbf8c416b684241f8ed9d96,"@@ -66,7 +66,7 @@ def get_deployment_pods(deployment): restarts = None age = None - if returned_pod.status.container_statuses is not None and len(returned_pod.status.container_statuses) < 0: + if returned_pod.status.container_statuses is not None and len(returned_pod.status.container_statuses) > 0: first_container = returned_pod.status.container_statuses[0] restarts = first_container.restart_count age = first_container.restart_count ",kube_pod.py,"ReplaceText(target='>' @(69,110)->(69,111))","def get_deployment_pods(deployment): restarts = None age = None if returned_pod.status.container_statuses is not None and len(returned_pod.status.container_statuses) < 0: first_container = returned_pod.status.container_statuses[0] restarts = first_container.restart_count age = first_container.restart_count","def get_deployment_pods(deployment): restarts = None age = None if returned_pod.status.container_statuses is not None and len(returned_pod.status.container_statuses) > 0: first_container = returned_pod.status.container_statuses[0] restarts = first_container.restart_count age = first_container.restart_count" 1279,https://:@github.com/nectar-cs/k8-kat.git,b27ef1a95763299653425c8968aa08d2f59b254e,"@@ -40,7 +40,7 @@ class StuntPod: return self._image def find(self): - return PodHelper.find(self.pod_name, self.namespace) + return PodHelper.find(self.namespace, self.pod_name) def labels(self): return {""nectar-type"": ""stunt-pod""} ",stunt_pods/stunt_pod.py,"ArgSwap(idxs=0<->1 @(43,11)->(43,25))","class StuntPod: return self._image def find(self): return PodHelper.find(self.pod_name, self.namespace) def labels(self): return {""nectar-type"": ""stunt-pod""}","class StuntPod: return self._image def find(self): return PodHelper.find(self.namespace, self.pod_name) def labels(self): return {""nectar-type"": ""stunt-pod""}" 1280,https://:@github.com/nectar-cs/k8-kat.git,8a2f45982919c69bc709aa14a16c7a402dcafd4b,"@@ -26,6 +26,6 @@ class KatServiceAccount(KatRes): def secrets(self) -> List[any]: from k8_kat.res.secret.kat_secret import KatSecret - make = lambda sd: KatSecret.find(sd.namespace or self.ns, sd.name) + make = lambda sd: KatSecret.find(sd.name, sd.namespace or self.ns) secret_descriptors = self.body().secrets or [] return [make(secret_desc) for secret_desc in secret_descriptors] ",k8_kat/res/sa/kat_service_account.py,"ArgSwap(idxs=0<->1 @(29,22)->(29,36))","class KatServiceAccount(KatRes): def secrets(self) -> List[any]: from k8_kat.res.secret.kat_secret import KatSecret make = lambda sd: KatSecret.find(sd.namespace or self.ns, sd.name) secret_descriptors = self.body().secrets or [] return [make(secret_desc) for secret_desc in secret_descriptors]","class KatServiceAccount(KatRes): def secrets(self) -> List[any]: from k8_kat.res.secret.kat_secret import KatSecret make = lambda sd: KatSecret.find(sd.name, sd.namespace or self.ns) secret_descriptors = self.body().secrets or [] return [make(secret_desc) for secret_desc in secret_descriptors]" 1281,https://:@github.com/nectar-cs/k8-kat.git,8a2f45982919c69bc709aa14a16c7a402dcafd4b,"@@ -12,7 +12,7 @@ class TestKatSvc(ClusterTest): test_helper.create_svc(cls.n1, 's1') def setUp(self) -> None: - self.subject: KatSvc = KatSvc.find(self.n1, 's1') + self.subject: KatSvc = KatSvc.find('s1', self.n1) def test_internal_ip(self): self.assertIsNotNone(self.subject.internal_ip) ",k8_kat/tests/res/svc/test_kat_svc.py,"ArgSwap(idxs=0<->1 @(15,27)->(15,38))","class TestKatSvc(ClusterTest): test_helper.create_svc(cls.n1, 's1') def setUp(self) -> None: self.subject: KatSvc = KatSvc.find(self.n1, 's1') def test_internal_ip(self): self.assertIsNotNone(self.subject.internal_ip)","class TestKatSvc(ClusterTest): test_helper.create_svc(cls.n1, 's1') def setUp(self) -> None: self.subject: KatSvc = KatSvc.find('s1', self.n1) def test_internal_ip(self): self.assertIsNotNone(self.subject.internal_ip)" 1282,https://:@github.com/hlmtre/pybot.git,d893f64e69b2d7a8393eacb3620e927f5c7ce10d,"@@ -155,7 +155,7 @@ class Event: self.verb = v break # channel is unset if it does not begin with # - if self.verb == ""PRIVMSG"" and len(self.channel): + if self.verb == ""PRIVMSG"" and not len(self.channel): self.is_pm = True for s in self.subscribers: try: ",event.py,"ReplaceText(target='not ' @(158,34)->(158,34))","class Event: self.verb = v break # channel is unset if it does not begin with # if self.verb == ""PRIVMSG"" and len(self.channel): self.is_pm = True for s in self.subscribers: try:","class Event: self.verb = v break # channel is unset if it does not begin with # if self.verb == ""PRIVMSG"" and not len(self.channel): self.is_pm = True for s in self.subscribers: try:" 1283,https://:@github.com/tboudreaux/vectorpy.git,55394cff47bf052127af1a64f0eb9043365864ae,"@@ -64,7 +64,7 @@ class vector: # Data type name return not self.__eq__(other) def cross(self, other): # Corss product - return vector(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y-other.x) + return vector(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) def dot(self, other): # dot product return self.x*other.x + self.y*other.y + self.z*other.z ",vectorpy/vector.py,"ReplaceText(target='*' @(67,111)->(67,112))","class vector: # Data type name return not self.__eq__(other) def cross(self, other): # Corss product return vector(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y-other.x) def dot(self, other): # dot product return self.x*other.x + self.y*other.y + self.z*other.z","class vector: # Data type name return not self.__eq__(other) def cross(self, other): # Corss product return vector(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x) def dot(self, other): # dot product return self.x*other.x + self.y*other.y + self.z*other.z" 1284,https://:@github.com/detectlabs/aioble.git,90e1e234ade4c5fa78df42bc856f3e3a8f571077,"@@ -116,7 +116,7 @@ async def connect_two(): cm_all = CentralManager() await cm_all.start_scan(scan_callback_all) - while d_10_device is None and d_5_device is None: + while d_10_device is None or d_5_device is None: await asyncio.sleep(.1) await cm_all.stop_scan() ",examples/connect.py,"ReplaceText(target='or' @(119,34)->(119,37))","async def connect_two(): cm_all = CentralManager() await cm_all.start_scan(scan_callback_all) while d_10_device is None and d_5_device is None: await asyncio.sleep(.1) await cm_all.stop_scan()","async def connect_two(): cm_all = CentralManager() await cm_all.start_scan(scan_callback_all) while d_10_device is None or d_5_device is None: await asyncio.sleep(.1) await cm_all.stop_scan()" 1285,https://:@github.com/speezepearson/prpg.git,aa36906fdc61e1f57250372d6b7c596c676bc203,"@@ -27,4 +27,4 @@ def dump_salts(f, salts): f.write(payload) else: with open(f, 'w') as true_f: - f.write(payload) + true_f.write(payload) ",__init__.py,"ReplaceText(target='true_f' @(30,6)->(30,7))","def dump_salts(f, salts): f.write(payload) else: with open(f, 'w') as true_f: f.write(payload)","def dump_salts(f, salts): f.write(payload) else: with open(f, 'w') as true_f: true_f.write(payload)" 1286,https://:@github.com/wehriam/awspider.git,cecf24d302f5a2d0f454fecfbb5915f7a4f19ed0,"@@ -178,4 +178,4 @@ class InterfaceServer(BaseServer): def _createReservationErrback(self, error, function_name, uuid): LOGGER.error(""Unable to create reservation for %s:%s, %s.\n"" % (function_name, uuid, error)) - return uuid \ No newline at end of file + return error \ No newline at end of file ",awspider/servers2/interface.py,"ReplaceText(target='error' @(181,15)->(181,19))","class InterfaceServer(BaseServer): def _createReservationErrback(self, error, function_name, uuid): LOGGER.error(""Unable to create reservation for %s:%s, %s.\n"" % (function_name, uuid, error)) return uuid \ No newline at end of file \ No newline at end of file","class InterfaceServer(BaseServer): def _createReservationErrback(self, error, function_name, uuid): LOGGER.error(""Unable to create reservation for %s:%s, %s.\n"" % (function_name, uuid, error)) \ No newline at end of file return error \ No newline at end of file" 1287,https://:@github.com/combatopera/diapyr.git,2deb919498af4943aa18a7281037468809bda2d0,"@@ -22,7 +22,7 @@ class BinMix(Node): self.blockbuf.copybuf(self.tone(self.block)) if not noiseflag: self.blockbuf.orbuf(self.noise(self.block)) - elif noiseflag: + elif not noiseflag: self.blockbuf.copybuf(self.noise(self.block)) else: self.blockbuf.fill(0) ",pym2149/mix.py,"ReplaceText(target='not ' @(25,9)->(25,9))","class BinMix(Node): self.blockbuf.copybuf(self.tone(self.block)) if not noiseflag: self.blockbuf.orbuf(self.noise(self.block)) elif noiseflag: self.blockbuf.copybuf(self.noise(self.block)) else: self.blockbuf.fill(0)","class BinMix(Node): self.blockbuf.copybuf(self.tone(self.block)) if not noiseflag: self.blockbuf.orbuf(self.noise(self.block)) elif not noiseflag: self.blockbuf.copybuf(self.noise(self.block)) else: self.blockbuf.fill(0)" 1288,https://:@github.com/InfluxGraph/graphite-api.git,2847d5788bc8adbd8d864a234d7e4cb39210fc29,"@@ -787,7 +787,7 @@ def file_fetch(fh, fromTime, untilTime, now = None): if untilTime > now: untilTime = now - diff = untilTime - fromTime + diff = now - fromTime for archive in header['archives']: if archive['retention'] >= diff: break ",graphite_api/_vendor/whisper.py,"ReplaceText(target='now' @(790,9)->(790,18))","def file_fetch(fh, fromTime, untilTime, now = None): if untilTime > now: untilTime = now diff = untilTime - fromTime for archive in header['archives']: if archive['retention'] >= diff: break","def file_fetch(fh, fromTime, untilTime, now = None): if untilTime > now: untilTime = now diff = now - fromTime for archive in header['archives']: if archive['retention'] >= diff: break" 1289,https://:@github.com/JulianKimmig/json_websocket.git,188740f4381fea77078950cd5540842f2e3dc75e,"@@ -11,7 +11,7 @@ def merge(new_values, default_values): for key, value in default_values.items(): nv = new_values.get(key, None) if isinstance(value, dict) and isinstance(nv, dict): - nd[key] = merge(value, nv) + nd[key] = merge(nv, value) else: if nv is None: nd[key] = value ",json_websocket/basic/abstract_json_socket.py,"ArgSwap(idxs=0<->1 @(14,22)->(14,27))","def merge(new_values, default_values): for key, value in default_values.items(): nv = new_values.get(key, None) if isinstance(value, dict) and isinstance(nv, dict): nd[key] = merge(value, nv) else: if nv is None: nd[key] = value","def merge(new_values, default_values): for key, value in default_values.items(): nv = new_values.get(key, None) if isinstance(value, dict) and isinstance(nv, dict): nd[key] = merge(nv, value) else: if nv is None: nd[key] = value" 1290,https://:@github.com/accurrently/evnrg.git,b045f854eb398a314608cdd195b114b3a8fa8231,"@@ -476,7 +476,7 @@ def charge_connected(input_batt, output_batt, fleet, home_bank, away_bank, min_p if may_charge: pot = (min_per_interval / 60.0) * power max_nrg = max_batt * max_soc - output_batt[i] = min(current_batt[i] + pot, max_nrg) + output_batt[i] = min(input_batt[i] + pot, max_nrg) @nb.njit(cache=True) ",evnrg/simulation_nb.py,"ReplaceText(target='input_batt' @(479,33)->(479,45))","def charge_connected(input_batt, output_batt, fleet, home_bank, away_bank, min_p if may_charge: pot = (min_per_interval / 60.0) * power max_nrg = max_batt * max_soc output_batt[i] = min(current_batt[i] + pot, max_nrg) @nb.njit(cache=True)","def charge_connected(input_batt, output_batt, fleet, home_bank, away_bank, min_p if may_charge: pot = (min_per_interval / 60.0) * power max_nrg = max_batt * max_soc output_batt[i] = min(input_batt[i] + pot, max_nrg) @nb.njit(cache=True)" 1291,https://:@github.com/Dominick1993/pyhelm.git,f91f0e9216f1436c3671d7eae8920900a398a01d,"@@ -106,7 +106,7 @@ def from_repo(repo_url, chart, version=None, headers=None): _get_from_repo( repo_scheme, repo_url, - url, + fname, stream=True, headers=headers, ) ",pyhelm/repo.py,"ReplaceText(target='fname' @(109,24)->(109,27))","def from_repo(repo_url, chart, version=None, headers=None): _get_from_repo( repo_scheme, repo_url, url, stream=True, headers=headers, )","def from_repo(repo_url, chart, version=None, headers=None): _get_from_repo( repo_scheme, repo_url, fname, stream=True, headers=headers, )" 1292,https://:@github.com/Dominick1993/pyhelm.git,7ce03b8f5b2d35015bf34f6df059d61ee4c57054,"@@ -106,7 +106,7 @@ def from_repo(repo_url, chart, version=None, headers=None): _get_from_repo( repo_scheme, repo_url, - fname, + url, stream=True, headers=headers, ) ",pyhelm/repo.py,"ReplaceText(target='url' @(109,24)->(109,29))","def from_repo(repo_url, chart, version=None, headers=None): _get_from_repo( repo_scheme, repo_url, fname, stream=True, headers=headers, )","def from_repo(repo_url, chart, version=None, headers=None): _get_from_repo( repo_scheme, repo_url, url, stream=True, headers=headers, )" 1293,https://:@github.com/tazle/bufrpy.git,eccb7469feec461e1ede41f8352c3700c7f7a885,"@@ -66,7 +66,7 @@ def read_tables(b_line_stream, d_line_stream=None): constituent_codes = [] for line in lines: l_parts = slices(line, [1,6,1,2,1,6]) - constituent_codes.append(fxy2int(parts[5])) + constituent_codes.append(fxy2int(l_parts[5])) descriptors[d_descriptor_code] = LazySequenceDescriptor(d_descriptor_code, constituent_codes, '', table) return table ",bufrpy/table/libbufr.py,"ReplaceText(target='l_parts' @(69,49)->(69,54))","def read_tables(b_line_stream, d_line_stream=None): constituent_codes = [] for line in lines: l_parts = slices(line, [1,6,1,2,1,6]) constituent_codes.append(fxy2int(parts[5])) descriptors[d_descriptor_code] = LazySequenceDescriptor(d_descriptor_code, constituent_codes, '', table) return table","def read_tables(b_line_stream, d_line_stream=None): constituent_codes = [] for line in lines: l_parts = slices(line, [1,6,1,2,1,6]) constituent_codes.append(fxy2int(l_parts[5])) descriptors[d_descriptor_code] = LazySequenceDescriptor(d_descriptor_code, constituent_codes, '', table) return table" 1294,https://:@bitbucket.org/mjr129/cluster_searcher.git,7af9e61f76366c820fe7bd23b935c2f59fe05c33,"@@ -250,7 +250,7 @@ def load_taxa( file_name: MOptional[Filename[EXT.TXT]] = None ) -> None: raise ValueError( ""load_taxa: Refused because the LECA must be loaded first."" ) num_clusters, num_taxa = state.leca_file.load_taxa( file_name ) - MCMD.print( ""{} taxa loaded into {} clusters."".format( num_clusters, num_taxa ) ) + MCMD.print( ""{} taxa loaded into {} clusters."".format( num_taxa, num_clusters ) ) state.settings.last_taxa = file_name ",cluster_searcher/commands.py,"ArgSwap(idxs=0<->1 @(253,16)->(253,57))","def load_taxa( file_name: MOptional[Filename[EXT.TXT]] = None ) -> None: raise ValueError( ""load_taxa: Refused because the LECA must be loaded first."" ) num_clusters, num_taxa = state.leca_file.load_taxa( file_name ) MCMD.print( ""{} taxa loaded into {} clusters."".format( num_clusters, num_taxa ) ) state.settings.last_taxa = file_name ","def load_taxa( file_name: MOptional[Filename[EXT.TXT]] = None ) -> None: raise ValueError( ""load_taxa: Refused because the LECA must be loaded first."" ) num_clusters, num_taxa = state.leca_file.load_taxa( file_name ) MCMD.print( ""{} taxa loaded into {} clusters."".format( num_taxa, num_clusters ) ) state.settings.last_taxa = file_name " 1295,https://:@github.com/thadhaines/PSLTDSim.git,5dc7e46a081628010935853d830aa82b98e2df69,"@@ -76,7 +76,7 @@ class tgov1Agent(): _, y3, self.x3 = sig.lsim(self.sys3, U=uVector, T=self.t, X0=[self.r_x1[self.mirror.c_dp-1],self.Gen.r_Pm[self.mirror.c_dp-1]]) # Addition of damping - Pmech = y3 - dwVec*self.Dt # effectively removing the second block... + Pmech = y2 - dwVec*self.Dt # effectively removing the second block... # Set Generator Mechanical Power self.Gen.Pm = float(Pmech[1]) ",psltdsim/dynamicAgents/tgov1Agent.py,"ReplaceText(target='y2' @(79,16)->(79,18))","class tgov1Agent(): _, y3, self.x3 = sig.lsim(self.sys3, U=uVector, T=self.t, X0=[self.r_x1[self.mirror.c_dp-1],self.Gen.r_Pm[self.mirror.c_dp-1]]) # Addition of damping Pmech = y3 - dwVec*self.Dt # effectively removing the second block... # Set Generator Mechanical Power self.Gen.Pm = float(Pmech[1])","class tgov1Agent(): _, y3, self.x3 = sig.lsim(self.sys3, U=uVector, T=self.t, X0=[self.r_x1[self.mirror.c_dp-1],self.Gen.r_Pm[self.mirror.c_dp-1]]) # Addition of damping Pmech = y2 - dwVec*self.Dt # effectively removing the second block... # Set Generator Mechanical Power self.Gen.Pm = float(Pmech[1])" 1296,https://:@github.com/rbn42/freetile.git,86701ce263f0551e005e9fe5ed11ff03ceb0ce68,"@@ -45,7 +45,7 @@ class WindowList: if name in EXCLUDE_APPLICATIONS: continue - wmclass, minimized = get_wm_class_and_state(winid) + wmclass, minimized = get_wm_class_and_state(win) dock = disp.intern_atom('_NET_WM_WINDOW_TYPE_DOCK') if dock in ewmh.getWmWindowType(win): continue ",windowlist.py,"ReplaceText(target='win' @(48,56)->(48,61))","class WindowList: if name in EXCLUDE_APPLICATIONS: continue wmclass, minimized = get_wm_class_and_state(winid) dock = disp.intern_atom('_NET_WM_WINDOW_TYPE_DOCK') if dock in ewmh.getWmWindowType(win): continue","class WindowList: if name in EXCLUDE_APPLICATIONS: continue wmclass, minimized = get_wm_class_and_state(win) dock = disp.intern_atom('_NET_WM_WINDOW_TYPE_DOCK') if dock in ewmh.getWmWindowType(win): continue" 1297,https://:@github.com/dpays/dpaygo.git,5f156fdf5a75367c32d85efb02e456abfa2719f6,"@@ -714,6 +714,6 @@ class RecentByPath(list): comments = [] for reply in replies: post = state[""content""][reply] - if category is None or (category is not None and post[""category""] != category): + if category is None or (category is not None and post[""category""] == category): comments.append(Comment(post, lazy=True, steem_instance=self.steem)) super(RecentByPath, self).__init__(comments) ",beem/comment.py,"ReplaceText(target='==' @(717,78)->(717,80))","class RecentByPath(list): comments = [] for reply in replies: post = state[""content""][reply] if category is None or (category is not None and post[""category""] != category): comments.append(Comment(post, lazy=True, steem_instance=self.steem)) super(RecentByPath, self).__init__(comments)","class RecentByPath(list): comments = [] for reply in replies: post = state[""content""][reply] if category is None or (category is not None and post[""category""] == category): comments.append(Comment(post, lazy=True, steem_instance=self.steem)) super(RecentByPath, self).__init__(comments)" 1298,https://:@github.com/ashinabraham/starlette-bugsnag.git,5772b5ab92c63c9f7e397ce976141a92095d2118,"@@ -11,7 +11,7 @@ class BugsnagMiddleware: async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if not self._debug: - await self.bugsnag_app(scope, send, receive) + await self.bugsnag_app(scope, receive, send) return await self.app(scope, receive, send) ",starlette_bugsnag/middleware.py,"ArgSwap(idxs=1<->2 @(14,18)->(14,34))","class BugsnagMiddleware: async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if not self._debug: await self.bugsnag_app(scope, send, receive) return await self.app(scope, receive, send) ","class BugsnagMiddleware: async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if not self._debug: await self.bugsnag_app(scope, receive, send) return await self.app(scope, receive, send) " 1299,https://:@github.com/LowieHuyghe/edmunds.git,a0a1669ebbe85c885f4bf1180c82d3c2c475ab61,"@@ -162,7 +162,7 @@ class EasierSetup(object): if value_path.lower().endswith('.md'): try: import pypandoc - value = pypandoc.convert_text(value_path, 'rst', format='md') + value = pypandoc.convert_text(value, 'rst', format='md') value = value.replace(""\r"", """") except ImportError: print(""Pandoc not found. Markdown to reStructuredText conversion failed."") ",easiersetup.py,"ReplaceText(target='value' @(165,54)->(165,64))","class EasierSetup(object): if value_path.lower().endswith('.md'): try: import pypandoc value = pypandoc.convert_text(value_path, 'rst', format='md') value = value.replace(""\r"", """") except ImportError: print(""Pandoc not found. Markdown to reStructuredText conversion failed."")","class EasierSetup(object): if value_path.lower().endswith('.md'): try: import pypandoc value = pypandoc.convert_text(value, 'rst', format='md') value = value.replace(""\r"", """") except ImportError: print(""Pandoc not found. Markdown to reStructuredText conversion failed."")" 1300,https://:@bitbucket.org/suprocktech/asphodel_py.git,ccc31dcfd872553cef4cee7f6790ce6d41ed564f,"@@ -309,7 +309,7 @@ def create_subproxy_util(device, func, proxy_id, identifier, *args, **kwargs): subproxy_device = func(device, *args, **kwargs) proxy_ids[proxy_id] = subproxy_device - subproxy_sn = device.get_serial_number() + subproxy_sn = subproxy_device.get_serial_number() subproxy_identifier = ""{}->{}"".format(identifier, subproxy_sn) device_identifiers[subproxy_device] = subproxy_identifier ",asphodel/proxy.py,"ReplaceText(target='subproxy_device' @(312,22)->(312,28))","def create_subproxy_util(device, func, proxy_id, identifier, *args, **kwargs): subproxy_device = func(device, *args, **kwargs) proxy_ids[proxy_id] = subproxy_device subproxy_sn = device.get_serial_number() subproxy_identifier = ""{}->{}"".format(identifier, subproxy_sn) device_identifiers[subproxy_device] = subproxy_identifier ","def create_subproxy_util(device, func, proxy_id, identifier, *args, **kwargs): subproxy_device = func(device, *args, **kwargs) proxy_ids[proxy_id] = subproxy_device subproxy_sn = subproxy_device.get_serial_number() subproxy_identifier = ""{}->{}"".format(identifier, subproxy_sn) device_identifiers[subproxy_device] = subproxy_identifier " 1301,https://:@github.com/Erotemic/dtool_ibeis.git,1be0ef6a963f9ec3409ccbe129b72669a153e222,"@@ -240,7 +240,7 @@ class DependencyCache(object): for args_, kwargs_ in reg_preproc: depc._register_prop(*args_, **kwargs_) print(' * regsitering %d global algos ' % len(reg_algos)) - for args_, kwargs_ in reg_preproc: + for args_, kwargs_ in reg_algos: depc._register_algo(*args_, **kwargs_) ut.ensuredir(depc.cache_dpath) ",dtool/depcache_control.py,"ReplaceText(target='reg_algos' @(243,34)->(243,45))","class DependencyCache(object): for args_, kwargs_ in reg_preproc: depc._register_prop(*args_, **kwargs_) print(' * regsitering %d global algos ' % len(reg_algos)) for args_, kwargs_ in reg_preproc: depc._register_algo(*args_, **kwargs_) ut.ensuredir(depc.cache_dpath)","class DependencyCache(object): for args_, kwargs_ in reg_preproc: depc._register_prop(*args_, **kwargs_) print(' * regsitering %d global algos ' % len(reg_algos)) for args_, kwargs_ in reg_algos: depc._register_algo(*args_, **kwargs_) ut.ensuredir(depc.cache_dpath)" 1302,https://:@github.com/Erotemic/dtool_ibeis.git,e94087b05c09fc2ebbaba09d55556eb467c77924,"@@ -2586,7 +2586,7 @@ class SQLDatabaseController(object): superkey_index = superkey_colnames_list.index(primary_superkey) superkey_paramx = superkey_paramxs_list[superkey_index] superkey_colnames = superkey_colnames_list[superkey_index] - elif len(superkey_colnames) == 1: + elif len(superkey_colnames_list) == 1: superkey_paramx = superkey_paramxs_list[0] superkey_colnames = superkey_colnames_list[0] else: ",dtool/sql_control.py,"ReplaceText(target='superkey_colnames_list' @(2589,21)->(2589,38))","class SQLDatabaseController(object): superkey_index = superkey_colnames_list.index(primary_superkey) superkey_paramx = superkey_paramxs_list[superkey_index] superkey_colnames = superkey_colnames_list[superkey_index] elif len(superkey_colnames) == 1: superkey_paramx = superkey_paramxs_list[0] superkey_colnames = superkey_colnames_list[0] else:","class SQLDatabaseController(object): superkey_index = superkey_colnames_list.index(primary_superkey) superkey_paramx = superkey_paramxs_list[superkey_index] superkey_colnames = superkey_colnames_list[superkey_index] elif len(superkey_colnames_list) == 1: superkey_paramx = superkey_paramxs_list[0] superkey_colnames = superkey_colnames_list[0] else:" 1303,https://:@github.com/m-laniakea/st_spin.git,0f3afc49b40a459947da9c45dc8f715b896f75a1,"@@ -91,7 +91,7 @@ class SpinDevice: :return: Response bytes as int """""" # payload and payload_size must be either both present, or both absent - assert((payload is None) != (payload_size is None)) + assert((payload is None) == (payload_size is None)) response = self._write(command) ",stspin/spin_device.py,"ReplaceText(target='==' @(94,33)->(94,35))","class SpinDevice: :return: Response bytes as int """""" # payload and payload_size must be either both present, or both absent assert((payload is None) != (payload_size is None)) response = self._write(command) ","class SpinDevice: :return: Response bytes as int """""" # payload and payload_size must be either both present, or both absent assert((payload is None) == (payload_size is None)) response = self._write(command) " 1304,https://:@github.com/pbromwelljr/gnewcash.git,340c6ca3b08b6389cc369878c960e2398b7f444a,"@@ -38,7 +38,7 @@ class Slot: slot_value_node.text = str(self.value) elif type(self.value) is list and self.value: for sub_slot in self.value: - slot_node.append(sub_slot.as_xml) + slot_value_node.append(sub_slot.as_xml) elif self.type == 'frame': pass # Empty frame element, just leave it else: ",gnewcash/slot.py,"ReplaceText(target='slot_value_node' @(41,16)->(41,25))","class Slot: slot_value_node.text = str(self.value) elif type(self.value) is list and self.value: for sub_slot in self.value: slot_node.append(sub_slot.as_xml) elif self.type == 'frame': pass # Empty frame element, just leave it else:","class Slot: slot_value_node.text = str(self.value) elif type(self.value) is list and self.value: for sub_slot in self.value: slot_value_node.append(sub_slot.as_xml) elif self.type == 'frame': pass # Empty frame element, just leave it else:" 1305,https://:@github.com/skibblenybbles/django-grunt.git,51fa1ede65b294e4610c85329293af6280be3783,"@@ -14,4 +14,4 @@ class GruntConfigMixin(object): def grunt_config(self, config=None, key=None): return grunt_conf( config={} if config is None else config, - key=key if key is None else self.grunt_config_key) + key=key if key is not None else self.grunt_config_key) ",grunt/views/mixins.py,"ReplaceText(target=' is not ' @(17,26)->(17,30))","class GruntConfigMixin(object): def grunt_config(self, config=None, key=None): return grunt_conf( config={} if config is None else config, key=key if key is None else self.grunt_config_key)","class GruntConfigMixin(object): def grunt_config(self, config=None, key=None): return grunt_conf( config={} if config is None else config, key=key if key is not None else self.grunt_config_key)" 1306,https://:@github.com/blixt/py-starbound.git,3563ff68b92dcf675adb5a861c61b02fc9e34b23,"@@ -103,7 +103,7 @@ class LeafReader(object): def read(self, length): offset = self._offset - if offset + length < len(self._leaf.data): + if offset + length <= len(self._leaf.data): self._offset += length return self._leaf.data[offset:offset + length] ",sbbf02.py,"ReplaceText(target='<=' @(106,27)->(106,28))","class LeafReader(object): def read(self, length): offset = self._offset if offset + length < len(self._leaf.data): self._offset += length return self._leaf.data[offset:offset + length] ","class LeafReader(object): def read(self, length): offset = self._offset if offset + length <= len(self._leaf.data): self._offset += length return self._leaf.data[offset:offset + length] " 1307,https://:@github.com/chrisrink10/basilisp.git,fbbc1c14b1e223aa22530a27d1013d97c61469c7,"@@ -61,7 +61,7 @@ def bootstrap_repl(which_ns: str) -> types.ModuleType: assert core_ns is not None ns.refer_all(core_ns) repl_module = importlib.import_module(REPL_NS) - ns.add_alias(sym.symbol(REPL_NS), repl_ns) + ns.add_alias(repl_ns, sym.symbol(REPL_NS)) ns.refer_all(repl_ns) return repl_module ",src/basilisp/cli.py,"ArgSwap(idxs=0<->1 @(64,4)->(64,16))","def bootstrap_repl(which_ns: str) -> types.ModuleType: assert core_ns is not None ns.refer_all(core_ns) repl_module = importlib.import_module(REPL_NS) ns.add_alias(sym.symbol(REPL_NS), repl_ns) ns.refer_all(repl_ns) return repl_module ","def bootstrap_repl(which_ns: str) -> types.ModuleType: assert core_ns is not None ns.refer_all(core_ns) repl_module = importlib.import_module(REPL_NS) ns.add_alias(repl_ns, sym.symbol(REPL_NS)) ns.refer_all(repl_ns) return repl_module " 1308,https://:@github.com/chrisrink10/basilisp.git,fbbc1c14b1e223aa22530a27d1013d97c61469c7,"@@ -420,7 +420,7 @@ class TestResolveAlias: foo_ns_sym = sym.symbol(""zux.bar.foo"") foo_ns = get_or_create_ns(foo_ns_sym) - ns.add_alias(sym.symbol(""foo""), foo_ns) + ns.add_alias(foo_ns, sym.symbol(""foo"")) assert sym.symbol( ""aliased-var"", ns=foo_ns_sym.name ) == runtime.resolve_alias(sym.symbol(""aliased-var"", ns=""foo""), ns=ns) ",tests/basilisp/runtime_test.py,"ArgSwap(idxs=0<->1 @(423,12)->(423,24))","class TestResolveAlias: foo_ns_sym = sym.symbol(""zux.bar.foo"") foo_ns = get_or_create_ns(foo_ns_sym) ns.add_alias(sym.symbol(""foo""), foo_ns) assert sym.symbol( ""aliased-var"", ns=foo_ns_sym.name ) == runtime.resolve_alias(sym.symbol(""aliased-var"", ns=""foo""), ns=ns)","class TestResolveAlias: foo_ns_sym = sym.symbol(""zux.bar.foo"") foo_ns = get_or_create_ns(foo_ns_sym) ns.add_alias(foo_ns, sym.symbol(""foo"")) assert sym.symbol( ""aliased-var"", ns=foo_ns_sym.name ) == runtime.resolve_alias(sym.symbol(""aliased-var"", ns=""foo""), ns=ns)" 1309,https://:@github.com/Blaok/haoda.git,66f4f1324648468e2e541ffb9ff37816490a4aca,"@@ -365,7 +365,7 @@ def print_kernel_xml(name: str, args: Iterable[Arg], kernel_xml: TextIO): size=size, offset=0 if is_stream else offset, host_size=host_size).rstrip('\n') - if is_stream: + if not is_stream: offset += size + 4 hw_ctrl_protocol = 'ap_ctrl_none' if has_s_axi_control: ",haoda/backend/xilinx.py,"ReplaceText(target='not ' @(368,7)->(368,7))","def print_kernel_xml(name: str, args: Iterable[Arg], kernel_xml: TextIO): size=size, offset=0 if is_stream else offset, host_size=host_size).rstrip('\n') if is_stream: offset += size + 4 hw_ctrl_protocol = 'ap_ctrl_none' if has_s_axi_control:","def print_kernel_xml(name: str, args: Iterable[Arg], kernel_xml: TextIO): size=size, offset=0 if is_stream else offset, host_size=host_size).rstrip('\n') if not is_stream: offset += size + 4 hw_ctrl_protocol = 'ap_ctrl_none' if has_s_axi_control:" 1310,https://:@github.com/domokane/FinancePy.git,0d71c33594ac248aeb473165ebfd0ae73dea5cab,"@@ -155,7 +155,7 @@ class FinCalendar(object): m = dt._m d = dt._d - startDate = FinDate(y, 1, 1) + startDate = FinDate(1, 1, y) dd = dt._excelDate - startDate._excelDate + 1 weekday = dt._weekday ",financepy/finutils/FinCalendar.py,"ArgSwap(idxs=0<->2 @(158,20)->(158,27))","class FinCalendar(object): m = dt._m d = dt._d startDate = FinDate(y, 1, 1) dd = dt._excelDate - startDate._excelDate + 1 weekday = dt._weekday ","class FinCalendar(object): m = dt._m d = dt._d startDate = FinDate(1, 1, y) dd = dt._excelDate - startDate._excelDate + 1 weekday = dt._weekday " 1311,https://:@github.com/domokane/FinancePy.git,e4edf39a2f8aa1caa804a63d7058c66dc458aefc,"@@ -94,7 +94,7 @@ def buildIborCurve(tradeDate): dcType) swaps.append(swap5) - liborCurve = FinIborSingleCurve(settlementDate, depos, fras, swaps) + liborCurve = FinIborSingleCurve(valuationDate, depos, fras, swaps) return liborCurve ",tests/TestFinCDSBasket.py,"ReplaceText(target='valuationDate' @(97,36)->(97,50))","def buildIborCurve(tradeDate): dcType) swaps.append(swap5) liborCurve = FinIborSingleCurve(settlementDate, depos, fras, swaps) return liborCurve ","def buildIborCurve(tradeDate): dcType) swaps.append(swap5) liborCurve = FinIborSingleCurve(valuationDate, depos, fras, swaps) return liborCurve " 1312,https://:@github.com/pypr/automan.git,55ada630a37e2dfcecebd69fef20d62eddb8d402,"@@ -310,7 +310,7 @@ class TestScheduler(unittest.TestCase): # Then self.assertEqual(len(s.workers), 2) count = 0 - while proxy.status() != 'done' and count < 10: + while proxy1.status() != 'done' and count < 10: time.sleep(0.1) count += 1 ",automan/tests/test_jobs.py,"ReplaceText(target='proxy1' @(313,14)->(313,19))","class TestScheduler(unittest.TestCase): # Then self.assertEqual(len(s.workers), 2) count = 0 while proxy.status() != 'done' and count < 10: time.sleep(0.1) count += 1 ","class TestScheduler(unittest.TestCase): # Then self.assertEqual(len(s.workers), 2) count = 0 while proxy1.status() != 'done' and count < 10: time.sleep(0.1) count += 1 " 1313,https://:@github.com/pyfarm/pyfarm-agent.git,66dacd9725338a5f49d12ccee0e0ec8f9e5f8068,"@@ -68,7 +68,7 @@ class Task(TaskModel): def __init__(self, job, frame, parent_task=None, state=None, priority=None, attempts=None, agent=None): # build parent job id - if not modelfor(job, TABLE_JOB): + if modelfor(job, TABLE_JOB): jobid = job.jobid if jobid is None: raise ValueError(""`job` with null id provided"") ",models/task.py,"ReplaceText(target='' @(71,11)->(71,15))","class Task(TaskModel): def __init__(self, job, frame, parent_task=None, state=None, priority=None, attempts=None, agent=None): # build parent job id if not modelfor(job, TABLE_JOB): jobid = job.jobid if jobid is None: raise ValueError(""`job` with null id provided"")","class Task(TaskModel): def __init__(self, job, frame, parent_task=None, state=None, priority=None, attempts=None, agent=None): # build parent job id if modelfor(job, TABLE_JOB): jobid = job.jobid if jobid is None: raise ValueError(""`job` with null id provided"")" 1314,https://:@github.com/pyfarm/pyfarm-agent.git,47a4cc9232a09974dea7f246b96d0338a4a4339b,"@@ -116,5 +116,5 @@ class Task(TaskModel): if priority is not None: self.priority = priority - if attempts is None: + if attempts is not None: self.attempts = attempts ",models/task.py,"ReplaceText(target=' is not ' @(119,19)->(119,23))","class Task(TaskModel): if priority is not None: self.priority = priority if attempts is None: self.attempts = attempts","class Task(TaskModel): if priority is not None: self.priority = priority if attempts is not None: self.attempts = attempts" 1315,https://:@github.com/pyfarm/pyfarm-agent.git,10b2c473daa02e8feed96c41cd929a8861b39286,"@@ -88,7 +88,7 @@ def skip(should_skip, reason): def wrapper(func): @wraps(func) def wrapped_func(*args, **kwargs): - if not should_skip: + if should_skip: raise SkipTest(reason) return func(*args, **kwargs) return wrapped_func ",pyfarm/agent/testutil.py,"ReplaceText(target='' @(91,15)->(91,19))","def skip(should_skip, reason): def wrapper(func): @wraps(func) def wrapped_func(*args, **kwargs): if not should_skip: raise SkipTest(reason) return func(*args, **kwargs) return wrapped_func","def skip(should_skip, reason): def wrapper(func): @wraps(func) def wrapped_func(*args, **kwargs): if should_skip: raise SkipTest(reason) return func(*args, **kwargs) return wrapped_func" 1316,https://:@github.com/pyfarm/pyfarm-agent.git,1f7a8e553f328860c1f268a668b1d216311e017e,"@@ -337,7 +337,7 @@ class TypeChecks(object): if not isinstance(value, STRING_TYPES): raise TypeError(""Expected a string for `value`"") - if environment is not None or not isinstance(environment, dict): + if environment is not None and not isinstance(environment, dict): raise TypeError(""Expected None or a dictionary for `environment`"") def _check_map_path_inputs(self, path): ",pyfarm/jobtypes/core/internals.py,"ReplaceText(target='and' @(340,35)->(340,37))","class TypeChecks(object): if not isinstance(value, STRING_TYPES): raise TypeError(""Expected a string for `value`"") if environment is not None or not isinstance(environment, dict): raise TypeError(""Expected None or a dictionary for `environment`"") def _check_map_path_inputs(self, path):","class TypeChecks(object): if not isinstance(value, STRING_TYPES): raise TypeError(""Expected a string for `value`"") if environment is not None and not isinstance(environment, dict): raise TypeError(""Expected None or a dictionary for `environment`"") def _check_map_path_inputs(self, path):" 1317,https://:@github.com/pyfarm/pyfarm-agent.git,01522e772abfd9c63be8afe679b4293454c1d3fb,"@@ -214,6 +214,6 @@ class Assign(APIResource): # are handled internally in this case. jobtype_loader = JobType.load(request_data) jobtype_loader.addCallback(loaded_jobtype, assignment_uuid) - jobtype_loader.addErrback(assignment_stopped, assignment_uuid) + jobtype_loader.addErrback(assignment_failed, assignment_uuid) return NOT_DONE_YET ",pyfarm/agent/http/api/assign.py,"ReplaceText(target='assignment_failed' @(217,34)->(217,52))","class Assign(APIResource): # are handled internally in this case. jobtype_loader = JobType.load(request_data) jobtype_loader.addCallback(loaded_jobtype, assignment_uuid) jobtype_loader.addErrback(assignment_stopped, assignment_uuid) return NOT_DONE_YET","class Assign(APIResource): # are handled internally in this case. jobtype_loader = JobType.load(request_data) jobtype_loader.addCallback(loaded_jobtype, assignment_uuid) jobtype_loader.addErrback(assignment_failed, assignment_uuid) return NOT_DONE_YET" 1318,https://:@github.com/pyfarm/pyfarm-agent.git,0a73697606f24b15de2a83cbbe226e399a4a9fb7,"@@ -348,7 +348,7 @@ class TestCase(_TestCase): msg, '%s not less than or equal to %s' % (a, b))) def assertGreaterEqual(self, a, b, msg=None): - if not a <= b: + if not a >= b: self.fail( self._formatMessage( msg, '%s not greater than or equal to %s' % (a, b))) ",pyfarm/agent/testutil.py,"ReplaceText(target='>=' @(351,21)->(351,23))","class TestCase(_TestCase): msg, '%s not less than or equal to %s' % (a, b))) def assertGreaterEqual(self, a, b, msg=None): if not a <= b: self.fail( self._formatMessage( msg, '%s not greater than or equal to %s' % (a, b)))","class TestCase(_TestCase): msg, '%s not less than or equal to %s' % (a, b))) def assertGreaterEqual(self, a, b, msg=None): if not a >= b: self.fail( self._formatMessage( msg, '%s not greater than or equal to %s' % (a, b)))" 1319,https://:@github.com/pyfarm/pyfarm-agent.git,8e2efd42e030089ef0afa266c89e34ed3d2b7a87,"@@ -158,7 +158,7 @@ class Assign(APIResource): request.finish() return NOT_DONE_YET # If there is only a partial overlap - elif existing_task_ids ^ new_task_ids: + elif existing_task_ids & new_task_ids: logger.error(""Rejecting assignment with partial overlap with "" ""existing assignment."") unknown_task_ids = new_task_ids - existing_task_ids ",pyfarm/agent/http/api/assign.py,"ReplaceText(target='&' @(161,35)->(161,36))","class Assign(APIResource): request.finish() return NOT_DONE_YET # If there is only a partial overlap elif existing_task_ids ^ new_task_ids: logger.error(""Rejecting assignment with partial overlap with "" ""existing assignment."") unknown_task_ids = new_task_ids - existing_task_ids","class Assign(APIResource): request.finish() return NOT_DONE_YET # If there is only a partial overlap elif existing_task_ids & new_task_ids: logger.error(""Rejecting assignment with partial overlap with "" ""existing assignment."") unknown_task_ids = new_task_ids - existing_task_ids" 1320,https://:@github.com/aliok/trnltk.git,025fc45d062d902d8c5567b36eaf3b832c5a296e,"@@ -218,7 +218,7 @@ class DoesntHaveRootAttributes(SuffixFormCondition): transitions = filter(lambda transition : not isinstance(transition.suffix_form_application.suffix_form.suffix, ZeroTransitionSuffix), transitions) transitions = filter(lambda transition : transition.suffix_form_application.applied_suffix_form, transitions) - if not transitions: + if transitions: return True if not parse_token.stem.dictionary_item.attributes: ",trnltk/suffixgraph/suffixconditions.py,"ReplaceText(target='' @(221,11)->(221,15))","class DoesntHaveRootAttributes(SuffixFormCondition): transitions = filter(lambda transition : not isinstance(transition.suffix_form_application.suffix_form.suffix, ZeroTransitionSuffix), transitions) transitions = filter(lambda transition : transition.suffix_form_application.applied_suffix_form, transitions) if not transitions: return True if not parse_token.stem.dictionary_item.attributes:","class DoesntHaveRootAttributes(SuffixFormCondition): transitions = filter(lambda transition : not isinstance(transition.suffix_form_application.suffix_form.suffix, ZeroTransitionSuffix), transitions) transitions = filter(lambda transition : transition.suffix_form_application.applied_suffix_form, transitions) if transitions: return True if not parse_token.stem.dictionary_item.attributes:" 1321,https://:@github.com/aliok/trnltk.git,46c9051f744ef8ce1b9f001281da68257693e20a,"@@ -89,7 +89,7 @@ class MockMorphemeContainerBuilder(object): def lexeme(self, lemma_root_str, lemma_root_syntactic_category=None, lemma_root_secondary_syntactic_category=None): self.lemma_root_str = lemma_root_str self.lemma_root_syntactic_category = lemma_root_syntactic_category - self.lemma_root_secondary_syntactic_category = lemma_root_syntactic_category + self.lemma_root_secondary_syntactic_category = lemma_root_secondary_syntactic_category return self ",trnltk/morphology/contextful/variantcontiguity/parsecontext.py,"ReplaceText(target='lemma_root_secondary_syntactic_category' @(92,55)->(92,84))","class MockMorphemeContainerBuilder(object): def lexeme(self, lemma_root_str, lemma_root_syntactic_category=None, lemma_root_secondary_syntactic_category=None): self.lemma_root_str = lemma_root_str self.lemma_root_syntactic_category = lemma_root_syntactic_category self.lemma_root_secondary_syntactic_category = lemma_root_syntactic_category return self ","class MockMorphemeContainerBuilder(object): def lexeme(self, lemma_root_str, lemma_root_syntactic_category=None, lemma_root_secondary_syntactic_category=None): self.lemma_root_str = lemma_root_str self.lemma_root_syntactic_category = lemma_root_syntactic_category self.lemma_root_secondary_syntactic_category = lemma_root_secondary_syntactic_category return self " 1322,https://:@github.com/dgaston/ddbio-ngsflow.git,fb220e0eba9a51929c032b6801c2c626f084dc3f,"@@ -151,7 +151,7 @@ def sambamba_coverage_summary(job, config, samples, outfile): for sample in samples: output.write(""\t{samp_reads}"" ""\t{s_perc1}"" - ""\t{s_perc1}"".format(samp_reads=amplicon[amplicon][sample], + ""\t{s_perc1}"".format(samp_reads=amplicon_coverage[amplicon][sample], s_perc1=amplicon_coverage[amplicon][""{}_percent_{}"".format(sample, config['coverage_threshold'])], s_perc2=amplicon_coverage[amplicon][""{}_percent_{}"".format(sample, config['coverage_threshold1'])])) ",ddb_ngsflow/utils/utilities.py,"ReplaceText(target='amplicon_coverage' @(154,61)->(154,69))","def sambamba_coverage_summary(job, config, samples, outfile): for sample in samples: output.write(""\t{samp_reads}"" ""\t{s_perc1}"" ""\t{s_perc1}"".format(samp_reads=amplicon[amplicon][sample], s_perc1=amplicon_coverage[amplicon][""{}_percent_{}"".format(sample, config['coverage_threshold'])], s_perc2=amplicon_coverage[amplicon][""{}_percent_{}"".format(sample, config['coverage_threshold1'])])) ","def sambamba_coverage_summary(job, config, samples, outfile): for sample in samples: output.write(""\t{samp_reads}"" ""\t{s_perc1}"" ""\t{s_perc1}"".format(samp_reads=amplicon_coverage[amplicon][sample], s_perc1=amplicon_coverage[amplicon][""{}_percent_{}"".format(sample, config['coverage_threshold'])], s_perc2=amplicon_coverage[amplicon][""{}_percent_{}"".format(sample, config['coverage_threshold1'])])) " 1323,https://:@github.com/dlamotte/statsd-ostools.git,531f3f6f2704fc5fa52d0316a5e00e4abfecf6d1,"@@ -64,7 +64,7 @@ def main(): for workerklass in worker.workers: pid = os.fork() kids.append(pid) - if pid != 0: + if pid == 0: sys.exit(workerklass(statsd, opts.interval).run()) while not SIGNALED: ",statsd_ostools/cmd.py,"ReplaceText(target='==' @(67,15)->(67,17))","def main(): for workerklass in worker.workers: pid = os.fork() kids.append(pid) if pid != 0: sys.exit(workerklass(statsd, opts.interval).run()) while not SIGNALED:","def main(): for workerklass in worker.workers: pid = os.fork() kids.append(pid) if pid == 0: sys.exit(workerklass(statsd, opts.interval).run()) while not SIGNALED:" 1324,https://:@github.com/ipal0/modbus.git,19458ca84601917e7d7721b03dce8aa647d20065,"@@ -60,7 +60,7 @@ class client: if FC == 5 or FC == 15: LEN = len(VAL) * 8 else: - LEN = len(VAL) / 2 + LEN = len(VAL) // 2 lLEN = LEN & 0x00FF mLEN = LEN >> 8 if self.TID < 255: ",client.py,"ReplaceText(target='//' @(63,18)->(63,19))","class client: if FC == 5 or FC == 15: LEN = len(VAL) * 8 else: LEN = len(VAL) / 2 lLEN = LEN & 0x00FF mLEN = LEN >> 8 if self.TID < 255: ","class client: if FC == 5 or FC == 15: LEN = len(VAL) * 8 else: LEN = len(VAL) // 2 lLEN = LEN & 0x00FF mLEN = LEN >> 8 if self.TID < 255: " 1325,https://:@github.com/CTPUG/pyntnclick.git,cde45aba4aee72d730343a89cc4975c29f2a4059,"@@ -37,7 +37,7 @@ class Widget(object): def event(self, ev): ""Don't override this without damn good reason"" if self.disabled or not self.visible: - return True + return False type_ = ev.type if type_ == USEREVENT: ",pyntnclick/widgets/base.py,"ReplaceText(target='False' @(40,19)->(40,23))","class Widget(object): def event(self, ev): ""Don't override this without damn good reason"" if self.disabled or not self.visible: return True type_ = ev.type if type_ == USEREVENT:","class Widget(object): def event(self, ev): ""Don't override this without damn good reason"" if self.disabled or not self.visible: return False type_ = ev.type if type_ == USEREVENT:" 1326,https://:@github.com/MakersF/LoLScraper.git,b2435d9938a6cc7e0cf49ace811f353cfd7e648c,"@@ -82,7 +82,7 @@ def download_matches(store_callback, seed_players, minimum_tier = Tier.bronze, # Iterate until matches_in_time_slice is big enough, and stop anyways after matches_per_time_slice iterations # this ensures the script will always terminate even in strange situations # (like when all our seeds have no matches in the time slice) - for _ in takewhile(lambda x: matches_in_time_slice >= matches_per_time_slice, range(matches_per_time_slice)): + for _ in takewhile(lambda x: matches_in_time_slice <= matches_per_time_slice, range(matches_per_time_slice)): for tier in Tier: for player_id, _ in zip(players_to_analyze.consume(tier), range(10)): match_list = get_match_list(player_id, begin_time=time_slice.begin, end_time=time_slice.end, ranked_queues=queue.name) ",TeamComp/main.py,"ReplaceText(target='<=' @(85,63)->(85,65))","def download_matches(store_callback, seed_players, minimum_tier = Tier.bronze, # Iterate until matches_in_time_slice is big enough, and stop anyways after matches_per_time_slice iterations # this ensures the script will always terminate even in strange situations # (like when all our seeds have no matches in the time slice) for _ in takewhile(lambda x: matches_in_time_slice >= matches_per_time_slice, range(matches_per_time_slice)): for tier in Tier: for player_id, _ in zip(players_to_analyze.consume(tier), range(10)): match_list = get_match_list(player_id, begin_time=time_slice.begin, end_time=time_slice.end, ranked_queues=queue.name)","def download_matches(store_callback, seed_players, minimum_tier = Tier.bronze, # Iterate until matches_in_time_slice is big enough, and stop anyways after matches_per_time_slice iterations # this ensures the script will always terminate even in strange situations # (like when all our seeds have no matches in the time slice) for _ in takewhile(lambda x: matches_in_time_slice <= matches_per_time_slice, range(matches_per_time_slice)): for tier in Tier: for player_id, _ in zip(players_to_analyze.consume(tier), range(10)): match_list = get_match_list(player_id, begin_time=time_slice.begin, end_time=time_slice.end, ranked_queues=queue.name)" 1327,https://:@github.com/MakersF/LoLScraper.git,9f39aab22be4783620f0d458f13e0b782d65bd2b,"@@ -205,7 +205,7 @@ def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf random.random() < EVICTION_RATE} # When a new patch is released, we can clear all the analyzed players and downloaded_matches if minimum_patch == 'latest' - if conf['minimum_patch'].lower() != LATEST and get_patch_changed(): + if conf['minimum_patch'].lower() == LATEST and get_patch_changed(): analyzed_players = set() downloaded_matches = set() ",lol_scraper/match_downloader.py,"ReplaceText(target='==' @(208,53)->(208,55))","def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf random.random() < EVICTION_RATE} # When a new patch is released, we can clear all the analyzed players and downloaded_matches if minimum_patch == 'latest' if conf['minimum_patch'].lower() != LATEST and get_patch_changed(): analyzed_players = set() downloaded_matches = set() ","def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf random.random() < EVICTION_RATE} # When a new patch is released, we can clear all the analyzed players and downloaded_matches if minimum_patch == 'latest' if conf['minimum_patch'].lower() == LATEST and get_patch_changed(): analyzed_players = set() downloaded_matches = set() " 1328,https://:@gitlab.com/claudiop/CLIPy.git,cf2bbbfc3877368c493ba97e8ffe3cd0d8e0875d,"@@ -55,7 +55,7 @@ def get_course_activity_years(page): year = int(urls.YEAR_EXP.findall(year_link.attrs['href'])[0]) if first is None or year < first: first = year - if last is None or year < last: + if last is None or year > last: last = year return first, last ",CLIPy/parser.py,"ReplaceText(target='>' @(58,32)->(58,33))","def get_course_activity_years(page): year = int(urls.YEAR_EXP.findall(year_link.attrs['href'])[0]) if first is None or year < first: first = year if last is None or year < last: last = year return first, last ","def get_course_activity_years(page): year = int(urls.YEAR_EXP.findall(year_link.attrs['href'])[0]) if first is None or year < first: first = year if last is None or year > last: last = year return first, last " 1329,https://:@github.com/pyserial/pyparallel.git,14213e1c7dda2d62d952305ce0a116f86f77bae2,"@@ -221,7 +221,7 @@ class Win32Serial(SerialBase): if n > 0: buf = ctypes.create_string_buffer(n) rc = win32.DWORD() - err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead)) + err = win32.ReadFile(self.hComPort, buf, n, ctypes.byref(rc), ctypes.byref(self._overlappedRead)) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: raise SerialException(""ReadFile failed (%s)"" % ctypes.WinError()) err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE) ",pyserial/serial/serialwin32.py,"ReplaceText(target='n' @(224,61)->(224,65))","class Win32Serial(SerialBase): if n > 0: buf = ctypes.create_string_buffer(n) rc = win32.DWORD() err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead)) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: raise SerialException(""ReadFile failed (%s)"" % ctypes.WinError()) err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE)","class Win32Serial(SerialBase): if n > 0: buf = ctypes.create_string_buffer(n) rc = win32.DWORD() err = win32.ReadFile(self.hComPort, buf, n, ctypes.byref(rc), ctypes.byref(self._overlappedRead)) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: raise SerialException(""ReadFile failed (%s)"" % ctypes.WinError()) err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE)" 1330,https://:@github.com/dschick/udkm1Dsim.git,1760819d1df4cb50af1f925c1c3df39c9b7ee020,"@@ -94,7 +94,7 @@ def finderb_nest(key, vector): # if the key is smaller than the first element of the # vector we return 1 if key < vector[0]: - return 1 + return 0 while (b-a) > 1: # loop until the intervall is larger than 1 c = int(np.floor((a+b)/2)) # center of intervall ",udkm1Dsim/helpers.py,"ReplaceText(target='0' @(97,15)->(97,16))","def finderb_nest(key, vector): # if the key is smaller than the first element of the # vector we return 1 if key < vector[0]: return 1 while (b-a) > 1: # loop until the intervall is larger than 1 c = int(np.floor((a+b)/2)) # center of intervall","def finderb_nest(key, vector): # if the key is smaller than the first element of the # vector we return 1 if key < vector[0]: return 0 while (b-a) > 1: # loop until the intervall is larger than 1 c = int(np.floor((a+b)/2)) # center of intervall" 1331,https://:@github.com/orsinium/pros.git,9ba4c47e7b9283e5dfe209a31ddcda0bc3b1bfbf,"@@ -70,7 +70,7 @@ class Catalog: if command: return self._register(name, command) else: - return partial(self._register, command) + return partial(self._register, name) def _register(self, name, command): if name in self.commands: ",pipecli/core.py,"ReplaceText(target='name' @(73,43)->(73,50))","class Catalog: if command: return self._register(name, command) else: return partial(self._register, command) def _register(self, name, command): if name in self.commands:","class Catalog: if command: return self._register(name, command) else: return partial(self._register, name) def _register(self, name, command): if name in self.commands:" 1332,https://:@github.com/ShaneKent/PyEventLogViewer.git,f97696fbe0a5bb94461ccfa2951667ab788aefd5,"@@ -53,7 +53,7 @@ def xml_convert(records, file_hash, recovered=True): sys = d['Event']['System'] - dictionary = parser(record, { + dictionary = parser(d, { 'timestamp_utc': sys['TimeCreated']['@SystemTime'], 'event_id': sys['EventID'], 'description': '', ",winlogtimeline/collector/collect.py,"ReplaceText(target='d' @(56,28)->(56,34))","def xml_convert(records, file_hash, recovered=True): sys = d['Event']['System'] dictionary = parser(record, { 'timestamp_utc': sys['TimeCreated']['@SystemTime'], 'event_id': sys['EventID'], 'description': '',","def xml_convert(records, file_hash, recovered=True): sys = d['Event']['System'] dictionary = parser(d, { 'timestamp_utc': sys['TimeCreated']['@SystemTime'], 'event_id': sys['EventID'], 'description': ''," 1333,https://:@github.com/BlackEarth/bsql.git,76eb385fb3dd8774e2689e2d661ae1338754525c,"@@ -58,7 +58,7 @@ class Database(Dict): elif isinstance(self.adaptor, str): self.adaptor = importlib.import_module(self.adaptor) - if self.connection_string is None: + if self.connection_string is not None: if self.adaptor.__name__ == 'psycopg2': self.pool = importlib.import_module('psycopg2.pool').ThreadedConnectionPool( self.minconn or 1, self.maxconn or 1, self.connection_string or '' ",bsql/database.py,"ReplaceText(target=' is not ' @(61,37)->(61,41))","class Database(Dict): elif isinstance(self.adaptor, str): self.adaptor = importlib.import_module(self.adaptor) if self.connection_string is None: if self.adaptor.__name__ == 'psycopg2': self.pool = importlib.import_module('psycopg2.pool').ThreadedConnectionPool( self.minconn or 1, self.maxconn or 1, self.connection_string or ''","class Database(Dict): elif isinstance(self.adaptor, str): self.adaptor = importlib.import_module(self.adaptor) if self.connection_string is not None: if self.adaptor.__name__ == 'psycopg2': self.pool = importlib.import_module('psycopg2.pool').ThreadedConnectionPool( self.minconn or 1, self.maxconn or 1, self.connection_string or ''" 1334,https://:@github.com/Pushkar-Singh-14/Polygon-Analysis.git,b66ac7e004c04178e8a0e84fd2363b4057b4a878,"@@ -50,7 +50,7 @@ def polygon_analysis(file_name, background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255)) offset = (0,0) background.paste(image, offset) - file_name2=f'{width_old*2}X{height_old*2}_{file_name}.png' + file_name2=f'{width_old*2}X{height_old*2}_{name_file}.png' save_image=os.path.join(cwd,file_name2) save_image_in_data=os.path.join(path_save,file_name2) ",py2pyPolygonAnalysis.py,"ReplaceText(target='name_file' @(53,47)->(53,56))","def polygon_analysis(file_name, background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255)) offset = (0,0) background.paste(image, offset) file_name2=f'{width_old*2}X{height_old*2}_{file_name}.png' save_image=os.path.join(cwd,file_name2) save_image_in_data=os.path.join(path_save,file_name2) ","def polygon_analysis(file_name, background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255)) offset = (0,0) background.paste(image, offset) file_name2=f'{width_old*2}X{height_old*2}_{name_file}.png' save_image=os.path.join(cwd,file_name2) save_image_in_data=os.path.join(path_save,file_name2) " 1335,https://:@github.com/awiddersheim/github-release-cicd.git,05ba9a8f3fea49778cf729dbd82594437b5db5e0,"@@ -89,7 +89,7 @@ def create(repo, tag, name, message, draft, prerelease, target, assets): release = repo.create_git_release( tag=tag, - name=tag, + name=name, message=message, target_commitish=target, prerelease=prerelease, ",github_release_cicd/cli.py,"ReplaceText(target='name' @(92,13)->(92,16))","def create(repo, tag, name, message, draft, prerelease, target, assets): release = repo.create_git_release( tag=tag, name=tag, message=message, target_commitish=target, prerelease=prerelease,","def create(repo, tag, name, message, draft, prerelease, target, assets): release = repo.create_git_release( tag=tag, name=name, message=message, target_commitish=target, prerelease=prerelease," 1336,https://:@github.com/jeiros/msmadapter.git,92a42219549fa6cab93250d4c961a72c0fc3de20,"@@ -289,7 +289,7 @@ class App(object): def run_local_GPU(self, folders_glob): bash_cmd = ""export CUDA_VISIBLE_DEVICES=0"" - if len(glob(folders_glob)) != (self.ngpus - self.gpus_in_use): + if len(glob(folders_glob)) > (self.ngpus - self.gpus_in_use): raise ValueError(""Cannot run jobs of {} folders as only {} GPUs are available"".format(len(glob(folders_glob)), self.ngpus - self.gpus_in_use)) for folder in glob(folders_glob): ",msmadapter/adaptive.py,"ReplaceText(target='>' @(292,35)->(292,37))","class App(object): def run_local_GPU(self, folders_glob): bash_cmd = ""export CUDA_VISIBLE_DEVICES=0"" if len(glob(folders_glob)) != (self.ngpus - self.gpus_in_use): raise ValueError(""Cannot run jobs of {} folders as only {} GPUs are available"".format(len(glob(folders_glob)), self.ngpus - self.gpus_in_use)) for folder in glob(folders_glob):","class App(object): def run_local_GPU(self, folders_glob): bash_cmd = ""export CUDA_VISIBLE_DEVICES=0"" if len(glob(folders_glob)) > (self.ngpus - self.gpus_in_use): raise ValueError(""Cannot run jobs of {} folders as only {} GPUs are available"".format(len(glob(folders_glob)), self.ngpus - self.gpus_in_use)) for folder in glob(folders_glob):" 1337,https://:@github.com/thoth-station/build-analysers.git,7bd3caaf26018c4fd5fea647a53c82aa7919e25a,"@@ -167,7 +167,7 @@ def build_breaker_predict( if reverse_scores: # reverse the scores scores = 1 / (scores * np.max(1 / scores)) - return np.vstack([winner_scores, winner_indices]) + return np.vstack([scores, winner_indices]) def build_breaker_analyze(log: str, *, colorize: bool = True): ",thoth/build_analysers/analysis.py,"ReplaceText(target='scores' @(170,22)->(170,35))","def build_breaker_predict( if reverse_scores: # reverse the scores scores = 1 / (scores * np.max(1 / scores)) return np.vstack([winner_scores, winner_indices]) def build_breaker_analyze(log: str, *, colorize: bool = True):","def build_breaker_predict( if reverse_scores: # reverse the scores scores = 1 / (scores * np.max(1 / scores)) return np.vstack([scores, winner_indices]) def build_breaker_analyze(log: str, *, colorize: bool = True):" 1338,https://:@github.com/lcvriend/humannotator.git,e39c518621d12bd7e91e9847a05df1c0b75ff0eb,"@@ -280,6 +280,6 @@ if __name__ == '__main__': ) # run annotator - annotator = Annotator([task1, task2], data) + annotator = Annotator(data, [task1, task2]) annotator(data.ids) print(annotator.annotated) ",humannotator/humannotator.py,"ArgSwap(idxs=0<->1 @(283,16)->(283,25))","if __name__ == '__main__': ) # run annotator annotator = Annotator([task1, task2], data) annotator(data.ids) print(annotator.annotated)","if __name__ == '__main__': ) # run annotator annotator = Annotator(data, [task1, task2]) annotator(data.ids) print(annotator.annotated)" 1339,https://:@github.com/paulsbond/autocoord.git,688d05f50a4c1ded44fdd3d0309fbeaadf762807,"@@ -88,7 +88,7 @@ class Pipeline(): def refmac(self, cycles): directory = self.job_directory(""refmac"") use_phases = self.args.unbiased and self.min_rwork > 0.35 - job = Refmac(self.args, directory, self.current_xyz, use_phases, cycles) + job = Refmac(self.args, directory, self.current_xyz, cycles, use_phases) self.jobs[self.cycle].append(job) self.current_hkl = job.hklout self.current_xyz = job.xyzout ",modelcraft/pipeline.py,"ArgSwap(idxs=3<->4 @(91,14)->(91,20))","class Pipeline(): def refmac(self, cycles): directory = self.job_directory(""refmac"") use_phases = self.args.unbiased and self.min_rwork > 0.35 job = Refmac(self.args, directory, self.current_xyz, use_phases, cycles) self.jobs[self.cycle].append(job) self.current_hkl = job.hklout self.current_xyz = job.xyzout","class Pipeline(): def refmac(self, cycles): directory = self.job_directory(""refmac"") use_phases = self.args.unbiased and self.min_rwork > 0.35 job = Refmac(self.args, directory, self.current_xyz, cycles, use_phases) self.jobs[self.cycle].append(job) self.current_hkl = job.hklout self.current_xyz = job.xyzout" 1340,https://:@github.com/cyril-s/aptly-ctl.git,b7e01c735809dca6ff0ed428d6f3062f5a2c1b86,"@@ -54,7 +54,7 @@ class PackageRef: @property def dir_ref(self): - return ""{}_{}_{}"".format(self.name, self.arch, self.version) + return ""{}_{}_{}"".format(self.name, self.version, self.arch) def __repr__(self): ",didww_aptly_ctl/utils/PackageRef.py,"ArgSwap(idxs=1<->2 @(57,15)->(57,32))","class PackageRef: @property def dir_ref(self): return ""{}_{}_{}"".format(self.name, self.arch, self.version) def __repr__(self):","class PackageRef: @property def dir_ref(self): return ""{}_{}_{}"".format(self.name, self.version, self.arch) def __repr__(self):" 1341,https://:@github.com/south-coast-science/scs_analysis.git,fd6148dff62ed13b561cddcce7fe9fd3fbc62532,"@@ -244,7 +244,7 @@ if __name__ == '__main__': while cmd.fill: filler = generator.next_localised_datetime(filler) - if filler == checkpoint: + if filler >= checkpoint: break print(JSONify.dumps(aggregate.report(filler))) ",src/scs_analysis/sample_aggregate.py,"ReplaceText(target='>=' @(247,30)->(247,32))","if __name__ == '__main__': while cmd.fill: filler = generator.next_localised_datetime(filler) if filler == checkpoint: break print(JSONify.dumps(aggregate.report(filler)))","if __name__ == '__main__': while cmd.fill: filler = generator.next_localised_datetime(filler) if filler >= checkpoint: break print(JSONify.dumps(aggregate.report(filler)))" 1342,https://:@github.com/txels/incywincy.git,cf0cdbbf2a52ee70b8369f503d3983bd97d8db03,"@@ -14,7 +14,7 @@ THRESHOLD = 1 def log(page, message, level=WARNING): - if level > THRESHOLD: + if level >= THRESHOLD: print("">> {0}: {1} | {2}"".format(CRITICALITY[level], message, page.url)) ",incywincy/report.py,"ReplaceText(target='>=' @(17,13)->(17,14))","THRESHOLD = 1 def log(page, message, level=WARNING): if level > THRESHOLD: print("">> {0}: {1} | {2}"".format(CRITICALITY[level], message, page.url)) ","THRESHOLD = 1 def log(page, message, level=WARNING): if level >= THRESHOLD: print("">> {0}: {1} | {2}"".format(CRITICALITY[level], message, page.url)) " 1343,https://:@github.com/oakeyc/azure-cli-interactive-shell.git,10de31097e20cab16a5edce1b043416cc0932d69,"@@ -171,7 +171,7 @@ def create_layout(lex, examLex, toolbarLex): Window( content=BufferControl( buffer_name='symbols', - lexer=lexer + lexer=examLex ) ), filter=ShowSymbol() ",azclishell/layout.py,"ReplaceText(target='examLex' @(174,30)->(174,35))","def create_layout(lex, examLex, toolbarLex): Window( content=BufferControl( buffer_name='symbols', lexer=lexer ) ), filter=ShowSymbol()","def create_layout(lex, examLex, toolbarLex): Window( content=BufferControl( buffer_name='symbols', lexer=examLex ) ), filter=ShowSymbol()" 1344,https://:@github.com/sage-home/sage-analysis.git,4fb6b2ca074cc5afc8d993ba63ce77f685065351,"@@ -129,7 +129,7 @@ def generate_func_dict( # No extra arguments for this. key_args = {} - func_dict[func_name] = (func, key_args) + func_dict[toggle] = (func, key_args) return func_dict ",sage_analysis/utils.py,"ReplaceText(target='toggle' @(132,22)->(132,31))","def generate_func_dict( # No extra arguments for this. key_args = {} func_dict[func_name] = (func, key_args) return func_dict ","def generate_func_dict( # No extra arguments for this. key_args = {} func_dict[toggle] = (func, key_args) return func_dict " 1345,https://:@github.com/dhess/lobbyists.git,8877cfa738b78dc77ed40533e5f4c7f2b14d95b7,"@@ -785,7 +785,7 @@ def _import_list(entities, id, filing, cur): importer, entity_id = _list_importers[id] db_keys = list() for entity in entities: - db_keys.append(importer(entity[entity_id], id, filing, cur)) + db_keys.append(importer(entity[entity_id], entity_id, filing, cur)) return db_keys ",lobbyists/lobbyists.py,"ReplaceText(target='entity_id' @(788,51)->(788,53))","def _import_list(entities, id, filing, cur): importer, entity_id = _list_importers[id] db_keys = list() for entity in entities: db_keys.append(importer(entity[entity_id], id, filing, cur)) return db_keys ","def _import_list(entities, id, filing, cur): importer, entity_id = _list_importers[id] db_keys = list() for entity in entities: db_keys.append(importer(entity[entity_id], entity_id, filing, cur)) return db_keys " 1346,https://:@github.com/yedivanseven/PLSA.git,12eeb77e941cb7153b009f07104eb3b6f1c99911,"@@ -76,7 +76,7 @@ class BasePLSA: def __rel_change(self, new: float) -> float: if self._likelihoods: old = self._likelihoods[-1] - return abs((new - old) / old) + return abs((new - old) / new) return inf def _result(self) -> PlsaResult: ",plsa/algorithms/base.py,"ReplaceText(target='new' @(79,37)->(79,40))","class BasePLSA: def __rel_change(self, new: float) -> float: if self._likelihoods: old = self._likelihoods[-1] return abs((new - old) / old) return inf def _result(self) -> PlsaResult:","class BasePLSA: def __rel_change(self, new: float) -> float: if self._likelihoods: old = self._likelihoods[-1] return abs((new - old) / new) return inf def _result(self) -> PlsaResult:" 1347,https://:@github.com/omarryhan/sanic-cookies.git,93f915b30b664918ed0877e2ca75c66922fb1c72,"@@ -29,7 +29,7 @@ class MockApp: if attach_to == 'request': self.req_middleware.append(middleware) elif attach_to == 'response': - self.res_middleware = [attach_to] + self.res_middleware + self.res_middleware = [middleware] + self.res_middleware class MockSession(Session): def __init__(self, app=MockApp(), master_interface=MockInterface(), *args, **kwargs): ",tests/common.py,"ReplaceText(target='middleware' @(32,35)->(32,44))","class MockApp: if attach_to == 'request': self.req_middleware.append(middleware) elif attach_to == 'response': self.res_middleware = [attach_to] + self.res_middleware class MockSession(Session): def __init__(self, app=MockApp(), master_interface=MockInterface(), *args, **kwargs):","class MockApp: if attach_to == 'request': self.req_middleware.append(middleware) elif attach_to == 'response': self.res_middleware = [middleware] + self.res_middleware class MockSession(Session): def __init__(self, app=MockApp(), master_interface=MockInterface(), *args, **kwargs):" 1348,https://:@github.com/Warths/pyTwitchIRC.git,8095007fc0d6eb1242b7f845b95b44d77349a2cc,"@@ -350,7 +350,7 @@ class IRC: # request channel join def join(self, channel: str): channels = list(self.channels) - if channel in channels: + if channel not in channels: self.__to_join.append((channel, 0, time.time())) else: self.__warning('Already connected to channel {}, connection aborted'.format(channel)) ",irc.py,"ReplaceText(target=' not in ' @(353,18)->(353,22))","class IRC: # request channel join def join(self, channel: str): channels = list(self.channels) if channel in channels: self.__to_join.append((channel, 0, time.time())) else: self.__warning('Already connected to channel {}, connection aborted'.format(channel))","class IRC: # request channel join def join(self, channel: str): channels = list(self.channels) if channel not in channels: self.__to_join.append((channel, 0, time.time())) else: self.__warning('Already connected to channel {}, connection aborted'.format(channel))" 1349,https://:@github.com/Warths/pyTwitchIRC.git,0088b156487239166a21466917d36b6b61e83bc8,"@@ -412,7 +412,7 @@ class IRC: # send a packet and log it[, obfuscate after a certain index][, ignore the throttling cap] def __send(self, packet, obfuscate_after=None, ignore_throttle=0): # verify throttling status - if self.__anti_throttle() or ignore_throttle: + if self.__anti_throttle() or not ignore_throttle: # verify socket instance if self.__wait_for_status(0): self.__socket.send(packet.encode('UTF-8')) ",irc.py,"ReplaceText(target='not ' @(415,37)->(415,37))","class IRC: # send a packet and log it[, obfuscate after a certain index][, ignore the throttling cap] def __send(self, packet, obfuscate_after=None, ignore_throttle=0): # verify throttling status if self.__anti_throttle() or ignore_throttle: # verify socket instance if self.__wait_for_status(0): self.__socket.send(packet.encode('UTF-8'))","class IRC: # send a packet and log it[, obfuscate after a certain index][, ignore the throttling cap] def __send(self, packet, obfuscate_after=None, ignore_throttle=0): # verify throttling status if self.__anti_throttle() or not ignore_throttle: # verify socket instance if self.__wait_for_status(0): self.__socket.send(packet.encode('UTF-8'))" 1350,https://:@github.com/Warths/pyTwitchIRC.git,6321f5177fa2b2f54f40f77a1aaed486f28cd6da,"@@ -451,7 +451,7 @@ class IRC: # send a message to a channel and prevent sending to disconnected channels def __send_message(self) -> None: # if there is message to send and socket ready and socket not throttling - if len(self.__to_send) > 0 and self.__wait_for_status() and not self.__anti_throttle(): + if len(self.__to_send) > 0 and self.__wait_for_status() and self.__anti_throttle(): # retrieve the first message to send item = self.__to_send.pop(0) channel = item[0] ",irc.py,"ReplaceText(target='' @(454,68)->(454,72))","class IRC: # send a message to a channel and prevent sending to disconnected channels def __send_message(self) -> None: # if there is message to send and socket ready and socket not throttling if len(self.__to_send) > 0 and self.__wait_for_status() and not self.__anti_throttle(): # retrieve the first message to send item = self.__to_send.pop(0) channel = item[0]","class IRC: # send a message to a channel and prevent sending to disconnected channels def __send_message(self) -> None: # if there is message to send and socket ready and socket not throttling if len(self.__to_send) > 0 and self.__wait_for_status() and self.__anti_throttle(): # retrieve the first message to send item = self.__to_send.pop(0) channel = item[0]" 1351,https://:@github.com/All-less/trace-generator.git,54a30158f1a22cbe8195a921495592e39875159c,"@@ -36,5 +36,5 @@ def iter_job(task_file, instance_file): while next_task[JOB_ID] != '': arrive_at, task_lines, instance_lines = next_task[ARR_TIME], [ next_task[REST] ], [ next_instance[REST] ] next_task = read_lines(task_file, next_task[JOB_ID], task_lines) - next_instance = read_lines(instance_file, next_task[JOB_ID], instance_lines) + next_instance = read_lines(instance_file, next_instance[JOB_ID], instance_lines) yield float(arrive_at), { 'tasks': task_lines, 'instances': instance_lines } ",spar/io.py,"ReplaceText(target='next_instance' @(39,50)->(39,59))","def iter_job(task_file, instance_file): while next_task[JOB_ID] != '': arrive_at, task_lines, instance_lines = next_task[ARR_TIME], [ next_task[REST] ], [ next_instance[REST] ] next_task = read_lines(task_file, next_task[JOB_ID], task_lines) next_instance = read_lines(instance_file, next_task[JOB_ID], instance_lines) yield float(arrive_at), { 'tasks': task_lines, 'instances': instance_lines }","def iter_job(task_file, instance_file): while next_task[JOB_ID] != '': arrive_at, task_lines, instance_lines = next_task[ARR_TIME], [ next_task[REST] ], [ next_instance[REST] ] next_task = read_lines(task_file, next_task[JOB_ID], task_lines) next_instance = read_lines(instance_file, next_instance[JOB_ID], instance_lines) yield float(arrive_at), { 'tasks': task_lines, 'instances': instance_lines }" 1352,https://:@github.com/brandonschabell/models.git,d0b6a34bb0dbd981e3785661f04f04cde9c4222b,"@@ -107,7 +107,7 @@ def run_mnist_eager(flags_obj): # Automatically determine device and data_format (device, data_format) = ('/gpu:0', 'channels_first') - if flags_obj.no_gpu or tf.test.is_gpu_available(): + if flags_obj.no_gpu or not tf.test.is_gpu_available(): (device, data_format) = ('/cpu:0', 'channels_last') # If data_format is defined in FLAGS, overwrite automatically set value. if flags_obj.data_format is not None: ",official/mnist/mnist_eager.py,"ReplaceText(target='not ' @(110,25)->(110,25))","def run_mnist_eager(flags_obj): # Automatically determine device and data_format (device, data_format) = ('/gpu:0', 'channels_first') if flags_obj.no_gpu or tf.test.is_gpu_available(): (device, data_format) = ('/cpu:0', 'channels_last') # If data_format is defined in FLAGS, overwrite automatically set value. if flags_obj.data_format is not None:","def run_mnist_eager(flags_obj): # Automatically determine device and data_format (device, data_format) = ('/gpu:0', 'channels_first') if flags_obj.no_gpu or not tf.test.is_gpu_available(): (device, data_format) = ('/cpu:0', 'channels_last') # If data_format is defined in FLAGS, overwrite automatically set value. if flags_obj.data_format is not None:" 1353,https://:@github.com/hoh/Billabong.git,43e4c8a9a42662dde86057a4cdb5d44ab577bd1a,"@@ -46,7 +46,7 @@ def copy_and_encrypt(filepath, key): source_file.close() dest_file.close() - storage.import_blob(open(tmp_destination, 'rb'), id_) + storage.import_blob(id_, open(tmp_destination, 'rb')) os.remove(tmp_destination) return enc_hash.hexdigest() ",diss/encryption.py,"ArgSwap(idxs=0<->1 @(49,4)->(49,23))","def copy_and_encrypt(filepath, key): source_file.close() dest_file.close() storage.import_blob(open(tmp_destination, 'rb'), id_) os.remove(tmp_destination) return enc_hash.hexdigest()","def copy_and_encrypt(filepath, key): source_file.close() dest_file.close() storage.import_blob(id_, open(tmp_destination, 'rb')) os.remove(tmp_destination) return enc_hash.hexdigest()" 1354,https://:@github.com/mkirchner/pockyll.git,fa6b9fb6f2e939e9cbe551db3c7fb4b7b2bf2637,"@@ -133,7 +133,7 @@ def get_list(config): def create_linkpost(config, item_id, title, url, timestamp, is_draft=True): path = '' - if is_draft: + if not is_draft: path = config.get(""linkpost_post_dir"", ""_posts/linkposts"") else: path = config.get(""linkpost_draft_dir"", ""_drafts/linkposts"") ",pockyll.py,"ReplaceText(target='not ' @(136,7)->(136,7))","def get_list(config): def create_linkpost(config, item_id, title, url, timestamp, is_draft=True): path = '' if is_draft: path = config.get(""linkpost_post_dir"", ""_posts/linkposts"") else: path = config.get(""linkpost_draft_dir"", ""_drafts/linkposts"")","def get_list(config): def create_linkpost(config, item_id, title, url, timestamp, is_draft=True): path = '' if not is_draft: path = config.get(""linkpost_post_dir"", ""_posts/linkposts"") else: path = config.get(""linkpost_draft_dir"", ""_drafts/linkposts"")" 1355,https://:@github.com/ArunTejCh/python-driver.git,6d34a00cee5b033bf285994af739a09419e447a2,"@@ -89,8 +89,8 @@ class Metadata(object): if keyspace in cf_def_rows: for table_row in cf_def_rows[keyspace]: table_meta = self._build_table_metadata( - keyspace_meta, table_row, col_def_rows[keyspace]) - keyspace.tables[table_meta.name] = table_meta + keyspace_meta, table_row, col_def_rows[keyspace]) + keyspace_meta.tables[table_meta.name] = table_meta def _build_keyspace_metadata(self, row): name = row[""keyspace_name""] ",cassandra/metadata.py,"ReplaceText(target='keyspace_meta' @(93,20)->(93,28))","class Metadata(object): if keyspace in cf_def_rows: for table_row in cf_def_rows[keyspace]: table_meta = self._build_table_metadata( keyspace_meta, table_row, col_def_rows[keyspace]) keyspace.tables[table_meta.name] = table_meta def _build_keyspace_metadata(self, row): name = row[""keyspace_name""]","class Metadata(object): if keyspace in cf_def_rows: for table_row in cf_def_rows[keyspace]: table_meta = self._build_table_metadata( keyspace_meta, table_row, col_def_rows[keyspace]) keyspace_meta.tables[table_meta.name] = table_meta def _build_keyspace_metadata(self, row): name = row[""keyspace_name""]" 1356,https://:@github.com/ArunTejCh/python-driver.git,c7a77b8862551e73fd09b749316c422eee7a2308,"@@ -26,7 +26,7 @@ class RoundRobinPolicy(LoadBalancingPolicy): def populate(self, cluster, hosts): self._live_hosts = set(hosts) - if len(hosts) == 1: + if len(hosts) <= 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1) ",cassandra/policies.py,"ReplaceText(target='<=' @(29,22)->(29,24))","class RoundRobinPolicy(LoadBalancingPolicy): def populate(self, cluster, hosts): self._live_hosts = set(hosts) if len(hosts) == 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1)","class RoundRobinPolicy(LoadBalancingPolicy): def populate(self, cluster, hosts): self._live_hosts = set(hosts) if len(hosts) <= 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1)" 1357,https://:@github.com/ArunTejCh/python-driver.git,2984ba71634e5c3d4b23bb42a977401ca60ffc01,"@@ -230,7 +230,7 @@ class BaseModel(object): 'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__) ) - if not issubclass(klass, poly_base): + if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) ) ",cqlengine/models.py,"ReplaceText(target='cls' @(233,37)->(233,46))","class BaseModel(object): 'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__) ) if not issubclass(klass, poly_base): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) )","class BaseModel(object): 'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__) ) if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) )" 1358,https://:@github.com/ArunTejCh/python-driver.git,5dc9e971267c2072c60ae9271c6e230813f72e15,"@@ -232,7 +232,7 @@ class BaseModel(object): if not issubclass(klass, cls): raise PolyMorphicModelException( - '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) + '{} is not a subclass of {}'.format(klass.__name__, cls.__name__) ) field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()} ",cqlengine/models.py,"ReplaceText(target='cls' @(235,72)->(235,81))","class BaseModel(object): if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) ) field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()}","class BaseModel(object): if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, cls.__name__) ) field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()}" 1359,https://:@github.com/ArunTejCh/python-driver.git,c40a1aa79e4721f7892be787eef3c3fe0f324959,"@@ -772,7 +772,7 @@ class DowngradingConsistencyRetryPolicy(RetryPolicy): received_responses, data_retrieved, retry_num): if retry_num != 0: return (self.RETHROW, None) - elif received_responses < required_responses: + elif received_responses <= required_responses: return self._pick_consistency(received_responses) elif not data_retrieved: return (self.RETRY, consistency) ",cassandra/policies.py,"ReplaceText(target='<=' @(775,32)->(775,33))","class DowngradingConsistencyRetryPolicy(RetryPolicy): received_responses, data_retrieved, retry_num): if retry_num != 0: return (self.RETHROW, None) elif received_responses < required_responses: return self._pick_consistency(received_responses) elif not data_retrieved: return (self.RETRY, consistency)","class DowngradingConsistencyRetryPolicy(RetryPolicy): received_responses, data_retrieved, retry_num): if retry_num != 0: return (self.RETHROW, None) elif received_responses <= required_responses: return self._pick_consistency(received_responses) elif not data_retrieved: return (self.RETRY, consistency)" 1360,https://:@github.com/ArunTejCh/python-driver.git,21081fb30673a52506de2ef2b3c38ae519afef99,"@@ -895,7 +895,7 @@ class ModelMetaClass(type): if MultipleObjectsReturnedBase is not None: break - MultipleObjectsReturnedBase = DoesNotExistBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) + MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) # create the class and add a QuerySet to it ",cassandra/cqlengine/models.py,"ReplaceText(target='MultipleObjectsReturnedBase' @(898,38)->(898,54))","class ModelMetaClass(type): if MultipleObjectsReturnedBase is not None: break MultipleObjectsReturnedBase = DoesNotExistBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) # create the class and add a QuerySet to it","class ModelMetaClass(type): if MultipleObjectsReturnedBase is not None: break MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) # create the class and add a QuerySet to it" 1361,https://:@github.com/unixpickle/mazenv-py.git,e1e12b285e2e366c19b99583d934e46cda3798e2,"@@ -17,7 +17,7 @@ def parse_2d_maze(maze_str): start_pos = None end_pos = None for row, row_str in enumerate(lines): - if len(row) != num_cols: + if len(row_str) != num_cols: raise ValueError('row length should be %d but got %d' % (num_cols, len(row))) sub_walls = [] ",mazenv/maze.py,"ReplaceText(target='row_str' @(20,15)->(20,18))","def parse_2d_maze(maze_str): start_pos = None end_pos = None for row, row_str in enumerate(lines): if len(row) != num_cols: raise ValueError('row length should be %d but got %d' % (num_cols, len(row))) sub_walls = []","def parse_2d_maze(maze_str): start_pos = None end_pos = None for row, row_str in enumerate(lines): if len(row_str) != num_cols: raise ValueError('row length should be %d but got %d' % (num_cols, len(row))) sub_walls = []" 1362,https://:@github.com/JGoutin/rfs.git,0f3baf03774e56ccdb3177ba5150b79446f84308,"@@ -122,7 +122,7 @@ def test_s3_raw_io(): s3object = S3RawIO(path) assert s3object._client_kwargs == client_args - assert s3object.name == url + assert s3object.name == path # Tests _head check_head_methods(s3object, m_time) ",tests/test_s3.py,"ReplaceText(target='path' @(125,32)->(125,35))","def test_s3_raw_io(): s3object = S3RawIO(path) assert s3object._client_kwargs == client_args assert s3object.name == url # Tests _head check_head_methods(s3object, m_time)","def test_s3_raw_io(): s3object = S3RawIO(path) assert s3object._client_kwargs == client_args assert s3object.name == path # Tests _head check_head_methods(s3object, m_time)" 1363,https://:@github.com/JGoutin/rfs.git,9997aa65673b3f42439ff5b46e1fd4f7bb42524a,"@@ -27,7 +27,7 @@ def _copy(src, dst, src_is_storage, dst_is_storage): if system is get_instance(dst): # Checks if same file - if system.relpath(src) != system.relpath(dst): + if system.relpath(src) == system.relpath(dst): raise same_file_error( ""'%s' and '%s' are the same file"" % (src, dst)) ",pycosio/_core/functions_shutil.py,"ReplaceText(target='==' @(30,35)->(30,37))","def _copy(src, dst, src_is_storage, dst_is_storage): if system is get_instance(dst): # Checks if same file if system.relpath(src) != system.relpath(dst): raise same_file_error( ""'%s' and '%s' are the same file"" % (src, dst)) ","def _copy(src, dst, src_is_storage, dst_is_storage): if system is get_instance(dst): # Checks if same file if system.relpath(src) == system.relpath(dst): raise same_file_error( ""'%s' and '%s' are the same file"" % (src, dst)) " 1364,https://:@github.com/JGoutin/rfs.git,76ae1f2720567a6121b264da9fbada3c49e4378b,"@@ -574,7 +574,7 @@ class SystemBase(ABC): stat[key] = S_IFREG # Add storage specific keys - for key, value in tuple(stat.items()): + for key, value in tuple(header.items()): stat['st_' + key.lower().replace('-', '_')] = value # Convert to ""os.stat_result"" like object ",pycosio/_core/io_system.py,"ReplaceText(target='header' @(577,32)->(577,36))","class SystemBase(ABC): stat[key] = S_IFREG # Add storage specific keys for key, value in tuple(stat.items()): stat['st_' + key.lower().replace('-', '_')] = value # Convert to ""os.stat_result"" like object","class SystemBase(ABC): stat[key] = S_IFREG # Add storage specific keys for key, value in tuple(header.items()): stat['st_' + key.lower().replace('-', '_')] = value # Convert to ""os.stat_result"" like object" 1365,https://:@github.com/ishikota/kyoka.git,3f844dec3d6320e376176eb8ff82227deb5ee164,"@@ -54,7 +54,7 @@ class BaseRLAlgorithmTest(BaseUnitTest): task = self.__setup_stub_task() policy = GreedyPolicy() value_func = self.__setup_stub_value_function() - episode = generate_episode(task, value_func, policy) + episode = generate_episode(task, policy, value_func) self.eq(3, len(episode)) self.eq((0, 1, 1, 1), episode[0]) self.eq((1, 2, 3, 9), episode[1]) ",tests/kyoka/algorithm_/rl_algorithm_test.py,"ArgSwap(idxs=1<->2 @(57,18)->(57,34))","class BaseRLAlgorithmTest(BaseUnitTest): task = self.__setup_stub_task() policy = GreedyPolicy() value_func = self.__setup_stub_value_function() episode = generate_episode(task, value_func, policy) self.eq(3, len(episode)) self.eq((0, 1, 1, 1), episode[0]) self.eq((1, 2, 3, 9), episode[1])","class BaseRLAlgorithmTest(BaseUnitTest): task = self.__setup_stub_task() policy = GreedyPolicy() value_func = self.__setup_stub_value_function() episode = generate_episode(task, policy, value_func) self.eq(3, len(episode)) self.eq((0, 1, 1, 1), episode[0]) self.eq((1, 2, 3, 9), episode[1])" 1366,https://:@bitbucket.org/batterio/regulome_web.git,1872e4fca0b62b46fea9e60f8e15729c37f39fb9,"@@ -12,7 +12,7 @@ def mark_as_active(pathname): """"""Mark the active page in the navbar"""""" for id_page in ('home', 'data', 'credits', 'contact', 'info'): if id_page in pathname: - document[pathname].class_name = 'active' + document[id_page].class_name = 'active' else: document[id_page].class_name = '' if 'show' in pathname: ",regulome_app/webapp/static/python/utils.py,"ReplaceText(target='id_page' @(15,21)->(15,29))","def mark_as_active(pathname): """"""Mark the active page in the navbar"""""" for id_page in ('home', 'data', 'credits', 'contact', 'info'): if id_page in pathname: document[pathname].class_name = 'active' else: document[id_page].class_name = '' if 'show' in pathname:","def mark_as_active(pathname): """"""Mark the active page in the navbar"""""" for id_page in ('home', 'data', 'credits', 'contact', 'info'): if id_page in pathname: document[id_page].class_name = 'active' else: document[id_page].class_name = '' if 'show' in pathname:" 1367,https://:@github.com/Mmodarre/pyfujitsu.git,956c0d2f02ee05c3312d5472f3921a59b7780ea4,"@@ -45,7 +45,7 @@ class splitAC: def changeTemperature(self,newTemperature): ## set temperature for degree C - if not isinstance(newTemperature,int) or not isinstance(newTemperature,float): + if not isinstance(newTemperature,int) and not isinstance(newTemperature,float): raise Exception('Wrong usage of method') ## Fixing temps if not given as multiplies of 10 less than 180 if newTemperature < 180: ",pyfujitsu/splitAC.py,"ReplaceText(target='and' @(48,46)->(48,48))","class splitAC: def changeTemperature(self,newTemperature): ## set temperature for degree C if not isinstance(newTemperature,int) or not isinstance(newTemperature,float): raise Exception('Wrong usage of method') ## Fixing temps if not given as multiplies of 10 less than 180 if newTemperature < 180:","class splitAC: def changeTemperature(self,newTemperature): ## set temperature for degree C if not isinstance(newTemperature,int) and not isinstance(newTemperature,float): raise Exception('Wrong usage of method') ## Fixing temps if not given as multiplies of 10 less than 180 if newTemperature < 180:" 1368,https://:@github.com/pushrbx/python3-mal.git,9c5710647f2486e53bc8853c71185349312a857a,"@@ -240,7 +240,7 @@ class Anime(Base): related_type = None while True: if not curr_elt: - raise MalformedAnimePageError(self, html, message=""Prematurely reached end of related anime listing"") + raise MalformedAnimePageError(self, related_elt, message=""Prematurely reached end of related anime listing"") if isinstance(curr_elt, bs4.NavigableString): type_match = re.match('(?P[a-zA-Z\ \-]+):', curr_elt) if type_match: ",myanimelist/anime.py,"ReplaceText(target='related_elt' @(243,48)->(243,52))","class Anime(Base): related_type = None while True: if not curr_elt: raise MalformedAnimePageError(self, html, message=""Prematurely reached end of related anime listing"") if isinstance(curr_elt, bs4.NavigableString): type_match = re.match('(?P[a-zA-Z\ \-]+):', curr_elt) if type_match:","class Anime(Base): related_type = None while True: if not curr_elt: raise MalformedAnimePageError(self, related_elt, message=""Prematurely reached end of related anime listing"") if isinstance(curr_elt, bs4.NavigableString): type_match = re.match('(?P[a-zA-Z\ \-]+):', curr_elt) if type_match:" 1369,https://:@github.com/pushrbx/python3-mal.git,36024bc1b0cfa62c59ce9528bed097079f144d1b,"@@ -38,7 +38,7 @@ class MediaList(Base, collections.Mapping): def __init__(self, session, user_name): super(MediaList, self).__init__(session) self.username = user_name - if not isinstance(self.username, unicode) or len(self.username) < 2: + if not isinstance(self.username, unicode) or len(self.username) < 1: raise InvalidMediaListError(self.username) self._list = None self._stats = None ",myanimelist/media_list.py,"ReplaceText(target='1' @(41,70)->(41,71))","class MediaList(Base, collections.Mapping): def __init__(self, session, user_name): super(MediaList, self).__init__(session) self.username = user_name if not isinstance(self.username, unicode) or len(self.username) < 2: raise InvalidMediaListError(self.username) self._list = None self._stats = None","class MediaList(Base, collections.Mapping): def __init__(self, session, user_name): super(MediaList, self).__init__(session) self.username = user_name if not isinstance(self.username, unicode) or len(self.username) < 1: raise InvalidMediaListError(self.username) self._list = None self._stats = None" 1370,https://:@github.com/DrLuke/effigy.git,c970d945fc22787bd6b95ec2f1dfd317876ef4dc,"@@ -41,7 +41,7 @@ class QNodeScene(QGraphicsScene): nodes = [x for x in selectedItems if issubclass(type(x), QNodeSceneNode) and not issubclass(type(x), QNodeSceneNodeUndeletable)] #remainder = [x for x in selectedItems if not issubclass(type(x), (QNodeSceneNode, NodeLink))] - if links and nodes: + if links or nodes: self.undostack.beginMacro(""Delete Stuff"") for link in links: self.undostack.push(type(link.startIO).DeleteLinkCommand(link.startIO)) ",effigy/QNodeScene.py,"ReplaceText(target='or' @(44,17)->(44,20))","class QNodeScene(QGraphicsScene): nodes = [x for x in selectedItems if issubclass(type(x), QNodeSceneNode) and not issubclass(type(x), QNodeSceneNodeUndeletable)] #remainder = [x for x in selectedItems if not issubclass(type(x), (QNodeSceneNode, NodeLink))] if links and nodes: self.undostack.beginMacro(""Delete Stuff"") for link in links: self.undostack.push(type(link.startIO).DeleteLinkCommand(link.startIO))","class QNodeScene(QGraphicsScene): nodes = [x for x in selectedItems if issubclass(type(x), QNodeSceneNode) and not issubclass(type(x), QNodeSceneNodeUndeletable)] #remainder = [x for x in selectedItems if not issubclass(type(x), (QNodeSceneNode, NodeLink))] if links or nodes: self.undostack.beginMacro(""Delete Stuff"") for link in links: self.undostack.push(type(link.startIO).DeleteLinkCommand(link.startIO))" 1371,https://:@github.com/carlosefr/python-kyototycoon-ng.git,0a988c311c7858eaa909a50f19d44a3cdf023aa0,"@@ -124,7 +124,7 @@ class Cursor(object): '''Jump the cursor to a record (last record if ""None"") for forward scan.''' db = str(db) if isinstance(db, int) else quote(db.encode('utf-8')) - path += '/rpc/cur_jump_back?DB=' + db + path = '/rpc/cur_jump_back?DB=' + db request_dict = {'CUR': self.cursor_id} if key: ",kyototycoon/kt_http.py,"ReplaceText(target='=' @(127,13)->(127,15))","class Cursor(object): '''Jump the cursor to a record (last record if ""None"") for forward scan.''' db = str(db) if isinstance(db, int) else quote(db.encode('utf-8')) path += '/rpc/cur_jump_back?DB=' + db request_dict = {'CUR': self.cursor_id} if key:","class Cursor(object): '''Jump the cursor to a record (last record if ""None"") for forward scan.''' db = str(db) if isinstance(db, int) else quote(db.encode('utf-8')) path = '/rpc/cur_jump_back?DB=' + db request_dict = {'CUR': self.cursor_id} if key:" 1372,https://:@github.com/uuazed/numerai_reports.git,923f6acc29faff293c02abb7f2b8d39ed9f4dae6,"@@ -184,7 +184,7 @@ def fetch_one(round_num, tournament): if 'nmr_returned' in df: df['nmr_returned'] = df['nmr_returned'].astype(float) if round_num == 158: - df['nmr_bonus'] = bonus_nmr_only.where(df['usd_staking'].isna(), bonus_nmr_only) + df['nmr_bonus'] = bonus_nmr_only.where(df['usd_staking'].isna(), bonus_split) df['usd_bonus'] = df['usd_staking'] - df['usd_staking'] / (1 + staking_bonus_perc) df['usd_staking'] = df['usd_staking'] - df['usd_bonus'] df['nmr_returned'] -= bonus_nmr_only ",numerai_reports/data.py,"ReplaceText(target='bonus_split' @(187,85)->(187,99))","def fetch_one(round_num, tournament): if 'nmr_returned' in df: df['nmr_returned'] = df['nmr_returned'].astype(float) if round_num == 158: df['nmr_bonus'] = bonus_nmr_only.where(df['usd_staking'].isna(), bonus_nmr_only) df['usd_bonus'] = df['usd_staking'] - df['usd_staking'] / (1 + staking_bonus_perc) df['usd_staking'] = df['usd_staking'] - df['usd_bonus'] df['nmr_returned'] -= bonus_nmr_only","def fetch_one(round_num, tournament): if 'nmr_returned' in df: df['nmr_returned'] = df['nmr_returned'].astype(float) if round_num == 158: df['nmr_bonus'] = bonus_nmr_only.where(df['usd_staking'].isna(), bonus_split) df['usd_bonus'] = df['usd_staking'] - df['usd_staking'] / (1 + staking_bonus_perc) df['usd_staking'] = df['usd_staking'] - df['usd_bonus'] df['nmr_returned'] -= bonus_nmr_only" 1373,https://:@github.com/internetimagery/surface.git,ebdcb1f548d4db39fa3e6fac087aeaf49272543b,"@@ -149,7 +149,7 @@ class ArgMapper(Mapper): def get_comment(func): # type: (Any) -> Optional[Tuple[Dict[str, str], str]] - if not inspect.isfunction(func) or not inspect.ismethod(func): + if not inspect.isfunction(func) and not inspect.ismethod(func): # Classes should be handled, but are not yet... # Handling them would involve determining if they use __new__ or __init__ # and using that as the function itself. ",surface/_comment.py,"ReplaceText(target='and' @(152,36)->(152,38))","class ArgMapper(Mapper): def get_comment(func): # type: (Any) -> Optional[Tuple[Dict[str, str], str]] if not inspect.isfunction(func) or not inspect.ismethod(func): # Classes should be handled, but are not yet... # Handling them would involve determining if they use __new__ or __init__ # and using that as the function itself.","class ArgMapper(Mapper): def get_comment(func): # type: (Any) -> Optional[Tuple[Dict[str, str], str]] if not inspect.isfunction(func) and not inspect.ismethod(func): # Classes should be handled, but are not yet... # Handling them would involve determining if they use __new__ or __init__ # and using that as the function itself." 1374,https://:@github.com/internetimagery/surface.git,ebdcb1f548d4db39fa3e6fac087aeaf49272543b,"@@ -12,7 +12,7 @@ from surface._utils import normalize_type def parse_docstring(func): # type: (Any) -> Optional[Tuple[Dict[str, str], str]] """""" Parse out typing information from docstring """""" - if not inspect.isfunction(func) or not inspect.ismethod(func): + if not inspect.isfunction(func) and not inspect.ismethod(func): # Classes should be handled, but are not yet... # Handling them would involve determining if they use __new__ or __init__ # and using that as the function itself. ",surface/_doc.py,"ReplaceText(target='and' @(15,36)->(15,38))","from surface._utils import normalize_type def parse_docstring(func): # type: (Any) -> Optional[Tuple[Dict[str, str], str]] """""" Parse out typing information from docstring """""" if not inspect.isfunction(func) or not inspect.ismethod(func): # Classes should be handled, but are not yet... # Handling them would involve determining if they use __new__ or __init__ # and using that as the function itself.","from surface._utils import normalize_type def parse_docstring(func): # type: (Any) -> Optional[Tuple[Dict[str, str], str]] """""" Parse out typing information from docstring """""" if not inspect.isfunction(func) and not inspect.ismethod(func): # Classes should be handled, but are not yet... # Handling them would involve determining if they use __new__ or __init__ # and using that as the function itself." 1375,https://:@github.com/Amper/opyum.git,444ce0427ba68f5a0d1f49dc039510476c978c2e,"@@ -47,6 +47,6 @@ class ConstantFolding(ASTOptimization): node = ast.copy_location(ast.Num(n = val), node) elif all(isinstance(value, ast.Str) for value in (left, right)): if isinstance(node.op, ast.Add): - val = left.s + left.s + val = left.s + right.s node = ast.copy_location(ast.Str(s = val), node) return node ",opyum/optimizations/constant_folding.py,"ReplaceText(target='right' @(50,32)->(50,36))","class ConstantFolding(ASTOptimization): node = ast.copy_location(ast.Num(n = val), node) elif all(isinstance(value, ast.Str) for value in (left, right)): if isinstance(node.op, ast.Add): val = left.s + left.s node = ast.copy_location(ast.Str(s = val), node) return node","class ConstantFolding(ASTOptimization): node = ast.copy_location(ast.Num(n = val), node) elif all(isinstance(value, ast.Str) for value in (left, right)): if isinstance(node.op, ast.Add): val = left.s + right.s node = ast.copy_location(ast.Str(s = val), node) return node" 1376,https://:@gitlab.com/lbartoletti/portsgraph.git,3e9e2cae7cc559fdaf062d18a7f6bd2fb0b25fed,"@@ -96,7 +96,7 @@ class portgraph: portname = self.__flavorname2port(ports) - self.__addnode(portname) + self.__addnode(ports) proc = subprocess.Popen(['make', '-C', portname, ",portgraph/portgraph.py,"ReplaceText(target='ports' @(99,23)->(99,31))","class portgraph: portname = self.__flavorname2port(ports) self.__addnode(portname) proc = subprocess.Popen(['make', '-C', portname,","class portgraph: portname = self.__flavorname2port(ports) self.__addnode(ports) proc = subprocess.Popen(['make', '-C', portname," 1377,https://:@github.com/biolab/orange3-recommendation.git,55f4a56c940175a50cd6ccf73783bf66cda42a92,"@@ -26,7 +26,7 @@ def ReciprocalRank(results, query): rank = np.where(results[i] == j)[0] if len(rank) == 0: # Check values not found - rank = len(query[i]) + rank = len(results[i]) else: rank = rank[0] all_rr.append(rank) ",orangecontrib/recommendation/evaluation/ranking.py,"ReplaceText(target='results' @(29,27)->(29,32))","def ReciprocalRank(results, query): rank = np.where(results[i] == j)[0] if len(rank) == 0: # Check values not found rank = len(query[i]) else: rank = rank[0] all_rr.append(rank)","def ReciprocalRank(results, query): rank = np.where(results[i] == j)[0] if len(rank) == 0: # Check values not found rank = len(results[i]) else: rank = rank[0] all_rr.append(rank)" 1378,https://:@github.com/biolab/orange3-recommendation.git,971301a39ce26450ac6bdeee8c9028699b9a240e,"@@ -157,7 +157,7 @@ class TestSVDPlusPlus(unittest.TestCase): recommender.compute_objective(data=data, P=recommender.P, Q=recommender.Q, Y=recommender.Y, - bias=learner.bias, + bias=recommender.bias, beta=learner.beta)) # Assert objective values decrease ",orangecontrib/recommendation/tests/test_svdplusplus.py,"ReplaceText(target='recommender' @(160,51)->(160,58))","class TestSVDPlusPlus(unittest.TestCase): recommender.compute_objective(data=data, P=recommender.P, Q=recommender.Q, Y=recommender.Y, bias=learner.bias, beta=learner.beta)) # Assert objective values decrease","class TestSVDPlusPlus(unittest.TestCase): recommender.compute_objective(data=data, P=recommender.P, Q=recommender.Q, Y=recommender.Y, bias=recommender.bias, beta=learner.beta)) # Assert objective values decrease" 1379,https://:@github.com/silvacms/silva.core.conf.git,306ed54d4a7497da3c21d172e5e00215a4746f7d,"@@ -53,7 +53,7 @@ class ExtensionGrokker(martian.GlobalGrokker): module_directory = extension.module_directory # Register Silva Views directory if os.path.exists(os.path.join(module_directory, 'views')): - registerDirectory(module_directory, 'views') + registerDirectory('views', module_directory) return True ",silva/core/conf/martiansupport/extension.py,"ArgSwap(idxs=0<->1 @(56,16)->(56,33))","class ExtensionGrokker(martian.GlobalGrokker): module_directory = extension.module_directory # Register Silva Views directory if os.path.exists(os.path.join(module_directory, 'views')): registerDirectory(module_directory, 'views') return True ","class ExtensionGrokker(martian.GlobalGrokker): module_directory = extension.module_directory # Register Silva Views directory if os.path.exists(os.path.join(module_directory, 'views')): registerDirectory('views', module_directory) return True " 1380,https://:@github.com/ryneches/pique.git,18e98cd6fcbf957012114313f108b7262fc5199d,"@@ -72,7 +72,7 @@ def detect( name, ipfile, bgfile, mapfile, alpha, l_thresh, pickle_file ) : # log inputs pique.msg( logfile, ' -> IP file : ' + ipfile ) - pique.msg( logfile, ' -> BG file : ' + ipfile ) + pique.msg( logfile, ' -> BG file : ' + bgfile ) pique.msg( logfile, ' -> map file : ' + mapfile ) pique.msg( logfile, ' -> alpha : ' + str(alpha) ) pique.msg( logfile, ' -> l_thresh : ' + str(l_thresh) ) ",pique/runtime.py,"ReplaceText(target='bgfile' @(75,45)->(75,51))","def detect( name, ipfile, bgfile, mapfile, alpha, l_thresh, pickle_file ) : # log inputs pique.msg( logfile, ' -> IP file : ' + ipfile ) pique.msg( logfile, ' -> BG file : ' + ipfile ) pique.msg( logfile, ' -> map file : ' + mapfile ) pique.msg( logfile, ' -> alpha : ' + str(alpha) ) pique.msg( logfile, ' -> l_thresh : ' + str(l_thresh) )","def detect( name, ipfile, bgfile, mapfile, alpha, l_thresh, pickle_file ) : # log inputs pique.msg( logfile, ' -> IP file : ' + ipfile ) pique.msg( logfile, ' -> BG file : ' + bgfile ) pique.msg( logfile, ' -> map file : ' + mapfile ) pique.msg( logfile, ' -> alpha : ' + str(alpha) ) pique.msg( logfile, ' -> l_thresh : ' + str(l_thresh) )" 1381,https://:@github.com/smok-serwis/coolamqp.git,e4c86dec8d84545d9616859290377338bf159df5,"@@ -87,7 +87,7 @@ class Order(object): """"""Return whether the operation failed, ie. completed but with an error code. Cancelled and discarded ops are considered failed. This assumes that this order has been .wait()ed upon"""""" - return self._result is True + return self._result is not True def result(self): """"""Wait until this is completed and return a response"""""" ",coolamqp/orders.py,"ReplaceText(target=' is not ' @(90,27)->(90,31))","class Order(object): """"""Return whether the operation failed, ie. completed but with an error code. Cancelled and discarded ops are considered failed. This assumes that this order has been .wait()ed upon"""""" return self._result is True def result(self): """"""Wait until this is completed and return a response""""""","class Order(object): """"""Return whether the operation failed, ie. completed but with an error code. Cancelled and discarded ops are considered failed. This assumes that this order has been .wait()ed upon"""""" return self._result is not True def result(self): """"""Wait until this is completed and return a response""""""" 1382,https://:@github.com/smok-serwis/coolamqp.git,2aadc44e07e1d6f23cecaf3c65a29807a1fa602c,"@@ -140,7 +140,7 @@ class Connection(object): (self.node_definition.host, self.node_definition.port)) except socket.error as e: time.sleep(0.5) # Connection refused? Very bad things? - if monotonic.monotonic() - start_at < timeout: + if monotonic.monotonic() - start_at > timeout: raise ConnectionDead() else: break ",coolamqp/uplink/connection/connection.py,"ReplaceText(target='>' @(143,52)->(143,53))","class Connection(object): (self.node_definition.host, self.node_definition.port)) except socket.error as e: time.sleep(0.5) # Connection refused? Very bad things? if monotonic.monotonic() - start_at < timeout: raise ConnectionDead() else: break","class Connection(object): (self.node_definition.host, self.node_definition.port)) except socket.error as e: time.sleep(0.5) # Connection refused? Very bad things? if monotonic.monotonic() - start_at > timeout: raise ConnectionDead() else: break" 1383,https://:@github.com/smok-serwis/coolamqp.git,a0e62d972ed89ad3a43838caf2f8c8dde438b151,"@@ -85,7 +85,7 @@ class Operation(object): self.enqueued_span = None def span_finished(self): - if self.processing_span is None: + if self.processing_span is not None: self.processing_span.finish() self.processing_span = None ",coolamqp/attaches/declarer.py,"ReplaceText(target=' is not ' @(88,31)->(88,35))","class Operation(object): self.enqueued_span = None def span_finished(self): if self.processing_span is None: self.processing_span.finish() self.processing_span = None ","class Operation(object): self.enqueued_span = None def span_finished(self): if self.processing_span is not None: self.processing_span.finish() self.processing_span = None " 1384,https://:@github.com/ryogrid/Over-NAT-Lib.git,86f4eca56bb460e898441cc13c55c663de9d8932,"@@ -323,7 +323,7 @@ async def sender_server_handler(reader, writer): while True: # if flag backed to False, end this handler because it means receiver side client disconnected - if remote_stdout_connected == False or file_transfer_mode == False: + if remote_stdout_connected == False and file_transfer_mode == False: # clear bufferd data if sender_fifo_q.empty() == False: print(""reset sender_fifo_q because it is not empty"") ",tools/p2p_com_local_server.py,"ReplaceText(target='and' @(326,48)->(326,50))","async def sender_server_handler(reader, writer): while True: # if flag backed to False, end this handler because it means receiver side client disconnected if remote_stdout_connected == False or file_transfer_mode == False: # clear bufferd data if sender_fifo_q.empty() == False: print(""reset sender_fifo_q because it is not empty"")","async def sender_server_handler(reader, writer): while True: # if flag backed to False, end this handler because it means receiver side client disconnected if remote_stdout_connected == False and file_transfer_mode == False: # clear bufferd data if sender_fifo_q.empty() == False: print(""reset sender_fifo_q because it is not empty"")" 1385,https://:@github.com/bitcaster-io/bitcaster.git,d02b5489dc239a6da6324aa62274ed1311808a15,"@@ -619,7 +619,7 @@ if DEBUG: if request.user.is_authenticated: if request.path in ignored: return False - return True + return False INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar'] MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ] ",src/bitcaster/config/settings.py,"ReplaceText(target='False' @(622,15)->(622,19))","if DEBUG: if request.user.is_authenticated: if request.path in ignored: return False return True INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar'] MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ]","if DEBUG: if request.user.is_authenticated: if request.path in ignored: return False return False INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar'] MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ]" 1386,https://:@github.com/bitcaster-io/bitcaster.git,8e32c0ae2bf35f2f7a959eeb34adfb80c4bf865a,"@@ -619,7 +619,7 @@ if DEBUG: if request.user.is_authenticated: if request.path in ignored: return False - return False + return True INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar'] MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ] ",src/bitcaster/config/settings.py,"ReplaceText(target='True' @(622,15)->(622,20))","if DEBUG: if request.user.is_authenticated: if request.path in ignored: return False return False INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar'] MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ]","if DEBUG: if request.user.is_authenticated: if request.path in ignored: return False return True INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar'] MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ]" 1387,https://:@github.com/cescalara/fancy.git,416c970b7b88aa138d2b288b0a9aa1a163334126,"@@ -57,7 +57,7 @@ class Corner(): N = np.shape(data_frame)[1] for j in range(N): for k in range(N): - if i != k: + if j != k: pairgrid.axes[i, k].spines['right'].set_visible(True) pairgrid.axes[i, k].spines['top'].set_visible(True) else: ",fancy/plotting/corner.py,"ReplaceText(target='j' @(60,23)->(60,24))","class Corner(): N = np.shape(data_frame)[1] for j in range(N): for k in range(N): if i != k: pairgrid.axes[i, k].spines['right'].set_visible(True) pairgrid.axes[i, k].spines['top'].set_visible(True) else: ","class Corner(): N = np.shape(data_frame)[1] for j in range(N): for k in range(N): if j != k: pairgrid.axes[i, k].spines['right'].set_visible(True) pairgrid.axes[i, k].spines['top'].set_visible(True) else: " 1388,https://:@github.com/cescalara/fancy.git,a05d109c3e85debb19ed2d3051fb178f2c19f409,"@@ -58,7 +58,7 @@ class Corner(): for i in range(N): for j in range(N): for k in range(N): - if j != k: + if i != k: pairgrid.axes[i, k].spines['right'].set_visible(True) pairgrid.axes[i, k].spines['top'].set_visible(True) else: ",fancy/plotting/corner.py,"ReplaceText(target='i' @(61,27)->(61,28))","class Corner(): for i in range(N): for j in range(N): for k in range(N): if j != k: pairgrid.axes[i, k].spines['right'].set_visible(True) pairgrid.axes[i, k].spines['top'].set_visible(True) else: ","class Corner(): for i in range(N): for j in range(N): for k in range(N): if i != k: pairgrid.axes[i, k].spines['right'].set_visible(True) pairgrid.axes[i, k].spines['top'].set_visible(True) else: " 1389,https://:@github.com/bbernhard/imagemonkey-libs.git,d393bd724b9531963bef3a6d8da74e9bcaae047b,"@@ -45,7 +45,7 @@ class PolyPoints(object): if p.y < 0: y = 0 elif p.y > rect.height: - x = rect.height + y = rect.height else: y = p.y ",python/pyimagemonkey/api.py,"ReplaceText(target='y' @(48,4)->(48,5))","class PolyPoints(object): if p.y < 0: y = 0 elif p.y > rect.height: x = rect.height else: y = p.y ","class PolyPoints(object): if p.y < 0: y = 0 elif p.y > rect.height: y = rect.height else: y = p.y " 1390,https://:@github.com/bbernhard/imagemonkey-libs.git,0cce51ce916ffb8f42ff0492bf91937a65cdb78b,"@@ -221,7 +221,7 @@ class TensorflowTrainer(object): if self._statistics is not None: self._statistics.output_path = self._statistics_dir + os.path.sep + ""statistics.json"" - self._statistics.generate(d) + self._statistics.generate(data) self._statistics.save() self._train_object_detection(labels, data, learning_rate) ",python/pyimagemonkey/utils.py,"ReplaceText(target='data' @(224,30)->(224,31))","class TensorflowTrainer(object): if self._statistics is not None: self._statistics.output_path = self._statistics_dir + os.path.sep + ""statistics.json"" self._statistics.generate(d) self._statistics.save() self._train_object_detection(labels, data, learning_rate)","class TensorflowTrainer(object): if self._statistics is not None: self._statistics.output_path = self._statistics_dir + os.path.sep + ""statistics.json"" self._statistics.generate(data) self._statistics.save() self._train_object_detection(labels, data, learning_rate)" 1391,https://:@github.com/OSSOS/MOP.git,2b9c4af87e1b899b7589cfb04aa272540d2e8a04,"@@ -61,7 +61,7 @@ class GeneralModelTest(FileReadingTestCase, DirectoryCleaningTestCase): # Put a real fits image on the first source, first observation apcor_str = ""4 15 0.19 0.01"" with open(self.get_abs_path(path), ""rb"") as fh: - self.first_image = DownloadedFitsImage(fh.read(), apcor_str, Mock(), in_memory=True) + self.first_image = DownloadedFitsImage(fh.read(), Mock(), apcor_str, in_memory=True) first_reading = self.model.get_current_workunit().get_sources()[0].get_readings()[0] self.model._on_image_loaded(first_reading, self.first_image) ",src/ossos-pipeline/tests/test_integration/test_models.py,"ArgSwap(idxs=1<->2 @(64,31)->(64,50))","class GeneralModelTest(FileReadingTestCase, DirectoryCleaningTestCase): # Put a real fits image on the first source, first observation apcor_str = ""4 15 0.19 0.01"" with open(self.get_abs_path(path), ""rb"") as fh: self.first_image = DownloadedFitsImage(fh.read(), apcor_str, Mock(), in_memory=True) first_reading = self.model.get_current_workunit().get_sources()[0].get_readings()[0] self.model._on_image_loaded(first_reading, self.first_image) ","class GeneralModelTest(FileReadingTestCase, DirectoryCleaningTestCase): # Put a real fits image on the first source, first observation apcor_str = ""4 15 0.19 0.01"" with open(self.get_abs_path(path), ""rb"") as fh: self.first_image = DownloadedFitsImage(fh.read(), Mock(), apcor_str, in_memory=True) first_reading = self.model.get_current_workunit().get_sources()[0].get_readings()[0] self.model._on_image_loaded(first_reading, self.first_image) " 1392,https://:@github.com/robofit/arcor2.git,08ed34b3a85635a6617ac785b067c3415227a6ce,"@@ -158,7 +158,7 @@ def object_actions(plugins: Dict[Type, Type[ParameterPlugin]], type_def: Union[T data = ObjectAction(name=method_name, meta=meta) - if method_def in type_def.CANCEL_MAPPING: + if method_name in type_def.CANCEL_MAPPING: meta.cancellable = True doc = parse_docstring(method_def.__doc__) ",arcor2/object_types_utils.py,"ReplaceText(target='method_name' @(161,11)->(161,21))","def object_actions(plugins: Dict[Type, Type[ParameterPlugin]], type_def: Union[T data = ObjectAction(name=method_name, meta=meta) if method_def in type_def.CANCEL_MAPPING: meta.cancellable = True doc = parse_docstring(method_def.__doc__)","def object_actions(plugins: Dict[Type, Type[ParameterPlugin]], type_def: Union[T data = ObjectAction(name=method_name, meta=meta) if method_name in type_def.CANCEL_MAPPING: meta.cancellable = True doc = parse_docstring(method_def.__doc__)" 1393,https://:@github.com/YoSTEALTH/Liburing.git,35981679eadc569fb31d154d245aeeeef086fff4,"@@ -81,7 +81,7 @@ def timespec(seconds=0, nanoseconds=0): >>> io_uring_wait_cqes(..., ts=timespec(), ...) >>> io_uring_wait_cqes(..., ts=timespec(None), ...) ''' - if not seconds or nanoseconds: + if seconds or nanoseconds: ts = ffi.new('struct __kernel_timespec[1]') ts[0].tv_sec = seconds or 0 ts[0].tv_nsec = nanoseconds or 0 ",liburing/helper.py,"ReplaceText(target='' @(84,7)->(84,11))","def timespec(seconds=0, nanoseconds=0): >>> io_uring_wait_cqes(..., ts=timespec(), ...) >>> io_uring_wait_cqes(..., ts=timespec(None), ...) ''' if not seconds or nanoseconds: ts = ffi.new('struct __kernel_timespec[1]') ts[0].tv_sec = seconds or 0 ts[0].tv_nsec = nanoseconds or 0","def timespec(seconds=0, nanoseconds=0): >>> io_uring_wait_cqes(..., ts=timespec(), ...) >>> io_uring_wait_cqes(..., ts=timespec(None), ...) ''' if seconds or nanoseconds: ts = ffi.new('struct __kernel_timespec[1]') ts[0].tv_sec = seconds or 0 ts[0].tv_nsec = nanoseconds or 0" 1394,https://:@github.com/shaldengeki/python-mal.git,9c5710647f2486e53bc8853c71185349312a857a,"@@ -240,7 +240,7 @@ class Anime(Base): related_type = None while True: if not curr_elt: - raise MalformedAnimePageError(self, html, message=""Prematurely reached end of related anime listing"") + raise MalformedAnimePageError(self, related_elt, message=""Prematurely reached end of related anime listing"") if isinstance(curr_elt, bs4.NavigableString): type_match = re.match('(?P[a-zA-Z\ \-]+):', curr_elt) if type_match: ",myanimelist/anime.py,"ReplaceText(target='related_elt' @(243,48)->(243,52))","class Anime(Base): related_type = None while True: if not curr_elt: raise MalformedAnimePageError(self, html, message=""Prematurely reached end of related anime listing"") if isinstance(curr_elt, bs4.NavigableString): type_match = re.match('(?P[a-zA-Z\ \-]+):', curr_elt) if type_match:","class Anime(Base): related_type = None while True: if not curr_elt: raise MalformedAnimePageError(self, related_elt, message=""Prematurely reached end of related anime listing"") if isinstance(curr_elt, bs4.NavigableString): type_match = re.match('(?P[a-zA-Z\ \-]+):', curr_elt) if type_match:" 1395,https://:@github.com/elastic-infra/kenetsu.git,03c7835bf88602e6fb8ab4d149338ed1cde30dba,"@@ -15,7 +15,7 @@ locale.setlocale(locale.LC_ALL, ""C"") def main(): - if len(sys.argv) <= 2: + if len(sys.argv) < 2: usage(sys.argv[0]) sys.exit(1) duration = int(sys.argv[1]) ",kenetsu/cli.py,"ReplaceText(target='<' @(18,21)->(18,23))","locale.setlocale(locale.LC_ALL, ""C"") def main(): if len(sys.argv) <= 2: usage(sys.argv[0]) sys.exit(1) duration = int(sys.argv[1])","locale.setlocale(locale.LC_ALL, ""C"") def main(): if len(sys.argv) < 2: usage(sys.argv[0]) sys.exit(1) duration = int(sys.argv[1])" 1396,https://:@github.com/Quansight-Labs/python-moa.git,5a344b476cee3d51e450d405f4b085eb05758358,"@@ -152,7 +152,7 @@ def _shape_plus_minus_divide_times(symbol_table, node): shape = shape + (left_element,) elif is_symbolic_element(left_element): # only left is symbolic array_name = generate_unique_array_name(symbol_table) - symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (left_element,)) + symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (right_element,)) conditions.append(BinaryNode(MOANodeTypes.EQUAL, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name))) shape = shape + (right_element,) elif is_symbolic_element(right_element): # only right is symbolic ",moa/shape.py,"ReplaceText(target='right_element' @(155,93)->(155,105))","def _shape_plus_minus_divide_times(symbol_table, node): shape = shape + (left_element,) elif is_symbolic_element(left_element): # only left is symbolic array_name = generate_unique_array_name(symbol_table) symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (left_element,)) conditions.append(BinaryNode(MOANodeTypes.EQUAL, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name))) shape = shape + (right_element,) elif is_symbolic_element(right_element): # only right is symbolic","def _shape_plus_minus_divide_times(symbol_table, node): shape = shape + (left_element,) elif is_symbolic_element(left_element): # only left is symbolic array_name = generate_unique_array_name(symbol_table) symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (right_element,)) conditions.append(BinaryNode(MOANodeTypes.EQUAL, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name))) shape = shape + (right_element,) elif is_symbolic_element(right_element): # only right is symbolic" 1397,https://:@github.com/Quansight-Labs/python-moa.git,a7983c3d549207db15510ccbfc24a07dbb7fa442,"@@ -116,7 +116,7 @@ def _shape_psi(symbol_table, node): conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, right_element)) elif is_symbolic_element(left_element): # only left is symbolic array_name = generate_unique_array_name(symbol_table) - symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (left_element,)) + symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (right_element,)) conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name))) elif is_symbolic_element(right_element): # only right is symbolic array_name = generate_unique_array_name(symbol_table) ",moa/shape.py,"ReplaceText(target='right_element' @(119,89)->(119,101))","def _shape_psi(symbol_table, node): conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, right_element)) elif is_symbolic_element(left_element): # only left is symbolic array_name = generate_unique_array_name(symbol_table) symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (left_element,)) conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name))) elif is_symbolic_element(right_element): # only right is symbolic array_name = generate_unique_array_name(symbol_table)","def _shape_psi(symbol_table, node): conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, right_element)) elif is_symbolic_element(left_element): # only left is symbolic array_name = generate_unique_array_name(symbol_table) symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (right_element,)) conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name))) elif is_symbolic_element(right_element): # only right is symbolic array_name = generate_unique_array_name(symbol_table)" 1398,https://:@github.com/felipeochoa/minecart.git,66e29717bab0079029db839a8868c2b7a1878873,"@@ -48,7 +48,7 @@ class DeviceLoader(pdfminer.pdfdevice.PDFTextDevice): device_path.append( (segment[0],) + pdfminer.utils.apply_matrix_pt(self.ctm, (x, y))) - self.page.add_shape(content.Shape(stroke, fill, evenodd, path)) + self.page.add_shape(content.Shape(stroke, fill, evenodd, device_path)) def render_image(self, name, stream): self.page.add_image(content.Image(self.ctm, stream)) ",src/miner.py,"ReplaceText(target='device_path' @(51,65)->(51,69))","class DeviceLoader(pdfminer.pdfdevice.PDFTextDevice): device_path.append( (segment[0],) + pdfminer.utils.apply_matrix_pt(self.ctm, (x, y))) self.page.add_shape(content.Shape(stroke, fill, evenodd, path)) def render_image(self, name, stream): self.page.add_image(content.Image(self.ctm, stream))","class DeviceLoader(pdfminer.pdfdevice.PDFTextDevice): device_path.append( (segment[0],) + pdfminer.utils.apply_matrix_pt(self.ctm, (x, y))) self.page.add_shape(content.Shape(stroke, fill, evenodd, device_path)) def render_image(self, name, stream): self.page.add_image(content.Image(self.ctm, stream))" 1399,https://:@bitbucket.org/creminslab/lib5c.git,9562f0ce961bd4ddadb3171783c27eedc8bcf577,"@@ -158,7 +158,7 @@ def joint_express_normalize(obs_matrices, exp_matrices, max_iter=1000, # apply optimized bias to observed log_corr_obs_matrices = [(log_obs_matrix.T - bias_factors).T - bias_factors - for log_obs_matrix in log_exp_matrices] + for log_obs_matrix in log_obs_matrices] # undo log transform normalized_matrices = [np.exp(log_corr_obs_matrix) - 1 ",lib5c/algorithms/express.py,"ReplaceText(target='log_obs_matrices' @(161,51)->(161,67))","def joint_express_normalize(obs_matrices, exp_matrices, max_iter=1000, # apply optimized bias to observed log_corr_obs_matrices = [(log_obs_matrix.T - bias_factors).T - bias_factors for log_obs_matrix in log_exp_matrices] # undo log transform normalized_matrices = [np.exp(log_corr_obs_matrix) - 1","def joint_express_normalize(obs_matrices, exp_matrices, max_iter=1000, # apply optimized bias to observed log_corr_obs_matrices = [(log_obs_matrix.T - bias_factors).T - bias_factors for log_obs_matrix in log_obs_matrices] # undo log transform normalized_matrices = [np.exp(log_corr_obs_matrix) - 1" 1400,https://:@github.com/phelimb/cbg.git,d35f6bbd778114d6350e81ed1953fd33a5e4148d,"@@ -21,7 +21,7 @@ def run(parser, args, conn_config): if i % 100000 == 0: mc.set_kmers(kmers, colour) kmers = [] - mc.set_kmers(kmers, i) + mc.set_kmers(kmers, colour) # kmers = inf.read().splitlines() ",remcdbg/cmds/insert.py,"ReplaceText(target='colour' @(24,28)->(24,29))","def run(parser, args, conn_config): if i % 100000 == 0: mc.set_kmers(kmers, colour) kmers = [] mc.set_kmers(kmers, i) # kmers = inf.read().splitlines() ","def run(parser, args, conn_config): if i % 100000 == 0: mc.set_kmers(kmers, colour) kmers = [] mc.set_kmers(kmers, colour) # kmers = inf.read().splitlines() " 1401,https://:@github.com/phelimb/cbg.git,8bdef6f8a055e739860a17113a4fb565aec4542e,"@@ -74,7 +74,7 @@ class AtlasSeq(object): def search(self, seq: hug.types.text=None, fasta_file: hug.types.text=None, threshold: hug.types.float_number=1.0): """"""Returns samples that contain the searched sequence. Use -f to search for sequence from fasta"""""" - if not seq or fasta_file: + if not seq or not fasta_file: return ""-s or -f must be provided"" return search(seq=seq, fasta_file=fasta_file, threshold=threshold, conn_config=CONN_CONFIG) ",atlasseq/__main__.py,"ReplaceText(target='not ' @(77,22)->(77,22))","class AtlasSeq(object): def search(self, seq: hug.types.text=None, fasta_file: hug.types.text=None, threshold: hug.types.float_number=1.0): """"""Returns samples that contain the searched sequence. Use -f to search for sequence from fasta"""""" if not seq or fasta_file: return ""-s or -f must be provided"" return search(seq=seq, fasta_file=fasta_file, threshold=threshold, conn_config=CONN_CONFIG)","class AtlasSeq(object): def search(self, seq: hug.types.text=None, fasta_file: hug.types.text=None, threshold: hug.types.float_number=1.0): """"""Returns samples that contain the searched sequence. Use -f to search for sequence from fasta"""""" if not seq or not fasta_file: return ""-s or -f must be provided"" return search(seq=seq, fasta_file=fasta_file, threshold=threshold, conn_config=CONN_CONFIG)" 1402,https://:@github.com/phelimb/cbg.git,6aeae99e79fe215eac5e4fa1defcb77882760891,"@@ -24,5 +24,5 @@ def build(bloomfilter_filepaths, samples, graph): bloomfilters = [] for f in bloomfilter_filepaths: bloomfilters.append(load_bloomfilter(f)) - graph.build(bloomfilter_filepaths, samples) + graph.build(bloomfilters, samples) return {'result': 'success'} ",bfg/cmds/build.py,"ReplaceText(target='bloomfilters' @(27,16)->(27,37))","def build(bloomfilter_filepaths, samples, graph): bloomfilters = [] for f in bloomfilter_filepaths: bloomfilters.append(load_bloomfilter(f)) graph.build(bloomfilter_filepaths, samples) return {'result': 'success'}","def build(bloomfilter_filepaths, samples, graph): bloomfilters = [] for f in bloomfilter_filepaths: bloomfilters.append(load_bloomfilter(f)) graph.build(bloomfilters, samples) return {'result': 'success'}" 1403,https://:@github.com/sebpiq/pychedelic.git,8bdd4ad6adae0b03e5e84e4667caaf7001fdb4f3,"@@ -28,7 +28,7 @@ class Buffer(object): else: raise StopIteration def pull(self, block_size, overlap=0, pad=False): - if overlap and overlap >= block_size: + if overlap and overlap > block_size: raise ValueError('overlap cannot be more than block_size') # First, get as much blocks of data as needed. ",pychedelic/core/buffering.py,"ReplaceText(target='>' @(31,31)->(31,33))","class Buffer(object): else: raise StopIteration def pull(self, block_size, overlap=0, pad=False): if overlap and overlap >= block_size: raise ValueError('overlap cannot be more than block_size') # First, get as much blocks of data as needed.","class Buffer(object): else: raise StopIteration def pull(self, block_size, overlap=0, pad=False): if overlap and overlap > block_size: raise ValueError('overlap cannot be more than block_size') # First, get as much blocks of data as needed." 1404,https://:@github.com/SilMon/NucDetect.git,422787856116a7ba2236825d558f51e59988945c,"@@ -65,7 +65,7 @@ class Detector: :param multi_analysis: Needed for multiprocess-analysis :return: The analysis results as dict """""" - if multi_analysis: + if ml_analysis: self.analyser = FCN() start = time.time() logging = logging if self.logging is None else self.logging ",core/Detector.py,"ReplaceText(target='ml_analysis' @(68,11)->(68,25))","class Detector: :param multi_analysis: Needed for multiprocess-analysis :return: The analysis results as dict """""" if multi_analysis: self.analyser = FCN() start = time.time() logging = logging if self.logging is None else self.logging","class Detector: :param multi_analysis: Needed for multiprocess-analysis :return: The analysis results as dict """""" if ml_analysis: self.analyser = FCN() start = time.time() logging = logging if self.logging is None else self.logging" 1405,https://:@github.com/lafrech/qbirthday.git,6c3b545ef66a656d55df7c6b297cadae0b97c491,"@@ -40,7 +40,7 @@ class DataBase(object): # new entries can be saved self.CAN_SAVE = can_save # additional config options for database connection or fukebane(s) - self.HAS_CONFIG = can_save + self.HAS_CONFIG = has_config # the widget for additional config self.widget = widget ",src/gbirthday/databases/__init__.py,"ReplaceText(target='has_config' @(43,26)->(43,34))","class DataBase(object): # new entries can be saved self.CAN_SAVE = can_save # additional config options for database connection or fukebane(s) self.HAS_CONFIG = can_save # the widget for additional config self.widget = widget ","class DataBase(object): # new entries can be saved self.CAN_SAVE = can_save # additional config options for database connection or fukebane(s) self.HAS_CONFIG = has_config # the widget for additional config self.widget = widget " 1406,https://:@github.com/c00w/btcnet_info.git,2501fff74e5c798da1bf15ebf40006198d1f1198,"@@ -46,7 +46,7 @@ class Site(baseobject.Base_Object): value = self.wrapper.handle(dict(self.config.items(item))) if value: setattr(self, item, value) - self.fields.add(value) + self.fields.add(item) def __repr__(self): return '' % (self.name, str(self.coins)) ",difficulty_sites.py,"ReplaceText(target='item' @(49,32)->(49,37))","class Site(baseobject.Base_Object): value = self.wrapper.handle(dict(self.config.items(item))) if value: setattr(self, item, value) self.fields.add(value) def __repr__(self): return '' % (self.name, str(self.coins))","class Site(baseobject.Base_Object): value = self.wrapper.handle(dict(self.config.items(item))) if value: setattr(self, item, value) self.fields.add(item) def __repr__(self): return '' % (self.name, str(self.coins))" 1407,https://:@github.com/nitros12/ics.py.git,9e76a3eef5e0d1d1e3d1a2b0fd48d45e9d3e2c5e,"@@ -76,7 +76,7 @@ class ContentLine: params = {} for paramstr in params_strings: if '=' not in paramstr: - raise ParseError(""No '=' in line '{}'"".format(line)) + raise ParseError(""No '=' in line '{}'"".format(paramstr)) pname, pvals = paramstr.split('=', 1) params[pname] = pvals.split(',') return cls(name, params, value) ",ics/parse.py,"ReplaceText(target='paramstr' @(79,62)->(79,66))","class ContentLine: params = {} for paramstr in params_strings: if '=' not in paramstr: raise ParseError(""No '=' in line '{}'"".format(line)) pname, pvals = paramstr.split('=', 1) params[pname] = pvals.split(',') return cls(name, params, value)","class ContentLine: params = {} for paramstr in params_strings: if '=' not in paramstr: raise ParseError(""No '=' in line '{}'"".format(paramstr)) pname, pvals = paramstr.split('=', 1) params[pname] = pvals.split(',') return cls(name, params, value)" 1408,https://:@github.com/shirtsgroup/cg_openmm.git,40e8d834fd0fb437b40b888c844c9668739999f2,"@@ -284,7 +284,7 @@ def build_mm_simulation(topology,system,positions,temperature=300.0 * unit.kelvi # print(""to confirm their validity for these model settings,"") # print(""before performing a full simulation."") time_step_list = [(10.0 * (0.5 ** i)) * unit.femtosecond for i in range(0,14)] - simulation_time_step,force_cutoff = get_simulation_time_step(topology,system,positions,temperature,time_step_list,total_simulation_time) + simulation_time_step,force_cutoff = get_simulation_time_step(topology,system,positions,temperature,total_simulation_time,time_step_list) friction = 0.0 integrator = LangevinIntegrator(temperature._value,friction,simulation_time_step.in_units_of(unit.picosecond)._value) ",src/build/cg_build.py,"ArgSwap(idxs=4<->5 @(287,46)->(287,70))","def build_mm_simulation(topology,system,positions,temperature=300.0 * unit.kelvi # print(""to confirm their validity for these model settings,"") # print(""before performing a full simulation."") time_step_list = [(10.0 * (0.5 ** i)) * unit.femtosecond for i in range(0,14)] simulation_time_step,force_cutoff = get_simulation_time_step(topology,system,positions,temperature,time_step_list,total_simulation_time) friction = 0.0 integrator = LangevinIntegrator(temperature._value,friction,simulation_time_step.in_units_of(unit.picosecond)._value)","def build_mm_simulation(topology,system,positions,temperature=300.0 * unit.kelvi # print(""to confirm their validity for these model settings,"") # print(""before performing a full simulation."") time_step_list = [(10.0 * (0.5 ** i)) * unit.femtosecond for i in range(0,14)] simulation_time_step,force_cutoff = get_simulation_time_step(topology,system,positions,temperature,total_simulation_time,time_step_list) friction = 0.0 integrator = LangevinIntegrator(temperature._value,friction,simulation_time_step.in_units_of(unit.picosecond)._value)" 1409,https://:@github.com/shirtsgroup/cg_openmm.git,47b5ee9ca688b3513f64fafab62f088b91bef6e5,"@@ -252,7 +252,7 @@ def test_expectations_fraction_contacts_pdb(tmpdir): # Test free energy fitting / derivative calculation: ddeltaF_out, d2deltaF_out, spline_tck = get_free_energy_derivative( deltaF_values, - temperature_list, + full_T_list, plotfile=f""{output_directory}/ddeltaF_dT.pdf"", ) ",cg_openmm/tests/test_native_contacts.py,"ReplaceText(target='full_T_list' @(255,8)->(255,24))","def test_expectations_fraction_contacts_pdb(tmpdir): # Test free energy fitting / derivative calculation: ddeltaF_out, d2deltaF_out, spline_tck = get_free_energy_derivative( deltaF_values, temperature_list, plotfile=f""{output_directory}/ddeltaF_dT.pdf"", ) ","def test_expectations_fraction_contacts_pdb(tmpdir): # Test free energy fitting / derivative calculation: ddeltaF_out, d2deltaF_out, spline_tck = get_free_energy_derivative( deltaF_values, full_T_list, plotfile=f""{output_directory}/ddeltaF_dT.pdf"", ) " 1410,https://:@github.com/wplct/yzs-work.git,b7c79866bf15c8a7a30b242f80944e8853331048,"@@ -35,7 +35,7 @@ class ResourceCodeManage: """""" resource_code = self.map.get(code) if not resource_code: - if resource_code != 0: + if code != 0: warnings.warn('未知错误码', DeprecationWarning) return """" return resource_code.get_message() ",yzs/tastypie_extend/response_code.py,"ReplaceText(target='code' @(38,15)->(38,28))","class ResourceCodeManage: """""" resource_code = self.map.get(code) if not resource_code: if resource_code != 0: warnings.warn('未知错误码', DeprecationWarning) return """" return resource_code.get_message()","class ResourceCodeManage: """""" resource_code = self.map.get(code) if not resource_code: if code != 0: warnings.warn('未知错误码', DeprecationWarning) return """" return resource_code.get_message()" 1411,https://:@github.com/wplct/yzs-work.git,1d84b0acfacc7c85a3bad11c5c1e4435663125b7,"@@ -12,7 +12,7 @@ logger = logging.getLogger('system') def upload_aliyun_oss(folder): - if hasattr(settings, 'ALIYUN_OSS'): + if not hasattr(settings, 'ALIYUN_OSS'): raise Exception('未配置oss') AccessKeyId = settings.ALIYUN_OSS[""AccessKeyId""] AccessKeySecret = settings.ALIYUN_OSS[""AccessKeySecret""] ",yzs/django_extend/image_upload.py,"ReplaceText(target='not ' @(15,7)->(15,7))","logger = logging.getLogger('system') def upload_aliyun_oss(folder): if hasattr(settings, 'ALIYUN_OSS'): raise Exception('未配置oss') AccessKeyId = settings.ALIYUN_OSS[""AccessKeyId""] AccessKeySecret = settings.ALIYUN_OSS[""AccessKeySecret""]","logger = logging.getLogger('system') def upload_aliyun_oss(folder): if not hasattr(settings, 'ALIYUN_OSS'): raise Exception('未配置oss') AccessKeyId = settings.ALIYUN_OSS[""AccessKeyId""] AccessKeySecret = settings.ALIYUN_OSS[""AccessKeySecret""]" 1412,https://:@github.com/tohojo/netperf-wrapper.git,9d88395014ba142084b83f8f02fc545976dcdcb9,"@@ -162,7 +162,7 @@ class TimeseriesAggregator(Aggregator): # size first_times = [i[0][0] for i in measurements.values() if i and i[0]] last_times = [i[-1][0] for i in measurements.values() if i and i[-1]] - if not (first_times or last_times): + if not (first_times and last_times): raise RuntimeError(u""No data to aggregate. Run with -l and check log file to investigate."") t_0 = min(first_times) t_max = max(last_times) ",aggregators.py,"ReplaceText(target='and' @(165,28)->(165,30))","class TimeseriesAggregator(Aggregator): # size first_times = [i[0][0] for i in measurements.values() if i and i[0]] last_times = [i[-1][0] for i in measurements.values() if i and i[-1]] if not (first_times or last_times): raise RuntimeError(u""No data to aggregate. Run with -l and check log file to investigate."") t_0 = min(first_times) t_max = max(last_times)","class TimeseriesAggregator(Aggregator): # size first_times = [i[0][0] for i in measurements.values() if i and i[0]] last_times = [i[-1][0] for i in measurements.values() if i and i[-1]] if not (first_times and last_times): raise RuntimeError(u""No data to aggregate. Run with -l and check log file to investigate."") t_0 = min(first_times) t_max = max(last_times)" 1413,https://:@github.com/tohojo/netperf-wrapper.git,39ec5a73b1c9a09e9e01881e89b53e807c1d2832,"@@ -422,7 +422,7 @@ class ResultWidget(get_ui_class(""resultwidget.ui"")): return self.settings.ZERO_Y def disable_log(self, val=None): - if val is not None and val != self.settings.LOG_SCALE: + if val is not None and val == self.settings.LOG_SCALE: self.settings.LOG_SCALE = not val self.update() return not self.settings.LOG_SCALE ",netperf_wrapper/gui.py,"ReplaceText(target='==' @(425,35)->(425,37))","class ResultWidget(get_ui_class(""resultwidget.ui"")): return self.settings.ZERO_Y def disable_log(self, val=None): if val is not None and val != self.settings.LOG_SCALE: self.settings.LOG_SCALE = not val self.update() return not self.settings.LOG_SCALE","class ResultWidget(get_ui_class(""resultwidget.ui"")): return self.settings.ZERO_Y def disable_log(self, val=None): if val is not None and val == self.settings.LOG_SCALE: self.settings.LOG_SCALE = not val self.update() return not self.settings.LOG_SCALE" 1414,https://:@github.com/tohojo/netperf-wrapper.git,79e727a68773475c9b0d903102f4bf5eb9593466,"@@ -281,7 +281,7 @@ class BatchRunner(object): settings.load_test(informational=settings.BATCH_DRY) settings.DATA_FILENAME = self.gen_filename(settings, b, argset, rep) - yield batch, settings + yield b, settings def get_argsets(self, batch): argsets = [] ",flent/batch.py,"ReplaceText(target='b' @(284,18)->(284,23))","class BatchRunner(object): settings.load_test(informational=settings.BATCH_DRY) settings.DATA_FILENAME = self.gen_filename(settings, b, argset, rep) yield batch, settings def get_argsets(self, batch): argsets = []","class BatchRunner(object): settings.load_test(informational=settings.BATCH_DRY) settings.DATA_FILENAME = self.gen_filename(settings, b, argset, rep) yield b, settings def get_argsets(self, batch): argsets = []" 1415,https://:@github.com/tohojo/netperf-wrapper.git,20f7794d4f06646cb739372e5fa9d55489a7ea9d,"@@ -133,7 +133,7 @@ def diff_parts(strings, sep): a separator and pruning parts that are identical for all strings"""""" parts = [s.split(sep) for s in strings] - np = [p for p in zip(*parts) if len(set(p)) > 1] + np = [p for p in zip(*parts) if len(set(p)) >= 1] return [sep.join(p) for p in zip(*np)] ",flent/util.py,"ReplaceText(target='>=' @(136,48)->(136,49))","def diff_parts(strings, sep): a separator and pruning parts that are identical for all strings"""""" parts = [s.split(sep) for s in strings] np = [p for p in zip(*parts) if len(set(p)) > 1] return [sep.join(p) for p in zip(*np)] ","def diff_parts(strings, sep): a separator and pruning parts that are identical for all strings"""""" parts = [s.split(sep) for s in strings] np = [p for p in zip(*parts) if len(set(p)) >= 1] return [sep.join(p) for p in zip(*np)] " 1416,https://:@github.com/tohojo/netperf-wrapper.git,07c49ab905f90817ee4ade86784241a257dc15bd,"@@ -1310,7 +1310,7 @@ class Plotter(ArgParam): if self.absolute_time: start += results.t0 - if end < 0: + if end <= 0: end += results.meta(""TOTAL_LENGTH"") min_idx = data[0].searchsorted(start, side='right') ",flent/plotters.py,"ReplaceText(target='<=' @(1313,19)->(1313,20))","class Plotter(ArgParam): if self.absolute_time: start += results.t0 if end < 0: end += results.meta(""TOTAL_LENGTH"") min_idx = data[0].searchsorted(start, side='right')","class Plotter(ArgParam): if self.absolute_time: start += results.t0 if end <= 0: end += results.meta(""TOTAL_LENGTH"") min_idx = data[0].searchsorted(start, side='right')" 1417,https://:@github.com/ShagaleevAlexey/openapi-core.git,56be4b10eb6dfa1020d451626a2f58f836f1729c,"@@ -654,4 +654,4 @@ class TestPetstore(object): response_result = response_validator.validate(request, response) assert response_result.errors == [] - assert response_result.data == data + assert response_result.data == data_json ",tests/integration/test_petstore.py,"ReplaceText(target='data_json' @(657,39)->(657,43))","class TestPetstore(object): response_result = response_validator.validate(request, response) assert response_result.errors == [] assert response_result.data == data","class TestPetstore(object): response_result = response_validator.validate(request, response) assert response_result.errors == [] assert response_result.data == data_json" 1418,https://:@github.com/markreidvfx/pyavb.git,8c822578aa3a9eef8da895125d6911e998d3b933,"@@ -331,7 +331,7 @@ class MSMLocator(core.AVBObject): self.mob_id = mob_id elif tag == 0x03: read_assert_tag(f, 76) - self.last_known_volume_utf8 = read_string(length, 'utf-8') + self.last_known_volume_utf8 = read_string(f, 'utf-8') else: raise ValueError(""%s: unknown ext tag 0x%02X %d"" % (str(self.class_id), tag,tag)) ",avb/misc.py,"ReplaceText(target='f' @(334,58)->(334,64))","class MSMLocator(core.AVBObject): self.mob_id = mob_id elif tag == 0x03: read_assert_tag(f, 76) self.last_known_volume_utf8 = read_string(length, 'utf-8') else: raise ValueError(""%s: unknown ext tag 0x%02X %d"" % (str(self.class_id), tag,tag)) ","class MSMLocator(core.AVBObject): self.mob_id = mob_id elif tag == 0x03: read_assert_tag(f, 76) self.last_known_volume_utf8 = read_string(f, 'utf-8') else: raise ValueError(""%s: unknown ext tag 0x%02X %d"" % (str(self.class_id), tag,tag)) " 1419,https://:@github.com/franklingu/comp-match.git,5fda1eac69ced79b9f489039e060840131f44184,"@@ -65,7 +65,7 @@ class CompanyUnderline(object): def setup_country(self): """"""Set country based on known information """""" - if not hasattr(self, 'exchange') and self.exchange is None: + if not hasattr(self, 'exchange') or self.exchange is None: return exch_country = find_country_for_exchange(self.exchange) if hasattr(self, 'country') and self.country: ",src/matchers/base.py,"ReplaceText(target='or' @(68,41)->(68,44))","class CompanyUnderline(object): def setup_country(self): """"""Set country based on known information """""" if not hasattr(self, 'exchange') and self.exchange is None: return exch_country = find_country_for_exchange(self.exchange) if hasattr(self, 'country') and self.country:","class CompanyUnderline(object): def setup_country(self): """"""Set country based on known information """""" if not hasattr(self, 'exchange') or self.exchange is None: return exch_country = find_country_for_exchange(self.exchange) if hasattr(self, 'country') and self.country:" 1420,https://:@github.com/drtconway/zotmer.git,e1742c21684efe296bbf81a90abbfb45e6927d89,"@@ -36,7 +36,7 @@ def main(argv): inp = opts[''] out = opts[''] (m, _) = probe(inp) - if opts['-D'] is not None: + if opts['-D'] is None: if opts['-S'] is not None: S = long(opts['-S']) random.seed(S) ",zotmer/commands/sample.py,"ReplaceText(target=' is ' @(39,17)->(39,25))","def main(argv): inp = opts[''] out = opts[''] (m, _) = probe(inp) if opts['-D'] is not None: if opts['-S'] is not None: S = long(opts['-S']) random.seed(S)","def main(argv): inp = opts[''] out = opts[''] (m, _) = probe(inp) if opts['-D'] is None: if opts['-S'] is not None: S = long(opts['-S']) random.seed(S)" 1421,https://:@github.com/programatt/drf-extensions.git,19ade585f7ce22c2018cdc0c73f5499f7ceaf877,"@@ -135,7 +135,7 @@ class ExtendedActionLinkRouterMixin(object): dynamic_routes_instances.append(Route( url=replace_methodname(route.url, endpoint), mapping=dict((httpmethod, methodname) for httpmethod in httpmethods), - name=replace_methodname(route.name, methodname), + name=replace_methodname(route.name, endpoint), initkwargs=initkwargs, )) return dynamic_routes_instances ",rest_framework_extensions/routers.py,"ReplaceText(target='endpoint' @(138,52)->(138,62))","class ExtendedActionLinkRouterMixin(object): dynamic_routes_instances.append(Route( url=replace_methodname(route.url, endpoint), mapping=dict((httpmethod, methodname) for httpmethod in httpmethods), name=replace_methodname(route.name, methodname), initkwargs=initkwargs, )) return dynamic_routes_instances","class ExtendedActionLinkRouterMixin(object): dynamic_routes_instances.append(Route( url=replace_methodname(route.url, endpoint), mapping=dict((httpmethod, methodname) for httpmethod in httpmethods), name=replace_methodname(route.name, endpoint), initkwargs=initkwargs, )) return dynamic_routes_instances" 1422,https://:@github.com/level12/keg-login.git,30308ddd1b45a74b89c280636ef9208fede53ae4,"@@ -67,7 +67,7 @@ class PasswordResetTokenGenerator: return False # Check the timestamp is within limit - if (self._num_days(self._today()) - ts) > self.timeout_days: + if (self._num_days(self._today()) - ts) >= self.timeout_days: return False return True ",keg_login/tokens.py,"ReplaceText(target='>=' @(70,48)->(70,49))","class PasswordResetTokenGenerator: return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > self.timeout_days: return False return True","class PasswordResetTokenGenerator: return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) >= self.timeout_days: return False return True" 1423,https://:@github.com/xtqxk/owl.git,3c8c2ad1dde6ffc87307e6e72fff42d42771bbde,"@@ -54,7 +54,7 @@ def main_tornado(): application = tornado.web.Application([(r""/"", MainHandler)]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(options.port) - loop.start() + xcfg.start() if __name__ == ""__main__"": ",demo/tornado_and_aiohttp.py,"ReplaceText(target='xcfg' @(57,4)->(57,8))","def main_tornado(): application = tornado.web.Application([(r""/"", MainHandler)]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(options.port) loop.start() if __name__ == ""__main__"":","def main_tornado(): application = tornado.web.Application([(r""/"", MainHandler)]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(options.port) xcfg.start() if __name__ == ""__main__"":" 1424,https://:@github.com/bburan/abr.git,24ce8fdca6aa62c713476e7a8ff984adcb98c6e4,"@@ -291,7 +291,7 @@ class SerialWaveformPresenter(WaveformPresenter): self.load(model) def load_next(self): - if self.current_model > len(self.unprocessed): + if self.current_model >= len(self.unprocessed): return self.current_model += 1 filename, frequency = self.unprocessed[self.current_model] ",abr/presenter.py,"ReplaceText(target='>=' @(294,30)->(294,31))","class SerialWaveformPresenter(WaveformPresenter): self.load(model) def load_next(self): if self.current_model > len(self.unprocessed): return self.current_model += 1 filename, frequency = self.unprocessed[self.current_model]","class SerialWaveformPresenter(WaveformPresenter): self.load(model) def load_next(self): if self.current_model >= len(self.unprocessed): return self.current_model += 1 filename, frequency = self.unprocessed[self.current_model]" 1425,https://:@github.com/caiovictormc/mqtt-sentinel.git,e582bfc4161cda70200ac4c84ec6d166d2b64386,"@@ -31,7 +31,7 @@ class WatcherWorker: raise NotImplementedError() def is_available(self): - return len(self.subscribed_topics) <= self.max_topics + return len(self.subscribed_topics) < self.max_topics def _subscribe(self, topic): self.subscribed_topics.append(str(topic)) ",sentinel/watcher/resources.py,"ReplaceText(target='<' @(34,43)->(34,45))","class WatcherWorker: raise NotImplementedError() def is_available(self): return len(self.subscribed_topics) <= self.max_topics def _subscribe(self, topic): self.subscribed_topics.append(str(topic))","class WatcherWorker: raise NotImplementedError() def is_available(self): return len(self.subscribed_topics) < self.max_topics def _subscribe(self, topic): self.subscribed_topics.append(str(topic))" 1426,https://:@github.com/nitely/http-lazy-headers.git,1dd901dcf50242d6beb031195c7039ef03d68252,"@@ -55,7 +55,7 @@ def is_quoted_cookie_octets(txt): if len(txt) <= 2: return False - if (not txt.startswith('""') and + if (not txt.startswith('""') or not txt.endswith('""')): return False ",http_lazy_headers/shared/common/cookies.py,"ReplaceText(target='or' @(58,32)->(58,35))","def is_quoted_cookie_octets(txt): if len(txt) <= 2: return False if (not txt.startswith('""') and not txt.endswith('""')): return False ","def is_quoted_cookie_octets(txt): if len(txt) <= 2: return False if (not txt.startswith('""') or not txt.endswith('""')): return False " 1427,https://:@github.com/AndreMiras/EtherollApp.git,dba25b52e26f01e84195aaf0f06598120fde6186,"@@ -18,7 +18,7 @@ class CoincurveRecipe(PythonRecipe): env['LDSHARED'] = env['CC'] + ' -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions' libsecp256k1 = self.get_recipe('libsecp256k1', self.ctx) libsecp256k1_dir = libsecp256k1.get_build_dir(arch.arch) - env['CFLAGS'] = ' -I' + os.path.join(libsecp256k1_dir, 'include') + env['CFLAGS'] += ' -I' + os.path.join(libsecp256k1_dir, 'include') # required additional library and path for Crystax if self.ctx.ndk == 'crystax': # only keeps major.minor (discards patch) ",src/python-for-android/recipes/coincurve/__init__.py,"ReplaceText(target='+=' @(21,22)->(21,23))","class CoincurveRecipe(PythonRecipe): env['LDSHARED'] = env['CC'] + ' -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions' libsecp256k1 = self.get_recipe('libsecp256k1', self.ctx) libsecp256k1_dir = libsecp256k1.get_build_dir(arch.arch) env['CFLAGS'] = ' -I' + os.path.join(libsecp256k1_dir, 'include') # required additional library and path for Crystax if self.ctx.ndk == 'crystax': # only keeps major.minor (discards patch)","class CoincurveRecipe(PythonRecipe): env['LDSHARED'] = env['CC'] + ' -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions' libsecp256k1 = self.get_recipe('libsecp256k1', self.ctx) libsecp256k1_dir = libsecp256k1.get_build_dir(arch.arch) env['CFLAGS'] += ' -I' + os.path.join(libsecp256k1_dir, 'include') # required additional library and path for Crystax if self.ctx.ndk == 'crystax': # only keeps major.minor (discards patch)" 1428,https://:@github.com/Kenny2github/brainfuck-fuck.git,e7370575f02852774b61cbf6d3d6251f30c4f14c,"@@ -14,7 +14,7 @@ def main(args=None): if '--stats' in args: args.remove('--stats') args.append('--stats') - if len(args) > 1: + if len(args) > 0: if args[0] == '-c': prog = args[1].strip('""') else: ",brainfuck_fuck/bf.py,"ReplaceText(target='0' @(17,19)->(17,20))","def main(args=None): if '--stats' in args: args.remove('--stats') args.append('--stats') if len(args) > 1: if args[0] == '-c': prog = args[1].strip('""') else:","def main(args=None): if '--stats' in args: args.remove('--stats') args.append('--stats') if len(args) > 0: if args[0] == '-c': prog = args[1].strip('""') else:" 1429,https://:@github.com/gpiantoni/boavus.git,1dc1245dead4d4c120ace0254b7bd6b9b56c1ad6,"@@ -35,6 +35,6 @@ def project_electrodes(electrodes_file, freesurfer_path): material = one_chans['material'] f.write(f'{_chan.label}\t{xyz}\t{elec_type}\t{size}\t{material}\n') - old_json = replace_underscore(Path(f.filename), 'coordframe.json') + old_json = replace_underscore(Path(electrodes_file.filename), 'coordframe.json') new_json = replace_underscore(tsv_electrodes, 'coordframe.json') copyfile(old_json, new_json) # TODO: add info about transformation ",boavus/ieeg/project_electrodes.py,"ReplaceText(target='electrodes_file' @(38,39)->(38,40))","def project_electrodes(electrodes_file, freesurfer_path): material = one_chans['material'] f.write(f'{_chan.label}\t{xyz}\t{elec_type}\t{size}\t{material}\n') old_json = replace_underscore(Path(f.filename), 'coordframe.json') new_json = replace_underscore(tsv_electrodes, 'coordframe.json') copyfile(old_json, new_json) # TODO: add info about transformation","def project_electrodes(electrodes_file, freesurfer_path): material = one_chans['material'] f.write(f'{_chan.label}\t{xyz}\t{elec_type}\t{size}\t{material}\n') old_json = replace_underscore(Path(electrodes_file.filename), 'coordframe.json') new_json = replace_underscore(tsv_electrodes, 'coordframe.json') copyfile(old_json, new_json) # TODO: add info about transformation" 1430,https://:@github.com/gpiantoni/boavus.git,6d383d0e6961f8c55db7d5a33aaf8b933d3a52de,"@@ -33,7 +33,7 @@ def main(output_dir): p.starmap(save_frequency, args) else: for arg in args: - save_frequency(*args) + save_frequency(*arg) def save_frequency(ieeg_file, cond): ",boavus/ieeg/psd.py,"ReplaceText(target='arg' @(36,28)->(36,32))","def main(output_dir): p.starmap(save_frequency, args) else: for arg in args: save_frequency(*args) def save_frequency(ieeg_file, cond):","def main(output_dir): p.starmap(save_frequency, args) else: for arg in args: save_frequency(*arg) def save_frequency(ieeg_file, cond):" 1431,https://:@github.com/gpiantoni/boavus.git,427af8efb68c77d24e4a1b88e14307817559dae0,"@@ -140,4 +140,4 @@ def make_segments(dat): out.axis['time'][i] = dat.axis['time'][0] out.axis['chan'][i] = dat.axis['chan'][0] - return dat + return out ",boavus/ieeg/preprocessing.py,"ReplaceText(target='out' @(143,11)->(143,14))","def make_segments(dat): out.axis['time'][i] = dat.axis['time'][0] out.axis['chan'][i] = dat.axis['chan'][0] return dat","def make_segments(dat): out.axis['time'][i] = dat.axis['time'][0] out.axis['chan'][i] = dat.axis['chan'][0] return out" 1432,https://:@github.com/UseAllFive/django-google-cloud-storage.git,6a63ffe6f06b4781099586ccff32b77877c93ae8,"@@ -94,7 +94,7 @@ class GoogleCloudStorage(Storage): return self.created_time(name) def url(self, name): - if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): + if not os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): # we need this in order to display images, links to files, etc from the local appengine server filename = ""/gs""+self.location+""/""+name key = create_gs_key(filename) ",django_google_cloud_storage/__init__.py,"ReplaceText(target='not ' @(97,11)->(97,11))","class GoogleCloudStorage(Storage): return self.created_time(name) def url(self, name): if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): # we need this in order to display images, links to files, etc from the local appengine server filename = ""/gs""+self.location+""/""+name key = create_gs_key(filename)","class GoogleCloudStorage(Storage): return self.created_time(name) def url(self, name): if not os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): # we need this in order to display images, links to files, etc from the local appengine server filename = ""/gs""+self.location+""/""+name key = create_gs_key(filename)" 1433,https://:@github.com/ConsumerAffairs/django-experiments.git,9f7d04c505a1fb1fd70eca209ec1ab285731b5bd,"@@ -35,7 +35,7 @@ def clear(key, participant_identifier): # Remove the direct entry cache_key = COUNTER_CACHE_KEY % key pipe = r.pipeline() - freq, _ = pipe.hget(key, participant_identifier).hdel(cache_key, participant_identifier).execute() + freq, _ = pipe.hget(cache_key, participant_identifier).hdel(cache_key, participant_identifier).execute() # Remove from the histogram freq_cache_key = COUNTER_FREQ_CACHE_KEY % key ",experiments/counters.py,"ReplaceText(target='cache_key' @(38,28)->(38,31))","def clear(key, participant_identifier): # Remove the direct entry cache_key = COUNTER_CACHE_KEY % key pipe = r.pipeline() freq, _ = pipe.hget(key, participant_identifier).hdel(cache_key, participant_identifier).execute() # Remove from the histogram freq_cache_key = COUNTER_FREQ_CACHE_KEY % key","def clear(key, participant_identifier): # Remove the direct entry cache_key = COUNTER_CACHE_KEY % key pipe = r.pipeline() freq, _ = pipe.hget(cache_key, participant_identifier).hdel(cache_key, participant_identifier).execute() # Remove from the histogram freq_cache_key = COUNTER_FREQ_CACHE_KEY % key" 1434,https://:@github.com/broiledmeat/pydgeot.git,54f264d9a0c8613e6c4c30819554777f0c785200,"@@ -74,7 +74,7 @@ class Generator: for s in self.app.sources.get_dependencies(c, reverse=True, recursive=True)]) # Add source and context dependencies to the changeset. - changes.generate |= source_deps | context_deps + dep_changes.generate |= source_deps | context_deps # Prepare dependent changes that weren't in the original changes list for path in (dep_changes.generate - changes.generate): ",pydgeot/generator.py,"ReplaceText(target='dep_changes' @(77,12)->(77,19))","class Generator: for s in self.app.sources.get_dependencies(c, reverse=True, recursive=True)]) # Add source and context dependencies to the changeset. changes.generate |= source_deps | context_deps # Prepare dependent changes that weren't in the original changes list for path in (dep_changes.generate - changes.generate):","class Generator: for s in self.app.sources.get_dependencies(c, reverse=True, recursive=True)]) # Add source and context dependencies to the changeset. dep_changes.generate |= source_deps | context_deps # Prepare dependent changes that weren't in the original changes list for path in (dep_changes.generate - changes.generate):" 1435,https://:@github.com/chameleoncloud/jupyterlab-zenodo.git,14517a0c6f765c0f9470fdae3de98fb82d4d36de,"@@ -189,7 +189,7 @@ class ZenodoUploadHandler(ZenodoBaseHandler): print(""doi: ""+str(doi)) self.set_status(201) self.write(json.dumps(info)) - store_record(doi, filename, directory_to_zip, access_token) + store_record(doi, path_to_file, directory_to_zip, access_token) #self.redirect(""http://127.0.0.1:7000/portal/upload/""+doi) self.finish() else: ",jupyterlab_zenodo/upload.py,"ReplaceText(target='path_to_file' @(192,30)->(192,38))","class ZenodoUploadHandler(ZenodoBaseHandler): print(""doi: ""+str(doi)) self.set_status(201) self.write(json.dumps(info)) store_record(doi, filename, directory_to_zip, access_token) #self.redirect(""http://127.0.0.1:7000/portal/upload/""+doi) self.finish() else:","class ZenodoUploadHandler(ZenodoBaseHandler): print(""doi: ""+str(doi)) self.set_status(201) self.write(json.dumps(info)) store_record(doi, path_to_file, directory_to_zip, access_token) #self.redirect(""http://127.0.0.1:7000/portal/upload/""+doi) self.finish() else:" 1436,https://:@github.com/overdev/raylib-py.git,db84739a19f8719c1f58cf6946741e29f1ef0262,"@@ -2126,7 +2126,7 @@ _rl.InitWindow.argtypes = [Int, Int, CharPtr] _rl.InitWindow.restype = None def init_window(width: int, height: int, title: AnyStr) -> None: """"""Initialize window and OpenGL context"""""" - return _rl.InitWindow(_int(width), _int(width), _str_in(title)) + return _rl.InitWindow(_int(width), _int(height), _str_in(title)) _rl.CloseWindow.argtypes = _NOARGS ",raylibpy/__init__.py,"ReplaceText(target='height' @(2129,44)->(2129,49))","_rl.InitWindow.argtypes = [Int, Int, CharPtr] _rl.InitWindow.restype = None def init_window(width: int, height: int, title: AnyStr) -> None: """"""Initialize window and OpenGL context"""""" return _rl.InitWindow(_int(width), _int(width), _str_in(title)) _rl.CloseWindow.argtypes = _NOARGS","_rl.InitWindow.argtypes = [Int, Int, CharPtr] _rl.InitWindow.restype = None def init_window(width: int, height: int, title: AnyStr) -> None: """"""Initialize window and OpenGL context"""""" return _rl.InitWindow(_int(width), _int(height), _str_in(title)) _rl.CloseWindow.argtypes = _NOARGS" 1437,https://:@github.com/NCI-GDC/bam_readgroup_to_gdc_json.git,3e7833e8ec3195f638bbdd3e7a56db429259db73,"@@ -237,7 +237,7 @@ def extract_readgroup_json(bam_path, logger): bam_name, bam_ext = os.path.splitext(bam_file) readgroups_json_file = bam_name+'.json' with open (bam_path) as f: - samfile = pysam.AlignmentFile(bam_path, 'rb', check_header=True, check_sq=False) + samfile = pysam.AlignmentFile(f, 'rb', check_header=True, check_sq=False) readgroup_dict_list = get_readgroup_dict_list(samfile) with open(readgroups_json_file, 'w') as f: json.dump(out_readgroup_dict_list, f, indent=4) ",bam_readgroup_to_gdc_json/extract_readgroup.py,"ReplaceText(target='f' @(240,38)->(240,46))","def extract_readgroup_json(bam_path, logger): bam_name, bam_ext = os.path.splitext(bam_file) readgroups_json_file = bam_name+'.json' with open (bam_path) as f: samfile = pysam.AlignmentFile(bam_path, 'rb', check_header=True, check_sq=False) readgroup_dict_list = get_readgroup_dict_list(samfile) with open(readgroups_json_file, 'w') as f: json.dump(out_readgroup_dict_list, f, indent=4)","def extract_readgroup_json(bam_path, logger): bam_name, bam_ext = os.path.splitext(bam_file) readgroups_json_file = bam_name+'.json' with open (bam_path) as f: samfile = pysam.AlignmentFile(f, 'rb', check_header=True, check_sq=False) readgroup_dict_list = get_readgroup_dict_list(samfile) with open(readgroups_json_file, 'w') as f: json.dump(out_readgroup_dict_list, f, indent=4)" 1438,https://:@github.com/NCI-GDC/bam_readgroup_to_gdc_json.git,e4573f93ab837ef2cd81c5276d089af9ba788575,"@@ -239,7 +239,7 @@ def extract_readgroup_json(bam_path, logger): if not bam_readgroup_dict_list: logger.error('There are no readgroups in BAM: {}'.format(samfile.filename)) raise NoReadGroupError - readgroup_dict_list = get_readgroup_dict_list(samfile, logger) + readgroup_dict_list = get_readgroup_dict_list(bam_readgroup_dict_list, logger) with open(readgroups_json_file, 'w') as f: json.dump(readgroup_dict_list, f, indent=4) return readgroups_json_file ",bam_readgroup_to_gdc_json/extract_readgroup.py,"ReplaceText(target='bam_readgroup_dict_list' @(242,54)->(242,61))","def extract_readgroup_json(bam_path, logger): if not bam_readgroup_dict_list: logger.error('There are no readgroups in BAM: {}'.format(samfile.filename)) raise NoReadGroupError readgroup_dict_list = get_readgroup_dict_list(samfile, logger) with open(readgroups_json_file, 'w') as f: json.dump(readgroup_dict_list, f, indent=4) return readgroups_json_file","def extract_readgroup_json(bam_path, logger): if not bam_readgroup_dict_list: logger.error('There are no readgroups in BAM: {}'.format(samfile.filename)) raise NoReadGroupError readgroup_dict_list = get_readgroup_dict_list(bam_readgroup_dict_list, logger) with open(readgroups_json_file, 'w') as f: json.dump(readgroup_dict_list, f, indent=4) return readgroups_json_file" 1439,https://:@github.com/Tynukua/mono.git,58368594340912bca030c0b559ce4e3bac205960,"@@ -11,7 +11,7 @@ def snakeize_dict(dict_): answer = {} for key in dict_: nkey = snakeize_s(key) - answer[key] = dict_[key] + answer[nkey] = dict_[key] return answer class MonoCard: ",mono/types.py,"ReplaceText(target='nkey' @(14,15)->(14,18))","def snakeize_dict(dict_): answer = {} for key in dict_: nkey = snakeize_s(key) answer[key] = dict_[key] return answer class MonoCard:","def snakeize_dict(dict_): answer = {} for key in dict_: nkey = snakeize_s(key) answer[nkey] = dict_[key] return answer class MonoCard:" 1440,https://:@github.com/Helios-Protocol/py-helios-node.git,24c35bc490eb8737da1d5a9ec90ad3be3ea5eecd,"@@ -24,7 +24,7 @@ def setup_trinity_logging(level): logger.setLevel(logging.DEBUG) logger.addHandler(handler) - listener = handlers.QueueListener(log_queue, logger) + listener = handlers.QueueListener(log_queue, handler) return logger, log_queue, listener ",trinity/utils/logging.py,"ReplaceText(target='handler' @(27,49)->(27,55))","def setup_trinity_logging(level): logger.setLevel(logging.DEBUG) logger.addHandler(handler) listener = handlers.QueueListener(log_queue, logger) return logger, log_queue, listener ","def setup_trinity_logging(level): logger.setLevel(logging.DEBUG) logger.addHandler(handler) listener = handlers.QueueListener(log_queue, handler) return logger, log_queue, listener " 1441,https://:@github.com/Helios-Protocol/py-helios-node.git,8f99b5b6628e75a80ca695750fb313ecb796bb49,"@@ -273,7 +273,7 @@ class BaseTransactionExecutor(metaclass=ABCMeta): valid_transaction = self.validate_transaction(transaction) message = self.build_evm_message(valid_transaction) computation = self.build_computation(message, valid_transaction) - finalized_computation = self.finalize_computation(computation, valid_transaction) + finalized_computation = self.finalize_computation(valid_transaction, computation) return finalized_computation @abstractmethod ",evm/vm/state.py,"ArgSwap(idxs=0<->1 @(276,32)->(276,57))","class BaseTransactionExecutor(metaclass=ABCMeta): valid_transaction = self.validate_transaction(transaction) message = self.build_evm_message(valid_transaction) computation = self.build_computation(message, valid_transaction) finalized_computation = self.finalize_computation(computation, valid_transaction) return finalized_computation @abstractmethod","class BaseTransactionExecutor(metaclass=ABCMeta): valid_transaction = self.validate_transaction(transaction) message = self.build_evm_message(valid_transaction) computation = self.build_computation(message, valid_transaction) finalized_computation = self.finalize_computation(valid_transaction, computation) return finalized_computation @abstractmethod" 1442,https://:@github.com/vectorhacker/pygeteventstore.git,c311377e282413e5b2e5763eed5931e61d713aa1,"@@ -44,7 +44,7 @@ class Reader(object): self._url = path if self._index < 0: - if self._feed_page is not feedparser.FeedParserDict: + if self._feed_page is feedparser.FeedParserDict: for link in self._feed_page.links: if link.rel == 'previous': self._url = link.href ",geteventstore/read_stream.py,"ReplaceText(target=' is ' @(47,30)->(47,38))","class Reader(object): self._url = path if self._index < 0: if self._feed_page is not feedparser.FeedParserDict: for link in self._feed_page.links: if link.rel == 'previous': self._url = link.href","class Reader(object): self._url = path if self._index < 0: if self._feed_page is feedparser.FeedParserDict: for link in self._feed_page.links: if link.rel == 'previous': self._url = link.href" 1443,https://:@github.com/javicacheiro/configuration-registry.git,c49d2d6ad4ce1edb22023d6ea97973b8d0f045b7,"@@ -745,4 +745,4 @@ def dn_from(id): Basically the ID string is equivalent to a DN but without certain characters that can cause problems like '/' """""" - return id.replace('.', DOT).replace(SLASH, '/') + return id.replace(DOT, '.').replace(SLASH, '/') ",registry.py,"ArgSwap(idxs=0<->1 @(748,11)->(748,21))","def dn_from(id): Basically the ID string is equivalent to a DN but without certain characters that can cause problems like '/' """""" return id.replace('.', DOT).replace(SLASH, '/')","def dn_from(id): Basically the ID string is equivalent to a DN but without certain characters that can cause problems like '/' """""" return id.replace(DOT, '.').replace(SLASH, '/')" 1444,https://:@github.com/andrefreitas/schwa.git,4a16e3bb49f2afe9c4749c2d8ab68a4f05f66761,"@@ -38,7 +38,7 @@ class JavaParser(AbstractParser): if current_class: current_class[1] = last_closing_bracket_number if current_method: - current_method[1] = last_closing_bracket_number + current_method[1] = penultimate_closing_bracket_number components.append(current_method) current_class = [line_counter, 0, search.group(2)] continue ",schwa/parsing/java_parser.py,"ReplaceText(target='penultimate_closing_bracket_number' @(41,40)->(41,67))","class JavaParser(AbstractParser): if current_class: current_class[1] = last_closing_bracket_number if current_method: current_method[1] = last_closing_bracket_number components.append(current_method) current_class = [line_counter, 0, search.group(2)] continue","class JavaParser(AbstractParser): if current_class: current_class[1] = last_closing_bracket_number if current_method: current_method[1] = penultimate_closing_bracket_number components.append(current_method) current_class = [line_counter, 0, search.group(2)] continue" 1445,https://:@github.com/pyconuk/conferencescheduler-cli.git,74d3dbfc5c23ac119d2a22f259363f0912245e0b,"@@ -83,7 +83,7 @@ def build(algorithm, objective, diff, input_dir, solution_dir, build_dir): if diff: schedule = solution_to_schedule(solution, events, slots) - event_diff = event_schedule_difference(schedule, original_schedule) + event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}') ",src/scheduler/cli.py,"ArgSwap(idxs=0<->1 @(86,21)->(86,46))","def build(algorithm, objective, diff, input_dir, solution_dir, build_dir): if diff: schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(schedule, original_schedule) logger.debug(f'\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}')","def build(algorithm, objective, diff, input_dir, solution_dir, build_dir): if diff: schedule = solution_to_schedule(solution, events, slots) event_diff = event_schedule_difference(original_schedule, schedule) logger.debug(f'\nevent_diff:') for item in event_diff: logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}')" 1446,https://:@github.com/kangasbros/django-bitcoin.git,0efe50d2a1ad192492ae360834e1403600cceb69,"@@ -46,7 +46,7 @@ class RatingManager(object): object_id = self.instance.id, key = self.field.key, ) - if not user: + if user: kwargs['user'] = user else: kwargs['user__isnull'] = True ",djangoratings/__init__.py,"ReplaceText(target='' @(49,11)->(49,15))","class RatingManager(object): object_id = self.instance.id, key = self.field.key, ) if not user: kwargs['user'] = user else: kwargs['user__isnull'] = True","class RatingManager(object): object_id = self.instance.id, key = self.field.key, ) if user: kwargs['user'] = user else: kwargs['user__isnull'] = True" 1447,https://:@github.com/faerbit/grade_change_emailer.git,e7c3f657704adf5a2e76cd22f29523f19a8f9113,"@@ -79,7 +79,7 @@ class GradeChangeEmailer: if old_html_table != html_table: mail_text = "" "" - mail_text = ""Es gab Änderungen in deinen Noten:\n"" + mail_text += ""Es gab Änderungen in deinen Noten:\n"" mail_text += html_table mail_text += """" self.send_mail(mail_text) ",main.py,"ReplaceText(target='+=' @(82,22)->(82,23))","class GradeChangeEmailer: if old_html_table != html_table: mail_text = "" "" mail_text = ""Es gab Änderungen in deinen Noten:\n"" mail_text += html_table mail_text += """" self.send_mail(mail_text)","class GradeChangeEmailer: if old_html_table != html_table: mail_text = "" "" mail_text += ""Es gab Änderungen in deinen Noten:\n"" mail_text += html_table mail_text += """" self.send_mail(mail_text)" 1448,https://:@github.com/dcramer/nose-quickunit.git,777b3ba3e0a7fd5948fff6f88583d61c1b6c2f2f,"@@ -72,7 +72,7 @@ class QuickUnitPlugin(Plugin): self.verbosity = options.verbosity if options.quickunit_prefix: self.prefixes = options.quickunit_prefix - if len(self.prefixes) == 0: + if len(self.prefixes) == 1: self.prefixes = self.prefixes[0].split('\n') else: self.prefixes = [""tests/""] ",quickunit/plugin.py,"ReplaceText(target='1' @(75,37)->(75,38))","class QuickUnitPlugin(Plugin): self.verbosity = options.verbosity if options.quickunit_prefix: self.prefixes = options.quickunit_prefix if len(self.prefixes) == 0: self.prefixes = self.prefixes[0].split('\n') else: self.prefixes = [""tests/""]","class QuickUnitPlugin(Plugin): self.verbosity = options.verbosity if options.quickunit_prefix: self.prefixes = options.quickunit_prefix if len(self.prefixes) == 1: self.prefixes = self.prefixes[0].split('\n') else: self.prefixes = [""tests/""]" 1449,https://:@gitlab.com/atviriduomenys/spinta.git,97920623601fc3be0e8623366b29e0cf1125903f,"@@ -972,7 +972,7 @@ class QueryBuilder: if _is_dtype(prop, (String, DateTime, Date)): field = jsonb.astext else: - field = sa.cast(field, JSONB) + field = sa.cast(jsonb, JSONB) else: field = self.table.main.c[prop.name] ",spinta/backends/postgresql/__init__.py,"ReplaceText(target='jsonb' @(975,32)->(975,37))","class QueryBuilder: if _is_dtype(prop, (String, DateTime, Date)): field = jsonb.astext else: field = sa.cast(field, JSONB) else: field = self.table.main.c[prop.name] ","class QueryBuilder: if _is_dtype(prop, (String, DateTime, Date)): field = jsonb.astext else: field = sa.cast(jsonb, JSONB) else: field = self.table.main.c[prop.name] " 1450,https://:@github.com/eduardostarling/restio.git,417c8fd882a8e922f831ca4ed8999607d3a09867,"@@ -155,7 +155,7 @@ class TestModel: model_b._internal_id = model_a._internal_id - assert model_a == model_b + assert model_a != model_b @pytest.mark.parametrize( ""model, expected_fields, expected_dependency_fields"", ",tests/unit/test_model.py,"ReplaceText(target='!=' @(158,23)->(158,25))","class TestModel: model_b._internal_id = model_a._internal_id assert model_a == model_b @pytest.mark.parametrize( ""model, expected_fields, expected_dependency_fields"",","class TestModel: model_b._internal_id = model_a._internal_id assert model_a != model_b @pytest.mark.parametrize( ""model, expected_fields, expected_dependency_fields""," 1451,https://:@github.com/dbehrlich/PsychRNN.git,aa2e83a6667bb398dc2b65dfac17a17b3c6766b5,"@@ -54,7 +54,7 @@ class FlipFlop(Task): for i, (input_start, echo_start) in enumerate(zip(input_times, echo_times)): if input_start <= t < input_start + echo_start: - x_t = 1.0 + x_t += 1.0 mask_t = np.zeros(self.N_out) elif echo_start <= t < echo_start + echo_duration: ",psychrnn/tasks/flip_flop.py,"ReplaceText(target='+=' @(57,20)->(57,21))","class FlipFlop(Task): for i, (input_start, echo_start) in enumerate(zip(input_times, echo_times)): if input_start <= t < input_start + echo_start: x_t = 1.0 mask_t = np.zeros(self.N_out) elif echo_start <= t < echo_start + echo_duration:","class FlipFlop(Task): for i, (input_start, echo_start) in enumerate(zip(input_times, echo_times)): if input_start <= t < input_start + echo_start: x_t += 1.0 mask_t = np.zeros(self.N_out) elif echo_start <= t < echo_start + echo_duration:" 1452,https://:@github.com/funkybob/knights-templater.git,8d4ea7037e74574d98dc376b7413e36b3fd6aa8e,"@@ -29,7 +29,7 @@ def load_template(name, paths=None, raw=False): with open(full_name, encoding='utf-8') as fin: src = fin.read() - return kompile(src, raw=raw, filename=name) + return kompile(src, raw=raw, filename=full_name) except FileNotFoundError: pass else: ",knights/loader.py,"ReplaceText(target='full_name' @(32,50)->(32,54))","def load_template(name, paths=None, raw=False): with open(full_name, encoding='utf-8') as fin: src = fin.read() return kompile(src, raw=raw, filename=name) except FileNotFoundError: pass else:","def load_template(name, paths=None, raw=False): with open(full_name, encoding='utf-8') as fin: src = fin.read() return kompile(src, raw=raw, filename=full_name) except FileNotFoundError: pass else:" 1453,https://:@github.com/pgeurin/predpy.git,dc4b2c89e719c6a94f3a4e0ab632aec2a5990c35,"@@ -488,7 +488,7 @@ def compare_predictions(df, y_var_name, percent_data=None, timeit(plot_rocs, models, df_X, y) plt.show() print(f'MAKE SUBSAMPLE TIME: {time() - starttotal}') - return names, results, models, pipeline, df_X + return names, results, fit_models, pipeline, df_X def bootstrap_train_premade(model, X, y, bootstraps=1000, **kwargs): """"""Train a (linear) model on multiple bootstrap samples of some data and ",autoregression/autoregression.py,"ReplaceText(target='fit_models' @(491,27)->(491,33))","def compare_predictions(df, y_var_name, percent_data=None, timeit(plot_rocs, models, df_X, y) plt.show() print(f'MAKE SUBSAMPLE TIME: {time() - starttotal}') return names, results, models, pipeline, df_X def bootstrap_train_premade(model, X, y, bootstraps=1000, **kwargs): """"""Train a (linear) model on multiple bootstrap samples of some data and","def compare_predictions(df, y_var_name, percent_data=None, timeit(plot_rocs, models, df_X, y) plt.show() print(f'MAKE SUBSAMPLE TIME: {time() - starttotal}') return names, results, fit_models, pipeline, df_X def bootstrap_train_premade(model, X, y, bootstraps=1000, **kwargs): """"""Train a (linear) model on multiple bootstrap samples of some data and" 1454,https://:@github.com/datastax/cstar_perf.git,775971343c59a597c45041ae9937d8d41fbff31c,"@@ -150,7 +150,7 @@ def nodetool(cmd): stderr=subprocess.STDOUT, shell=True) output = proc.communicate() - if output.returncode != 0: + if proc.returncode != 0: raise NodetoolException(output) return output[0] ",tool/cstar_perf/tool/benchmark.py,"ReplaceText(target='proc' @(153,7)->(153,13))","def nodetool(cmd): stderr=subprocess.STDOUT, shell=True) output = proc.communicate() if output.returncode != 0: raise NodetoolException(output) return output[0] ","def nodetool(cmd): stderr=subprocess.STDOUT, shell=True) output = proc.communicate() if proc.returncode != 0: raise NodetoolException(output) return output[0] " 1455,https://:@github.com/azazel75/metapensiero.signal.git,58a8b6bfb2993e3137b59da1d83da816a67437ed,"@@ -373,7 +373,7 @@ class Signal: if instance is None: fnotify = self._fnotify else: - fnotify = types.MethodType(instance, self._fnotify) + fnotify = types.MethodType(self._fnotify, instance) validator = self._fvalidation if validator is not None and instance is not None: validator = types.MethodType(validator, instance) ",src/metapensiero/signal/core.py,"ArgSwap(idxs=0<->1 @(376,26)->(376,42))","class Signal: if instance is None: fnotify = self._fnotify else: fnotify = types.MethodType(instance, self._fnotify) validator = self._fvalidation if validator is not None and instance is not None: validator = types.MethodType(validator, instance)","class Signal: if instance is None: fnotify = self._fnotify else: fnotify = types.MethodType(self._fnotify, instance) validator = self._fvalidation if validator is not None and instance is not None: validator = types.MethodType(validator, instance)" 1456,https://:@github.com/datasnakes/rinse.git,fe669e8c2ea26510a9509f954272544b95b50ddb,"@@ -129,7 +129,7 @@ class LInstallR(InstallR): version_name = ""R-%s"" % version if Path(self.bin_path / ""R"").exists(): remove(str(self.bin_path / ""R"")) - symlink(str(self.lib_path / version_name / ""bin"" / ""R""), str(self.bin_path / ""R"")) + symlink(str(self.bin_path / ""R""), str(self.lib_path / version_name / ""bin"" / ""R"")) def clear_tmp_dir(self): # Set up the temporary directory for installation ",rinse/core.py,"ArgSwap(idxs=0<->1 @(132,8)->(132,15))","class LInstallR(InstallR): version_name = ""R-%s"" % version if Path(self.bin_path / ""R"").exists(): remove(str(self.bin_path / ""R"")) symlink(str(self.lib_path / version_name / ""bin"" / ""R""), str(self.bin_path / ""R"")) def clear_tmp_dir(self): # Set up the temporary directory for installation","class LInstallR(InstallR): version_name = ""R-%s"" % version if Path(self.bin_path / ""R"").exists(): remove(str(self.bin_path / ""R"")) symlink(str(self.bin_path / ""R""), str(self.lib_path / version_name / ""bin"" / ""R"")) def clear_tmp_dir(self): # Set up the temporary directory for installation" 1457,https://:@github.com/Ircam-Web/mezzanine-organization.git,5d66d26e44c82ff7f5c1fd02b8bd368ba1179650,"@@ -255,7 +255,7 @@ def order_links(links): minor = link except TypeError: pass - ordered_links.append(link) + ordered_links.append(minor) links_list.remove(minor) return ordered_links ",organization/core/templatetags/organization_tags.py,"ReplaceText(target='minor' @(258,29)->(258,33))","def order_links(links): minor = link except TypeError: pass ordered_links.append(link) links_list.remove(minor) return ordered_links ","def order_links(links): minor = link except TypeError: pass ordered_links.append(minor) links_list.remove(minor) return ordered_links " 1458,https://:@github.com/Ircam-Web/mezzanine-organization.git,ae8a7252690d9c7801549d30b8734e3e9d76af36,"@@ -192,7 +192,7 @@ class TopicFilterForm(forms.Form): topics = ProjectTopic.objects.all() topics_list = [] - for topic in topics_list: + for topic in topics: if topic.projects.count(): topics_list.append((topic.id, topic.name)) return topics_list ",organization/projects/forms.py,"ReplaceText(target='topics' @(195,21)->(195,32))","class TopicFilterForm(forms.Form): topics = ProjectTopic.objects.all() topics_list = [] for topic in topics_list: if topic.projects.count(): topics_list.append((topic.id, topic.name)) return topics_list","class TopicFilterForm(forms.Form): topics = ProjectTopic.objects.all() topics_list = [] for topic in topics: if topic.projects.count(): topics_list.append((topic.id, topic.name)) return topics_list" 1459,https://:@github.com/Jumpscale/core9.git,5fc90cb3a2a909103cc735b979a55253cca15f68,"@@ -1426,7 +1426,7 @@ class SystemFS: for root, dirs, files in os.walk(startDir): for name in files: if fnmatch.fnmatch(name, fileregex): - result.append(os.path.join(root, fileregex)) + result.append(os.path.join(root, name)) return result def grep(self, fileregex, lineregex): ",JumpScale9/fs/SystemFS.py,"ReplaceText(target='name' @(1429,53)->(1429,62))","class SystemFS: for root, dirs, files in os.walk(startDir): for name in files: if fnmatch.fnmatch(name, fileregex): result.append(os.path.join(root, fileregex)) return result def grep(self, fileregex, lineregex):","class SystemFS: for root, dirs, files in os.walk(startDir): for name in files: if fnmatch.fnmatch(name, fileregex): result.append(os.path.join(root, name)) return result def grep(self, fileregex, lineregex):" 1460,https://:@github.com/woctezuma/download-steam-reviews.git,b34328a97fe7a21d2fdb944fd3f3e1f16084dc27,"@@ -216,7 +216,7 @@ def download_reviews_for_app_id(app_id, else: collection_keyword = 'first posted' print('Collecting reviews {} after {}'.format(collection_keyword, - timestamp_threshold)) + date_threshold)) review_dict = load_review_dict(app_id) ",steamreviews/download_reviews.py,"ReplaceText(target='date_threshold' @(219,58)->(219,77))","def download_reviews_for_app_id(app_id, else: collection_keyword = 'first posted' print('Collecting reviews {} after {}'.format(collection_keyword, timestamp_threshold)) review_dict = load_review_dict(app_id) ","def download_reviews_for_app_id(app_id, else: collection_keyword = 'first posted' print('Collecting reviews {} after {}'.format(collection_keyword, date_threshold)) review_dict = load_review_dict(app_id) " 1461,https://:@github.com/merlin-neurotech/WizardHat.git,6c4b0cb72f062a0e59034f9a1483c6e207695f99,"@@ -153,7 +153,7 @@ class PacketHandler(BasePacketHandler): # convert from packet to sample ID sample_id = (packet_id - 1) * 2 + delta_id + 1 # 19bit packets hold deltas between two samples - self._last_eeg_data += np.array(deltas[delta_id]) + self._last_eeg_data -= np.array(deltas[delta_id]) self._update_counts_and_enqueue(""EEG"", sample_id) def _parse_compressed_19bit(self, packet_id, packet): ",ble2lsl/devices/ganglion/ganglion.py,"ReplaceText(target='-=' @(156,32)->(156,34))","class PacketHandler(BasePacketHandler): # convert from packet to sample ID sample_id = (packet_id - 1) * 2 + delta_id + 1 # 19bit packets hold deltas between two samples self._last_eeg_data += np.array(deltas[delta_id]) self._update_counts_and_enqueue(""EEG"", sample_id) def _parse_compressed_19bit(self, packet_id, packet):","class PacketHandler(BasePacketHandler): # convert from packet to sample ID sample_id = (packet_id - 1) * 2 + delta_id + 1 # 19bit packets hold deltas between two samples self._last_eeg_data -= np.array(deltas[delta_id]) self._update_counts_and_enqueue(""EEG"", sample_id) def _parse_compressed_19bit(self, packet_id, packet):" 1462,https://:@github.com/PiecePaperCode/pyogame2.git,ba010e0c9b6c884195448c98c1ef493fba075624,"@@ -616,7 +616,7 @@ class OGame2(object): fleets_list = [] response = self.session.get('https://s{}-{}.ogame.gameforge.com/game/index.php?page=ingame&component=movement' .format(self.server_number, self.server_language)) - if response.status_code == 302: + if response.status_code != 302: fleets = response.text.split('
(619,34))","class OGame2(object): fleets_list = [] response = self.session.get('https://s{}-{}.ogame.gameforge.com/game/index.php?page=ingame&component=movement' .format(self.server_number, self.server_language)) if response.status_code == 302: fleets = response.text.split('
(24,20))","class FilteredListView(ListView): filter_dict = {} if not value in self.filter_keys: raise ImproperlyConfigured( ""%s is not present in filter_keys (%s)"" % (key, self.filter_keys) )","class FilteredListView(ListView): filter_dict = {} if not key in self.filter_keys: raise ImproperlyConfigured( ""%s is not present in filter_keys (%s)"" % (key, self.filter_keys) )" 1464,https://:@github.com/pstch/django-crucrudile.git,399d14d8b52601ce12858af06a0e93f6bf2ade33,"@@ -337,7 +337,7 @@ class AutoPatternsMixin(object): """"""View URL name (unprefixed, this is the name we give to url())"""""" return cls.get_url_name(view) - if view not in view.get_views(): + if view not in cls.get_views(): raise ImproperlyConfigured( ""Tried to get the URL patterns for a view (%s)"" "" that is not defined by get_views"" % view ",django_crucrudile/models/mixins.py,"ReplaceText(target='cls' @(340,23)->(340,27))","class AutoPatternsMixin(object): """"""View URL name (unprefixed, this is the name we give to url())"""""" return cls.get_url_name(view) if view not in view.get_views(): raise ImproperlyConfigured( ""Tried to get the URL patterns for a view (%s)"" "" that is not defined by get_views"" % view","class AutoPatternsMixin(object): """"""View URL name (unprefixed, this is the name we give to url())"""""" return cls.get_url_name(view) if view not in cls.get_views(): raise ImproperlyConfigured( ""Tried to get the URL patterns for a view (%s)"" "" that is not defined by get_views"" % view" 1465,https://:@github.com/pstch/django-crucrudile.git,fb0a3af53e4c57ea50164c28ecd872ae379e74b4,"@@ -119,7 +119,7 @@ def make_model_mixin(view_class, setattr(ModelMixin, 'get_%s_url_name' % view_class.get_underscored_action_name(), - _get_url) + _get_url_name) if extra_funcs: for func_name, func in extra_funcs.items(): ",django_crucrudile/models/mixins.py,"ReplaceText(target='_get_url_name' @(122,12)->(122,20))","def make_model_mixin(view_class, setattr(ModelMixin, 'get_%s_url_name' % view_class.get_underscored_action_name(), _get_url) if extra_funcs: for func_name, func in extra_funcs.items():","def make_model_mixin(view_class, setattr(ModelMixin, 'get_%s_url_name' % view_class.get_underscored_action_name(), _get_url_name) if extra_funcs: for func_name, func in extra_funcs.items():" 1466,https://:@github.com/gawseed/threat-feed-tools.git,da1b21ecf69131800d1d782e169de3f1a8535572,"@@ -28,7 +28,7 @@ class FsdbThreatFeed(): for (count,entry) in enumerate(self._tfh): array.append(entry) dictionary[entry[index_column]] = entry # note, may erase older ones; build array? - if max_records and count >= max_records: + if max_records and count > max_records: break return (array, dictionary) ",gawseed/threatfeed/feeds/fsdb.py,"ReplaceText(target='>' @(31,37)->(31,39))","class FsdbThreatFeed(): for (count,entry) in enumerate(self._tfh): array.append(entry) dictionary[entry[index_column]] = entry # note, may erase older ones; build array? if max_records and count >= max_records: break return (array, dictionary)","class FsdbThreatFeed(): for (count,entry) in enumerate(self._tfh): array.append(entry) dictionary[entry[index_column]] = entry # note, may erase older ones; build array? if max_records and count > max_records: break return (array, dictionary)" 1467,https://:@github.com/gawseed/threat-feed-tools.git,354e753fde2635223ce189079a16b4b6a6ef8b36,"@@ -62,7 +62,7 @@ class KafkaDataSource(DataSource): if self._end_time: self.verbose(""searching forward from:"") self.verbose(decoded_row) - count += 0 + count = 0 while True: count += 1 decoded_time = decoded_row[self._time_column] ",gawseed/threatfeed/datasources/kafka.py,"ReplaceText(target='=' @(65,18)->(65,20))","class KafkaDataSource(DataSource): if self._end_time: self.verbose(""searching forward from:"") self.verbose(decoded_row) count += 0 while True: count += 1 decoded_time = decoded_row[self._time_column]","class KafkaDataSource(DataSource): if self._end_time: self.verbose(""searching forward from:"") self.verbose(decoded_row) count = 0 while True: count += 1 decoded_time = decoded_row[self._time_column]" 1468,https://:@github.com/gawseed/threat-feed-tools.git,41e2731d9ccb0df59446cc0b0aa0f23ffe945a51,"@@ -51,4 +51,4 @@ class ConnectionCounter(Config): results = {'connections': conns, 'ports': ports} - return (self._output_key, conns) + return (self._output_key, results) ",gawseed/threatfeed/enrichments/connectionCounter.py,"ReplaceText(target='results' @(54,34)->(54,39))","class ConnectionCounter(Config): results = {'connections': conns, 'ports': ports} return (self._output_key, conns)","class ConnectionCounter(Config): results = {'connections': conns, 'ports': ports} return (self._output_key, results)" 1469,https://:@github.com/jlazear/pyoscope.git,8d5c3639de70f788c3cfcde695678031f6a8acb7,"@@ -409,7 +409,7 @@ class PyOscopeStatic(object): elif isinstance(y, Iterable): newy = y yname = 'y_{j}'.format(j=j) - elif isinstance(x, NoneType): + elif isinstance(y, NoneType): yname = None temp = self.data.columns[0] newy = range(len(self.data[temp])) ",pyoscope.py,"ReplaceText(target='y' @(412,28)->(412,29))","class PyOscopeStatic(object): elif isinstance(y, Iterable): newy = y yname = 'y_{j}'.format(j=j) elif isinstance(x, NoneType): yname = None temp = self.data.columns[0] newy = range(len(self.data[temp]))","class PyOscopeStatic(object): elif isinstance(y, Iterable): newy = y yname = 'y_{j}'.format(j=j) elif isinstance(y, NoneType): yname = None temp = self.data.columns[0] newy = range(len(self.data[temp]))" 1470,https://:@gitlab.com/LISTERINE/dj_arp_storm.git,06a3ee8610a39c0768a2ef98afdb930a1aa0c1cf,"@@ -87,7 +87,7 @@ def get_timeout(conf): :rtype: int, float """""" timeout = conf.getint('general', 'timeout') - if timeout > 0: + if timeout < 0: return float('inf') return timeout ",dj_arp_storm/dj_arp_storm.py,"ReplaceText(target='<' @(90,15)->(90,16))","def get_timeout(conf): :rtype: int, float """""" timeout = conf.getint('general', 'timeout') if timeout > 0: return float('inf') return timeout ","def get_timeout(conf): :rtype: int, float """""" timeout = conf.getint('general', 'timeout') if timeout < 0: return float('inf') return timeout " 1471,https://:@github.com/mozilla/CANOSP-2019.git,cada35d7f44d921471da056f272f17c44705bb43,"@@ -100,7 +100,7 @@ def server_update( # calculate the number of clients used in this round m = max(int(client_num * C), 1) # random set of m client's index - S = np.array(random.sample(range(client_num), client_num)) + S = np.array(random.sample(range(client_num), m)) num_samples = [] ",simulation_util.py,"ReplaceText(target='m' @(103,54)->(103,64))","def server_update( # calculate the number of clients used in this round m = max(int(client_num * C), 1) # random set of m client's index S = np.array(random.sample(range(client_num), client_num)) num_samples = [] ","def server_update( # calculate the number of clients used in this round m = max(int(client_num * C), 1) # random set of m client's index S = np.array(random.sample(range(client_num), m)) num_samples = [] " 1472,https://:@github.com/pattern-inc/cynetworkx.git,7ad6ebdb79672222fbd37571b9414d80a2eb31d1,"@@ -679,7 +679,7 @@ def eigenvector_centrality(G,max_iter=100,tol=1.0e-6,nstart=None): for n in x: x[n]*=s # check convergence err=sum([abs(x[n]-xlast[n]) for n in x]) - if err < n*tol: + if err < nnodes*tol: return x raise NetworkXError(""eigenvector_centrality(): power iteration failed to converge in %d iterations.""%(i+1)) ",networkx/algorithms/centrality.py,"ReplaceText(target='nnodes' @(682,17)->(682,18))","def eigenvector_centrality(G,max_iter=100,tol=1.0e-6,nstart=None): for n in x: x[n]*=s # check convergence err=sum([abs(x[n]-xlast[n]) for n in x]) if err < n*tol: return x raise NetworkXError(""eigenvector_centrality(): power iteration failed to converge in %d iterations.""%(i+1))","def eigenvector_centrality(G,max_iter=100,tol=1.0e-6,nstart=None): for n in x: x[n]*=s # check convergence err=sum([abs(x[n]-xlast[n]) for n in x]) if err < nnodes*tol: return x raise NetworkXError(""eigenvector_centrality(): power iteration failed to converge in %d iterations.""%(i+1))" 1473,https://:@github.com/pattern-inc/cynetworkx.git,e9c5b23d0348c6587955208c0c806fd129ba4a1c,"@@ -49,7 +49,7 @@ def _initial_tree_solution(G, r, demand = 'demand', capacity = 'capacity', maxWeight = 0 hugeWeight = 1 + n * maxWeight - labelGenerator = _gen_node_label(G) + labelGenerator = _gen_node_label(H) for v, d in G.nodes(data = True)[1:]: vDemand = d.get(demand, 0) ",networkx/algorithms/flow/mincost.py,"ReplaceText(target='H' @(52,37)->(52,38))","def _initial_tree_solution(G, r, demand = 'demand', capacity = 'capacity', maxWeight = 0 hugeWeight = 1 + n * maxWeight labelGenerator = _gen_node_label(G) for v, d in G.nodes(data = True)[1:]: vDemand = d.get(demand, 0)","def _initial_tree_solution(G, r, demand = 'demand', capacity = 'capacity', maxWeight = 0 hugeWeight = 1 + n * maxWeight labelGenerator = _gen_node_label(H) for v, d in G.nodes(data = True)[1:]: vDemand = d.get(demand, 0)" 1474,https://:@github.com/pattern-inc/cynetworkx.git,9a9b57ed411305c6f8c3a52d424014f17ed2ac5f,"@@ -85,7 +85,7 @@ def topological_sort(G,nbunch=None): if nbunch is None: nbunch = G.nodes_iter() - for v in G: # process all vertices in G + for v in nbunch: # process all vertices in G if v in explored: continue fringe=[v] # nodes yet to look at ",networkx/algorithms/dag.py,"ReplaceText(target='nbunch' @(88,13)->(88,14))","def topological_sort(G,nbunch=None): if nbunch is None: nbunch = G.nodes_iter() for v in G: # process all vertices in G if v in explored: continue fringe=[v] # nodes yet to look at","def topological_sort(G,nbunch=None): if nbunch is None: nbunch = G.nodes_iter() for v in nbunch: # process all vertices in G if v in explored: continue fringe=[v] # nodes yet to look at" 1475,https://:@github.com/pattern-inc/cynetworkx.git,f22c0f25b393ad63c2a0273dea3bd095bcb4d63f,"@@ -67,7 +67,7 @@ def all_simple_paths(G, source, target, cutoff=None): if source not in G: raise nx.NetworkXError('source node %s not in graph'%source) if target not in G: - raise nx.NetworkXError('target node %s not in graph'%source) + raise nx.NetworkXError('target node %s not in graph'%target) if cutoff is None: cutoff = len(G)-1 if G.is_multigraph(): ",networkx/algorithms/simple_paths.py,"ReplaceText(target='target' @(70,61)->(70,67))","def all_simple_paths(G, source, target, cutoff=None): if source not in G: raise nx.NetworkXError('source node %s not in graph'%source) if target not in G: raise nx.NetworkXError('target node %s not in graph'%source) if cutoff is None: cutoff = len(G)-1 if G.is_multigraph():","def all_simple_paths(G, source, target, cutoff=None): if source not in G: raise nx.NetworkXError('source node %s not in graph'%source) if target not in G: raise nx.NetworkXError('target node %s not in graph'%target) if cutoff is None: cutoff = len(G)-1 if G.is_multigraph():" 1476,https://:@github.com/pattern-inc/cynetworkx.git,6ac082b2bdc9d91db7c5c9d84080787f7a98a953,"@@ -201,7 +201,7 @@ def simple_cycles(G): if thisnode in closed: _unblock(thisnode,blocked,B) else: - for nbr in G[thisnode]: + for nbr in subG[thisnode]: if thisnode not in B[nbr]: B[nbr].add(thisnode) stack.pop() ",networkx/algorithms/cycles.py,"ReplaceText(target='subG' @(204,31)->(204,32))","def simple_cycles(G): if thisnode in closed: _unblock(thisnode,blocked,B) else: for nbr in G[thisnode]: if thisnode not in B[nbr]: B[nbr].add(thisnode) stack.pop()","def simple_cycles(G): if thisnode in closed: _unblock(thisnode,blocked,B) else: for nbr in subG[thisnode]: if thisnode not in B[nbr]: B[nbr].add(thisnode) stack.pop()" 1477,https://:@github.com/pattern-inc/cynetworkx.git,31a656f9dd9ca015b4cdfc41c60e27995fb76f30,"@@ -89,7 +89,7 @@ def current_flow_closeness_centrality(G, normalized=True, weight='weight', # this could be done without a copy if we really wanted to H = nx.relabel_nodes(G, dict(zip(ordering, range(n)))) betweenness = dict.fromkeys(H, 0.0) # b[v]=0 for v in H - n = G.number_of_nodes() + n = H.number_of_nodes() L = laplacian_sparse_matrix(H, nodelist=range(n), weight=weight, dtype=dtype, format='csc') C2 = solvername[solver](L, width=1, dtype=dtype) # initialize solver ",networkx/algorithms/centrality/current_flow_closeness.py,"ReplaceText(target='H' @(92,8)->(92,9))","def current_flow_closeness_centrality(G, normalized=True, weight='weight', # this could be done without a copy if we really wanted to H = nx.relabel_nodes(G, dict(zip(ordering, range(n)))) betweenness = dict.fromkeys(H, 0.0) # b[v]=0 for v in H n = G.number_of_nodes() L = laplacian_sparse_matrix(H, nodelist=range(n), weight=weight, dtype=dtype, format='csc') C2 = solvername[solver](L, width=1, dtype=dtype) # initialize solver","def current_flow_closeness_centrality(G, normalized=True, weight='weight', # this could be done without a copy if we really wanted to H = nx.relabel_nodes(G, dict(zip(ordering, range(n)))) betweenness = dict.fromkeys(H, 0.0) # b[v]=0 for v in H n = H.number_of_nodes() L = laplacian_sparse_matrix(H, nodelist=range(n), weight=weight, dtype=dtype, format='csc') C2 = solvername[solver](L, width=1, dtype=dtype) # initialize solver" 1478,https://:@github.com/pattern-inc/cynetworkx.git,1f1ee6761d04f572bc9afd892a6b43a77dad1150,"@@ -38,6 +38,6 @@ class TestDispersion(object): disp = nx.dispersion(G) for d in disp: for dd in d: - assert d >= 0 + assert dd >= 0 ",networkx/algorithms/centrality/tests/test_dispersion.py,"ReplaceText(target='dd' @(41,23)->(41,24))","class TestDispersion(object): disp = nx.dispersion(G) for d in disp: for dd in d: assert d >= 0 ","class TestDispersion(object): disp = nx.dispersion(G) for d in disp: for dd in d: assert dd >= 0 " 1479,https://:@github.com/pattern-inc/cynetworkx.git,6f01f084cbf7fd71f3e2e670a2d25c0358d54cd1,"@@ -89,7 +89,7 @@ def shortest_augmenting_path_impl(G, s, t, capacity, two_phase): path = [s] u = s d = n if not two_phase else int(min(m ** 0.5, 2 * n ** (2. / 3))) - done = R.node[s]['height'] < d + done = R.node[s]['height'] >= d while not done: height = R.node[u]['height'] curr_edge = R.node[u]['curr_edge'] ",networkx/algorithms/flow/shortest_augmenting_path.py,"ReplaceText(target='>=' @(92,31)->(92,32))","def shortest_augmenting_path_impl(G, s, t, capacity, two_phase): path = [s] u = s d = n if not two_phase else int(min(m ** 0.5, 2 * n ** (2. / 3))) done = R.node[s]['height'] < d while not done: height = R.node[u]['height'] curr_edge = R.node[u]['curr_edge']","def shortest_augmenting_path_impl(G, s, t, capacity, two_phase): path = [s] u = s d = n if not two_phase else int(min(m ** 0.5, 2 * n ** (2. / 3))) done = R.node[s]['height'] >= d while not done: height = R.node[u]['height'] curr_edge = R.node[u]['curr_edge']" 1480,https://:@github.com/pattern-inc/cynetworkx.git,6b2dbffd2132b4d7034f59d8a9b089f8c9ca848f,"@@ -158,5 +158,5 @@ def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs): else: ky = target_data.pop(key, None) graph.add_edge(source, target, key=ky) - graph[source][target][ky].update(target_data) + graph[source][target][ky].update(tdata) return graph ",networkx/readwrite/json_graph/adjacency.py,"ReplaceText(target='tdata' @(161,49)->(161,60))","def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs): else: ky = target_data.pop(key, None) graph.add_edge(source, target, key=ky) graph[source][target][ky].update(target_data) return graph","def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs): else: ky = target_data.pop(key, None) graph.add_edge(source, target, key=ky) graph[source][target][ky].update(tdata) return graph" 1481,https://:@github.com/pattern-inc/cynetworkx.git,5864982dd97baf21aac4e743de5fbbb103860017,"@@ -48,7 +48,7 @@ def cytoscape_data(G, attrs=None): n = {""data"" : j.copy()} n[""data""][""id""] = str(i) n[""data""][""value""] = i - n[""data""][""name""] = n.get(name) or str(i) + n[""data""][""name""] = j.get(name) or str(i) nodes.append(n) for e in G.edges(): ",networkx/readwrite/json_graph/cytoscape.py,"ReplaceText(target='j' @(51,28)->(51,29))","def cytoscape_data(G, attrs=None): n = {""data"" : j.copy()} n[""data""][""id""] = str(i) n[""data""][""value""] = i n[""data""][""name""] = n.get(name) or str(i) nodes.append(n) for e in G.edges():","def cytoscape_data(G, attrs=None): n = {""data"" : j.copy()} n[""data""][""id""] = str(i) n[""data""][""value""] = i n[""data""][""name""] = j.get(name) or str(i) nodes.append(n) for e in G.edges():" 1482,https://:@github.com/pattern-inc/cynetworkx.git,fbc901aa2d30c8dfbe145af747097e92d9b5e5c9,"@@ -594,5 +594,5 @@ def _add_nodes_with_bipartite_label(G, lena, lenb): G.add_nodes_from(range(0,lena+lenb)) b=dict(zip(range(0,lena),[0]*lena)) b.update(dict(zip(range(lena,lena+lenb),[1]*lenb))) - nx.set_node_attributes(G,'bipartite',b) + nx.set_node_attributes(G, b, 'bipartite') return G ",networkx/algorithms/bipartite/generators.py,"ArgSwap(idxs=1<->2 @(597,4)->(597,26))","def _add_nodes_with_bipartite_label(G, lena, lenb): G.add_nodes_from(range(0,lena+lenb)) b=dict(zip(range(0,lena),[0]*lena)) b.update(dict(zip(range(lena,lena+lenb),[1]*lenb))) nx.set_node_attributes(G,'bipartite',b) return G","def _add_nodes_with_bipartite_label(G, lena, lenb): G.add_nodes_from(range(0,lena+lenb)) b=dict(zip(range(0,lena),[0]*lena)) b.update(dict(zip(range(lena,lena+lenb),[1]*lenb))) nx.set_node_attributes(G, b, 'bipartite') return G" 1483,https://:@github.com/pattern-inc/cynetworkx.git,fbc901aa2d30c8dfbe145af747097e92d9b5e5c9,"@@ -440,7 +440,7 @@ def condensation(G, scc=None): C.add_edges_from((mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]) # Add a list of members (ie original nodes) to each node (ie scc) in C. - nx.set_node_attributes(C, 'members', members) + nx.set_node_attributes(C, members, 'members') # Add mapping dict as graph attribute C.graph['mapping'] = mapping return C ",networkx/algorithms/components/strongly_connected.py,"ArgSwap(idxs=1<->2 @(443,4)->(443,26))","def condensation(G, scc=None): C.add_edges_from((mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]) # Add a list of members (ie original nodes) to each node (ie scc) in C. nx.set_node_attributes(C, 'members', members) # Add mapping dict as graph attribute C.graph['mapping'] = mapping return C","def condensation(G, scc=None): C.add_edges_from((mapping[u], mapping[v]) for u, v in G.edges() if mapping[u] != mapping[v]) # Add a list of members (ie original nodes) to each node (ie scc) in C. nx.set_node_attributes(C, members, 'members') # Add mapping dict as graph attribute C.graph['mapping'] = mapping return C" 1484,https://:@github.com/pattern-inc/cynetworkx.git,fbc901aa2d30c8dfbe145af747097e92d9b5e5c9,"@@ -502,8 +502,8 @@ class TestCutoff: def test_complete_graph_cutoff(self): G = nx.complete_graph(5) - nx.set_edge_attributes(G, 'capacity', - dict(((u, v), 1) for u, v in G.edges())) + nx.set_edge_attributes(G, dict(((u, v), 1) for u, v in G.edges()), + 'capacity') for flow_func in [shortest_augmenting_path, edmonds_karp]: for cutoff in [3, 2, 1]: result = nx.maximum_flow_value(G, 0, 4, flow_func=flow_func, ",networkx/algorithms/flow/tests/test_maxflow.py,"ArgSwap(idxs=1<->2 @(505,8)->(505,30))","class TestCutoff: def test_complete_graph_cutoff(self): G = nx.complete_graph(5) nx.set_edge_attributes(G, 'capacity', dict(((u, v), 1) for u, v in G.edges())) for flow_func in [shortest_augmenting_path, edmonds_karp]: for cutoff in [3, 2, 1]: result = nx.maximum_flow_value(G, 0, 4, flow_func=flow_func,","class TestCutoff: def test_complete_graph_cutoff(self): G = nx.complete_graph(5) nx.set_edge_attributes(G, dict(((u, v), 1) for u, v in G.edges()), 'capacity') for flow_func in [shortest_augmenting_path, edmonds_karp]: for cutoff in [3, 2, 1]: result = nx.maximum_flow_value(G, 0, 4, flow_func=flow_func," 1485,https://:@github.com/pattern-inc/cynetworkx.git,fbc901aa2d30c8dfbe145af747097e92d9b5e5c9,"@@ -85,7 +85,7 @@ class TestMaxflowLargeGraph: def test_complete_graph(self): N = 50 G = nx.complete_graph(N) - nx.set_edge_attributes(G, 'capacity', 5) + nx.set_edge_attributes(G, 5, 'capacity') R = build_residual_network(G, 'capacity') kwargs = dict(residual=R) ",networkx/algorithms/flow/tests/test_maxflow_large_graph.py,"ArgSwap(idxs=1<->2 @(88,8)->(88,30))","class TestMaxflowLargeGraph: def test_complete_graph(self): N = 50 G = nx.complete_graph(N) nx.set_edge_attributes(G, 'capacity', 5) R = build_residual_network(G, 'capacity') kwargs = dict(residual=R) ","class TestMaxflowLargeGraph: def test_complete_graph(self): N = 50 G = nx.complete_graph(N) nx.set_edge_attributes(G, 5, 'capacity') R = build_residual_network(G, 'capacity') kwargs = dict(residual=R) " 1486,https://:@github.com/kundajelab/keras-genomics.git,6b6c1a9d123f91193e5311ccd22d169a6c9d0733,"@@ -4,5 +4,5 @@ from keras import backend as K def ambig_binary_crossentropy(y_true,y_pred): non_ambig = K.cast((y_true > -0.5),'float32') - return K.mean(K.binary_crossentropy(y_pred, y_true) + return K.mean(K.binary_crossentropy(y_true, y_pred) *non_ambig, axis=-1) ",keras_genomics/losses.py,"ArgSwap(idxs=0<->1 @(7,22)->(7,43))","from keras import backend as K def ambig_binary_crossentropy(y_true,y_pred): non_ambig = K.cast((y_true > -0.5),'float32') return K.mean(K.binary_crossentropy(y_pred, y_true) *non_ambig, axis=-1)","from keras import backend as K def ambig_binary_crossentropy(y_true,y_pred): non_ambig = K.cast((y_true > -0.5),'float32') return K.mean(K.binary_crossentropy(y_true, y_pred) *non_ambig, axis=-1)" 1487,https://:@github.com/Nekmo/nekumo-cloud.git,f111818974631fad02fa0146f04638783b3da8df,"@@ -41,7 +41,7 @@ class NekumoManagement(object): args = self.parser.parse_args(argv[1:]) self.nekumo.gateways = list(self.parse_gateways(args)) self.nekumo.ifaces = list(self.parse_ifaces(args)) - if 'NEKUMO_DEBUG_IFACE' in os.environ: + if 'NEKUMO_DEBUG_IFACE' not in os.environ: loop = asyncio.get_event_loop() loop.run_forever() ",nekumo/core/management.py,"ReplaceText(target=' not in ' @(44,31)->(44,35))","class NekumoManagement(object): args = self.parser.parse_args(argv[1:]) self.nekumo.gateways = list(self.parse_gateways(args)) self.nekumo.ifaces = list(self.parse_ifaces(args)) if 'NEKUMO_DEBUG_IFACE' in os.environ: loop = asyncio.get_event_loop() loop.run_forever() ","class NekumoManagement(object): args = self.parser.parse_args(argv[1:]) self.nekumo.gateways = list(self.parse_gateways(args)) self.nekumo.ifaces = list(self.parse_ifaces(args)) if 'NEKUMO_DEBUG_IFACE' not in os.environ: loop = asyncio.get_event_loop() loop.run_forever() " 1488,https://:@github.com/stonebig/baresql.git,edeb2171759dc758dfa557404982c34e2fe385f2,"@@ -225,7 +225,7 @@ class baresql(object): level = 0 status=""normal"" self.cte_dico = {} - elif token == ""TK_OTHER"" and not cte_inline: + elif token == ""TK_OTHER"" and cte_inline: if tk_value.lower() == ""from"": from_lvl[level] = True elif from_lvl[level]: ",baresql/baresql.py,"ReplaceText(target='' @(228,41)->(228,45))","class baresql(object): level = 0 status=""normal"" self.cte_dico = {} elif token == ""TK_OTHER"" and not cte_inline: if tk_value.lower() == ""from"": from_lvl[level] = True elif from_lvl[level]:","class baresql(object): level = 0 status=""normal"" self.cte_dico = {} elif token == ""TK_OTHER"" and cte_inline: if tk_value.lower() == ""from"": from_lvl[level] = True elif from_lvl[level]:" 1489,https://:@github.com/stonebig/baresql.git,12ac74b6d6f75f723938608ef1b3202e81f8d7d5,"@@ -437,7 +437,7 @@ class baresql(object): for table_ref in tables: table_sql = table_ref+""$$"" - df = env[table_ref] + df = names_env[table_ref] df = self._ensure_data_frame(df, table_ref) #destroy previous Python temp table before importing the new one pre_q = ""DROP TABLE IF EXISTS %s"" % table_sql ",baresql/baresql.py,"ReplaceText(target='names_env' @(440,17)->(440,20))","class baresql(object): for table_ref in tables: table_sql = table_ref+""$$"" df = env[table_ref] df = self._ensure_data_frame(df, table_ref) #destroy previous Python temp table before importing the new one pre_q = ""DROP TABLE IF EXISTS %s"" % table_sql","class baresql(object): for table_ref in tables: table_sql = table_ref+""$$"" df = names_env[table_ref] df = self._ensure_data_frame(df, table_ref) #destroy previous Python temp table before importing the new one pre_q = ""DROP TABLE IF EXISTS %s"" % table_sql" 1490,https://:@github.com/takluyver/astsearch.git,68b9fe6322acccd76ff8353726e5cb9010064d9b,"@@ -31,7 +31,7 @@ class ASTPatternFinder(object): with open(file, 'rb') as f: tree = ast.parse(f.read()) else: - tree = ast.parse(f.read()) + tree = ast.parse(file.read()) yield from self.scan_ast(tree) def filter_subdirs(self, dirnames): ",astsearch.py,"ReplaceText(target='file' @(34,29)->(34,30))","class ASTPatternFinder(object): with open(file, 'rb') as f: tree = ast.parse(f.read()) else: tree = ast.parse(f.read()) yield from self.scan_ast(tree) def filter_subdirs(self, dirnames):","class ASTPatternFinder(object): with open(file, 'rb') as f: tree = ast.parse(f.read()) else: tree = ast.parse(file.read()) yield from self.scan_ast(tree) def filter_subdirs(self, dirnames):" 1491,https://:@github.com/rsanchezgarc/micrograph_cleaner_em.git,df470ae67588e8a1c7ba04ce14b517552e0ad788,"@@ -41,7 +41,7 @@ def cleanOneMic(micFname, boxSize, deepLearningModel=DEFAULT_MODEL_PATH, inputCo global MASK_PREDICTOR_HANDLER with LOCK: if MASK_PREDICTOR_HANDLER is None: - MASK_PREDICTOR_HANDLER= MaskPredictor(deepLearningModel, boxSize, gpus) + MASK_PREDICTOR_HANDLER= MaskPredictor(boxSize, deepLearningModel, gpus) maskPredictor= MASK_PREDICTOR_HANDLER ",micrograph_cleaner_em/cleanOneMic.py,"ArgSwap(idxs=0<->1 @(44,30)->(44,43))","def cleanOneMic(micFname, boxSize, deepLearningModel=DEFAULT_MODEL_PATH, inputCo global MASK_PREDICTOR_HANDLER with LOCK: if MASK_PREDICTOR_HANDLER is None: MASK_PREDICTOR_HANDLER= MaskPredictor(deepLearningModel, boxSize, gpus) maskPredictor= MASK_PREDICTOR_HANDLER","def cleanOneMic(micFname, boxSize, deepLearningModel=DEFAULT_MODEL_PATH, inputCo global MASK_PREDICTOR_HANDLER with LOCK: if MASK_PREDICTOR_HANDLER is None: MASK_PREDICTOR_HANDLER= MaskPredictor(boxSize, deepLearningModel, gpus) maskPredictor= MASK_PREDICTOR_HANDLER" 1492,https://:@github.com/rsanchezgarc/micrograph_cleaner_em.git,df470ae67588e8a1c7ba04ce14b517552e0ad788,"@@ -19,7 +19,7 @@ class TestMaskPredictor(TestCase): with mrcfile.open(micFname, permissive=True) as f: mic = f.data.copy() - with MaskPredictor(deepLearningModelFname, boxSize, gpus=[0]) as mp: + with MaskPredictor(boxSize, deepLearningModelFname, gpus=[0]) as mp: mask = mp.predictMask(mic) self.assertTrue(mask.shape==mic.shape, ""Error, mask shape is not the same that mic shape"") ",micrograph_cleaner_em/tests/test_maskPredictor.py,"ArgSwap(idxs=0<->1 @(22,9)->(22,22))","class TestMaskPredictor(TestCase): with mrcfile.open(micFname, permissive=True) as f: mic = f.data.copy() with MaskPredictor(deepLearningModelFname, boxSize, gpus=[0]) as mp: mask = mp.predictMask(mic) self.assertTrue(mask.shape==mic.shape, ""Error, mask shape is not the same that mic shape"")","class TestMaskPredictor(TestCase): with mrcfile.open(micFname, permissive=True) as f: mic = f.data.copy() with MaskPredictor(boxSize, deepLearningModelFname, gpus=[0]) as mp: mask = mp.predictMask(mic) self.assertTrue(mask.shape==mic.shape, ""Error, mask shape is not the same that mic shape"")" 1493,https://:@github.com/maebert/snoo.git,d2d822c48b4acc5046b4ca28a63153a0d0576615,"@@ -116,7 +116,7 @@ class Client: arrow.get(self.session[""last_updated""]).shift( seconds=int(self.config[""update_interval""]) ) - < arrow.utcnow() + > arrow.utcnow() ): return self.session ",snoo/client.py,"ReplaceText(target='>' @(119,16)->(119,17))","class Client: arrow.get(self.session[""last_updated""]).shift( seconds=int(self.config[""update_interval""]) ) < arrow.utcnow() ): return self.session ","class Client: arrow.get(self.session[""last_updated""]).shift( seconds=int(self.config[""update_interval""]) ) > arrow.utcnow() ): return self.session " 1494,https://:@github.com/maebert/snoo.git,4f8657a2132e8c1dfa84b1a49fb043610b70c934,"@@ -234,7 +234,7 @@ class Client: method=""get"", params={""startTime"": day.format(""MM/DD/YYYY hh:mm:ss"")}, ) - result.append(Day._from_data(start_time, data)) + result.append(Day._from_data(day, data)) return result def export_sessions(self, start_time, end_time): ",snoo/client.py,"ReplaceText(target='day' @(237,41)->(237,51))","class Client: method=""get"", params={""startTime"": day.format(""MM/DD/YYYY hh:mm:ss"")}, ) result.append(Day._from_data(start_time, data)) return result def export_sessions(self, start_time, end_time):","class Client: method=""get"", params={""startTime"": day.format(""MM/DD/YYYY hh:mm:ss"")}, ) result.append(Day._from_data(day, data)) return result def export_sessions(self, start_time, end_time):" 1495,https://:@github.com/Microsoft/Recommenders.git,57d99ce3be798dd2d48a169fbeaaec76a6d9637e,"@@ -58,7 +58,7 @@ def _merge_rating_true_pred( # Select the columns needed for evaluations rating_true = rating_true[[col_user, col_item, col_rating]] - rating_pred = rating_true[[col_user, col_item, col_prediction]] + rating_pred = rating_pred[[col_user, col_item, col_prediction]] if col_rating == col_prediction: rating_true_pred = pd.merge( ",reco_utils/evaluation/python_evaluation.py,"ReplaceText(target='rating_pred' @(61,18)->(61,29))","def _merge_rating_true_pred( # Select the columns needed for evaluations rating_true = rating_true[[col_user, col_item, col_rating]] rating_pred = rating_true[[col_user, col_item, col_prediction]] if col_rating == col_prediction: rating_true_pred = pd.merge(","def _merge_rating_true_pred( # Select the columns needed for evaluations rating_true = rating_true[[col_user, col_item, col_rating]] rating_pred = rating_pred[[col_user, col_item, col_prediction]] if col_rating == col_prediction: rating_true_pred = pd.merge(" 1496,https://:@github.com/Microsoft/Recommenders.git,367ca689d059d7569beb7b3cf153720fed323e30,"@@ -160,7 +160,7 @@ def split_pandas_data_with_ratios(data, ratios, seed=1234, resample=False): splits = np.split(data, [round(x * len(data)) for x in split_index]) # Add split index (this makes splitting by group more efficient). - for i in range(len(split_index)): + for i in range(len(ratios)): splits[i]['split_index'] = i return splits ",reco_utils/dataset/split_utils.py,"ReplaceText(target='ratios' @(163,23)->(163,34))","def split_pandas_data_with_ratios(data, ratios, seed=1234, resample=False): splits = np.split(data, [round(x * len(data)) for x in split_index]) # Add split index (this makes splitting by group more efficient). for i in range(len(split_index)): splits[i]['split_index'] = i return splits","def split_pandas_data_with_ratios(data, ratios, seed=1234, resample=False): splits = np.split(data, [round(x * len(data)) for x in split_index]) # Add split index (this makes splitting by group more efficient). for i in range(len(ratios)): splits[i]['split_index'] = i return splits" 1497,https://:@github.com/jkreklow/radproc.git,b319770b94b707a4cdaa335911e857a311f3f92c,"@@ -374,7 +374,7 @@ def export_dfrows_to_gdb(dataDF, idRaster, outGDBPath, GDBName, statistics=""""): outRaster = ""R_%i"" % (index.year) elif dataDF.index.is_month_end.all() == True or dataDF.index.is_month_start.all() == True: outRaster = ""R_%i%02i"" % (index.year, index.month) - elif dataDF.index.hour.all() == 0: + elif dataDF.index.hour.all() != 0: outRaster = ""R_%i%02i%02i"" % (index.year, index.month, index.day) else: outRaster = ""R_%i%02i%02i_%02i%02i"" % (index.year, index.month, index.day, index.hour, index.minute) ",build/lib/radproc/arcgis.py,"ReplaceText(target='!=' @(377,41)->(377,43))","def export_dfrows_to_gdb(dataDF, idRaster, outGDBPath, GDBName, statistics=""""): outRaster = ""R_%i"" % (index.year) elif dataDF.index.is_month_end.all() == True or dataDF.index.is_month_start.all() == True: outRaster = ""R_%i%02i"" % (index.year, index.month) elif dataDF.index.hour.all() == 0: outRaster = ""R_%i%02i%02i"" % (index.year, index.month, index.day) else: outRaster = ""R_%i%02i%02i_%02i%02i"" % (index.year, index.month, index.day, index.hour, index.minute)","def export_dfrows_to_gdb(dataDF, idRaster, outGDBPath, GDBName, statistics=""""): outRaster = ""R_%i"" % (index.year) elif dataDF.index.is_month_end.all() == True or dataDF.index.is_month_start.all() == True: outRaster = ""R_%i%02i"" % (index.year, index.month) elif dataDF.index.hour.all() != 0: outRaster = ""R_%i%02i%02i"" % (index.year, index.month, index.day) else: outRaster = ""R_%i%02i%02i_%02i%02i"" % (index.year, index.month, index.day, index.hour, index.minute)" 1498,https://:@github.com/graham/python_xid.git,232f0ae87a6feee945a1b9e09bf99eefbf30c7a5,"@@ -146,7 +146,7 @@ class Xid(object): def from_string(cls, s): # type: (str) -> Xid val = base32hex.b32decode(s.upper()) - value_check = [0 < x < 255 for x in val] + value_check = [0 <= x < 255 for x in val] if not all(value_check): raise InvalidXid(s) ",xid.py,"ReplaceText(target='<=' @(149,25)->(149,26))","class Xid(object): def from_string(cls, s): # type: (str) -> Xid val = base32hex.b32decode(s.upper()) value_check = [0 < x < 255 for x in val] if not all(value_check): raise InvalidXid(s)","class Xid(object): def from_string(cls, s): # type: (str) -> Xid val = base32hex.b32decode(s.upper()) value_check = [0 <= x < 255 for x in val] if not all(value_check): raise InvalidXid(s)" 1499,https://:@github.com/tboser/cwltool.git,5d633799f2eae4a5e0fedcae72381213ae9aba30,"@@ -117,7 +117,7 @@ class Builder(object): if ""secondaryFiles"" in binding: if ""secondaryFiles"" not in datum: datum[""secondaryFiles""] = [] - for sf in aslist(schema[""secondaryFiles""]): + for sf in aslist(binding[""secondaryFiles""]): if isinstance(sf, dict): sfpath = expression.do_eval(sf, self.job, self.requirements, self.docpath, datum[""path""]) else: ",reference/cwltool/draft2tool.py,"ReplaceText(target='binding' @(120,41)->(120,47))","class Builder(object): if ""secondaryFiles"" in binding: if ""secondaryFiles"" not in datum: datum[""secondaryFiles""] = [] for sf in aslist(schema[""secondaryFiles""]): if isinstance(sf, dict): sfpath = expression.do_eval(sf, self.job, self.requirements, self.docpath, datum[""path""]) else:","class Builder(object): if ""secondaryFiles"" in binding: if ""secondaryFiles"" not in datum: datum[""secondaryFiles""] = [] for sf in aslist(binding[""secondaryFiles""]): if isinstance(sf, dict): sfpath = expression.do_eval(sf, self.job, self.requirements, self.docpath, datum[""path""]) else:" 1500,https://:@github.com/tboser/cwltool.git,c22c762ba871bbe9ab4f6be7f639ad69a7b78942,"@@ -40,7 +40,7 @@ def _draft2toDraft3dev1(doc, loader, baseuri): # type: (Any, Loader, str) -> An impLoaded = loader.fetch(imp) r = None # type: Dict[str, Any] if isinstance(impLoaded, list): - r = {""@graph"": r} + r = {""@graph"": impLoaded} elif isinstance(impLoaded, dict): r = impLoaded else: ",cwltool/update.py,"ReplaceText(target='impLoaded' @(43,35)->(43,36))","def _draft2toDraft3dev1(doc, loader, baseuri): # type: (Any, Loader, str) -> An impLoaded = loader.fetch(imp) r = None # type: Dict[str, Any] if isinstance(impLoaded, list): r = {""@graph"": r} elif isinstance(impLoaded, dict): r = impLoaded else:","def _draft2toDraft3dev1(doc, loader, baseuri): # type: (Any, Loader, str) -> An impLoaded = loader.fetch(imp) r = None # type: Dict[str, Any] if isinstance(impLoaded, list): r = {""@graph"": impLoaded} elif isinstance(impLoaded, dict): r = impLoaded else:" 1501,https://:@github.com/tboser/cwltool.git,ad34521788edfe8b9c98841b16846c5eebb07edc,"@@ -337,7 +337,7 @@ class Loader(object): for k in sorted(idmapFieldValue.keys()): val = idmapFieldValue[k] v = None # type: Dict[unicode, Any] - if not isinstance(v, dict): + if not isinstance(val, dict): if idmapField in loader.mapPredicate: v = {loader.mapPredicate[idmapField]: val} else: ",schema_salad/ref_resolver.py,"ReplaceText(target='val' @(340,42)->(340,43))","class Loader(object): for k in sorted(idmapFieldValue.keys()): val = idmapFieldValue[k] v = None # type: Dict[unicode, Any] if not isinstance(v, dict): if idmapField in loader.mapPredicate: v = {loader.mapPredicate[idmapField]: val} else:","class Loader(object): for k in sorted(idmapFieldValue.keys()): val = idmapFieldValue[k] v = None # type: Dict[unicode, Any] if not isinstance(val, dict): if idmapField in loader.mapPredicate: v = {loader.mapPredicate[idmapField]: val} else:" 1502,https://:@github.com/MichaelScript/zerorpc-python.git,74899a7f9f7ebe06e08ce486d3e55145131e399e,"@@ -241,7 +241,7 @@ class ClientBase(object): return self._process_response(request_event, bufchan, timeout) async_result = gevent.event.AsyncResult() - gevent.spawn(self._process_response, method, bufchan, + gevent.spawn(self._process_response, request_event, bufchan, timeout).link(async_result) return async_result except: ",zerorpc/core.py,"ReplaceText(target='request_event' @(244,49)->(244,55))","class ClientBase(object): return self._process_response(request_event, bufchan, timeout) async_result = gevent.event.AsyncResult() gevent.spawn(self._process_response, method, bufchan, timeout).link(async_result) return async_result except:","class ClientBase(object): return self._process_response(request_event, bufchan, timeout) async_result = gevent.event.AsyncResult() gevent.spawn(self._process_response, request_event, bufchan, timeout).link(async_result) return async_result except:" 1503,https://:@github.com/CellProfiling/cam_acq.git,ff589fdfb73715b09fe27ffd8a2040ae286eca4c,"@@ -191,7 +191,7 @@ class CamImage(Base): """"""Return the part of the name of the image, matching regex."""""" if path is None: path = self.path - return super(CamImage, self).get_name(path, regex) + return super(CamImage, self).get_name(regex, path) def make_proj(self, path_list): """"""Make a dict of max projections from a list of image paths. ",camacq/image.py,"ArgSwap(idxs=0<->1 @(194,15)->(194,45))","class CamImage(Base): """"""Return the part of the name of the image, matching regex."""""" if path is None: path = self.path return super(CamImage, self).get_name(path, regex) def make_proj(self, path_list): """"""Make a dict of max projections from a list of image paths.","class CamImage(Base): """"""Return the part of the name of the image, matching regex."""""" if path is None: path = self.path return super(CamImage, self).get_name(regex, path) def make_proj(self, path_list): """"""Make a dict of max projections from a list of image paths." 1504,https://:@github.com/mvrozanti/youtube-curses.git,f4d58ba3be350a25dd70c607be565ac8a21ad1ff,"@@ -107,7 +107,7 @@ try: stdscr.addstr(1,0,""too small"") key = stdscr.getch() if key == curses.KEY_DOWN: - if highlight + page * maxitems + 1 != totalitems: + if highlight + page * maxitems + 1 < totalitems: if highlight + 1 == maxitems: page += 1 highlight = 0 ",twitch-curses.py,"ReplaceText(target='<' @(110,38)->(110,40))","try: stdscr.addstr(1,0,""too small"") key = stdscr.getch() if key == curses.KEY_DOWN: if highlight + page * maxitems + 1 != totalitems: if highlight + 1 == maxitems: page += 1 highlight = 0","try: stdscr.addstr(1,0,""too small"") key = stdscr.getch() if key == curses.KEY_DOWN: if highlight + page * maxitems + 1 < totalitems: if highlight + 1 == maxitems: page += 1 highlight = 0" 1505,https://:@github.com/seblin/shcol.git,96a07be4ba75dcd00374dbf0bf69aabf55bedf36,"@@ -51,7 +51,7 @@ class ColumnWidthCalculator(object): item_widths = [len(item) for item in items] if not item_widths: column_widths, num_lines = [], 0 - elif any(width > self.max_line_width for width in item_widths): + elif any(width >= self.max_line_width for width in item_widths): column_widths, num_lines = [self.max_line_width], len(item_widths) else: column_widths, num_lines = self.calculate_columns(item_widths) ",shcol.py,"ReplaceText(target='>=' @(54,23)->(54,24))","class ColumnWidthCalculator(object): item_widths = [len(item) for item in items] if not item_widths: column_widths, num_lines = [], 0 elif any(width > self.max_line_width for width in item_widths): column_widths, num_lines = [self.max_line_width], len(item_widths) else: column_widths, num_lines = self.calculate_columns(item_widths)","class ColumnWidthCalculator(object): item_widths = [len(item) for item in items] if not item_widths: column_widths, num_lines = [], 0 elif any(width >= self.max_line_width for width in item_widths): column_widths, num_lines = [self.max_line_width], len(item_widths) else: column_widths, num_lines = self.calculate_columns(item_widths)" 1506,https://:@github.com/biothings/biothings_explorer.git,aaf17dd35289147c1eb701f6739e576a16a08ca1,"@@ -41,7 +41,7 @@ class ConnectTwoConcepts(): print('q2 original nodes', q2.G.nodes()) q2_subset = q2.G.subgraph(q1_common + [self.output_values]) print('q2_subset nodes', q2_subset.nodes()) - self.G = nx.compose(q1_subset, q2_subset) + self.G = nx.compose(q2_subset, q1_subset) def visualize(self): return visualize(self.G.edges()) ",biothings_explorer/connect.py,"ArgSwap(idxs=0<->1 @(44,21)->(44,31))","class ConnectTwoConcepts(): print('q2 original nodes', q2.G.nodes()) q2_subset = q2.G.subgraph(q1_common + [self.output_values]) print('q2_subset nodes', q2_subset.nodes()) self.G = nx.compose(q1_subset, q2_subset) def visualize(self): return visualize(self.G.edges())","class ConnectTwoConcepts(): print('q2 original nodes', q2.G.nodes()) q2_subset = q2.G.subgraph(q1_common + [self.output_values]) print('q2_subset nodes', q2_subset.nodes()) self.G = nx.compose(q2_subset, q1_subset) def visualize(self): return visualize(self.G.edges())" 1507,https://:@github.com/QwilApp/gasofo.git,839d7bf88cc2ccbc92b980502586614db35b4f42,"@@ -144,7 +144,7 @@ class ServiceMetaclass(type): raise UnknownPort('{}.{} references undeclared Needs - {}'.format( class_name, attr_name, - ', '.join(sorted(deps_used)) + ', '.join(sorted(invalid_ports)) )) unused_needs = needs_ports_defined.difference(all_deps_used) ",gasofo/service.py,"ReplaceText(target='invalid_ports' @(147,41)->(147,50))","class ServiceMetaclass(type): raise UnknownPort('{}.{} references undeclared Needs - {}'.format( class_name, attr_name, ', '.join(sorted(deps_used)) )) unused_needs = needs_ports_defined.difference(all_deps_used)","class ServiceMetaclass(type): raise UnknownPort('{}.{} references undeclared Needs - {}'.format( class_name, attr_name, ', '.join(sorted(invalid_ports)) )) unused_needs = needs_ports_defined.difference(all_deps_used)" 1508,https://:@github.com/mila-udem/blocks.git,8f71ba948707c3bc7ddbe28e0bfb2a6f26c2f626,"@@ -274,7 +274,7 @@ class Application(object): annotations = getattr(copy.tag, 'annotations', []) + [brick, call] copy.tag.annotations = annotations copy.tag.name = name # Blocks name - VariableRole.add_role(variable, role) + VariableRole.add_role(copy, role) return copy for i, input_ in enumerate(args): ",blocks/bricks/base.py,"ReplaceText(target='copy' @(277,34)->(277,42))","class Application(object): annotations = getattr(copy.tag, 'annotations', []) + [brick, call] copy.tag.annotations = annotations copy.tag.name = name # Blocks name VariableRole.add_role(variable, role) return copy for i, input_ in enumerate(args):","class Application(object): annotations = getattr(copy.tag, 'annotations', []) + [brick, call] copy.tag.annotations = annotations copy.tag.name = name # Blocks name VariableRole.add_role(copy, role) return copy for i, input_ in enumerate(args):" 1509,https://:@github.com/mila-udem/blocks.git,a8c99adf643eb8c4edb40acd9c95210a07b36aea,"@@ -28,7 +28,7 @@ def test_gaussian(): rng = numpy.random.RandomState(1) def check_gaussian(rng, mean, std, shape): - weights = IsotropicGaussian(mean, std).generate(rng, shape) + weights = IsotropicGaussian(std, mean).generate(rng, shape) assert weights.shape == shape assert weights.dtype == theano.config.floatX assert_allclose(weights.mean(), mean, atol=1e-2) ",tests/test_initialization.py,"ArgSwap(idxs=0<->1 @(31,18)->(31,35))","def test_gaussian(): rng = numpy.random.RandomState(1) def check_gaussian(rng, mean, std, shape): weights = IsotropicGaussian(mean, std).generate(rng, shape) assert weights.shape == shape assert weights.dtype == theano.config.floatX assert_allclose(weights.mean(), mean, atol=1e-2)","def test_gaussian(): rng = numpy.random.RandomState(1) def check_gaussian(rng, mean, std, shape): weights = IsotropicGaussian(std, mean).generate(rng, shape) assert weights.shape == shape assert weights.dtype == theano.config.floatX assert_allclose(weights.mean(), mean, atol=1e-2)" 1510,https://:@github.com/mila-udem/blocks.git,a76f7c437ff32103fd9a66c31a1fbcc963dcc82e,"@@ -105,7 +105,7 @@ def inject_parameter_values(bricks, param_values): params = bricks.get_params() for name in params.keys(): - if name not in params: + if name not in param_values: logger.error(""No value is provided for the parameter {}"" .format(name)) ",blocks/serialization.py,"ReplaceText(target='param_values' @(108,23)->(108,29))","def inject_parameter_values(bricks, param_values): params = bricks.get_params() for name in params.keys(): if name not in params: logger.error(""No value is provided for the parameter {}"" .format(name)) ","def inject_parameter_values(bricks, param_values): params = bricks.get_params() for name in params.keys(): if name not in param_values: logger.error(""No value is provided for the parameter {}"" .format(name)) " 1511,https://:@github.com/mila-udem/blocks.git,54dd52f080177aede81a63f58b276dd1e9cfc915,"@@ -622,7 +622,7 @@ class VariableClipping(StepRule): def compute_step(self, param, previous_step): if any(axis >= previous_step.ndim for axis in self.axes): raise ValueError(""Invalid axes {} for {}, ndim={}"".format( - self.axes, param, param.ndim)) + self.axes, param, previous_step.ndim)) squares = tensor.sqr(previous_step) if len(self.axes) == 0: norms = l2_norm([previous_step]) ",blocks/algorithms/__init__.py,"ReplaceText(target='previous_step' @(625,34)->(625,39))","class VariableClipping(StepRule): def compute_step(self, param, previous_step): if any(axis >= previous_step.ndim for axis in self.axes): raise ValueError(""Invalid axes {} for {}, ndim={}"".format( self.axes, param, param.ndim)) squares = tensor.sqr(previous_step) if len(self.axes) == 0: norms = l2_norm([previous_step])","class VariableClipping(StepRule): def compute_step(self, param, previous_step): if any(axis >= previous_step.ndim for axis in self.axes): raise ValueError(""Invalid axes {} for {}, ndim={}"".format( self.axes, param, previous_step.ndim)) squares = tensor.sqr(previous_step) if len(self.axes) == 0: norms = l2_norm([previous_step])" 1512,https://:@github.com/jeremiedecock/pywi-cta.git,51ea19f5d8cec9f4759eb8079dc4c01295719577,"@@ -228,7 +228,7 @@ class AbstractCleaningAlgorithm(object): image_dict[""img_cleaned_max_pe""] = float(np.nanmax(cleaned_img)) image_dict[""img_cleaned_num_pix""] = int( (cleaned_img[np.isfinite(cleaned_img)] > 0).sum() ) - cleaned_img1d = geometry_converter.image_2d_to_1d(reference_img, fits_metadata_dict['cam_id']) + cleaned_img1d = geometry_converter.image_2d_to_1d(cleaned_img, fits_metadata_dict['cam_id']) hillas_params_2_cleaned_img = get_hillas_parameters(geom1d, cleaned_img1d, HILLAS_IMPLEMENTATION) # GEOM image_dict[""img_cleaned_hillas_2_size""] = float(hillas_params_2_cleaned_img.size) ",datapipe/denoising/abstract_cleaning_algorithm.py,"ReplaceText(target='cleaned_img' @(231,74)->(231,87))","class AbstractCleaningAlgorithm(object): image_dict[""img_cleaned_max_pe""] = float(np.nanmax(cleaned_img)) image_dict[""img_cleaned_num_pix""] = int( (cleaned_img[np.isfinite(cleaned_img)] > 0).sum() ) cleaned_img1d = geometry_converter.image_2d_to_1d(reference_img, fits_metadata_dict['cam_id']) hillas_params_2_cleaned_img = get_hillas_parameters(geom1d, cleaned_img1d, HILLAS_IMPLEMENTATION) # GEOM image_dict[""img_cleaned_hillas_2_size""] = float(hillas_params_2_cleaned_img.size)","class AbstractCleaningAlgorithm(object): image_dict[""img_cleaned_max_pe""] = float(np.nanmax(cleaned_img)) image_dict[""img_cleaned_num_pix""] = int( (cleaned_img[np.isfinite(cleaned_img)] > 0).sum() ) cleaned_img1d = geometry_converter.image_2d_to_1d(cleaned_img, fits_metadata_dict['cam_id']) hillas_params_2_cleaned_img = get_hillas_parameters(geom1d, cleaned_img1d, HILLAS_IMPLEMENTATION) # GEOM image_dict[""img_cleaned_hillas_2_size""] = float(hillas_params_2_cleaned_img.size)" 1513,https://:@github.com/jeremiedecock/pywi-cta.git,339e74ccf897012a30b4077d3ffa81a37bb005b9,"@@ -171,7 +171,7 @@ class ObjectiveFunction: filter_thresholds_str = "","".join([str(sigma) for sigma in filter_thresholds]) # Check the length of filter_thresholds_str is consistent with self.num_scales - if len(filter_thresholds_str) != (self.num_scales - 1): + if len(filter_thresholds) != (self.num_scales - 1): raise ValueError(""The tested solution has a wrong number of dimensions: "" ""{} instead of {}"".format(len(filter_thresholds), self.num_scales - 1)) ",pywicta/optimization/objectivefunc/wavelets_mrfilter.py,"ReplaceText(target='filter_thresholds' @(174,15)->(174,36))","class ObjectiveFunction: filter_thresholds_str = "","".join([str(sigma) for sigma in filter_thresholds]) # Check the length of filter_thresholds_str is consistent with self.num_scales if len(filter_thresholds_str) != (self.num_scales - 1): raise ValueError(""The tested solution has a wrong number of dimensions: "" ""{} instead of {}"".format(len(filter_thresholds), self.num_scales - 1))","class ObjectiveFunction: filter_thresholds_str = "","".join([str(sigma) for sigma in filter_thresholds]) # Check the length of filter_thresholds_str is consistent with self.num_scales if len(filter_thresholds) != (self.num_scales - 1): raise ValueError(""The tested solution has a wrong number of dimensions: "" ""{} instead of {}"".format(len(filter_thresholds), self.num_scales - 1))" 1514,https://:@github.com/ros/urdf_parser_py.git,c0183ac51435815923a9a8aab17698ae29230338,"@@ -237,7 +237,7 @@ class Inertial(object): mass=0.0, origin=None): self.matrix = {} self.matrix['ixx'] = ixx - self.matrix['ixy'] = iyy + self.matrix['ixy'] = ixy self.matrix['ixz'] = ixz self.matrix['iyy'] = iyy self.matrix['iyz'] = iyz ",src/urdf_parser_py/urdf.py,"ReplaceText(target='ixy' @(240,29)->(240,32))","class Inertial(object): mass=0.0, origin=None): self.matrix = {} self.matrix['ixx'] = ixx self.matrix['ixy'] = iyy self.matrix['ixz'] = ixz self.matrix['iyy'] = iyy self.matrix['iyz'] = iyz","class Inertial(object): mass=0.0, origin=None): self.matrix = {} self.matrix['ixx'] = ixx self.matrix['ixy'] = ixy self.matrix['ixz'] = ixz self.matrix['iyy'] = iyy self.matrix['iyz'] = iyz" 1515,https://:@github.com/Faithforus/Colour-printing.git,f927c250c967ea52a74d60587a9709bc9a073454,"@@ -17,7 +17,7 @@ class Markers: self.__cal_flag_len() def __cal_flag_len(self): - if Markers.__flag_len < len(self.__flag_name): + if Markers.__flag_len <= len(self.__flag_name): Markers.__flag_len = len(self.__flag_name)+2 def message_style(self, mode='', fore='', back=''): ",colour_printing/custom/markers.py,"ReplaceText(target='<=' @(20,30)->(20,31))","class Markers: self.__cal_flag_len() def __cal_flag_len(self): if Markers.__flag_len < len(self.__flag_name): Markers.__flag_len = len(self.__flag_name)+2 def message_style(self, mode='', fore='', back=''):","class Markers: self.__cal_flag_len() def __cal_flag_len(self): if Markers.__flag_len <= len(self.__flag_name): Markers.__flag_len = len(self.__flag_name)+2 def message_style(self, mode='', fore='', back=''):" 1516,https://:@github.com/ccarocean/pyrads.git,11fd786460c69972560cb02cce0a8b8b8a9ab2c9,"@@ -82,7 +82,7 @@ def ensure_open( .. seealso:: :func:`open` """""" if hasattr(file, ""read""): - if closeio: + if not closeio: return cast(IO[Any], _NoCloseIOWrapper(file)) return cast(IO[Any], file) return open( ",rads/utility.py,"ReplaceText(target='not ' @(85,11)->(85,11))","def ensure_open( .. seealso:: :func:`open` """""" if hasattr(file, ""read""): if closeio: return cast(IO[Any], _NoCloseIOWrapper(file)) return cast(IO[Any], file) return open(","def ensure_open( .. seealso:: :func:`open` """""" if hasattr(file, ""read""): if not closeio: return cast(IO[Any], _NoCloseIOWrapper(file)) return cast(IO[Any], file) return open(" 1517,https://:@github.com/paulsbond/modelcraft.git,688d05f50a4c1ded44fdd3d0309fbeaadf762807,"@@ -88,7 +88,7 @@ class Pipeline(): def refmac(self, cycles): directory = self.job_directory(""refmac"") use_phases = self.args.unbiased and self.min_rwork > 0.35 - job = Refmac(self.args, directory, self.current_xyz, use_phases, cycles) + job = Refmac(self.args, directory, self.current_xyz, cycles, use_phases) self.jobs[self.cycle].append(job) self.current_hkl = job.hklout self.current_xyz = job.xyzout ",modelcraft/pipeline.py,"ArgSwap(idxs=3<->4 @(91,14)->(91,20))","class Pipeline(): def refmac(self, cycles): directory = self.job_directory(""refmac"") use_phases = self.args.unbiased and self.min_rwork > 0.35 job = Refmac(self.args, directory, self.current_xyz, use_phases, cycles) self.jobs[self.cycle].append(job) self.current_hkl = job.hklout self.current_xyz = job.xyzout","class Pipeline(): def refmac(self, cycles): directory = self.job_directory(""refmac"") use_phases = self.args.unbiased and self.min_rwork > 0.35 job = Refmac(self.args, directory, self.current_xyz, cycles, use_phases) self.jobs[self.cycle].append(job) self.current_hkl = job.hklout self.current_xyz = job.xyzout" 1518,https://:@github.com/gaoyunzhi/readee.git,699c229fdcc1ddd2dd52b72d7b7e4b4da76a7585,"@@ -33,7 +33,7 @@ def _tagReplace(soup, args = {}): if len(children) != 1 or not isinstance(children[0], str): continue to_replace = None - if l.parent.name != 'blockquote': # douban status specific + if l.parent.name == 'blockquote': # douban status specific to_replace = l.parent if 'review-content' in str(l.parent.attrs): # douban reviews specific to_replace = l ",readee/tag_replace.py,"ReplaceText(target='==' @(36,19)->(36,21))","def _tagReplace(soup, args = {}): if len(children) != 1 or not isinstance(children[0], str): continue to_replace = None if l.parent.name != 'blockquote': # douban status specific to_replace = l.parent if 'review-content' in str(l.parent.attrs): # douban reviews specific to_replace = l","def _tagReplace(soup, args = {}): if len(children) != 1 or not isinstance(children[0], str): continue to_replace = None if l.parent.name == 'blockquote': # douban status specific to_replace = l.parent if 'review-content' in str(l.parent.attrs): # douban reviews specific to_replace = l" 1519,https://:@github.com/bkad/gevent.git,3444f110d767c8985127c4421c4f79f206122ad5,"@@ -313,7 +313,7 @@ def _parse_address(address): host = '' return family, (host, int(port)) else: - return _socket.AF_INET, ('', int(port)) + return _socket.AF_INET, ('', int(address)) elif isinstance(address, integer_types): return _socket.AF_INET, ('', int(address)) else: ",gevent/baseserver.py,"ReplaceText(target='address' @(316,45)->(316,49))","def _parse_address(address): host = '' return family, (host, int(port)) else: return _socket.AF_INET, ('', int(port)) elif isinstance(address, integer_types): return _socket.AF_INET, ('', int(address)) else:","def _parse_address(address): host = '' return family, (host, int(port)) else: return _socket.AF_INET, ('', int(address)) elif isinstance(address, integer_types): return _socket.AF_INET, ('', int(address)) else:" 1520,https://:@github.com/jerith/txTwitter.git,05cb3871bd345ea0850b223388f37f5a7cf5c3c5,"@@ -517,7 +517,7 @@ class FakeTwitterAPI(object): self._twitter_data.iter_tweets_from(user_id), count, since_id, max_id) if exclude_replies: - tweets = [tweet for tweet in tweets if tweet.reply_to is not None] + tweets = [tweet for tweet in tweets if tweet.reply_to is None] if include_rts is not None: raise NotImplementedError(""exclude_rts param"") return [ ",txtwitter/tests/fake_twitter.py,"ReplaceText(target=' is ' @(520,65)->(520,73))","class FakeTwitterAPI(object): self._twitter_data.iter_tweets_from(user_id), count, since_id, max_id) if exclude_replies: tweets = [tweet for tweet in tweets if tweet.reply_to is not None] if include_rts is not None: raise NotImplementedError(""exclude_rts param"") return [","class FakeTwitterAPI(object): self._twitter_data.iter_tweets_from(user_id), count, since_id, max_id) if exclude_replies: tweets = [tweet for tweet in tweets if tweet.reply_to is None] if include_rts is not None: raise NotImplementedError(""exclude_rts param"") return [" 1521,https://:@github.com/rainwoodman/gaepsi.git,2a3b9fca6494eeb84a68cd82e4c8bd1e04f7652f,"@@ -49,7 +49,7 @@ class Snapshot: return [self.P[ptype][bn] for bn in blocknames] def has(self, blockname, ptype): - return self.reader.has_block(self, ptype, blockname) + return self.reader.has_block(self, blockname, ptype) def save_header(self): self.reader.write_header(self) ",snapshot.py,"ArgSwap(idxs=1<->2 @(52,11)->(52,32))","class Snapshot: return [self.P[ptype][bn] for bn in blocknames] def has(self, blockname, ptype): return self.reader.has_block(self, ptype, blockname) def save_header(self): self.reader.write_header(self)","class Snapshot: return [self.P[ptype][bn] for bn in blocknames] def has(self, blockname, ptype): return self.reader.has_block(self, blockname, ptype) def save_header(self): self.reader.write_header(self)" 1522,https://:@github.com/staffanm/ferenda.git,250cc870c14cbb8089ffd9b1f4dab44865ab4e7d,"@@ -4,7 +4,7 @@ from ferenda.sources.legal.se import SwedishLegalSource class LocalURI(SwedishLegalSource): def infer_triples(self, d, basefile=None): - super(self, LocalURI).infer_triples(d,basefile) + super(LocalURI, self).infer_triples(d,basefile) canonicalminter = ... sameas = self.canonicalminter(d) d.rel(OWL.sameAs, sameas) ",lagen/nu/localuri.py,"ArgSwap(idxs=0<->1 @(7,8)->(7,13))","from ferenda.sources.legal.se import SwedishLegalSource class LocalURI(SwedishLegalSource): def infer_triples(self, d, basefile=None): super(self, LocalURI).infer_triples(d,basefile) canonicalminter = ... sameas = self.canonicalminter(d) d.rel(OWL.sameAs, sameas)","from ferenda.sources.legal.se import SwedishLegalSource class LocalURI(SwedishLegalSource): def infer_triples(self, d, basefile=None): super(LocalURI, self).infer_triples(d,basefile) canonicalminter = ... sameas = self.canonicalminter(d) d.rel(OWL.sameAs, sameas)" 1523,https://:@github.com/staffanm/ferenda.git,268b56a25bb57f04675661603eea670fe33d7085,"@@ -458,7 +458,7 @@ class Offtryck(SwedishLegalSource): else: initialstate['pageno'] = lastpagebreak.ordinal + 1 allbody += body[:] - self.validate_body(body, basefile) # Throws exception if invalid + self.validate_body(allbody, basefile) # Throws exception if invalid return allbody except Exception as e: errmsg = str(e) ",ferenda/sources/legal/se/offtryck.py,"ReplaceText(target='allbody' @(461,35)->(461,39))","class Offtryck(SwedishLegalSource): else: initialstate['pageno'] = lastpagebreak.ordinal + 1 allbody += body[:] self.validate_body(body, basefile) # Throws exception if invalid return allbody except Exception as e: errmsg = str(e)","class Offtryck(SwedishLegalSource): else: initialstate['pageno'] = lastpagebreak.ordinal + 1 allbody += body[:] self.validate_body(allbody, basefile) # Throws exception if invalid return allbody except Exception as e: errmsg = str(e)" 1524,https://:@github.com/staffanm/ferenda.git,133ebd33435acb8a7d6ed611341c50755881538e,"@@ -56,7 +56,7 @@ class TestGlue(unittest.TestCase): self._f('') textbox = self._p('Det är nu hög tid att göra en kraftsamling för informationsförsörj-') prevbox = self._p('ningen till forskning och utbildning.') - self.assertTrue(self.gluefunc(prevbox, prevbox, textbox)) + self.assertTrue(self.gluefunc(textbox, prevbox, textbox)) textbox = textbox + prevbox nextbox = self._p(' Den tekniska utvecklingen går ') self.assertTrue(self.gluefunc(textbox, nextbox, prevbox)) ",test/integrationOfftryck.py,"ReplaceText(target='textbox' @(59,38)->(59,45))","class TestGlue(unittest.TestCase): self._f('') textbox = self._p('Det är nu hög tid att göra en kraftsamling för informationsförsörj-') prevbox = self._p('ningen till forskning och utbildning.') self.assertTrue(self.gluefunc(prevbox, prevbox, textbox)) textbox = textbox + prevbox nextbox = self._p(' Den tekniska utvecklingen går ') self.assertTrue(self.gluefunc(textbox, nextbox, prevbox))","class TestGlue(unittest.TestCase): self._f('') textbox = self._p('Det är nu hög tid att göra en kraftsamling för informationsförsörj-') prevbox = self._p('ningen till forskning och utbildning.') self.assertTrue(self.gluefunc(textbox, prevbox, textbox)) textbox = textbox + prevbox nextbox = self._p(' Den tekniska utvecklingen går ') self.assertTrue(self.gluefunc(textbox, nextbox, prevbox))" 1525,https://:@github.com/staffanm/ferenda.git,699fb245c4cb447a0f8cf7d4fd62bbb1d6efcfec,"@@ -986,7 +986,7 @@ with the *config* object as single parameter. if response.status_code == 304: self.log.debug(""%s: 304 Not modified"" % url) return False # ie not updated - elif response.status_code > 400: + elif response.status_code >= 400: self.log.error(""Failed to retrieve %s"" % url) response.raise_for_status() ",ferenda/documentrepository.py,"ReplaceText(target='>=' @(989,34)->(989,35))","with the *config* object as single parameter. if response.status_code == 304: self.log.debug(""%s: 304 Not modified"" % url) return False # ie not updated elif response.status_code > 400: self.log.error(""Failed to retrieve %s"" % url) response.raise_for_status() ","with the *config* object as single parameter. if response.status_code == 304: self.log.debug(""%s: 304 Not modified"" % url) return False # ie not updated elif response.status_code >= 400: self.log.error(""Failed to retrieve %s"" % url) response.raise_for_status() " 1526,https://:@github.com/staffanm/ferenda.git,158f09f9d9152ccb71b1af4a60a17e53349f0226,"@@ -561,7 +561,7 @@ class Offtryck(SwedishLegalSource): # fix the json file at pagemapping_path as well? for idx, page in enumerate(sanitized): sanitized[idx].number = idx + 1 - sanitized[idx].src = ""%s/sid%s.png"" % (basefile, idx+1) + sanitized[idx].src = ""%s/sid%s.png"" % (baseuri, idx+1) else: analyzer = sanitized.analyzer if not os.path.exists(pagemapping_path) or self.config.force: ",ferenda/sources/legal/se/offtryck.py,"ReplaceText(target='baseuri' @(564,55)->(564,63))","class Offtryck(SwedishLegalSource): # fix the json file at pagemapping_path as well? for idx, page in enumerate(sanitized): sanitized[idx].number = idx + 1 sanitized[idx].src = ""%s/sid%s.png"" % (basefile, idx+1) else: analyzer = sanitized.analyzer if not os.path.exists(pagemapping_path) or self.config.force:","class Offtryck(SwedishLegalSource): # fix the json file at pagemapping_path as well? for idx, page in enumerate(sanitized): sanitized[idx].number = idx + 1 sanitized[idx].src = ""%s/sid%s.png"" % (baseuri, idx+1) else: analyzer = sanitized.analyzer if not os.path.exists(pagemapping_path) or self.config.force:" 1527,https://:@github.com/pyopenapi/pyopenapi.git,fbe951506252bffe083942c246736bca14f13a4c,"@@ -30,7 +30,7 @@ class SwaggerApp(BaseObj): # default initialization is passing the url # you can override this behavior by passing an # initialized getter object. - local_getter = getter(url) + local_getter = local_getter(url) ctx = ResourceListContext(None, local_getter) ctx.parse() ",pyopenapi/core.py,"ReplaceText(target='local_getter' @(33,27)->(33,33))","class SwaggerApp(BaseObj): # default initialization is passing the url # you can override this behavior by passing an # initialized getter object. local_getter = getter(url) ctx = ResourceListContext(None, local_getter) ctx.parse()","class SwaggerApp(BaseObj): # default initialization is passing the url # you can override this behavior by passing an # initialized getter object. local_getter = local_getter(url) ctx = ResourceListContext(None, local_getter) ctx.parse()" 1528,https://:@github.com/pyopenapi/pyopenapi.git,54bdc346b45deb8277831a7ac70886bc81568696,"@@ -39,7 +39,7 @@ class ScopeDict(dict): def __init__(self, sep=SCOPE_SEPARATOR): self.__sep = sep - super(self, ScopeDict).__init__() + super(ScopeDict, self).__init__() def __getitem__(self, *keys): """""" to access an obj with key: 'n!##!m...!##!z', caller can pass as key: ",pyopenapi/utils.py,"ArgSwap(idxs=0<->1 @(42,8)->(42,13))","class ScopeDict(dict): def __init__(self, sep=SCOPE_SEPARATOR): self.__sep = sep super(self, ScopeDict).__init__() def __getitem__(self, *keys): """""" to access an obj with key: 'n!##!m...!##!z', caller can pass as key:","class ScopeDict(dict): def __init__(self, sep=SCOPE_SEPARATOR): self.__sep = sep super(ScopeDict, self).__init__() def __getitem__(self, *keys): """""" to access an obj with key: 'n!##!m...!##!z', caller can pass as key:" 1529,https://:@github.com/clindatsci/dicomweb-client.git,a8426098bf10c893366be9043bc3366a47c22b48,"@@ -1427,7 +1427,7 @@ class DICOMwebClient(object): response = self._session.post( url=url, data=data_chunks, - headers=headers + headers=chunked_headers ) else: response = self._session.post(url=url, data=data, headers=headers) ",src/dicomweb_client/api.py,"ReplaceText(target='chunked_headers' @(1430,24)->(1430,31))","class DICOMwebClient(object): response = self._session.post( url=url, data=data_chunks, headers=headers ) else: response = self._session.post(url=url, data=data, headers=headers)","class DICOMwebClient(object): response = self._session.post( url=url, data=data_chunks, headers=chunked_headers ) else: response = self._session.post(url=url, data=data, headers=headers)" 1530,https://:@github.com/clindatsci/dicomweb-client.git,e9d9410e7de9108e6cda82c5c44a3fb177e32163,"@@ -403,7 +403,7 @@ class DICOMwebClient(object): self._session.proxies = proxies if callback is not None: self._session.hooks = {'response': [callback, ]} - if chunk_size is not None: + if chunk_size is None: # There is a bug in the requests library that sets the Host header # again when using chunked transer encoding. Apparently this is # tricky to fix (see https://github.com/psf/requests/issues/4392). ",src/dicomweb_client/api.py,"ReplaceText(target=' is ' @(406,21)->(406,29))","class DICOMwebClient(object): self._session.proxies = proxies if callback is not None: self._session.hooks = {'response': [callback, ]} if chunk_size is not None: # There is a bug in the requests library that sets the Host header # again when using chunked transer encoding. Apparently this is # tricky to fix (see https://github.com/psf/requests/issues/4392).","class DICOMwebClient(object): self._session.proxies = proxies if callback is not None: self._session.hooks = {'response': [callback, ]} if chunk_size is None: # There is a bug in the requests library that sets the Host header # again when using chunked transer encoding. Apparently this is # tricky to fix (see https://github.com/psf/requests/issues/4392)." 1531,https://:@gitlab.com/koala-lms/django-learning.git,600bf3b8691699936ebffccd7f31f2f937eab388,"@@ -88,7 +88,7 @@ class ActivityCreateOnCourseView(LoginRequiredMixin, PermissionRequiredMixin, Up def form_invalid(self, form): for sub_form in form: - update_valid_or_invalid_form_fields(form) + update_valid_or_invalid_form_fields(sub_form) for error in sub_form.errors: messages.error(self.request, sub_form.errors[error]) return self.get_success_url() ",learning/views/activity.py,"ReplaceText(target='sub_form' @(91,48)->(91,52))","class ActivityCreateOnCourseView(LoginRequiredMixin, PermissionRequiredMixin, Up def form_invalid(self, form): for sub_form in form: update_valid_or_invalid_form_fields(form) for error in sub_form.errors: messages.error(self.request, sub_form.errors[error]) return self.get_success_url()","class ActivityCreateOnCourseView(LoginRequiredMixin, PermissionRequiredMixin, Up def form_invalid(self, form): for sub_form in form: update_valid_or_invalid_form_fields(sub_form) for error in sub_form.errors: messages.error(self.request, sub_form.errors[error]) return self.get_success_url()" 1532,https://:@github.com/finderseyes/upkit.git,5f39342aa3261683f3aa675617c9f505409c346f,"@@ -172,7 +172,7 @@ class PackageLinker(object): item_source = os.path.abspath(os.path.join(source, item['source'])) item_target = os.path.abspath(self._render_template(item['target'], params)) - content = package_linkspec.get('content', None) + content = item.get('content', None) if not content: utils.fs_link(item_source, item_target, hard_link=True, forced=forced) else: ",unity_tools/package_linker.py,"ReplaceText(target='item' @(175,26)->(175,42))","class PackageLinker(object): item_source = os.path.abspath(os.path.join(source, item['source'])) item_target = os.path.abspath(self._render_template(item['target'], params)) content = package_linkspec.get('content', None) if not content: utils.fs_link(item_source, item_target, hard_link=True, forced=forced) else:","class PackageLinker(object): item_source = os.path.abspath(os.path.join(source, item['source'])) item_target = os.path.abspath(self._render_template(item['target'], params)) content = item.get('content', None) if not content: utils.fs_link(item_source, item_target, hard_link=True, forced=forced) else:" 1533,https://:@github.com/spoorcc/cppumockify.git,8b4f2089cda3cc3071cd8fb5d83a36c5f6b0552b,"@@ -82,7 +82,7 @@ class MockError(Exception): def generate_mock(mocked_module, mock_prototype): ''' Generates the mock ''' mock_filename = ""{0}_mock.cpp"".format(mocked_module) - include_filename = ""{0}.h"".format(mock_filename) + include_filename = ""{0}.h"".format(mocked_module) logger.debug(""working directory: %s"", os.getcwd()) logger.debug(""mock_filename: %s"", mock_filename) logger.debug(""include_filename: %s"", include_filename) ",cppumockify.py,"ReplaceText(target='mocked_module' @(85,38)->(85,51))","class MockError(Exception): def generate_mock(mocked_module, mock_prototype): ''' Generates the mock ''' mock_filename = ""{0}_mock.cpp"".format(mocked_module) include_filename = ""{0}.h"".format(mock_filename) logger.debug(""working directory: %s"", os.getcwd()) logger.debug(""mock_filename: %s"", mock_filename) logger.debug(""include_filename: %s"", include_filename)","class MockError(Exception): def generate_mock(mocked_module, mock_prototype): ''' Generates the mock ''' mock_filename = ""{0}_mock.cpp"".format(mocked_module) include_filename = ""{0}.h"".format(mocked_module) logger.debug(""working directory: %s"", os.getcwd()) logger.debug(""mock_filename: %s"", mock_filename) logger.debug(""include_filename: %s"", include_filename)" 1534,https://:@github.com/pigmonkey/django-vellum.git,f8edc139fe9f8a6d6e63af6d6b1a2a42d3c38002,"@@ -208,7 +208,7 @@ def tag_detail(request, slug, page=0, **kwargs): return list_detail.object_list( request, - queryset=Post.objects.filter(tags__name__in=[slug]), + queryset=Post.objects.filter(tags__name__in=[tag]), paginate_by=blog_settings.BLOG_PAGESIZE, page=page, extra_context={ ",basic/blog/views.py,"ReplaceText(target='tag' @(211,53)->(211,57))","def tag_detail(request, slug, page=0, **kwargs): return list_detail.object_list( request, queryset=Post.objects.filter(tags__name__in=[slug]), paginate_by=blog_settings.BLOG_PAGESIZE, page=page, extra_context={","def tag_detail(request, slug, page=0, **kwargs): return list_detail.object_list( request, queryset=Post.objects.filter(tags__name__in=[tag]), paginate_by=blog_settings.BLOG_PAGESIZE, page=page, extra_context={" 1535,https://:@github.com/asoroa/ical2org.py.git,ac33b4760b1d87eb35ce9892e329dc6926d83f57,"@@ -63,7 +63,7 @@ def recurring_event_days(event_start, event_end, delta_str, start_utc, end_utc): else : event_aux = event_start - while event_aux < end_utc: + while event_aux <= end_utc: result.append( (event_aux, event_aux.tzinfo.normalize(event_aux + event_duration), 1) ) event_aux = add_delta_dst(event_aux, delta) return result ",ical2org.py,"ReplaceText(target='<=' @(66,20)->(66,21))","def recurring_event_days(event_start, event_end, delta_str, start_utc, end_utc): else : event_aux = event_start while event_aux < end_utc: result.append( (event_aux, event_aux.tzinfo.normalize(event_aux + event_duration), 1) ) event_aux = add_delta_dst(event_aux, delta) return result","def recurring_event_days(event_start, event_end, delta_str, start_utc, end_utc): else : event_aux = event_start while event_aux <= end_utc: result.append( (event_aux, event_aux.tzinfo.normalize(event_aux + event_duration), 1) ) event_aux = add_delta_dst(event_aux, delta) return result" 1536,https://:@github.com/PaloAltoNetworks/ansible-pan.git,370d08e2204b387e30596c6cec3ddb388acc11dc,"@@ -434,7 +434,7 @@ def main(): if destination_lower <= obj <= destination_upper: destination_ip_match = True else: - if source_ip == object_string: + if destination_ip == object_string: destination_ip_match = True if isinstance(obj, objects.AddressObject) and addr_in_obj(destination_ip, obj): destination_ip_match = True ",library/panos_query_rules.py,"ReplaceText(target='destination_ip' @(437,31)->(437,40))","def main(): if destination_lower <= obj <= destination_upper: destination_ip_match = True else: if source_ip == object_string: destination_ip_match = True if isinstance(obj, objects.AddressObject) and addr_in_obj(destination_ip, obj): destination_ip_match = True","def main(): if destination_lower <= obj <= destination_upper: destination_ip_match = True else: if destination_ip == object_string: destination_ip_match = True if isinstance(obj, objects.AddressObject) and addr_in_obj(destination_ip, obj): destination_ip_match = True" 1537,https://:@github.com/bond005/impartial_text_cls.git,d81895309fc7a26004fb50e5b5ced3fd62307c46,"@@ -97,7 +97,7 @@ class ImpatialTextClassifier(BaseEstimator, ClassifierMixin): if self.verbose: lengths_of_texts = [] sum_of_lengths = 0 - for sample_idx in range(len(y_train_)): + for sample_idx in range(len(y_train_tokenized)): lengths_of_texts.append(sum(X_train_tokenized[1][sample_idx])) sum_of_lengths += lengths_of_texts[-1] if X_unlabeled_tokenized is not None: ",impatial_text_cls/impatial_text_cls.py,"ReplaceText(target='y_train_tokenized' @(100,40)->(100,48))","class ImpatialTextClassifier(BaseEstimator, ClassifierMixin): if self.verbose: lengths_of_texts = [] sum_of_lengths = 0 for sample_idx in range(len(y_train_)): lengths_of_texts.append(sum(X_train_tokenized[1][sample_idx])) sum_of_lengths += lengths_of_texts[-1] if X_unlabeled_tokenized is not None:","class ImpatialTextClassifier(BaseEstimator, ClassifierMixin): if self.verbose: lengths_of_texts = [] sum_of_lengths = 0 for sample_idx in range(len(y_train_tokenized)): lengths_of_texts.append(sum(X_train_tokenized[1][sample_idx])) sum_of_lengths += lengths_of_texts[-1] if X_unlabeled_tokenized is not None:" 1538,https://:@bitbucket.org/padraicshafer/pkgscript.git,2839ec817483697e30480486957df7e82994eae1,"@@ -131,7 +131,7 @@ def get_versions(): pass return_key_values = _get_versions() - return_key_values[""authors""] = pieces[""authors""] + return_key_values[""authors""] = default_keys_values[""authors""] return return_key_values ",pkgscript/version.py,"ReplaceText(target='default_keys_values' @(134,35)->(134,41))","def get_versions(): pass return_key_values = _get_versions() return_key_values[""authors""] = pieces[""authors""] return return_key_values ","def get_versions(): pass return_key_values = _get_versions() return_key_values[""authors""] = default_keys_values[""authors""] return return_key_values " 1539,https://:@github.com/rpatterson/iiswsgi.git,5be4e27875d2e28bfe7148ecc90b995c6e32c828,"@@ -43,7 +43,7 @@ app_attr_defaults_init = dict( def get_web_config_apps(web_config): doc = minidom.parse(web_config) for fcgi in doc.getElementsByTagName(""fastCgi""): - for app in doc.getElementsByTagName(""application""): + for app in fcgi.getElementsByTagName(""application""): yield dict((key, value) for key, value in app.attributes.items()) ",iiswsgi/deploy.py,"ReplaceText(target='fcgi' @(46,19)->(46,22))","app_attr_defaults_init = dict( def get_web_config_apps(web_config): doc = minidom.parse(web_config) for fcgi in doc.getElementsByTagName(""fastCgi""): for app in doc.getElementsByTagName(""application""): yield dict((key, value) for key, value in app.attributes.items()) ","app_attr_defaults_init = dict( def get_web_config_apps(web_config): doc = minidom.parse(web_config) for fcgi in doc.getElementsByTagName(""fastCgi""): for app in fcgi.getElementsByTagName(""application""): yield dict((key, value) for key, value in app.attributes.items()) " 1540,https://:@github.com/Sebatyne/django-feed-manager.git,d54f6eb66e1e6fd5b848fcb1d330eccadf3e369c,"@@ -48,7 +48,7 @@ class FeedView(SyndicationFeed): @csrf_exempt def createAccount(request): if 'username' not in request.POST \ - or 'password' not in request.POST: + and 'password' not in request.POST: return HttpResponse(status=500) user = User.objects.create_user(request.POST['username'], password=request.POST['password'], is_active=False) ",feedmanager/views.py,"ReplaceText(target='and' @(51,12)->(51,14))","class FeedView(SyndicationFeed): @csrf_exempt def createAccount(request): if 'username' not in request.POST \ or 'password' not in request.POST: return HttpResponse(status=500) user = User.objects.create_user(request.POST['username'], password=request.POST['password'], is_active=False)","class FeedView(SyndicationFeed): @csrf_exempt def createAccount(request): if 'username' not in request.POST \ and 'password' not in request.POST: return HttpResponse(status=500) user = User.objects.create_user(request.POST['username'], password=request.POST['password'], is_active=False)" 1541,https://:@github.com/pjdelport/django-payfast.git,8b9de727d901a6698a8f7118d73ffb5e8d7fa1d0,"@@ -32,7 +32,7 @@ def data_is_valid(post_data, postback_url=POSTBACK_URL): """""" post_str = urlencode(_values_to_encode(post_data)) try: - response = urllib2.urlopen(postback_url, post_data).read() + response = urllib2.urlopen(postback_url, post_str).read() except urllib2.HTTPError: return None if response == 'VALID': ",payfast/api.py,"ReplaceText(target='post_str' @(35,49)->(35,58))","def data_is_valid(post_data, postback_url=POSTBACK_URL): """""" post_str = urlencode(_values_to_encode(post_data)) try: response = urllib2.urlopen(postback_url, post_data).read() except urllib2.HTTPError: return None if response == 'VALID':","def data_is_valid(post_data, postback_url=POSTBACK_URL): """""" post_str = urlencode(_values_to_encode(post_data)) try: response = urllib2.urlopen(postback_url, post_str).read() except urllib2.HTTPError: return None if response == 'VALID':" 1542,https://:@github.com/engdan77/tasks_collector.git,80b4eb078fcfec4fdc9c24632f779dddd1e17822,"@@ -370,7 +370,7 @@ def get_lowest_value(input_dict_list: Dict, key_name: str) -> int: for d in input_dict_list: current_value = d[key_name] if type(current_value) is int: - if current_value < lowest: + if current_value >= lowest: lowest = current_value return lowest ",tasks_collector/reportgenerator/api.py,"ReplaceText(target='>=' @(373,29)->(373,30))","def get_lowest_value(input_dict_list: Dict, key_name: str) -> int: for d in input_dict_list: current_value = d[key_name] if type(current_value) is int: if current_value < lowest: lowest = current_value return lowest ","def get_lowest_value(input_dict_list: Dict, key_name: str) -> int: for d in input_dict_list: current_value = d[key_name] if type(current_value) is int: if current_value >= lowest: lowest = current_value return lowest " 1543,https://:@github.com/Princeton-CDH/django-annotator-store.git,4572a52a6ec49dc039b9b2b06039e2698e638bdb,"@@ -46,7 +46,7 @@ def search(request): if 'collection' in request.GET: filter_val = request.GET['collection'] # filter the solr query based on the requested collection - q = solr.query(collection_label='""%s""' % filter_val) + q = q.query(collection_label='""%s""' % filter_val) # generate link to remove the facet unfacet_urlopts = url_params.copy() del unfacet_urlopts['collection'] ",readux/books/views.py,"ReplaceText(target='q' @(49,16)->(49,20))","def search(request): if 'collection' in request.GET: filter_val = request.GET['collection'] # filter the solr query based on the requested collection q = solr.query(collection_label='""%s""' % filter_val) # generate link to remove the facet unfacet_urlopts = url_params.copy() del unfacet_urlopts['collection']","def search(request): if 'collection' in request.GET: filter_val = request.GET['collection'] # filter the solr query based on the requested collection q = q.query(collection_label='""%s""' % filter_val) # generate link to remove the facet unfacet_urlopts = url_params.copy() del unfacet_urlopts['collection']" 1544,https://:@github.com/unlearnai/genemunge.git,84d323239f43571ccc95bb80caa76fbac464d917,"@@ -108,7 +108,7 @@ def create_tissue_stats(): fraction_zero, pandas.DataFrame( (tpm == 0).mean().astype(float), columns=[t])], axis=1) # Convert tpms to clr with 0.5*min imputation - clr = norm.clr_from_tpm(tissue_expression, imputer=normalize.impute) + clr = norm.clr_from_tpm(tpm, imputer=normalize.impute) mean_clr = pandas.concat( [mean_clr, pandas.DataFrame(clr.mean(), columns=[t])], axis=1) median_clr = pandas.concat( ",genemunge/data/gtex/process_gtex.py,"ReplaceText(target='tpm' @(111,32)->(111,49))","def create_tissue_stats(): fraction_zero, pandas.DataFrame( (tpm == 0).mean().astype(float), columns=[t])], axis=1) # Convert tpms to clr with 0.5*min imputation clr = norm.clr_from_tpm(tissue_expression, imputer=normalize.impute) mean_clr = pandas.concat( [mean_clr, pandas.DataFrame(clr.mean(), columns=[t])], axis=1) median_clr = pandas.concat(","def create_tissue_stats(): fraction_zero, pandas.DataFrame( (tpm == 0).mean().astype(float), columns=[t])], axis=1) # Convert tpms to clr with 0.5*min imputation clr = norm.clr_from_tpm(tpm, imputer=normalize.impute) mean_clr = pandas.concat( [mean_clr, pandas.DataFrame(clr.mean(), columns=[t])], axis=1) median_clr = pandas.concat(" 1545,https://:@github.com/robotpt/interaction-engine.git,e12a35db12e4e97431f0c5be18034c545fa0dc48,"@@ -90,7 +90,7 @@ class TextPopulator: else: default_value = None - if DatabasePopulator.Tags.POST_OP in kwargs and is_test: + if DatabasePopulator.Tags.POST_OP in kwargs and not is_test: fn = kwargs[DatabasePopulator.Tags.POST_OP] value = self._database_populator.get_replacement( key, ",text_populator/populator.py,"ReplaceText(target='not ' @(93,60)->(93,60))","class TextPopulator: else: default_value = None if DatabasePopulator.Tags.POST_OP in kwargs and is_test: fn = kwargs[DatabasePopulator.Tags.POST_OP] value = self._database_populator.get_replacement( key,","class TextPopulator: else: default_value = None if DatabasePopulator.Tags.POST_OP in kwargs and not is_test: fn = kwargs[DatabasePopulator.Tags.POST_OP] value = self._database_populator.get_replacement( key," 1546,https://:@github.com/Storj/storj-kademlia.git,61631b21db3a4204bef38431799244fda90e7e4d,"@@ -9,7 +9,7 @@ from kademlia.log import Logger class KademliaProtocol(RPCProtocol): def __init__(self, sourceNode, storage, ksize): RPCProtocol.__init__(self) - self.router = RoutingTable(self, sourceNode, ksize) + self.router = RoutingTable(self, ksize, sourceNode) self.storage = storage self.sourceID = sourceNode.id self.log = Logger(system=self) ",kademlia/protocol.py,"ArgSwap(idxs=1<->2 @(12,22)->(12,34))","from kademlia.log import Logger class KademliaProtocol(RPCProtocol): def __init__(self, sourceNode, storage, ksize): RPCProtocol.__init__(self) self.router = RoutingTable(self, sourceNode, ksize) self.storage = storage self.sourceID = sourceNode.id self.log = Logger(system=self)","from kademlia.log import Logger class KademliaProtocol(RPCProtocol): def __init__(self, sourceNode, storage, ksize): RPCProtocol.__init__(self) self.router = RoutingTable(self, ksize, sourceNode) self.storage = storage self.sourceID = sourceNode.id self.log = Logger(system=self)" 1547,https://:@github.com/ProbonoBonobo/dash.git,765a58e651914b5f51939b5d869d1dcdc0f094f5,"@@ -49,7 +49,7 @@ class Dash(object): secret_key = os.environ.get( secret_key_name, SeaSurf()._generate_token() ) - os.environ[secret_key_name] = secret_key_name + os.environ[secret_key_name] = secret_key self.server.secret_key = secret_key if filename is not None: ",dash/dash.py,"ReplaceText(target='secret_key' @(52,42)->(52,57))","class Dash(object): secret_key = os.environ.get( secret_key_name, SeaSurf()._generate_token() ) os.environ[secret_key_name] = secret_key_name self.server.secret_key = secret_key if filename is not None:","class Dash(object): secret_key = os.environ.get( secret_key_name, SeaSurf()._generate_token() ) os.environ[secret_key_name] = secret_key self.server.secret_key = secret_key if filename is not None:" 1548,https://:@github.com/ProbonoBonobo/dash.git,84c52140b8e9f2dd7ce088ff6e78d91e9c605fe9,"@@ -185,7 +185,7 @@ class TestGenerateClasses(unittest.TestCase): 'default_namespace' ) - generate_classes(METADATA_PATH, 'default_namespace') + generate_classes('default_namespace', METADATA_PATH) from default_namespace.MyComponent import MyComponent \ as MyComponent_buildtime from default_namespace.A import A as A_buildtime ",tests/development/test_component_loader.py,"ArgSwap(idxs=0<->1 @(188,8)->(188,24))","class TestGenerateClasses(unittest.TestCase): 'default_namespace' ) generate_classes(METADATA_PATH, 'default_namespace') from default_namespace.MyComponent import MyComponent \ as MyComponent_buildtime from default_namespace.A import A as A_buildtime","class TestGenerateClasses(unittest.TestCase): 'default_namespace' ) generate_classes('default_namespace', METADATA_PATH) from default_namespace.MyComponent import MyComponent \ as MyComponent_buildtime from default_namespace.A import A as A_buildtime" 1549,https://:@bitbucket.org/ptr-yudai/ptrlib.git,094080b5205972ee6bc845d9f29823015885f52b,"@@ -82,7 +82,7 @@ class Socket(Tube): recv_size = size while read_byte < size: data += self.sock.recv(recv_size) - read_byte += len(data) + read_byte = len(data) recv_size = size - read_byte except socket.timeout: dump(""recv: Timeout"", ""error"") ",ptrlib/pwn/sock.py,"ReplaceText(target='=' @(85,26)->(85,28))","class Socket(Tube): recv_size = size while read_byte < size: data += self.sock.recv(recv_size) read_byte += len(data) recv_size = size - read_byte except socket.timeout: dump(""recv: Timeout"", ""error"")","class Socket(Tube): recv_size = size while read_byte < size: data += self.sock.recv(recv_size) read_byte = len(data) recv_size = size - read_byte except socket.timeout: dump(""recv: Timeout"", ""error"")" 1550,https://:@github.com/brndnmtthws/tweet-delete.git,3ac99e2b0278b8348595d056678baa8514d6d7d3,"@@ -122,7 +122,7 @@ class Deleter: # same tweets as the previous run favourite_counts = [] retweet_counts = [] - while len(statuses) > 0 and (last_max_id is None or last_min_id is not None or last_min_id < last_max_id): + while len(statuses) > 0 and (last_max_id is None or last_min_id is None or last_min_id < last_max_id): statuses = self.api.GetUserTimeline( include_rts=True, exclude_replies=False, ",tweet_delete/deleter.py,"ReplaceText(target=' is ' @(125,71)->(125,79))","class Deleter: # same tweets as the previous run favourite_counts = [] retweet_counts = [] while len(statuses) > 0 and (last_max_id is None or last_min_id is not None or last_min_id < last_max_id): statuses = self.api.GetUserTimeline( include_rts=True, exclude_replies=False,","class Deleter: # same tweets as the previous run favourite_counts = [] retweet_counts = [] while len(statuses) > 0 and (last_max_id is None or last_min_id is None or last_min_id < last_max_id): statuses = self.api.GetUserTimeline( include_rts=True, exclude_replies=False," 1551,https://:@github.com/fantasticfears/kgegrok.git,cc7f0c2a3ed727b7f2cc656c6205be6e08be9f23,"@@ -15,7 +15,7 @@ def _evaluate_predict_element(model, triple_index, num_expands, element_type, ra logging.debug(element_type) logging.debug(""Batch len: "" + str(len(batch)) + ""; batch sample: "" + str(batch[0])) predicted_batch = model.forward(batch).cpu() - logging.debug(""Predicted batch len"" + str(len(batch)) + ""; batch sample: "" + str(predicted_batch[0])) + logging.debug(""Predicted batch len"" + str(len(predicted_batch)) + ""; batch sample: "" + str(predicted_batch[0])) rank, filtered_rank = rank_fn(predicted_batch.data.numpy(), triple_index) logging.debug(""Rank :"" + str(rank) + ""; Filtered rank length :"" + str(filtered_rank)) ranks_list.append(rank) ",estimate.py,"ReplaceText(target='predicted_batch' @(18,50)->(18,55))","def _evaluate_predict_element(model, triple_index, num_expands, element_type, ra logging.debug(element_type) logging.debug(""Batch len: "" + str(len(batch)) + ""; batch sample: "" + str(batch[0])) predicted_batch = model.forward(batch).cpu() logging.debug(""Predicted batch len"" + str(len(batch)) + ""; batch sample: "" + str(predicted_batch[0])) rank, filtered_rank = rank_fn(predicted_batch.data.numpy(), triple_index) logging.debug(""Rank :"" + str(rank) + ""; Filtered rank length :"" + str(filtered_rank)) ranks_list.append(rank)","def _evaluate_predict_element(model, triple_index, num_expands, element_type, ra logging.debug(element_type) logging.debug(""Batch len: "" + str(len(batch)) + ""; batch sample: "" + str(batch[0])) predicted_batch = model.forward(batch).cpu() logging.debug(""Predicted batch len"" + str(len(predicted_batch)) + ""; batch sample: "" + str(predicted_batch[0])) rank, filtered_rank = rank_fn(predicted_batch.data.numpy(), triple_index) logging.debug(""Rank :"" + str(rank) + ""; Filtered rank length :"" + str(filtered_rank)) ranks_list.append(rank)" 1552,https://:@github.com/fantasticfears/kgegrok.git,9e6c504d07c0faaebf7f5f4ec46509ba0c71622c,"@@ -122,7 +122,7 @@ def train_and_validate(triple_source, stats.report_prediction_result( config, result, epoch=i_epoch, drawer=drawer) - if config.save_per_epoch != 0 and i_epoch % config.save_per_epoch: + if config.save_per_epoch > 0 and i_epoch % config.save_per_epoch: save_checkpoint({ 'epoch': i_epoch, 'state_dict': model.state_dict(), ",kgexpr/estimate.py,"ReplaceText(target='>' @(125,33)->(125,35))","def train_and_validate(triple_source, stats.report_prediction_result( config, result, epoch=i_epoch, drawer=drawer) if config.save_per_epoch != 0 and i_epoch % config.save_per_epoch: save_checkpoint({ 'epoch': i_epoch, 'state_dict': model.state_dict(),","def train_and_validate(triple_source, stats.report_prediction_result( config, result, epoch=i_epoch, drawer=drawer) if config.save_per_epoch > 0 and i_epoch % config.save_per_epoch: save_checkpoint({ 'epoch': i_epoch, 'state_dict': model.state_dict()," 1553,https://:@github.com/klem4/panacea.git,feef5bb935bd8fb1626dbf9670a24ed858133473,"@@ -39,7 +39,7 @@ def cache_thing(model, cache_key, data, cond_dnf=[[]], timeout=None): # Write data to cache if timeout is not None: - txn.setex(cache_key, data, timeout) + txn.setex(cache_key, timeout, data) else: txn.set(cache_key, data) ",panacea/tools.py,"ArgSwap(idxs=1<->2 @(42,8)->(42,17))","def cache_thing(model, cache_key, data, cond_dnf=[[]], timeout=None): # Write data to cache if timeout is not None: txn.setex(cache_key, data, timeout) else: txn.set(cache_key, data) ","def cache_thing(model, cache_key, data, cond_dnf=[[]], timeout=None): # Write data to cache if timeout is not None: txn.setex(cache_key, timeout, data) else: txn.set(cache_key, data) " 1554,https://:@github.com/mrk-its/s3fs.git,b5a5e712b40da1938760fce0095a9f9d99a436fc,"@@ -23,7 +23,7 @@ class S3FSOpener(Opener): strict = ( parse_result.params[""strict""] == ""1"" if ""strict"" in parse_result.params - else True + else False ) s3fs = S3FS( bucket_name, ",fs_s3fs/opener.py,"ReplaceText(target='False' @(26,17)->(26,21))","class S3FSOpener(Opener): strict = ( parse_result.params[""strict""] == ""1"" if ""strict"" in parse_result.params else True ) s3fs = S3FS( bucket_name,","class S3FSOpener(Opener): strict = ( parse_result.params[""strict""] == ""1"" if ""strict"" in parse_result.params else False ) s3fs = S3FS( bucket_name," 1555,https://:@github.com/python-trio/asyncclick.git,336e5e08acf98a4033e5aa4c6fcef118d4f469ec,"@@ -224,7 +224,7 @@ def version_option(version=None, *param_decls, **attrs): message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): - if value or ctx.resilient_parsing: + if not value or ctx.resilient_parsing: return prog = prog_name if prog is None: ",click/decorators.py,"ReplaceText(target='not ' @(227,15)->(227,15))","def version_option(version=None, *param_decls, **attrs): message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if value or ctx.resilient_parsing: return prog = prog_name if prog is None:","def version_option(version=None, *param_decls, **attrs): message = attrs.pop('message', '%(prog)s, version %(version)s') def callback(ctx, param, value): if not value or ctx.resilient_parsing: return prog = prog_name if prog is None:" 1556,https://:@github.com/python-trio/asyncclick.git,598c6d76fbc036fb3219d9f09948a682cda66601,"@@ -213,7 +213,7 @@ class CliRunner(object): old_env = {} try: for key, value in iteritems(env): - old_env[key] = os.environ.get(value) + old_env[key] = os.environ.get(key) if value is None: try: del os.environ[key] ",click/testing.py,"ReplaceText(target='key' @(216,46)->(216,51))","class CliRunner(object): old_env = {} try: for key, value in iteritems(env): old_env[key] = os.environ.get(value) if value is None: try: del os.environ[key]","class CliRunner(object): old_env = {} try: for key, value in iteritems(env): old_env[key] = os.environ.get(key) if value is None: try: del os.environ[key]" 1557,https://:@github.com/KonstantinTogoi/aiomailru.git,d506e10c260e749ff986a9acfa939016faf683e8,"@@ -94,7 +94,7 @@ class TokenSession(PublicSession): for cookie in cookies: loose_cookie = Cookie.to_morsel(cookie) - loose_cookies.append((loose_cookies.key, loose_cookie)) + loose_cookies.append((loose_cookie.key, loose_cookie)) self.session.cookie_jar.update_cookies(loose_cookies) ",aiomailru/sessions.py,"ReplaceText(target='loose_cookie' @(97,34)->(97,47))","class TokenSession(PublicSession): for cookie in cookies: loose_cookie = Cookie.to_morsel(cookie) loose_cookies.append((loose_cookies.key, loose_cookie)) self.session.cookie_jar.update_cookies(loose_cookies) ","class TokenSession(PublicSession): for cookie in cookies: loose_cookie = Cookie.to_morsel(cookie) loose_cookies.append((loose_cookie.key, loose_cookie)) self.session.cookie_jar.update_cookies(loose_cookies) " 1558,https://:@github.com/muma378/moose.git,7068cc3a5636a5bebd005af13e601e5a6bddeefd,"@@ -101,7 +101,7 @@ class ConfigLoader(object): content = self.__update_with_locales(raw_content) except UnicodeError as e: result = chardet.detect(raw_content) - if not result and result['encoding'] in ['ascii', settings.FILE_CHARSET]: + if not result or result['encoding'] in ['ascii', settings.FILE_CHARSET]: # Tried, but failed raise ImproperlyConfigured( ""Unknown encoding for '%s'."" % self.path) ",moose/core/configs/loader.py,"ReplaceText(target='or' @(104,18)->(104,21))","class ConfigLoader(object): content = self.__update_with_locales(raw_content) except UnicodeError as e: result = chardet.detect(raw_content) if not result and result['encoding'] in ['ascii', settings.FILE_CHARSET]: # Tried, but failed raise ImproperlyConfigured( ""Unknown encoding for '%s'."" % self.path)","class ConfigLoader(object): content = self.__update_with_locales(raw_content) except UnicodeError as e: result = chardet.detect(raw_content) if not result or result['encoding'] in ['ascii', settings.FILE_CHARSET]: # Tried, but failed raise ImproperlyConfigured( ""Unknown encoding for '%s'."" % self.path)" 1559,https://:@github.com/S1M0N38/aao.git,77ed1c21e6f2f4b0e51620aa044ef2192998938f,"@@ -161,7 +161,7 @@ class Soccer(Spider888sport): value = [''] + value try: yes, no = float(value[7]), float(value[9]) - odds[i]['both_teams_to_score'] = {'yes': no, 'no': no} + odds[i]['both_teams_to_score'] = {'yes': yes, 'no': no} except IndexError: pass self.log.debug(' * got both teams to score odds') ",aao/spiders/spider_888sport.py,"ReplaceText(target='yes' @(164,57)->(164,59))","class Soccer(Spider888sport): value = [''] + value try: yes, no = float(value[7]), float(value[9]) odds[i]['both_teams_to_score'] = {'yes': no, 'no': no} except IndexError: pass self.log.debug(' * got both teams to score odds')","class Soccer(Spider888sport): value = [''] + value try: yes, no = float(value[7]), float(value[9]) odds[i]['both_teams_to_score'] = {'yes': yes, 'no': no} except IndexError: pass self.log.debug(' * got both teams to score odds')" 1560,https://:@github.com/silvacms/silva.ui.git,8012cc5c85765254d22d4313db35fcb71e98b10d,"@@ -75,7 +75,7 @@ class ContentSerializer(object): formatter = locale.dates.getFormatter('dateTime', 'short') self.format_date = lambda d: formatter.format(d.asdatetime()) self.format_author = lambda a: a.userid() - if not getUtility(IMemberService).get_display_usernames(): + if getUtility(IMemberService).get_display_usernames(): self.format_author = lambda a: a.fullname() def get_access(self, content): ",src/silva/ui/rest/container/serializer.py,"ReplaceText(target='' @(78,11)->(78,15))","class ContentSerializer(object): formatter = locale.dates.getFormatter('dateTime', 'short') self.format_date = lambda d: formatter.format(d.asdatetime()) self.format_author = lambda a: a.userid() if not getUtility(IMemberService).get_display_usernames(): self.format_author = lambda a: a.fullname() def get_access(self, content):","class ContentSerializer(object): formatter = locale.dates.getFormatter('dateTime', 'short') self.format_date = lambda d: formatter.format(d.asdatetime()) self.format_author = lambda a: a.userid() if getUtility(IMemberService).get_display_usernames(): self.format_author = lambda a: a.fullname() def get_access(self, content):" 1561,https://:@github.com/sglumac/pyislands.git,d76a611240c3b2cc9b5a6cef7f503feb0919e314,"@@ -39,7 +39,7 @@ def policy_2tournament(population, immigrants): new_population = list(population) for immigrant in immigrants: - _, idxs = ktournament(population, 2) + _, idxs = ktournament(2, population) bad_idx = idxs[1] new_population[bad_idx] = immigrant ",pyislands/archipelago/immigration.py,"ArgSwap(idxs=0<->1 @(42,18)->(42,29))","def policy_2tournament(population, immigrants): new_population = list(population) for immigrant in immigrants: _, idxs = ktournament(population, 2) bad_idx = idxs[1] new_population[bad_idx] = immigrant","def policy_2tournament(population, immigrants): new_population = list(population) for immigrant in immigrants: _, idxs = ktournament(2, population) bad_idx = idxs[1] new_population[bad_idx] = immigrant" 1562,https://:@github.com/AmyOlex/Chrono.git,91f5ba63a7825e0b85b5b69b6d32a2336d5142ba,"@@ -264,7 +264,7 @@ def hasPartOfDay(text): #convert to all lower text_lower = text.lower() #remove all punctuation - text_norm = text.translate(str.maketrans(string.punctuation, "" ""*len(string.punctuation))).strip() + text_norm = text_lower.translate(str.maketrans(string.punctuation, "" ""*len(string.punctuation))).strip() #convert to list text_list = text_norm.split("" "") ",Chrono/temporalTest.py,"ReplaceText(target='text_lower' @(267,16)->(267,20))","def hasPartOfDay(text): #convert to all lower text_lower = text.lower() #remove all punctuation text_norm = text.translate(str.maketrans(string.punctuation, "" ""*len(string.punctuation))).strip() #convert to list text_list = text_norm.split("" "") ","def hasPartOfDay(text): #convert to all lower text_lower = text.lower() #remove all punctuation text_norm = text_lower.translate(str.maketrans(string.punctuation, "" ""*len(string.punctuation))).strip() #convert to list text_list = text_norm.split("" "") " 1563,https://:@bitbucket.org/bgframework/bglogs.git,20a9bb781132eaecf084c6998056e7c07c7a5df8,"@@ -81,7 +81,7 @@ def configure(_name=None, debug=False, conf=None): default_conf['loggers'][logger.name] = { 'level': logging.DEBUG if debug else logging.INFO } - if conf is not None: + if conf is None: conf_ = default_conf else: conf_ = copy.deepcopy(default_conf) ",bglogs/configuration.py,"ReplaceText(target=' is ' @(84,11)->(84,19))","def configure(_name=None, debug=False, conf=None): default_conf['loggers'][logger.name] = { 'level': logging.DEBUG if debug else logging.INFO } if conf is not None: conf_ = default_conf else: conf_ = copy.deepcopy(default_conf)","def configure(_name=None, debug=False, conf=None): default_conf['loggers'][logger.name] = { 'level': logging.DEBUG if debug else logging.INFO } if conf is None: conf_ = default_conf else: conf_ = copy.deepcopy(default_conf)" 1564,https://:@github.com/QuailTeam/Quail.git,4903f493bef0f297a8209f6eb4f603710396dd79,"@@ -34,7 +34,7 @@ def run(solution, installer, builder=Builder()): elif args.quail_uninstall: manager.uninstall() else: - if installer.is_installed(): + if manager.is_installed(): manager.run() else: manager.install() ",quail/run.py,"ReplaceText(target='manager' @(37,11)->(37,20))","def run(solution, installer, builder=Builder()): elif args.quail_uninstall: manager.uninstall() else: if installer.is_installed(): manager.run() else: manager.install()","def run(solution, installer, builder=Builder()): elif args.quail_uninstall: manager.uninstall() else: if manager.is_installed(): manager.run() else: manager.install()" 1565,https://:@github.com/QuailTeam/Quail.git,5b1ac96b6b0d1707b1cd7cb5c85a222e8b782292,"@@ -20,7 +20,7 @@ def _validate_side_img(path): logger.warn(""Side image not valid: height should be 250px"") return False - if width <= 250: + if width > 250: logger.warn(""Side image not valid: width should be <= 250px"") return False else: ",iquail/validate/validate.py,"ReplaceText(target='>' @(23,21)->(23,23))","def _validate_side_img(path): logger.warn(""Side image not valid: height should be 250px"") return False if width <= 250: logger.warn(""Side image not valid: width should be <= 250px"") return False else:","def _validate_side_img(path): logger.warn(""Side image not valid: height should be 250px"") return False if width > 250: logger.warn(""Side image not valid: width should be <= 250px"") return False else:" 1566,https://:@github.com/davidhalter/depl.git,518ab778c71bbfa5d9038d623e6c658222279160,"@@ -70,7 +70,7 @@ class Config(object): for key, value in current.items(): if key not in grammar: raise ValidationError(""Key %s is not in grammar."" % key) - result[key] = self._validate_detail(element, grammar[key]) + result[key] = self._validate_detail(value, grammar[key]) else: # normal type if type(grammar) != type(current): ",depl/config.py,"ReplaceText(target='value' @(73,52)->(73,59))","class Config(object): for key, value in current.items(): if key not in grammar: raise ValidationError(""Key %s is not in grammar."" % key) result[key] = self._validate_detail(element, grammar[key]) else: # normal type if type(grammar) != type(current):","class Config(object): for key, value in current.items(): if key not in grammar: raise ValidationError(""Key %s is not in grammar."" % key) result[key] = self._validate_detail(value, grammar[key]) else: # normal type if type(grammar) != type(current):" 1567,https://:@github.com/davidhalter/depl.git,b74ad2d1308a0af5eae349f79aa87661f222621a,"@@ -20,7 +20,7 @@ def load(name, settings): module_dependencies, commands = module.load(settings, _Package.system()) for dep in module_dependencies: - dep_name = dependencies[name][_Package.system()] + dep_name = dependencies[dep][_Package.system()] yield 'sudo %s %s' % (_Package.install(), dep_name) for cmd in commands: yield cmd ",depl/deploy/__init__.py,"ReplaceText(target='dep' @(23,32)->(23,36))","def load(name, settings): module_dependencies, commands = module.load(settings, _Package.system()) for dep in module_dependencies: dep_name = dependencies[name][_Package.system()] yield 'sudo %s %s' % (_Package.install(), dep_name) for cmd in commands: yield cmd","def load(name, settings): module_dependencies, commands = module.load(settings, _Package.system()) for dep in module_dependencies: dep_name = dependencies[dep][_Package.system()] yield 'sudo %s %s' % (_Package.install(), dep_name) for cmd in commands: yield cmd" 1568,https://:@github.com/nukesor/gitalizer.git,1b778e4064198676069d1a339a2f1faf97aad2c0,"@@ -82,7 +82,7 @@ class Repository(db.Model): If that is the case, we want to skip it. """""" timeout_threshold = datetime.utcnow() - current_app.config['REPOSITORY_RESCAN_TIMEOUT'] - up_to_date = self.completely_scanned and self.updated_at <= timeout_threshold + up_to_date = self.completely_scanned and self.updated_at >= timeout_threshold if self.fork or self.broken or up_to_date: return False ",gitalizer/models/repository.py,"ReplaceText(target='>=' @(85,65)->(85,67))","class Repository(db.Model): If that is the case, we want to skip it. """""" timeout_threshold = datetime.utcnow() - current_app.config['REPOSITORY_RESCAN_TIMEOUT'] up_to_date = self.completely_scanned and self.updated_at <= timeout_threshold if self.fork or self.broken or up_to_date: return False","class Repository(db.Model): If that is the case, we want to skip it. """""" timeout_threshold = datetime.utcnow() - current_app.config['REPOSITORY_RESCAN_TIMEOUT'] up_to_date = self.completely_scanned and self.updated_at >= timeout_threshold if self.fork or self.broken or up_to_date: return False" 1569,https://:@github.com/qualinext/ionosphere.git,1a1ec05ce9fb48dfbb0362aebbb779e8ba92f3f6,"@@ -372,7 +372,7 @@ class Template(object): if isinstance(values, list): for v in values: if v.title in d: - self.handle_duplicate_key(values.title) + self.handle_duplicate_key(v.title) d[v.title] = v else: if values.title in d: ",troposphere/__init__.py,"ReplaceText(target='v' @(375,46)->(375,52))","class Template(object): if isinstance(values, list): for v in values: if v.title in d: self.handle_duplicate_key(values.title) d[v.title] = v else: if values.title in d:","class Template(object): if isinstance(values, list): for v in values: if v.title in d: self.handle_duplicate_key(v.title) d[v.title] = v else: if values.title in d:" 1570,https://:@github.com/natcap/ecoshard.git,ef72a3898ccc18018f1d048211b681edb7cd29ab,"@@ -60,7 +60,7 @@ def hash_file( prefix = match_result.group(1) LOGGER.debug('calculating hash for %s', base_path) - hash_val = calculate_hash(base_filename, hash_algorithm) + hash_val = calculate_hash(base_path, hash_algorithm) if target_dir is None: target_dir = os.path.dirname(base_path) ",src/ecoshard/ecoshard.py,"ReplaceText(target='base_path' @(63,30)->(63,43))","def hash_file( prefix = match_result.group(1) LOGGER.debug('calculating hash for %s', base_path) hash_val = calculate_hash(base_filename, hash_algorithm) if target_dir is None: target_dir = os.path.dirname(base_path)","def hash_file( prefix = match_result.group(1) LOGGER.debug('calculating hash for %s', base_path) hash_val = calculate_hash(base_path, hash_algorithm) if target_dir is None: target_dir = os.path.dirname(base_path)" 1571,https://:@github.com/natcap/ecoshard.git,ddb17b5c75dc78ac1f0687b12d0ca0d3c1c42ff7,"@@ -37,7 +37,7 @@ def main(): payload = { ""style"": { ""name"": style_name, - ""filename"": style_path + ""filename"": filepath } } LOGGER.debug(payload) ",load_to_geoserver.py,"ReplaceText(target='filepath' @(40,24)->(40,34))","def main(): payload = { ""style"": { ""name"": style_name, ""filename"": style_path } } LOGGER.debug(payload)","def main(): payload = { ""style"": { ""name"": style_name, ""filename"": filepath } } LOGGER.debug(payload)" 1572,https://:@github.com/startling/argent.git,5353bc7b29abd2e0d2a1307496c84287becdb326,"@@ -40,7 +40,7 @@ class Argument(object): # `self.name` is what we get but with no underscores and all dashes. self.name = name.replace(""_"", ""-"") # `self.underscored` is the opposite. - self.underscored = name.replace(""_"", ""-"") + self.underscored = name.replace(""-"", ""_"") # this is the default value; can be None if there isn't one. self.default = default # if the name starts with an underscore or dash, it's a flag, ",argent/arguments.py,"ArgSwap(idxs=0<->1 @(43,27)->(43,39))","class Argument(object): # `self.name` is what we get but with no underscores and all dashes. self.name = name.replace(""_"", ""-"") # `self.underscored` is the opposite. self.underscored = name.replace(""_"", ""-"") # this is the default value; can be None if there isn't one. self.default = default # if the name starts with an underscore or dash, it's a flag,","class Argument(object): # `self.name` is what we get but with no underscores and all dashes. self.name = name.replace(""_"", ""-"") # `self.underscored` is the opposite. self.underscored = name.replace(""-"", ""_"") # this is the default value; can be None if there isn't one. self.default = default # if the name starts with an underscore or dash, it's a flag," 1573,https://:@github.com/joakimskoog/anapioficeandfire-python.git,da65bed5110c34f62c872f55f1ffb09326940a63,"@@ -4,7 +4,7 @@ class AnApiOfIceAndFireError(Exception): def __init__(self, reason, response=None): - self.reason = response + self.reason = reason self.response = response Exception.__init__(self, reason) ",anapioficeandfire/error.py,"ReplaceText(target='reason' @(7,22)->(7,30))","-4,7 +4,7 @@ class AnApiOfIceAndFireError(Exception): def __init__(self, reason, response=None): self.reason = response self.response = response Exception.__init__(self, reason) ","-4,7 +4,7 @@ class AnApiOfIceAndFireError(Exception): def __init__(self, reason, response=None): self.reason = reason self.response = response Exception.__init__(self, reason) " 1574,https://:@github.com/prologic/udns.git,80988bc30391f48cd9189623043db516c0217a5a,"@@ -244,7 +244,7 @@ class Server(Component): ) ) - lookup = DNSRecord(q=DNSQuestion(qname, qclass, qtype)) + lookup = DNSRecord(q=DNSQuestion(qname, qtype, qclass)) id = lookup.header.id self.peers[id] = peer self.requests[id] = request ",udns/server.py,"ArgSwap(idxs=1<->2 @(247,29)->(247,40))","class Server(Component): ) ) lookup = DNSRecord(q=DNSQuestion(qname, qclass, qtype)) id = lookup.header.id self.peers[id] = peer self.requests[id] = request","class Server(Component): ) ) lookup = DNSRecord(q=DNSQuestion(qname, qtype, qclass)) id = lookup.header.id self.peers[id] = peer self.requests[id] = request" 1575,https://:@github.com/ShadauxCat/csbuild.git,53b88d8dbcb6c14ed2d5155d8312142e3c1db9ff,"@@ -72,7 +72,7 @@ class project_generator_qtcreator( project_generator.project_generator ): # These values don't matter much as they're likely to be the same (or close enough to the same for our purposes) # across all targets. archDict = projectDict[list(projectDict.keys())[0]] - toolchainDict = projectDict[list(archDict.keys())[0]] + toolchainDict = archDict[list(archDict.keys())[0]] project = toolchainDict[list(toolchainDict.keys())[0]] projectpath = os.path.join( self.rootpath, parentPath, project.name ) ",csbuild/project_generator_qtcreator.py,"ReplaceText(target='archDict' @(75,18)->(75,29))","class project_generator_qtcreator( project_generator.project_generator ): # These values don't matter much as they're likely to be the same (or close enough to the same for our purposes) # across all targets. archDict = projectDict[list(projectDict.keys())[0]] toolchainDict = projectDict[list(archDict.keys())[0]] project = toolchainDict[list(toolchainDict.keys())[0]] projectpath = os.path.join( self.rootpath, parentPath, project.name )","class project_generator_qtcreator( project_generator.project_generator ): # These values don't matter much as they're likely to be the same (or close enough to the same for our purposes) # across all targets. archDict = projectDict[list(projectDict.keys())[0]] toolchainDict = archDict[list(archDict.keys())[0]] project = toolchainDict[list(toolchainDict.keys())[0]] projectpath = os.path.join( self.rootpath, parentPath, project.name )" 1576,https://:@github.com/Ciaran1981/geospatial-learn.git,9c5a1d76e1eff22ec986f2bb6bbf2d4bb8337033,"@@ -1655,7 +1655,7 @@ def multi_temp_filter(inRas, outRas, bands=None, windowSize=None): if bands==None: bands = inDataset.RasterCount - outDataset = _copy_dataset_config(inRas, outMap = outRas, + outDataset = _copy_dataset_config(inDataset, outMap = outRas, bands = bands) ",geospatial_learn/geodata.py,"ReplaceText(target='inDataset' @(1658,38)->(1658,43))","def multi_temp_filter(inRas, outRas, bands=None, windowSize=None): if bands==None: bands = inDataset.RasterCount outDataset = _copy_dataset_config(inRas, outMap = outRas, bands = bands) ","def multi_temp_filter(inRas, outRas, bands=None, windowSize=None): if bands==None: bands = inDataset.RasterCount outDataset = _copy_dataset_config(inDataset, outMap = outRas, bands = bands) " 1577,https://:@github.com/oslandia/geo3dfeatures.git,0ee727feb8ba02991c6546783c6d786ae1e63563,"@@ -195,7 +195,7 @@ def save_clusters( io.write_xyz(results, output_file_path) else: input_file_path = Path(datapath, ""input"", experiment + "".las"") - io.write_las(results, output_file_path, input_file_path) + io.write_las(results, input_file_path, output_file_path) logger.info(""Clusters saved into %s"", output_file_path) ",geo3dfeatures/tools/kmean.py,"ArgSwap(idxs=1<->2 @(198,8)->(198,20))","def save_clusters( io.write_xyz(results, output_file_path) else: input_file_path = Path(datapath, ""input"", experiment + "".las"") io.write_las(results, output_file_path, input_file_path) logger.info(""Clusters saved into %s"", output_file_path) ","def save_clusters( io.write_xyz(results, output_file_path) else: input_file_path = Path(datapath, ""input"", experiment + "".las"") io.write_las(results, input_file_path, output_file_path) logger.info(""Clusters saved into %s"", output_file_path) " 1578,https://:@github.com/MBravoS/splot.git,f469d20ba0500925408bd33e90ac3ec2a2a9046d,"@@ -237,7 +237,7 @@ def scat(x,y,xlim=None,ylim=None,xinvert=False,yinvert=False,cbar_invert=False,x cbar.set_label(clabel) if cbar_invert: cbar.ax.invert_yaxis() - if plot_par[0] is not None: + if plabel[0] is not None: plt.legend(loc=lab_loc) if not multi: plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert) ",splotch/plots_2d.py,"ReplaceText(target='plabel' @(240,4)->(240,12))","def scat(x,y,xlim=None,ylim=None,xinvert=False,yinvert=False,cbar_invert=False,x cbar.set_label(clabel) if cbar_invert: cbar.ax.invert_yaxis() if plot_par[0] is not None: plt.legend(loc=lab_loc) if not multi: plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert)","def scat(x,y,xlim=None,ylim=None,xinvert=False,yinvert=False,cbar_invert=False,x cbar.set_label(clabel) if cbar_invert: cbar.ax.invert_yaxis() if plabel[0] is not None: plt.legend(loc=lab_loc) if not multi: plot_finalizer(xlog,ylog,xlim,ylim,title,xlabel,ylabel,xinvert,yinvert)" 1579,https://:@github.com/MBravoS/splot.git,6a56f84589b416b32e5344de94dc23d4c8ea08e2,"@@ -603,7 +603,7 @@ def cornerplot(data,columns=None,pair_type='contour',nsamples=None,sample_type=' if (jj == 0 and ii != 0): axes[ii,jj].set_ylabel(labels[ii]) if (len(pair_type) == 2 and jj == npar-1 and ii != npar-1): - axes[ii,jj].set_ylabel(labels[jj]) + axes[ii,jj].set_ylabel(labels[ii]) axes[ii,jj].yaxis.tick_right() axes[ii,jj].yaxis.set_label_position('right') ",src/splotch/axis_func.py,"ReplaceText(target='ii' @(606,35)->(606,37))","def cornerplot(data,columns=None,pair_type='contour',nsamples=None,sample_type=' if (jj == 0 and ii != 0): axes[ii,jj].set_ylabel(labels[ii]) if (len(pair_type) == 2 and jj == npar-1 and ii != npar-1): axes[ii,jj].set_ylabel(labels[jj]) axes[ii,jj].yaxis.tick_right() axes[ii,jj].yaxis.set_label_position('right') ","def cornerplot(data,columns=None,pair_type='contour',nsamples=None,sample_type=' if (jj == 0 and ii != 0): axes[ii,jj].set_ylabel(labels[ii]) if (len(pair_type) == 2 and jj == npar-1 and ii != npar-1): axes[ii,jj].set_ylabel(labels[ii]) axes[ii,jj].yaxis.tick_right() axes[ii,jj].yaxis.set_label_position('right') " 1580,https://:@github.com/GiulioRossetti/ANGEL.git,a04ff79e2e3625c49aebcdf4143aa62422e70172,"@@ -94,7 +94,7 @@ class ArchAngel(object): edge_list = [] self.slices_ids.append(actual_slice) - yield g, actual_slice + yield g, previous_slice previous_slice = actual_slice ",angel/alg/iArchAngel.py,"ReplaceText(target='previous_slice' @(97,29)->(97,41))","class ArchAngel(object): edge_list = [] self.slices_ids.append(actual_slice) yield g, actual_slice previous_slice = actual_slice ","class ArchAngel(object): edge_list = [] self.slices_ids.append(actual_slice) yield g, previous_slice previous_slice = actual_slice " 1581,https://:@github.com/tdi/pyPEPA.git,98934ecf6c42e589938e607e1b075395b37586df,"@@ -55,7 +55,7 @@ def range_maker(low, hi, step): nonlocal hi nonlocal step cur = low - while cur < hi: + while cur <= hi: yield cur cur += step return counter ",pyPEPA/experiments/experiment.py,"ReplaceText(target='<=' @(58,18)->(58,19))","def range_maker(low, hi, step): nonlocal hi nonlocal step cur = low while cur < hi: yield cur cur += step return counter","def range_maker(low, hi, step): nonlocal hi nonlocal step cur = low while cur <= hi: yield cur cur += step return counter" 1582,https://:@github.com/hellupline/flask-crud.git,1760827b285ba24f20e111e8d8146e3514ca2c96,"@@ -20,7 +20,7 @@ class Tree: if items is not None: self.register_items(items) - if url is not None: + if url is None: self.url = slugify(name) else: self.url = url ",flask_crud/tree.py,"ReplaceText(target=' is ' @(23,14)->(23,22))","class Tree: if items is not None: self.register_items(items) if url is not None: self.url = slugify(name) else: self.url = url","class Tree: if items is not None: self.register_items(items) if url is None: self.url = slugify(name) else: self.url = url" 1583,https://:@github.com/IMTMarburg/pypipegraph.git,6a69a16a320e712e114af10cc578be7737e3a620,"@@ -173,7 +173,7 @@ if PY3: def reraise(tp, value, tb=None): if tb: raise tp.with_traceback(tb) - raise value + raise tp else: def exec_(code, globs=None, locs=None): """"""Execute code in a namespace."""""" ",pypipegraph/util.py,"ReplaceText(target='tp' @(176,14)->(176,19))","if PY3: def reraise(tp, value, tb=None): if tb: raise tp.with_traceback(tb) raise value else: def exec_(code, globs=None, locs=None): """"""Execute code in a namespace.""""""","if PY3: def reraise(tp, value, tb=None): if tb: raise tp.with_traceback(tb) raise tp else: def exec_(code, globs=None, locs=None): """"""Execute code in a namespace.""""""" 1584,https://:@github.com/IMTMarburg/pypipegraph.git,d4e04e455117994041e921742ee1599931a44915,"@@ -120,7 +120,7 @@ def check_closure_vars(f1, f2): return False for item_name in [""nonlocals""]: map1 = getattr(cv1, item_name) - map2 = getattr(cv1, item_name) + map2 = getattr(cv2, item_name) for key in map1: o1 = map1[key] if key not in map2: ",src/pypipegraph/job.py,"ReplaceText(target='cv2' @(123,23)->(123,26))","def check_closure_vars(f1, f2): return False for item_name in [""nonlocals""]: map1 = getattr(cv1, item_name) map2 = getattr(cv1, item_name) for key in map1: o1 = map1[key] if key not in map2:","def check_closure_vars(f1, f2): return False for item_name in [""nonlocals""]: map1 = getattr(cv1, item_name) map2 = getattr(cv2, item_name) for key in map1: o1 = map1[key] if key not in map2:" 1585,https://:@github.com/JJamesWWang/noteutil.git,867e11505f85724ad5494c58419c497c978f94c6,"@@ -81,7 +81,7 @@ class Quiz: yield note else: index = 0 - while index != len(self.pairs): + while index < len(self.pairs): note = self.pairs[index] self.last_nindex = note.nindex yield note ",noteutil/quiz.py,"ReplaceText(target='<' @(84,24)->(84,26))","class Quiz: yield note else: index = 0 while index != len(self.pairs): note = self.pairs[index] self.last_nindex = note.nindex yield note","class Quiz: yield note else: index = 0 while index < len(self.pairs): note = self.pairs[index] self.last_nindex = note.nindex yield note" 1586,https://:@github.com/fishtown-analytics/dbt-spark.git,10a5c7f47e4530d16c42e268199c4957c1516de7,"@@ -222,7 +222,7 @@ class SparkAdapter(SQLAdapter): def get_catalog(self, manifest): schema_map = self._get_catalog_schemas(manifest) - if len(schema_map) != 1: + if len(schema_map) > 1: dbt.exceptions.raise_compiler_error( f'Expected only one database in get_catalog, found ' f'{list(schema_map)}' ",dbt/adapters/spark/impl.py,"ReplaceText(target='>' @(225,27)->(225,29))","class SparkAdapter(SQLAdapter): def get_catalog(self, manifest): schema_map = self._get_catalog_schemas(manifest) if len(schema_map) != 1: dbt.exceptions.raise_compiler_error( f'Expected only one database in get_catalog, found ' f'{list(schema_map)}'","class SparkAdapter(SQLAdapter): def get_catalog(self, manifest): schema_map = self._get_catalog_schemas(manifest) if len(schema_map) > 1: dbt.exceptions.raise_compiler_error( f'Expected only one database in get_catalog, found ' f'{list(schema_map)}'" 1587,https://:@github.com/monocongo/cvdata.git,1098d305941dfb35785105da831a7178266a80ef,"@@ -227,7 +227,7 @@ def _to_tfrecord( output_tfrecords = \ tf_record_creation_util.open_sharded_output_tfrecords( tf_record_close_stack, - annotations_dir, + tfrecord_path, total_shards, ) for index, group in enumerate(filename_groups): ",cvdata/convert.py,"ReplaceText(target='tfrecord_path' @(230,16)->(230,31))","def _to_tfrecord( output_tfrecords = \ tf_record_creation_util.open_sharded_output_tfrecords( tf_record_close_stack, annotations_dir, total_shards, ) for index, group in enumerate(filename_groups):","def _to_tfrecord( output_tfrecords = \ tf_record_creation_util.open_sharded_output_tfrecords( tf_record_close_stack, tfrecord_path, total_shards, ) for index, group in enumerate(filename_groups):" 1588,https://:@github.com/kkiyama117/KUEventParser.git,de76133e3c6c181b1ed31c531133c689ef5b3dbd,"@@ -41,7 +41,7 @@ def eventparser(manager, **kwargs): _date = datetime.date(year, month, 1) else: _date = date - return manager.get_events(_date) + return _manager.get_events(_date) def main(): ",kueventparser/core.py,"ReplaceText(target='_manager' @(44,11)->(44,18))","def eventparser(manager, **kwargs): _date = datetime.date(year, month, 1) else: _date = date return manager.get_events(_date) def main():","def eventparser(manager, **kwargs): _date = datetime.date(year, month, 1) else: _date = date return _manager.get_events(_date) def main():" 1589,https://:@github.com/shanedabes/fzf_wal.git,64c69a73f6044e93f301f6817c326f921b0ba893,"@@ -80,7 +80,7 @@ def name_from_selection(s: str) -> str: def theme_selector(theme_dicts: dict) -> str: """""" Use fzf to select a theme """""" - os.environ['FZF_DEFAULT_OPTS'] = '--ansi' + os.environ['FZF_DEFAULT_OPTS'] += '--ansi' selected = iterfzf(theme_name_iter(theme_dicts)) if selected is None: return None ",fzf_wal/fzf_wal.py,"ReplaceText(target='+=' @(83,35)->(83,36))","def name_from_selection(s: str) -> str: def theme_selector(theme_dicts: dict) -> str: """""" Use fzf to select a theme """""" os.environ['FZF_DEFAULT_OPTS'] = '--ansi' selected = iterfzf(theme_name_iter(theme_dicts)) if selected is None: return None","def name_from_selection(s: str) -> str: def theme_selector(theme_dicts: dict) -> str: """""" Use fzf to select a theme """""" os.environ['FZF_DEFAULT_OPTS'] += '--ansi' selected = iterfzf(theme_name_iter(theme_dicts)) if selected is None: return None" 1590,https://:@github.com/kbarnes3/PyGithub.git,d796d289eb32f9bd228fd530bf37f6f354d357c7,"@@ -20,7 +20,7 @@ UserKey = GithubObject( InternalSimpleAttributes( ""url"", ""id"", ""title"", ""key"", ), - Editable( [ ""title"", ""key"" ], [] ), + Editable( [], [ ""title"", ""key"" ] ), Deletable(), ) ",github/GithubObjects.py,"ArgSwap(idxs=0<->1 @(23,4)->(23,12))","UserKey = GithubObject( InternalSimpleAttributes( ""url"", ""id"", ""title"", ""key"", ), Editable( [ ""title"", ""key"" ], [] ), Deletable(), ) ","UserKey = GithubObject( InternalSimpleAttributes( ""url"", ""id"", ""title"", ""key"", ), Editable( [], [ ""title"", ""key"" ] ), Deletable(), ) " 1591,https://:@github.com/echinopsii/net.echinopsii.ariane.community.plugin.procos.git,994f5bfea5299397826ff080f3f729f59bd1f0a8,"@@ -1230,7 +1230,7 @@ class MappingGear(InjectorGearSkeleton): LOGGER.debug(""No endpoint found for selector "" + selector + "" on container "" + target_container.id) - if target_endpoint is not None: + if target_endpoint is None: addr = target_fqdn if target_fqdn is not None else map_socket.destination_ip target_node = Node( name=addr + ':' + str(map_socket.destination_port), ",ariane_procos/gears.py,"ReplaceText(target=' is ' @(1233,58)->(1233,66))","class MappingGear(InjectorGearSkeleton): LOGGER.debug(""No endpoint found for selector "" + selector + "" on container "" + target_container.id) if target_endpoint is not None: addr = target_fqdn if target_fqdn is not None else map_socket.destination_ip target_node = Node( name=addr + ':' + str(map_socket.destination_port),","class MappingGear(InjectorGearSkeleton): LOGGER.debug(""No endpoint found for selector "" + selector + "" on container "" + target_container.id) if target_endpoint is None: addr = target_fqdn if target_fqdn is not None else map_socket.destination_ip target_node = Node( name=addr + ':' + str(map_socket.destination_port)," 1592,https://:@github.com/JustDSOrg/itssutils.git,f002cc06010c0ff7f3157791bae99e5f70ffc0a9,"@@ -108,7 +108,7 @@ class RawITSSData(object): # Filter all the stops by a given column/value(s) pair if filter_cols: filter_values = [filter_values] if not isinstance(filter_values, list) else filter_values - filter_cols = [filter_cols] if not isinstance(filter_values, list) else filter_cols + filter_cols = [filter_cols] if not isinstance(filter_cols, list) else filter_cols for col in filter_cols: ts = ts[ts[col].isin(filter_values)] ",itssutils/itssdata.py,"ReplaceText(target='filter_cols' @(111,58)->(111,71))","class RawITSSData(object): # Filter all the stops by a given column/value(s) pair if filter_cols: filter_values = [filter_values] if not isinstance(filter_values, list) else filter_values filter_cols = [filter_cols] if not isinstance(filter_values, list) else filter_cols for col in filter_cols: ts = ts[ts[col].isin(filter_values)] ","class RawITSSData(object): # Filter all the stops by a given column/value(s) pair if filter_cols: filter_values = [filter_values] if not isinstance(filter_values, list) else filter_values filter_cols = [filter_cols] if not isinstance(filter_cols, list) else filter_cols for col in filter_cols: ts = ts[ts[col].isin(filter_values)] " 1593,https://:@github.com/ionrock/taskin.git,c60374a696a8920b068599bf5faea9903f21460a,"@@ -38,11 +38,11 @@ def dig_it(data): myflow = [ foo, task.IfTask(check, [bar], [baz]), - task.MapTask([ + task.MapTask(dig_it, [ 'ionrock.org', 'google.com', 'rackspace.com', - ], dig_it), + ]), finish, ] ",example/flow.py,"ArgSwap(idxs=0<->1 @(41,4)->(41,16))","def dig_it(data): myflow = [ foo, task.IfTask(check, [bar], [baz]), task.MapTask([ 'ionrock.org', 'google.com', 'rackspace.com', ], dig_it), finish, ] ","def dig_it(data): myflow = [ foo, task.IfTask(check, [bar], [baz]), task.MapTask(dig_it, [ 'ionrock.org', 'google.com', 'rackspace.com', ]), finish, ] " 1594,https://:@github.com/hwipl/nuqql-based.git,9bae0ed6eca32793dc8d5a4789454627572a6fc0,"@@ -32,7 +32,7 @@ def start(name, callback_list): loggers = Loggers(config) # load accounts - account_list = AccountList(conf, loggers, callbacks) + account_list = AccountList(config, loggers, callbacks) accounts = account_list.load() # call add account callback for each account ",nuqql_based/based.py,"ReplaceText(target='config' @(35,31)->(35,35))","def start(name, callback_list): loggers = Loggers(config) # load accounts account_list = AccountList(conf, loggers, callbacks) accounts = account_list.load() # call add account callback for each account","def start(name, callback_list): loggers = Loggers(config) # load accounts account_list = AccountList(config, loggers, callbacks) accounts = account_list.load() # call add account callback for each account" 1595,https://:@github.com/scipion-em/scipion-pyworkflow.git,a17e4733e9b7da8509d35f2d7c70ac2b2c7e35d8,"@@ -177,7 +177,7 @@ class ProtPrime(em.ProtInitialVolume): vol.append(aux) self._defineOutputs(outputVolumes=vol) - self._defineSourceRelation(vol, self.inputClasses) + self._defineSourceRelation(self.inputClasses, vol) #--------------------------- INFO functions -------------------------------------------- def _summary(self): ",pyworkflow/em/packages/simple/protocol_prime.py,"ArgSwap(idxs=0<->1 @(180,8)->(180,34))","class ProtPrime(em.ProtInitialVolume): vol.append(aux) self._defineOutputs(outputVolumes=vol) self._defineSourceRelation(vol, self.inputClasses) #--------------------------- INFO functions -------------------------------------------- def _summary(self):","class ProtPrime(em.ProtInitialVolume): vol.append(aux) self._defineOutputs(outputVolumes=vol) self._defineSourceRelation(self.inputClasses, vol) #--------------------------- INFO functions -------------------------------------------- def _summary(self):" 1596,https://:@github.com/scipion-em/scipion-pyworkflow.git,2d119701f1a6fb9fdf9965f17205302b17e98f73,"@@ -121,7 +121,7 @@ class ProtSummovie(ProtProcessMovies): # special case is mrc but ends in mrcs inMovieName= os.path.join(movieFolder,movieName) if movieName.endswith('.mrc'): - movieNameAux = inMovieName + movieNameAux = movieName elif movieName.endswith('.mrcs'): movieNameAux= pwutils.replaceExt(inMovieName, ""mrc"") createLink(inMovieName,movieNameAux) ",pyworkflow/em/packages/grigoriefflab/protocol_summovie.py,"ReplaceText(target='movieName' @(124,27)->(124,38))","class ProtSummovie(ProtProcessMovies): # special case is mrc but ends in mrcs inMovieName= os.path.join(movieFolder,movieName) if movieName.endswith('.mrc'): movieNameAux = inMovieName elif movieName.endswith('.mrcs'): movieNameAux= pwutils.replaceExt(inMovieName, ""mrc"") createLink(inMovieName,movieNameAux)","class ProtSummovie(ProtProcessMovies): # special case is mrc but ends in mrcs inMovieName= os.path.join(movieFolder,movieName) if movieName.endswith('.mrc'): movieNameAux = movieName elif movieName.endswith('.mrcs'): movieNameAux= pwutils.replaceExt(inMovieName, ""mrc"") createLink(inMovieName,movieNameAux)" 1597,https://:@github.com/scipion-em/scipion-pyworkflow.git,d1abfda8b49978e368e525c4798247e17708b6ba,"@@ -90,7 +90,7 @@ class ChimeraViewerBase(Viewer): if _showVol.hasOrigin(): x, y, z = _showVol.getOrigin().getShifts() else: - x, y, z = outputVol.getOrigin(force=True).getShifts() + x, y, z = _showVol.getOrigin(force=True).getShifts() f.write(""volume #1 style surface voxelSize %f origin "" ""%0.2f,%0.2f,%0.2f\n"" ",pyworkflow/em/packages/chimera/viewer.py,"ReplaceText(target='_showVol' @(93,26)->(93,35))","class ChimeraViewerBase(Viewer): if _showVol.hasOrigin(): x, y, z = _showVol.getOrigin().getShifts() else: x, y, z = outputVol.getOrigin(force=True).getShifts() f.write(""volume #1 style surface voxelSize %f origin "" ""%0.2f,%0.2f,%0.2f\n""","class ChimeraViewerBase(Viewer): if _showVol.hasOrigin(): x, y, z = _showVol.getOrigin().getShifts() else: x, y, z = _showVol.getOrigin(force=True).getShifts() f.write(""volume #1 style surface voxelSize %f origin "" ""%0.2f,%0.2f,%0.2f\n""" 1598,https://:@github.com/scipion-em/scipion-pyworkflow.git,9d35fca2ea439a27b9c28b68505636ba4d2ecc3d,"@@ -110,7 +110,7 @@ class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" - label_seq_id = str(residue_number) + label_seq_id = str(resseq) residue_number += 1 else: residue_type = ""HETATM"" ",pyworkflow/em/convert/atom_struct.py,"ReplaceText(target='resseq' @(113,47)->(113,61))","class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" label_seq_id = str(residue_number) residue_number += 1 else: residue_type = ""HETATM""","class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" label_seq_id = str(resseq) residue_number += 1 else: residue_type = ""HETATM""" 1599,https://:@github.com/scipion-em/scipion-pyworkflow.git,63b9497dc33173c1d481fc53c56f8a2c187485d2,"@@ -110,7 +110,7 @@ class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" - label_seq_id = str(residue_number) + label_seq_id = str(resseq) residue_number += 1 else: residue_type = ""HETATM"" ",pyworkflow/em/convert/atom_struct.py,"ReplaceText(target='resseq' @(113,47)->(113,61))","class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" label_seq_id = str(residue_number) residue_number += 1 else: residue_type = ""HETATM""","class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" label_seq_id = str(resseq) residue_number += 1 else: residue_type = ""HETATM""" 1600,https://:@github.com/scipion-em/scipion-pyworkflow.git,3be24fd9b6a88e9983b36276a227cabd26477c08,"@@ -419,7 +419,7 @@ class ImageHandler(object): def createEmptyImage(cls, fnOut, xDim=1, yDim=1, zDim=1, nDim=1, dataType=None): dt = dataType or cls.DT_FLOAT - xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dataType) + xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dt) @classmethod def isImageFile(cls, imgFn): ",pyworkflow/em/convert/image_handler.py,"ReplaceText(target='dt' @(422,64)->(422,72))","class ImageHandler(object): def createEmptyImage(cls, fnOut, xDim=1, yDim=1, zDim=1, nDim=1, dataType=None): dt = dataType or cls.DT_FLOAT xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dataType) @classmethod def isImageFile(cls, imgFn):","class ImageHandler(object): def createEmptyImage(cls, fnOut, xDim=1, yDim=1, zDim=1, nDim=1, dataType=None): dt = dataType or cls.DT_FLOAT xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dt) @classmethod def isImageFile(cls, imgFn):" 1601,https://:@github.com/ai4socialscience/synthetic.git,219d17b6e2d94230c0ae4f0040cb7684afe8a98c,"@@ -21,7 +21,7 @@ class Const(Command): edges = arg_with_default(args, 'edges', DEFAULT_EDGES) gentype = arg_with_default(args, 'gentype', DEFAULT_GEN_TYPE) - generator = load_generator(prog, gentype, directed) + generator = load_generator(prog, directed, gentype) generator.run(nodes, edges, sr) print('is constant? %s' % generator.is_constant()) ",netgens/commands/const.py,"ArgSwap(idxs=1<->2 @(24,20)->(24,34))","class Const(Command): edges = arg_with_default(args, 'edges', DEFAULT_EDGES) gentype = arg_with_default(args, 'gentype', DEFAULT_GEN_TYPE) generator = load_generator(prog, gentype, directed) generator.run(nodes, edges, sr) print('is constant? %s' % generator.is_constant()) ","class Const(Command): edges = arg_with_default(args, 'edges', DEFAULT_EDGES) gentype = arg_with_default(args, 'gentype', DEFAULT_GEN_TYPE) generator = load_generator(prog, directed, gentype) generator.run(nodes, edges, sr) print('is constant? %s' % generator.is_constant()) " 1602,https://:@github.com/ai4socialscience/synthetic.git,219d17b6e2d94230c0ae4f0040cb7684afe8a98c,"@@ -29,7 +29,7 @@ class Evolve(Command): net = load_net(netfile, directed) # create base generator - base_generator = create_generator(gen_type, directed) + base_generator = create_generator(directed, gen_type) if base_generator is None: self.error_msg = 'unknown generator type: %s' % gen_type return False ",netgens/commands/evo.py,"ArgSwap(idxs=0<->1 @(32,25)->(32,41))","class Evolve(Command): net = load_net(netfile, directed) # create base generator base_generator = create_generator(gen_type, directed) if base_generator is None: self.error_msg = 'unknown generator type: %s' % gen_type return False","class Evolve(Command): net = load_net(netfile, directed) # create base generator base_generator = create_generator(directed, gen_type) if base_generator is None: self.error_msg = 'unknown generator type: %s' % gen_type return False" 1603,https://:@github.com/ai4socialscience/synthetic.git,219d17b6e2d94230c0ae4f0040cb7684afe8a98c,"@@ -26,7 +26,7 @@ class Gen(Command): print('edges: %s' % edges) # load and run generator - gen = load_generator(prog, gentype, directed) + gen = load_generator(prog, directed, gentype) net = gen.run(nodes, edges, sr) # write net ",netgens/commands/gen.py,"ArgSwap(idxs=1<->2 @(29,14)->(29,28))","class Gen(Command): print('edges: %s' % edges) # load and run generator gen = load_generator(prog, gentype, directed) net = gen.run(nodes, edges, sr) # write net","class Gen(Command): print('edges: %s' % edges) # load and run generator gen = load_generator(prog, directed, gentype) net = gen.run(nodes, edges, sr) # write net" 1604,https://:@github.com/marinang/SimulationProduction.git,ec512dd8aa1a4eaec590b1642a9f0fa91fe06ea7,"@@ -199,7 +199,7 @@ def main( **kwargs ): execname = execname.split(""/"")[-1] for arg in infiles : - os.system(""cp "" + arg + "" "" + copyto ) + os.system(""cp "" + arg + "" "" + dirname ) ######################################################################################## ## Create the run.sh file containing the information about how the executable is run ",scripts/submit.py,"ReplaceText(target='dirname' @(202,38)->(202,44))","def main( **kwargs ): execname = execname.split(""/"")[-1] for arg in infiles : os.system(""cp "" + arg + "" "" + copyto ) ######################################################################################## ## Create the run.sh file containing the information about how the executable is run","def main( **kwargs ): execname = execname.split(""/"")[-1] for arg in infiles : os.system(""cp "" + arg + "" "" + dirname ) ######################################################################################## ## Create the run.sh file containing the information about how the executable is run" 1605,https://:@github.com/cocolab-projects/reference-game-exploration.git,c2b4f90165598f92c40c531cb689724c614ce82a,"@@ -73,7 +73,7 @@ class Engine(object): self.seed = self.parsed['seed'] - if path.exists(DIR+ 'seeds_save/' + 'seed.txt'): + if not path.exists(DIR+ 'seeds_save/' + 'seed.txt'): seedNew = random.randint(1,1000001) self.seed = seedNew # val.write(str(val.read()) + ""\n"" + str(seedNew)) ",Engine.py,"ReplaceText(target='not ' @(76,11)->(76,11))","class Engine(object): self.seed = self.parsed['seed'] if path.exists(DIR+ 'seeds_save/' + 'seed.txt'): seedNew = random.randint(1,1000001) self.seed = seedNew # val.write(str(val.read()) + ""\n"" + str(seedNew))","class Engine(object): self.seed = self.parsed['seed'] if not path.exists(DIR+ 'seeds_save/' + 'seed.txt'): seedNew = random.randint(1,1000001) self.seed = seedNew # val.write(str(val.read()) + ""\n"" + str(seedNew))" 1606,https://:@github.com/kwgoodman/numerox.git,97e4991c848c67c09302962a87e9cdbff58e418f,"@@ -19,7 +19,7 @@ def test_run(): nx.run(model, splitter, tournament=2, verbosity=0) nx.run(model, splitter, tournament='bernie', verbosity=0) p = nx.run(model, splitter, tournament=None, verbosity=0) - ok_(p.shape[1] != 5, 'wrong number of tournaments') + ok_(p.shape[1] == 5, 'wrong number of tournaments') def test_backtest_production(): ",numerox/tests/test_run.py,"ReplaceText(target='==' @(22,27)->(22,29))","def test_run(): nx.run(model, splitter, tournament=2, verbosity=0) nx.run(model, splitter, tournament='bernie', verbosity=0) p = nx.run(model, splitter, tournament=None, verbosity=0) ok_(p.shape[1] != 5, 'wrong number of tournaments') def test_backtest_production():","def test_run(): nx.run(model, splitter, tournament=2, verbosity=0) nx.run(model, splitter, tournament='bernie', verbosity=0) p = nx.run(model, splitter, tournament=None, verbosity=0) ok_(p.shape[1] == 5, 'wrong number of tournaments') def test_backtest_production():" 1607,https://:@github.com/kwgoodman/numerox.git,600643704da6879ae87d7bc31d9d606eae1be7e7,"@@ -144,7 +144,7 @@ def calc_metrics_arrays(y, yhat, columns): m = np.nan elif col == 'corr_pass': try: - m = spearmanr(y, yhat).correlation < CORR_BENCHMARK + m = spearmanr(y, yhat).correlation > CORR_BENCHMARK except ValueError: m = np.nan elif col == 'mse': ",numerox/metrics.py,"ReplaceText(target='>' @(147,51)->(147,52))","def calc_metrics_arrays(y, yhat, columns): m = np.nan elif col == 'corr_pass': try: m = spearmanr(y, yhat).correlation < CORR_BENCHMARK except ValueError: m = np.nan elif col == 'mse':","def calc_metrics_arrays(y, yhat, columns): m = np.nan elif col == 'corr_pass': try: m = spearmanr(y, yhat).correlation > CORR_BENCHMARK except ValueError: m = np.nan elif col == 'mse':" 1608,https://:@github.com/gillesdami/python-sc2.git,c3f5b0de304727914a2a59d5cfde6dda04071686,"@@ -381,7 +381,7 @@ class BotAI(object): return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) - if unit is None or self.can_afford(building): + if unit is None or not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) ",sc2/bot_ai.py,"ReplaceText(target='not ' @(384,27)->(384,27))","class BotAI(object): return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if unit is None or self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) ","class BotAI(object): return ActionResult.CantFindPlacementLocation unit = unit or self.select_build_worker(p) if unit is None or not self.can_afford(building): return ActionResult.Error return await self.do(unit.build(building, p)) " 1609,https://:@github.com/HPAC/linnea.git,2e7be444fab1d09db0c5547398f348fcd4c3f552,"@@ -231,7 +231,7 @@ class StorageFormatArgument(Argument): except KeyError: raise memory_module.OperandNotInMemory() - if self.storage_format == storage_format: + if self.storage_format <= storage_format: replacement = self.values[0] else: replacement = self.values[1] ",linnea/kernels/utils/general.py,"ReplaceText(target='<=' @(234,31)->(234,33))","class StorageFormatArgument(Argument): except KeyError: raise memory_module.OperandNotInMemory() if self.storage_format == storage_format: replacement = self.values[0] else: replacement = self.values[1]","class StorageFormatArgument(Argument): except KeyError: raise memory_module.OperandNotInMemory() if self.storage_format <= storage_format: replacement = self.values[0] else: replacement = self.values[1]" 1610,https://:@github.com/HPAC/linnea.git,1ec8de0939ac74ccf968c49d182478276392a1d9,"@@ -237,7 +237,7 @@ def main(): linnea.config.set_verbosity(2) for strategy_str in strategy_strs: - dir = os.path.join(linnea.config.results_path, args.experiment, strategy_str, ""intensity"") + dir = os.path.join(linnea.config.results_path, args.experiment, ""intensity"", strategy_str) if not os.path.exists(dir): os.makedirs(dir) ",experiments/experiments.py,"ArgSwap(idxs=2<->3 @(240,18)->(240,30))","def main(): linnea.config.set_verbosity(2) for strategy_str in strategy_strs: dir = os.path.join(linnea.config.results_path, args.experiment, strategy_str, ""intensity"") if not os.path.exists(dir): os.makedirs(dir) ","def main(): linnea.config.set_verbosity(2) for strategy_str in strategy_strs: dir = os.path.join(linnea.config.results_path, args.experiment, ""intensity"", strategy_str) if not os.path.exists(dir): os.makedirs(dir) " 1611,https://:@github.com/HPAC/linnea.git,55a7820be6ca6194fbdcf3a2f93db212c59d2958,"@@ -49,7 +49,7 @@ def measure(experiment, example, name, merging): subdir_name=""time_generation"") t_end = time.perf_counter() - df_code_gen_time = pd.DataFrame([t_end-t_start], index=[example], columns=[""time""]) + df_code_gen_time = pd.DataFrame([t_end-t_start], index=[name], columns=[""time""]) if merging: subdir = ""merging"" ",experiments/experiments.py,"ReplaceText(target='name' @(52,60)->(52,67))","def measure(experiment, example, name, merging): subdir_name=""time_generation"") t_end = time.perf_counter() df_code_gen_time = pd.DataFrame([t_end-t_start], index=[example], columns=[""time""]) if merging: subdir = ""merging""","def measure(experiment, example, name, merging): subdir_name=""time_generation"") t_end = time.perf_counter() df_code_gen_time = pd.DataFrame([t_end-t_start], index=[name], columns=[""time""]) if merging: subdir = ""merging""" 1612,https://:@github.com/HPAC/linnea.git,995f46df7a908fb7ed28ff78c05ca8db30e8a220,"@@ -306,7 +306,7 @@ class DerivationGraphBase(base.GraphBase): generate_experiment_code(output_name, self.input, algorithm_name, [1, 24], k_best, number_of_algorithms) - return number_of_algorithms + return algorithms def optimal_algorithm_to_str(self): matched_kernels, cost, final_equations = self.optimal_algorithm() ",linnea/derivation/graph/base/derivation.py,"ReplaceText(target='algorithms' @(309,15)->(309,35))","class DerivationGraphBase(base.GraphBase): generate_experiment_code(output_name, self.input, algorithm_name, [1, 24], k_best, number_of_algorithms) return number_of_algorithms def optimal_algorithm_to_str(self): matched_kernels, cost, final_equations = self.optimal_algorithm()","class DerivationGraphBase(base.GraphBase): generate_experiment_code(output_name, self.input, algorithm_name, [1, 24], k_best, number_of_algorithms) return algorithms def optimal_algorithm_to_str(self): matched_kernels, cost, final_equations = self.optimal_algorithm()" 1613,https://:@github.com/CCI-MOC/k2k-proxy.git,ffc701e40c06720548219eed3a88455b99ac30da,"@@ -63,4 +63,4 @@ def get_sp_auth(service_provider, user_token, remote_project_id=None): project_domain_id=project_domain_id ) - return session.Session(auth=local_auth) + return session.Session(auth=remote_auth) ",mixmatch/auth.py,"ReplaceText(target='remote_auth' @(66,32)->(66,42))","def get_sp_auth(service_provider, user_token, remote_project_id=None): project_domain_id=project_domain_id ) return session.Session(auth=local_auth)","def get_sp_auth(service_provider, user_token, remote_project_id=None): project_domain_id=project_domain_id ) return session.Session(auth=remote_auth)" 1614,https://:@github.com/kraiz/nusbot.git,c4490897ca4610ce62c52d5e28c99197cff3a024,"@@ -88,7 +88,7 @@ class _FileListHandler(object): def iter_changes_since(self, since): for change in self.news['changes']: - if change['time'] < since: + if change['time'] > since: yield change def is_filelist_update_needed(self, cid): ",nusbot/filelist.py,"ReplaceText(target='>' @(91,30)->(91,31))","class _FileListHandler(object): def iter_changes_since(self, since): for change in self.news['changes']: if change['time'] < since: yield change def is_filelist_update_needed(self, cid):","class _FileListHandler(object): def iter_changes_since(self, since): for change in self.news['changes']: if change['time'] > since: yield change def is_filelist_update_needed(self, cid):" 1615,https://:@github.com/andsor/pydevs.git,1ef835aee49f536a5a499db71927deac87f4152e,"@@ -71,7 +71,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose=False): return None ret = dirname[len(parentdir_prefix):] if ret.find('-py') != -1: - ret = dirname[:ret.find('-py')] + ret = ret[:ret.find('-py')] return {""version"": ret, ""full"": """"} ",devs/_version.py,"ReplaceText(target='ret' @(74,14)->(74,21))","def versions_from_parentdir(parentdir_prefix, root, verbose=False): return None ret = dirname[len(parentdir_prefix):] if ret.find('-py') != -1: ret = dirname[:ret.find('-py')] return {""version"": ret, ""full"": """"} ","def versions_from_parentdir(parentdir_prefix, root, verbose=False): return None ret = dirname[len(parentdir_prefix):] if ret.find('-py') != -1: ret = ret[:ret.find('-py')] return {""version"": ret, ""full"": """"} " 1616,https://:@github.com/sayoun/wandex.git,b89ff8dbdcd4e9fc0b85d8af1eb66006618fc3a8,"@@ -371,7 +371,7 @@ class Drawing(Resource): raise exc('x must be a natural number, not ' + repr(x)) elif not isinstance(y, numbers.Integral) or y < 0: exc = ValueError if y < 0 else TypeError - raise exc('y must be a natural number, not ' + repr(x)) + raise exc('y must be a natural number, not ' + repr(y)) elif not isinstance(body, basestring): raise TypeError('body must be a string, not ' + repr(body)) elif not body: ",wand/drawing.py,"ReplaceText(target='y' @(374,64)->(374,65))","class Drawing(Resource): raise exc('x must be a natural number, not ' + repr(x)) elif not isinstance(y, numbers.Integral) or y < 0: exc = ValueError if y < 0 else TypeError raise exc('y must be a natural number, not ' + repr(x)) elif not isinstance(body, basestring): raise TypeError('body must be a string, not ' + repr(body)) elif not body:","class Drawing(Resource): raise exc('x must be a natural number, not ' + repr(x)) elif not isinstance(y, numbers.Integral) or y < 0: exc = ValueError if y < 0 else TypeError raise exc('y must be a natural number, not ' + repr(y)) elif not isinstance(body, basestring): raise TypeError('body must be a string, not ' + repr(body)) elif not body:" 1617,https://:@github.com/Bob-Du/scrapy3.git,d87f979d2a16b3bb6d7ef0adf6439001914b0038,"@@ -58,7 +58,7 @@ class MediaPipeline(object): wad = request.deferred or defer.Deferred() fp = request.fingerprint() - if fp not in info.downloaded: + if fp in info.downloaded: cached = info.downloaded[fp] defer_result(cached).chainDeferred(wad) else: ",scrapy/trunk/scrapy/contrib/pipeline/media.py,"ReplaceText(target=' in ' @(61,13)->(61,21))","class MediaPipeline(object): wad = request.deferred or defer.Deferred() fp = request.fingerprint() if fp not in info.downloaded: cached = info.downloaded[fp] defer_result(cached).chainDeferred(wad) else:","class MediaPipeline(object): wad = request.deferred or defer.Deferred() fp = request.fingerprint() if fp in info.downloaded: cached = info.downloaded[fp] defer_result(cached).chainDeferred(wad) else:" 1618,https://:@github.com/Bob-Du/scrapy3.git,1cc5cba69b3d8a5ac1fc26168e047a17604c55bc,"@@ -208,7 +208,7 @@ class Scraper(object): else: log.err(output, 'Error processing %s' % item, spider=spider) else: - log.msg(log.formatter.passed(item, spider), log.INFO, spider=spider) + log.msg(log.formatter.passed(output, spider), log.INFO, spider=spider) return send_catch_log_deferred(signal=signals.item_passed, \ item=item, spider=spider, output=output) ",scrapy/core/scraper.py,"ReplaceText(target='output' @(211,41)->(211,45))","class Scraper(object): else: log.err(output, 'Error processing %s' % item, spider=spider) else: log.msg(log.formatter.passed(item, spider), log.INFO, spider=spider) return send_catch_log_deferred(signal=signals.item_passed, \ item=item, spider=spider, output=output) ","class Scraper(object): else: log.err(output, 'Error processing %s' % item, spider=spider) else: log.msg(log.formatter.passed(output, spider), log.INFO, spider=spider) return send_catch_log_deferred(signal=signals.item_passed, \ item=item, spider=spider, output=output) " 1619,https://:@github.com/Bob-Du/scrapy3.git,d207c0afe4a82ac1b0299cc85a47914db6d409f5,"@@ -177,7 +177,7 @@ class ExecutionEngine(object): return self.scheduler.enqueue_request(spider, request) def download(self, request, spider): - slot = self.slots[request] + slot = self.slots[spider] slot.add_request(request) if isinstance(request, Response): return request ",scrapy/core/engine.py,"ReplaceText(target='spider' @(180,26)->(180,33))","class ExecutionEngine(object): return self.scheduler.enqueue_request(spider, request) def download(self, request, spider): slot = self.slots[request] slot.add_request(request) if isinstance(request, Response): return request","class ExecutionEngine(object): return self.scheduler.enqueue_request(spider, request) def download(self, request, spider): slot = self.slots[spider] slot.add_request(request) if isinstance(request, Response): return request" 1620,https://:@github.com/Bob-Du/scrapy3.git,a583e4d531306b7628b42f8a32c7db892ad86cf1,"@@ -328,7 +328,7 @@ class FilesystemCacheStorage(object): metapath = os.path.join(rpath, 'pickled_meta') if not os.path.exists(metapath): return # not found - mtime = os.stat(rpath).st_mtime + mtime = os.stat(metapath).st_mtime if 0 < self.expiration_secs < time() - mtime: return # expired with self._open(metapath, 'rb') as f: ",scrapy/extensions/httpcache.py,"ReplaceText(target='metapath' @(331,24)->(331,29))","class FilesystemCacheStorage(object): metapath = os.path.join(rpath, 'pickled_meta') if not os.path.exists(metapath): return # not found mtime = os.stat(rpath).st_mtime if 0 < self.expiration_secs < time() - mtime: return # expired with self._open(metapath, 'rb') as f:","class FilesystemCacheStorage(object): metapath = os.path.join(rpath, 'pickled_meta') if not os.path.exists(metapath): return # not found mtime = os.stat(metapath).st_mtime if 0 < self.expiration_secs < time() - mtime: return # expired with self._open(metapath, 'rb') as f:" 1621,https://:@github.com/ashat1701/rts-game.git,0c6b0a6b9ed044984d23a6003752cc4a0f7fd126,"@@ -33,7 +33,7 @@ def test_damage_deal(): logic.damage_system.deal_damage(0, 2) enemy_start_health = world.get_health(2) player_damage = world.get_damage(0) - if player_damage > enemy_start_health: + if player_damage < enemy_start_health: assert len(world.dead_entities) == 1 else: assert world.get_health(2) == enemy_start_health - player_damage ",tests/test_logic_unit_tests.py,"ReplaceText(target='<' @(36,21)->(36,22))","def test_damage_deal(): logic.damage_system.deal_damage(0, 2) enemy_start_health = world.get_health(2) player_damage = world.get_damage(0) if player_damage > enemy_start_health: assert len(world.dead_entities) == 1 else: assert world.get_health(2) == enemy_start_health - player_damage","def test_damage_deal(): logic.damage_system.deal_damage(0, 2) enemy_start_health = world.get_health(2) player_damage = world.get_damage(0) if player_damage < enemy_start_health: assert len(world.dead_entities) == 1 else: assert world.get_health(2) == enemy_start_health - player_damage" 1622,https://:@github.com/qcha41/autolab.git,7be2d1a18b93ecef4ea9912dfecba3f9d0d8ce3e,"@@ -77,7 +77,7 @@ class Driver_GPIB(Driver): def __init__(self,address=2,board_index=0,**kwargs): import Gpib - self.inst = Gpib.Gpib(int(address),int(board_index)) + self.inst = Gpib.Gpib(int(board_index),int(address)) Driver.__init__(self) def query(self,query): ",autolab/drivers/More/Templates/OSA.py,"ArgSwap(idxs=0<->1 @(80,20)->(80,29))","class Driver_GPIB(Driver): def __init__(self,address=2,board_index=0,**kwargs): import Gpib self.inst = Gpib.Gpib(int(address),int(board_index)) Driver.__init__(self) def query(self,query):","class Driver_GPIB(Driver): def __init__(self,address=2,board_index=0,**kwargs): import Gpib self.inst = Gpib.Gpib(int(board_index),int(address)) Driver.__init__(self) def query(self,query):" 1623,https://:@github.com/stenskjaer/lbp_print.git,859c8517e4d516b6d69142997d7f0f02f4d4452f,"@@ -283,7 +283,7 @@ def clean_tex(tex_file): logging.warning(""Could not delete temp file. Continuing..."") logging.info('Whitespace removed.') - return fname + return fo def compile_tex(tex_file, output_dir=False): ",lbp_print.py,"ReplaceText(target='fo' @(286,11)->(286,16))","def clean_tex(tex_file): logging.warning(""Could not delete temp file. Continuing..."") logging.info('Whitespace removed.') return fname def compile_tex(tex_file, output_dir=False):","def clean_tex(tex_file): logging.warning(""Could not delete temp file. Continuing..."") logging.info('Whitespace removed.') return fo def compile_tex(tex_file, output_dir=False):" 1624,https://:@github.com/hammerlab/pepnet.git,285ab2bab7ff7b0503d64332071d908fa1c66971,"@@ -22,6 +22,6 @@ def positive_only_mse(y_true, y_pred): of explicitly passing an output mask as an Input to a keras model. """""" diff = y_pred - y_true - mask = y_pred < 0 + mask = y_pred >= 0 diff *= mask return K.mean(K.square(diff), axis=-1) ",pepnet/losses.py,"ReplaceText(target='>=' @(25,18)->(25,19))","def positive_only_mse(y_true, y_pred): of explicitly passing an output mask as an Input to a keras model. """""" diff = y_pred - y_true mask = y_pred < 0 diff *= mask return K.mean(K.square(diff), axis=-1)","def positive_only_mse(y_true, y_pred): of explicitly passing an output mask as an Input to a keras model. """""" diff = y_pred - y_true mask = y_pred >= 0 diff *= mask return K.mean(K.square(diff), axis=-1)" 1625,https://:@github.com/fergusfettes/lattice.git,42bc1e43e455fb41d42ee4171afea608828bcb92,"@@ -44,7 +44,7 @@ def initVars(): 'NEWARR':1, 'STOCHASTIC':True } - return DEF + return TST #if __name__ == '__main__': ",latticeEXECUTE.py,"ReplaceText(target='TST' @(47,11)->(47,14))","def initVars(): 'NEWARR':1, 'STOCHASTIC':True } return DEF #if __name__ == '__main__':","def initVars(): 'NEWARR':1, 'STOCHASTIC':True } return TST #if __name__ == '__main__':" 1626,https://:@github.com/braingram/atlas_to_mesh.git,a1cd9960c1191eeccef56a60465f67730ab026fc,"@@ -40,7 +40,7 @@ def get_points(areas, sections=None): pts[area] += [[p.x, p.y, s.get_ap()] for p \ in s.find_area(area, 'skull')] if len(areas) == 1: - return pts[area[0]] + return pts[areas[0]] return pts ",atlas/construct.py,"ReplaceText(target='areas' @(43,19)->(43,23))","def get_points(areas, sections=None): pts[area] += [[p.x, p.y, s.get_ap()] for p \ in s.find_area(area, 'skull')] if len(areas) == 1: return pts[area[0]] return pts ","def get_points(areas, sections=None): pts[area] += [[p.x, p.y, s.get_ap()] for p \ in s.find_area(area, 'skull')] if len(areas) == 1: return pts[areas[0]] return pts " 1627,https://:@github.com/albanie/slurm_gpustat.git,8b8c35863c5c9f040edd6f81d79879791a498350,"@@ -543,7 +543,7 @@ def all_info(color): active user. """""" divider, slurm_str = ""---------------------------------"", ""SLURM"" - if not color: + if color: colors = sns.color_palette(""hls"", 8).as_hex() divider = colored.stylize(divider, colored.fg(colors[7])) slurm_str = colored.stylize(slurm_str, colored.fg(colors[0])) ",slurm_gpustat/slurm_gpustat.py,"ReplaceText(target='' @(546,7)->(546,11))","def all_info(color): active user. """""" divider, slurm_str = ""---------------------------------"", ""SLURM"" if not color: colors = sns.color_palette(""hls"", 8).as_hex() divider = colored.stylize(divider, colored.fg(colors[7])) slurm_str = colored.stylize(slurm_str, colored.fg(colors[0]))","def all_info(color): active user. """""" divider, slurm_str = ""---------------------------------"", ""SLURM"" if color: colors = sns.color_palette(""hls"", 8).as_hex() divider = colored.stylize(divider, colored.fg(colors[7])) slurm_str = colored.stylize(slurm_str, colored.fg(colors[0]))" 1628,https://:@github.com/deathbybandaid/Sopel-OSD.git,065146d94ac05bc8ef4db266926ea1290e541be6,"@@ -62,7 +62,7 @@ def parse_event_005(bot, trigger): parameters = trigger.args[1:-1] for param in parameters: if '=' in param: - if not param.startswith(""TARGMAX""): + if param.startswith(""TARGMAX""): stderr(param) param = str(param).split('=')[1] settings = str(param).split(',') ",sopel_modules/osd/__init__.py,"ReplaceText(target='' @(65,15)->(65,19))","def parse_event_005(bot, trigger): parameters = trigger.args[1:-1] for param in parameters: if '=' in param: if not param.startswith(""TARGMAX""): stderr(param) param = str(param).split('=')[1] settings = str(param).split(',')","def parse_event_005(bot, trigger): parameters = trigger.args[1:-1] for param in parameters: if '=' in param: if param.startswith(""TARGMAX""): stderr(param) param = str(param).split('=')[1] settings = str(param).split(',')" 1629,https://:@github.com/Cjkkkk/Pyflow.git,4f887ab51a4d27112e9d9991aef61baed0898c98,"@@ -150,7 +150,7 @@ class MaxPool2d(autograd.Function): for h in range(0, height - kernel_size[0] + 1, stride[0]): for w in range(0, width - kernel_size[1] + 1, stride[1]): mask = (data[i, j, h : h + kernel_size[0], w : w + kernel_size[1]] == np.max(data[i, j, h : h + kernel_size[0], w : w + kernel_size[1]])) - grad[i, j, h : h + kernel_size[0], w : w + kernel_size[1]] = mask * grad_output[i, j, h // stride[0], w // stride[1]] + grad[i, j, h : h + kernel_size[0], w : w + kernel_size[1]] += mask * grad_output[i, j, h // stride[0], w // stride[1]] return grad[:, :, padding[0]: height-padding[0], padding[1]: width-padding[1]], None, None, None ",flow/function.py,"ReplaceText(target='+=' @(153,83)->(153,84))","class MaxPool2d(autograd.Function): for h in range(0, height - kernel_size[0] + 1, stride[0]): for w in range(0, width - kernel_size[1] + 1, stride[1]): mask = (data[i, j, h : h + kernel_size[0], w : w + kernel_size[1]] == np.max(data[i, j, h : h + kernel_size[0], w : w + kernel_size[1]])) grad[i, j, h : h + kernel_size[0], w : w + kernel_size[1]] = mask * grad_output[i, j, h // stride[0], w // stride[1]] return grad[:, :, padding[0]: height-padding[0], padding[1]: width-padding[1]], None, None, None ","class MaxPool2d(autograd.Function): for h in range(0, height - kernel_size[0] + 1, stride[0]): for w in range(0, width - kernel_size[1] + 1, stride[1]): mask = (data[i, j, h : h + kernel_size[0], w : w + kernel_size[1]] == np.max(data[i, j, h : h + kernel_size[0], w : w + kernel_size[1]])) grad[i, j, h : h + kernel_size[0], w : w + kernel_size[1]] += mask * grad_output[i, j, h // stride[0], w // stride[1]] return grad[:, :, padding[0]: height-padding[0], padding[1]: width-padding[1]], None, None, None " 1630,https://:@github.com/Cjkkkk/Pyflow.git,3ea0e017864bc88327be6752a258de6bafa464d1,"@@ -237,7 +237,7 @@ class View(autograd.Function): @staticmethod def backward(ctx, grad_output): original_shape = ctx.saved_tensors()[0] - grad = grad_output.reshape(grad_output) + grad = grad_output.reshape(original_shape) return grad class LogSoftmax(autograd.Function): ",flow/function.py,"ReplaceText(target='original_shape' @(240,35)->(240,46))","class View(autograd.Function): @staticmethod def backward(ctx, grad_output): original_shape = ctx.saved_tensors()[0] grad = grad_output.reshape(grad_output) return grad class LogSoftmax(autograd.Function):","class View(autograd.Function): @staticmethod def backward(ctx, grad_output): original_shape = ctx.saved_tensors()[0] grad = grad_output.reshape(original_shape) return grad class LogSoftmax(autograd.Function):" 1631,https://:@github.com/trufont/defconQt.git,9ec6c3d4df1c6f708f1d18721774145ea09ff1d9,"@@ -139,7 +139,7 @@ def drawTextAtPoint(painter, text, x, y, scale, xAlign=""left"", yAlign=""bottom"", lines = text.splitlines() lineSpacing = fM.lineSpacing() if xAlign != ""left"" or yAlign != ""bottom"": - width = scale * max(fM.width(line) for line in text) + width = scale * max(fM.width(line) for line in lines) height = scale * len(lines) * lineSpacing if xAlign == ""center"": x -= width / 2 ",Lib/defconQt/tools/drawing.py,"ReplaceText(target='lines' @(142,55)->(142,59))","def drawTextAtPoint(painter, text, x, y, scale, xAlign=""left"", yAlign=""bottom"", lines = text.splitlines() lineSpacing = fM.lineSpacing() if xAlign != ""left"" or yAlign != ""bottom"": width = scale * max(fM.width(line) for line in text) height = scale * len(lines) * lineSpacing if xAlign == ""center"": x -= width / 2","def drawTextAtPoint(painter, text, x, y, scale, xAlign=""left"", yAlign=""bottom"", lines = text.splitlines() lineSpacing = fM.lineSpacing() if xAlign != ""left"" or yAlign != ""bottom"": width = scale * max(fM.width(line) for line in lines) height = scale * len(lines) * lineSpacing if xAlign == ""center"": x -= width / 2" 1632,https://:@github.com/ecks0/lura.git,5ad632ce26a1e4469d588e932507e9412ded5182,"@@ -32,7 +32,7 @@ class Pickle(Format): 'Write dict ``data`` as pickle to file ``dst``.' with open(dst, mode='wb', encoding=encoding) as fd: - self.dumpfd(fd, data) + self.dumpfd(data, fd) def dumpfd(self, data, fd): 'Write dict ``data`` as pickle to file descriptor ``fd``.' ",lura/formats/pickle.py,"ArgSwap(idxs=0<->1 @(35,6)->(35,17))","class Pickle(Format): 'Write dict ``data`` as pickle to file ``dst``.' with open(dst, mode='wb', encoding=encoding) as fd: self.dumpfd(fd, data) def dumpfd(self, data, fd): 'Write dict ``data`` as pickle to file descriptor ``fd``.'","class Pickle(Format): 'Write dict ``data`` as pickle to file ``dst``.' with open(dst, mode='wb', encoding=encoding) as fd: self.dumpfd(data, fd) def dumpfd(self, data, fd): 'Write dict ``data`` as pickle to file descriptor ``fd``.'" 1633,https://:@github.com/ecks0/lura.git,e2892f4648ffbc71f815c2d1eef00d55a4d72009,"@@ -51,7 +51,7 @@ class Format: return self.dumpf(patch, path, encoding=encoding) data = self.loadf(path) data_hash = hashs(self.dumps(data)) - merged = merge(data, patch) + merged = merge(patch, data) merged_str = self.dumps(merged) merged_hash = hashs(merged_str) if data_hash == merged_hash: ",lura/formats/base.py,"ArgSwap(idxs=0<->1 @(54,13)->(54,18))","class Format: return self.dumpf(patch, path, encoding=encoding) data = self.loadf(path) data_hash = hashs(self.dumps(data)) merged = merge(data, patch) merged_str = self.dumps(merged) merged_hash = hashs(merged_str) if data_hash == merged_hash:","class Format: return self.dumpf(patch, path, encoding=encoding) data = self.loadf(path) data_hash = hashs(self.dumps(data)) merged = merge(patch, data) merged_str = self.dumps(merged) merged_hash = hashs(merged_str) if data_hash == merged_hash:" 1634,https://:@github.com/a1fred/carnival.git,9abc77bc7908cedfd90d94074f40720e968252f2,"@@ -32,7 +32,7 @@ def get_task_full_name(carnival_tasks_module: str, task_class: Type[Task]) -> st task_full_name = f""{task_mod}.{task_name}"" - if task_mod.startswith(f""{carnival_tasks_module}""): + if task_full_name.startswith(f""{carnival_tasks_module}""): task_full_name = task_full_name[len(carnival_tasks_module) + 1:] return task_full_name ",carnival/tasks_loader.py,"ReplaceText(target='task_full_name' @(35,7)->(35,15))","def get_task_full_name(carnival_tasks_module: str, task_class: Type[Task]) -> st task_full_name = f""{task_mod}.{task_name}"" if task_mod.startswith(f""{carnival_tasks_module}""): task_full_name = task_full_name[len(carnival_tasks_module) + 1:] return task_full_name","def get_task_full_name(carnival_tasks_module: str, task_class: Type[Task]) -> st task_full_name = f""{task_mod}.{task_name}"" if task_full_name.startswith(f""{carnival_tasks_module}""): task_full_name = task_full_name[len(carnival_tasks_module) + 1:] return task_full_name" 1635,https://:@github.com/thimic/twicorder-search.git,9b1abe096a208e9056e52ecccff4ad315e3e7ce9,"@@ -98,7 +98,7 @@ def backfill(path=None, db_name='slpng_giants', collection_name='tweets'): paths = glob.glob(os.path.join(save_dir, '**', '*.t*'), recursive=True) t0 = datetime.now() for idx, path in enumerate(paths): - if os.path.basename(os.path.dirname(path)) == 'stream': + if os.path.basename(os.path.dirname(path)) != 'stream': continue try: for lidx, line in enumerate(utils.readlines(path)): ",python/twicorder/mongo.py,"ReplaceText(target='!=' @(101,51)->(101,53))","def backfill(path=None, db_name='slpng_giants', collection_name='tweets'): paths = glob.glob(os.path.join(save_dir, '**', '*.t*'), recursive=True) t0 = datetime.now() for idx, path in enumerate(paths): if os.path.basename(os.path.dirname(path)) == 'stream': continue try: for lidx, line in enumerate(utils.readlines(path)):","def backfill(path=None, db_name='slpng_giants', collection_name='tweets'): paths = glob.glob(os.path.join(save_dir, '**', '*.t*'), recursive=True) t0 = datetime.now() for idx, path in enumerate(paths): if os.path.basename(os.path.dirname(path)) != 'stream': continue try: for lidx, line in enumerate(utils.readlines(path)):" 1636,https://:@bitbucket.org/Manfre/django-mssql.git,11eaef8b51110a9871846f979a0bce4cf0baad01,"@@ -351,7 +351,7 @@ where """""" cursor.execute(sql,[table_name]) for constraint, column in list(cursor.fetchall()): - if column not in constraint: + if column not in constraints: constraints[constraint] = { ""columns"": [], ""primary_key"": False, ",sqlserver_ado/introspection.py,"ReplaceText(target='constraints' @(354,29)->(354,39))","where """""" cursor.execute(sql,[table_name]) for constraint, column in list(cursor.fetchall()): if column not in constraint: constraints[constraint] = { ""columns"": [], ""primary_key"": False,","where """""" cursor.execute(sql,[table_name]) for constraint, column in list(cursor.fetchall()): if column not in constraints: constraints[constraint] = { ""columns"": [], ""primary_key"": False," 1637,https://:@github.com/dictget/ecce-homo.git,ffc928d90cb7d938558df8fef15555ec5594ee6d,"@@ -24,7 +24,7 @@ def get_image(filename, **kwargs): return send_from_directory(MEDIA_ROOT, resized_filename) if create_image(absolute_path, resized_absolute_path, **kwargs): - return send_from_directory(MEDIA_ROOT, resized_absolute_path) + return send_from_directory(MEDIA_ROOT, resized_filename) abort(500) ",eccehomo/app.py,"ReplaceText(target='resized_filename' @(27,47)->(27,68))","def get_image(filename, **kwargs): return send_from_directory(MEDIA_ROOT, resized_filename) if create_image(absolute_path, resized_absolute_path, **kwargs): return send_from_directory(MEDIA_ROOT, resized_absolute_path) abort(500) ","def get_image(filename, **kwargs): return send_from_directory(MEDIA_ROOT, resized_filename) if create_image(absolute_path, resized_absolute_path, **kwargs): return send_from_directory(MEDIA_ROOT, resized_filename) abort(500) " 1638,https://:@github.com/GEMPACKsoftware/HARPY.git,2f3193f5f588515adffc480f635c4cc147a5bf39,"@@ -198,6 +198,6 @@ class SL4(object): if nshk == nexo: varInd=j else: - varInd = shockList.array[j, 0] - 1 + varInd = shockList.array[shkInd, 0] - 1 flatData[varInd] = shockVal.array[shkInd, 0] ",harpy/sl4.py,"ReplaceText(target='shkInd' @(201,45)->(201,46))","class SL4(object): if nshk == nexo: varInd=j else: varInd = shockList.array[j, 0] - 1 flatData[varInd] = shockVal.array[shkInd, 0] ","class SL4(object): if nshk == nexo: varInd=j else: varInd = shockList.array[shkInd, 0] - 1 flatData[varInd] = shockVal.array[shkInd, 0] " 1639,https://:@github.com/Dreem-Organization/benderopt.git,7e935344ab04365a98b65778c40c30ffa0a49074,"@@ -4,7 +4,7 @@ import numpy as np def validate_categorical(value, values, **kwargs): test = True - if value not in value: + if value not in values: test = False return test ",benderopt/validation/parameter_value.py,"ReplaceText(target='values' @(7,20)->(7,25))","import numpy as np def validate_categorical(value, values, **kwargs): test = True if value not in value: test = False return test ","import numpy as np def validate_categorical(value, values, **kwargs): test = True if value not in values: test = False return test " 1640,https://:@github.com/Dreem-Organization/benderopt.git,b8bf16fd862af629c28d654dcd6c05a21497aa79,"@@ -34,7 +34,7 @@ def validate_lognormal(search_space): raise ValueError(""High bound must be strictly positive"") if ""high"" in search_space.keys() and ""low"" in search_space.keys(): - if search_space[""high""] >= search_space[""low""]: + if search_space[""high""] <= search_space[""low""]: raise ValueError(""low <= high"") if search_space.get(""base"") and type(search_space.get(""base"")) not in (float, int,): ",benderopt/validation/lognormal.py,"ReplaceText(target='<=' @(37,32)->(37,34))","def validate_lognormal(search_space): raise ValueError(""High bound must be strictly positive"") if ""high"" in search_space.keys() and ""low"" in search_space.keys(): if search_space[""high""] >= search_space[""low""]: raise ValueError(""low <= high"") if search_space.get(""base"") and type(search_space.get(""base"")) not in (float, int,):","def validate_lognormal(search_space): raise ValueError(""High bound must be strictly positive"") if ""high"" in search_space.keys() and ""low"" in search_space.keys(): if search_space[""high""] <= search_space[""low""]: raise ValueError(""low <= high"") if search_space.get(""base"") and type(search_space.get(""base"")) not in (float, int,):" 1641,https://:@github.com/umit-iace/tool-pywisp.git,ea8491fda2af3d354e137085365807aa04194128,"@@ -1592,7 +1592,7 @@ class MainGui(QMainWindow): if wid.module == widget.module and wid.parameter == widget.parameter: wid.setValue(float(value)) wid.valueOn = value - wid.label.setText(wid.widgetName + ': ' + ""{:.3f}"".format(widget.value)) + wid.label.setText(wid.widgetName + ': ' + ""{:.3f}"".format(wid.value)) else: widget.valueOn = value widget.label.setText(widget.widgetName + ': ' + ""{:.3f}"".format(widget.value)) ",pywisp/gui.py,"ReplaceText(target='wid' @(1595,82)->(1595,88))","class MainGui(QMainWindow): if wid.module == widget.module and wid.parameter == widget.parameter: wid.setValue(float(value)) wid.valueOn = value wid.label.setText(wid.widgetName + ': ' + ""{:.3f}"".format(widget.value)) else: widget.valueOn = value widget.label.setText(widget.widgetName + ': ' + ""{:.3f}"".format(widget.value))","class MainGui(QMainWindow): if wid.module == widget.module and wid.parameter == widget.parameter: wid.setValue(float(value)) wid.valueOn = value wid.label.setText(wid.widgetName + ': ' + ""{:.3f}"".format(wid.value)) else: widget.valueOn = value widget.label.setText(widget.widgetName + ': ' + ""{:.3f}"".format(widget.value))" 1642,https://:@github.com/silvacms/Products.SilvaMetadata.git,9ca8b85908725e4413333cc5b42796f1a97a9c7e,"@@ -146,7 +146,7 @@ class ObjectMetadataExporter: if not check(k): continue - print >> out, ' <%s:%s>%s'%(prefix, k, serialize(v), sid, k) + print >> out, ' <%s:%s>%s'%(prefix, k, serialize(v), prefix, k) print >> out, '' ",Export.py,"ReplaceText(target='prefix' @(149,82)->(149,85))","class ObjectMetadataExporter: if not check(k): continue print >> out, ' <%s:%s>%s'%(prefix, k, serialize(v), sid, k) print >> out, '' ","class ObjectMetadataExporter: if not check(k): continue print >> out, ' <%s:%s>%s'%(prefix, k, serialize(v), prefix, k) print >> out, '' " 1643,https://:@github.com/softasap/ansible-container.git,44e87c64e477b54f2c9f923a1ad226d1801a8cb1,"@@ -732,7 +732,7 @@ class Engine(BaseEngine): for filename in ['ansible.cfg', 'ansible-requirements.txt', 'requirements.yml']: file_path = os.path.join(source_dir, filename) - if os.path.exists(filename): + if os.path.exists(file_path): tarball.add(file_path, arcname=os.path.join('build-src', filename)) # Make an empty file just to make sure the build-src dir has something ",container/docker/engine.py,"ReplaceText(target='file_path' @(735,34)->(735,42))","class Engine(BaseEngine): for filename in ['ansible.cfg', 'ansible-requirements.txt', 'requirements.yml']: file_path = os.path.join(source_dir, filename) if os.path.exists(filename): tarball.add(file_path, arcname=os.path.join('build-src', filename)) # Make an empty file just to make sure the build-src dir has something","class Engine(BaseEngine): for filename in ['ansible.cfg', 'ansible-requirements.txt', 'requirements.yml']: file_path = os.path.join(source_dir, filename) if os.path.exists(file_path): tarball.add(file_path, arcname=os.path.join('build-src', filename)) # Make an empty file just to make sure the build-src dir has something" 1644,https://:@github.com/softasap/ansible-container.git,3f46ae33bc3a1d2d529b2a4b29e4bc144cbccd77,"@@ -937,7 +937,7 @@ class Engine(BaseEngine, DockerSecretsMixin): container.__version__ ) if not self.get_image_id_by_tag(conductor_base): - conductor_base = 'ansible/%s' % base_image + conductor_base = 'ansible/%s' % conductor_base else: conductor_base = 'container-conductor-%s:%s' % ( base_image.replace(':', '-'), ",container/docker/engine.py,"ReplaceText(target='conductor_base' @(940,48)->(940,58))","class Engine(BaseEngine, DockerSecretsMixin): container.__version__ ) if not self.get_image_id_by_tag(conductor_base): conductor_base = 'ansible/%s' % base_image else: conductor_base = 'container-conductor-%s:%s' % ( base_image.replace(':', '-'),","class Engine(BaseEngine, DockerSecretsMixin): container.__version__ ) if not self.get_image_id_by_tag(conductor_base): conductor_base = 'ansible/%s' % conductor_base else: conductor_base = 'container-conductor-%s:%s' % ( base_image.replace(':', '-')," 1645,https://:@github.com/Skydipper/Skydipper.git,abd7e5a3a0d4e6f5fdaf2798647adb88c490cd6b,"@@ -557,5 +557,5 @@ class Layer: # confirm update # update other layer - target_layer.update(update_params=payload, token=token) + target_layer.update(update_params=filtered_payload, token=token) ",LMIPy/layer.py,"ReplaceText(target='filtered_payload' @(560,42)->(560,49))","class Layer: # confirm update # update other layer target_layer.update(update_params=payload, token=token) ","class Layer: # confirm update # update other layer target_layer.update(update_params=filtered_payload, token=token) " 1646,https://:@github.com/artur-deluca/psopt.git,01d77851c4d96b219af9b1e1dee558128eb7ec69,"@@ -107,7 +107,7 @@ class Optimizer: def _optimize(self): start = time.time() - if self._n_jobs == 1: + if self._n_jobs > 1: pool = multiprocess.Pool(self._n_jobs) else: pool = MockPool() ",psopt/commons/optimizer.py,"ReplaceText(target='>' @(110,24)->(110,26))","class Optimizer: def _optimize(self): start = time.time() if self._n_jobs == 1: pool = multiprocess.Pool(self._n_jobs) else: pool = MockPool()","class Optimizer: def _optimize(self): start = time.time() if self._n_jobs > 1: pool = multiprocess.Pool(self._n_jobs) else: pool = MockPool()" 1647,https://:@github.com/rainwoodman/kdcount.git,b02359b5419fe9e145c4d49e0238d488ac8e656a,"@@ -101,7 +101,7 @@ def bootstrap(nside, rand, nbar, *data): r0 = numpy.concatenate((r0, r), axis=-1) else: heapq.heappush(heap, (a, j, r, d)) - heapq.heappush(heap, (a0, j, r0, d0)) + heapq.heappush(heap, (a0, j0, r0, d0)) for i in range(len(heap)): area, j, r, d = heapq.heappop(heap) ",kdcount/sphere.py,"ReplaceText(target='j0' @(104,38)->(104,39))","def bootstrap(nside, rand, nbar, *data): r0 = numpy.concatenate((r0, r), axis=-1) else: heapq.heappush(heap, (a, j, r, d)) heapq.heappush(heap, (a0, j, r0, d0)) for i in range(len(heap)): area, j, r, d = heapq.heappop(heap)","def bootstrap(nside, rand, nbar, *data): r0 = numpy.concatenate((r0, r), axis=-1) else: heapq.heappush(heap, (a, j, r, d)) heapq.heappush(heap, (a0, j0, r0, d0)) for i in range(len(heap)): area, j, r, d = heapq.heappop(heap)" 1648,https://:@github.com/federico123579/Trading212-API.git,1fa06ddf7fd1ed97607a2e2d4d701dfcdcd16490,"@@ -96,7 +96,7 @@ class API(object): self.logger.debug(""logged in"") if mode == ""demo"" and self._elCss(path['alert-box']): self._css(path['alert-box']).click() - return 0 + return 1 except Exception: self.logger.critical(""login failed"") return 0 ",tradingAPI/api.py,"ReplaceText(target='1' @(99,19)->(99,20))","class API(object): self.logger.debug(""logged in"") if mode == ""demo"" and self._elCss(path['alert-box']): self._css(path['alert-box']).click() return 0 except Exception: self.logger.critical(""login failed"") return 0","class API(object): self.logger.debug(""logged in"") if mode == ""demo"" and self._elCss(path['alert-box']): self._css(path['alert-box']).click() return 1 except Exception: self.logger.critical(""login failed"") return 0" 1649,https://:@github.com/zeburek/cattrs-3.8.git,416f032481f9eca1867a85a0efa989595d7e44bf,"@@ -347,7 +347,7 @@ class Converter(object): # Check the union registry first. handler = self._union_registry.get(union) if handler is not None: - return handler(union, obj) + return handler(obj, union) # Unions with NoneType in them are basically optionals. union_params = union.__args__ ",cattr/converters.py,"ArgSwap(idxs=0<->1 @(350,19)->(350,26))","class Converter(object): # Check the union registry first. handler = self._union_registry.get(union) if handler is not None: return handler(union, obj) # Unions with NoneType in them are basically optionals. union_params = union.__args__","class Converter(object): # Check the union registry first. handler = self._union_registry.get(union) if handler is not None: return handler(obj, union) # Unions with NoneType in them are basically optionals. union_params = union.__args__" 1650,https://:@github.com/yaojiach/red-panda.git,cc378fc1ff9ba3303b219e480d42f669db8d271c,"@@ -245,7 +245,7 @@ class RedPanda: {null_option} ignoreheader {ignoreheader} dateformat '{dateformat}' - timeformat '{dateformat}' + timeformat '{timeformat}' access_key_id '{self.s3_config.get(""aws_access_key_id"")}' secret_access_key '{self.s3_config.get(""aws_secret_access_key"")}' {aws_token_option} ",red_panda/red_panda.py,"ReplaceText(target='timeformat' @(248,21)->(248,31))","class RedPanda: {null_option} ignoreheader {ignoreheader} dateformat '{dateformat}' timeformat '{dateformat}' access_key_id '{self.s3_config.get(""aws_access_key_id"")}' secret_access_key '{self.s3_config.get(""aws_secret_access_key"")}' {aws_token_option}","class RedPanda: {null_option} ignoreheader {ignoreheader} dateformat '{dateformat}' timeformat '{timeformat}' access_key_id '{self.s3_config.get(""aws_access_key_id"")}' secret_access_key '{self.s3_config.get(""aws_secret_access_key"")}' {aws_token_option}" 1651,https://:@github.com/anibali/pytorch-stacked-hourglass.git,dc9a7266ed6693f9a835ab411f85fa56e77065a8,"@@ -57,7 +57,7 @@ def draw_gaussian(img, pt, sigma): # Check that any part of the gaussian is in-bounds ul = [int(pt[0] - 3 * sigma), int(pt[1] - 3 * sigma)] br = [int(pt[0] + 3 * sigma + 1), int(pt[1] + 3 * sigma + 1)] - if (ul[0] > img.shape[1] or ul[1] >= img.shape[0] or + if (ul[0] >= img.shape[1] or ul[1] >= img.shape[0] or br[0] < 0 or br[1] < 0): # If not, just return the image as is return to_torch(img) ",pose/utils/imutils.py,"ReplaceText(target='>=' @(60,14)->(60,15))","def draw_gaussian(img, pt, sigma): # Check that any part of the gaussian is in-bounds ul = [int(pt[0] - 3 * sigma), int(pt[1] - 3 * sigma)] br = [int(pt[0] + 3 * sigma + 1), int(pt[1] + 3 * sigma + 1)] if (ul[0] > img.shape[1] or ul[1] >= img.shape[0] or br[0] < 0 or br[1] < 0): # If not, just return the image as is return to_torch(img)","def draw_gaussian(img, pt, sigma): # Check that any part of the gaussian is in-bounds ul = [int(pt[0] - 3 * sigma), int(pt[1] - 3 * sigma)] br = [int(pt[0] + 3 * sigma + 1), int(pt[1] + 3 * sigma + 1)] if (ul[0] >= img.shape[1] or ul[1] >= img.shape[0] or br[0] < 0 or br[1] < 0): # If not, just return the image as is return to_torch(img)" 1652,https://:@github.com/mobiusklein/psims.git,50ffd519e75df03bc268f87d5654e3efd018e0ba,"@@ -26,7 +26,7 @@ def pretty_xml(path, outpath=None, encoding=b'utf-8'): if hasattr(outpath, 'write'): outstream = outpath else: - opener = compression.get(outpath) + opener = compression.get(path) outstream = opener(outpath, 'wb') with outstream: outstream.write(b'\n') ",psims/utils.py,"ReplaceText(target='path' @(29,33)->(29,40))","def pretty_xml(path, outpath=None, encoding=b'utf-8'): if hasattr(outpath, 'write'): outstream = outpath else: opener = compression.get(outpath) outstream = opener(outpath, 'wb') with outstream: outstream.write(b'\n')","def pretty_xml(path, outpath=None, encoding=b'utf-8'): if hasattr(outpath, 'write'): outstream = outpath else: opener = compression.get(path) outstream = opener(outpath, 'wb') with outstream: outstream.write(b'\n')" 1653,https://:@github.com/mobiusklein/psims.git,b93998c7e42ef5ef04c43bd2b0b59a31f01be3a6,"@@ -35,7 +35,7 @@ log.enable() def differ(a, b): - if issubclass(type(a), type(b)): + if not issubclass(type(a), type(b)): return False if isinstance(a, dict): return dict_diff(a, b) ",psims/transform/utils.py,"ReplaceText(target='not ' @(38,7)->(38,7))","log.enable() def differ(a, b): if issubclass(type(a), type(b)): return False if isinstance(a, dict): return dict_diff(a, b)","log.enable() def differ(a, b): if not issubclass(type(a), type(b)): return False if isinstance(a, dict): return dict_diff(a, b)" 1654,https://:@github.com/patchboard/patchboard-py.git,0bd7da5b765f2b87bf92404b3c56c411790b3daa,"@@ -52,7 +52,7 @@ class Action(object): raw = self.patchboard.session.request( self.method, url, - args + options ) response = Response(raw) if response.status != self.success_status: ",patchboard/action.py,"ReplaceText(target='options' @(55,12)->(55,16))","class Action(object): raw = self.patchboard.session.request( self.method, url, args ) response = Response(raw) if response.status != self.success_status:","class Action(object): raw = self.patchboard.session.request( self.method, url, options ) response = Response(raw) if response.status != self.success_status:" 1655,https://:@github.com/quantastica/qiskit-toaster.git,179f1e1ffea7ac084b6d94775ac71f326339894c,"@@ -96,7 +96,7 @@ class ToasterHttpInterface: txt = response.read().decode(""utf8"") break - return res + return txt def _fetch_last_response(self, timeout, job_id): req = request.Request(""%s/pollresult/%s"" % (self.toaster_url, job_id)) ",quantastica/qiskit_toaster/ToasterHttpInterface.py,"ReplaceText(target='txt' @(99,15)->(99,18))","class ToasterHttpInterface: txt = response.read().decode(""utf8"") break return res def _fetch_last_response(self, timeout, job_id): req = request.Request(""%s/pollresult/%s"" % (self.toaster_url, job_id))","class ToasterHttpInterface: txt = response.read().decode(""utf8"") break return txt def _fetch_last_response(self, timeout, job_id): req = request.Request(""%s/pollresult/%s"" % (self.toaster_url, job_id))" 1656,https://:@github.com/rcosnita/fantastico.git,0b94c55189d36b41866e822eecc605319f483594,"@@ -43,7 +43,7 @@ class Router(object): if len(conf_loaders) == 0: raise FantasticoNoRoutesError(""No loaders configured."") - if self._loader_lock is not None and len(self._loaders) == 0: + if self._loader_lock is None and len(self._loaders) == 0: self._loader_lock = threading.Lock() self._loaders = [] ",fantastico/routing_engine/router.py,"ReplaceText(target=' is ' @(46,28)->(46,36))","class Router(object): if len(conf_loaders) == 0: raise FantasticoNoRoutesError(""No loaders configured."") if self._loader_lock is not None and len(self._loaders) == 0: self._loader_lock = threading.Lock() self._loaders = [] ","class Router(object): if len(conf_loaders) == 0: raise FantasticoNoRoutesError(""No loaders configured."") if self._loader_lock is None and len(self._loaders) == 0: self._loader_lock = threading.Lock() self._loaders = [] " 1657,https://:@github.com/rcosnita/fantastico.git,b64cd9293ff05d184f1a3945b30a0821d8721ff0,"@@ -71,7 +71,7 @@ class SdkCommandActivateExtension(SdkCommand): root_folder = instantiator.get_component_path_data(SettingsFacade().get_config().__class__)[1] comp_root_folder = contrib_path.replace(contrib_path, ""%s%s/%s"" % (root_folder, self._arguments.comp_root, comp_name)) - if os_lib.path.exists(comp_root_folder): + if not os_lib.path.exists(comp_root_folder): os_lib.mkdir(comp_root_folder) instantiator.scan_folder_by_criteria( ",fantastico/sdk/commands/command_activate_extension.py,"ReplaceText(target='not ' @(74,11)->(74,11))","class SdkCommandActivateExtension(SdkCommand): root_folder = instantiator.get_component_path_data(SettingsFacade().get_config().__class__)[1] comp_root_folder = contrib_path.replace(contrib_path, ""%s%s/%s"" % (root_folder, self._arguments.comp_root, comp_name)) if os_lib.path.exists(comp_root_folder): os_lib.mkdir(comp_root_folder) instantiator.scan_folder_by_criteria(","class SdkCommandActivateExtension(SdkCommand): root_folder = instantiator.get_component_path_data(SettingsFacade().get_config().__class__)[1] comp_root_folder = contrib_path.replace(contrib_path, ""%s%s/%s"" % (root_folder, self._arguments.comp_root, comp_name)) if not os_lib.path.exists(comp_root_folder): os_lib.mkdir(comp_root_folder) instantiator.scan_folder_by_criteria(" 1658,https://:@github.com/bjherger/auto_dl.git,76c7d4e84069ae0aeeb8a796db40c7c797f81437,"@@ -58,7 +58,7 @@ class TestAutomater(unittest.TestCase): # A single numerical data = {'numerical_vars': ['n1']} input_mapper, output_mapper = Automater()._create_mappers(data) - self.assertEqual(1, len(output_mapper.features)) + self.assertEqual(1, len(input_mapper.features)) # Two numerical data = {'numerical_vars': ['n1', 'n2']} ",tests/testautomater.py,"ReplaceText(target='input_mapper' @(61,32)->(61,45))","class TestAutomater(unittest.TestCase): # A single numerical data = {'numerical_vars': ['n1']} input_mapper, output_mapper = Automater()._create_mappers(data) self.assertEqual(1, len(output_mapper.features)) # Two numerical data = {'numerical_vars': ['n1', 'n2']}","class TestAutomater(unittest.TestCase): # A single numerical data = {'numerical_vars': ['n1']} input_mapper, output_mapper = Automater()._create_mappers(data) self.assertEqual(1, len(input_mapper.features)) # Two numerical data = {'numerical_vars': ['n1', 'n2']}" 1659,https://:@github.com/NSLS-II/doct.git,c14ceb3c14d88e2a0f747b5f96ef56260e13832e,"@@ -87,7 +87,7 @@ class Document(dict): try: return vstr(self) except ImportError: - return super(self, Document).__str__() + return super(Document, self).__str__() def to_name_dict_pair(self): """"""Convert to (name, dict) pair ",doc.py,"ArgSwap(idxs=0<->1 @(90,19)->(90,24))","class Document(dict): try: return vstr(self) except ImportError: return super(self, Document).__str__() def to_name_dict_pair(self): """"""Convert to (name, dict) pair","class Document(dict): try: return vstr(self) except ImportError: return super(Document, self).__str__() def to_name_dict_pair(self): """"""Convert to (name, dict) pair" 1660,https://:@github.com/pmrowla/pylivemaker.git,d62510b20bc650220570cbb619cfaf9efb685bd6,"@@ -797,7 +797,7 @@ class LMArchive(object): if self.mode != 'w': raise ValueError('Cannot write to archive opened for reading.') if arcname is None: - arcpath = PureWindowsPath(filename) + arcpath = PureWindowsPath(packname) else: arcpath = PureWindowsPath(arcname) # strip drive and leading pathsep ",livemaker/archive.py,"ReplaceText(target='packname' @(800,38)->(800,46))","class LMArchive(object): if self.mode != 'w': raise ValueError('Cannot write to archive opened for reading.') if arcname is None: arcpath = PureWindowsPath(filename) else: arcpath = PureWindowsPath(arcname) # strip drive and leading pathsep","class LMArchive(object): if self.mode != 'w': raise ValueError('Cannot write to archive opened for reading.') if arcname is None: arcpath = PureWindowsPath(packname) else: arcpath = PureWindowsPath(arcname) # strip drive and leading pathsep" 1661,https://:@github.com/pmrowla/pylivemaker.git,6b562c3a400595dc1da0e467a4c3348365be1333,"@@ -671,7 +671,7 @@ class LMScript(BaseSerializable): for line_no in replacement_choices: try: index, _ = self.get_command(line_no) - menu = make_menu(self, line_no) + menu = make_menu(self, index) except LiveMakerException: raise BadTextIdentifierError(f""invalid text block: LSB command '{line_no}' is not start of a menu"") ",livemaker/lsb/lmscript.py,"ReplaceText(target='index' @(674,39)->(674,46))","class LMScript(BaseSerializable): for line_no in replacement_choices: try: index, _ = self.get_command(line_no) menu = make_menu(self, line_no) except LiveMakerException: raise BadTextIdentifierError(f""invalid text block: LSB command '{line_no}' is not start of a menu"") ","class LMScript(BaseSerializable): for line_no in replacement_choices: try: index, _ = self.get_command(line_no) menu = make_menu(self, index) except LiveMakerException: raise BadTextIdentifierError(f""invalid text block: LSB command '{line_no}' is not start of a menu"") " 1662,https://:@github.com/costular/flask-restbolt.git,4dfe49f1de3dfd9598b4ae92b9e6b6644fa999f7,"@@ -338,7 +338,7 @@ class APITestCase(unittest.TestCase): def record(sender, exception): recorded.append(exception) - got_request_exception.connect(record, api) + got_request_exception.connect(record, app) try: with app.test_request_context(""/foo""): api.handle_error(exception) ",tests/test_api.py,"ReplaceText(target='app' @(341,46)->(341,49))","class APITestCase(unittest.TestCase): def record(sender, exception): recorded.append(exception) got_request_exception.connect(record, api) try: with app.test_request_context(""/foo""): api.handle_error(exception)","class APITestCase(unittest.TestCase): def record(sender, exception): recorded.append(exception) got_request_exception.connect(record, app) try: with app.test_request_context(""/foo""): api.handle_error(exception)" 1663,https://:@github.com/chrisrycx/DataBear.git,dc8bf94fea026fd5666be235bafa0cfc613c21fc,"@@ -86,7 +86,7 @@ class dyaconTPH: savedata = [] data = self.data[name] for val in data: - if (val[0]=enddt): + if (val[0]=enddt): savedata.append(val) self.data[name] = savedata ",databear/sensors/dyaconTPH1.py,"ReplaceText(target='or' @(89,32)->(89,35))","class dyaconTPH: savedata = [] data = self.data[name] for val in data: if (val[0]=enddt): savedata.append(val) self.data[name] = savedata","class dyaconTPH: savedata = [] data = self.data[name] for val in data: if (val[0]=enddt): savedata.append(val) self.data[name] = savedata" 1664,https://:@gitlab.com/slumber/replication.git,efb33c3dc01fcd928c2251a42987fc1c69beae41,"@@ -302,7 +302,7 @@ class Session(object): """""" assert(uuid and new_owner) - if uuid in self._graph.keys() and self._graph[uuid].owner == self._id: + if uuid in self._graph.keys() and self._graph[uuid].owner != self._id: for node in self._node_deps(node=uuid): self.change_owner(uuid=node,new_owner=new_owner) ",replication/interface.py,"ReplaceText(target='!=' @(305,66)->(305,68))","class Session(object): """""" assert(uuid and new_owner) if uuid in self._graph.keys() and self._graph[uuid].owner == self._id: for node in self._node_deps(node=uuid): self.change_owner(uuid=node,new_owner=new_owner) ","class Session(object): """""" assert(uuid and new_owner) if uuid in self._graph.keys() and self._graph[uuid].owner != self._id: for node in self._node_deps(node=uuid): self.change_owner(uuid=node,new_owner=new_owner) " 1665,https://:@github.com/akrog/ember-csi.git,4fc79e94918db66a40c319fa4497575bca633f4b,"@@ -561,7 +561,7 @@ class NodeBase(IdentityBase): if persistence_config: cinderlib_extra_config = ember_config.copy() cinderlib_extra_config.pop('disabled') - ember_config['fail_on_missing_backend'] = False + cinderlib_extra_config['fail_on_missing_backend'] = False cinderlib.setup(persistence_config=persistence_config, **cinderlib_extra_config) IdentityBase.__init__(self, server, ember_config) ",ember_csi/base.py,"ReplaceText(target='cinderlib_extra_config' @(564,12)->(564,24))","class NodeBase(IdentityBase): if persistence_config: cinderlib_extra_config = ember_config.copy() cinderlib_extra_config.pop('disabled') ember_config['fail_on_missing_backend'] = False cinderlib.setup(persistence_config=persistence_config, **cinderlib_extra_config) IdentityBase.__init__(self, server, ember_config)","class NodeBase(IdentityBase): if persistence_config: cinderlib_extra_config = ember_config.copy() cinderlib_extra_config.pop('disabled') cinderlib_extra_config['fail_on_missing_backend'] = False cinderlib.setup(persistence_config=persistence_config, **cinderlib_extra_config) IdentityBase.__init__(self, server, ember_config)" 1666,https://:@github.com/akrog/ember-csi.git,52a690250873a10850e51ca9ee1a6fe90f6847f1,"@@ -305,7 +305,7 @@ class ControllerBase(IdentityBase): cinderlib_extra_config = ember_config.copy() cinderlib_extra_config.pop('disabled') cinderlib.setup(persistence_config=persistence_config, - **ember_config) + **cinderlib_extra_config) self.backend = cinderlib.Backend(**backend_config) IdentityBase.__init__(self, server, ember_config) self.CSI.add_ControllerServicer_to_server(self, server) ",ember_csi/base.py,"ReplaceText(target='cinderlib_extra_config' @(308,26)->(308,38))","class ControllerBase(IdentityBase): cinderlib_extra_config = ember_config.copy() cinderlib_extra_config.pop('disabled') cinderlib.setup(persistence_config=persistence_config, **ember_config) self.backend = cinderlib.Backend(**backend_config) IdentityBase.__init__(self, server, ember_config) self.CSI.add_ControllerServicer_to_server(self, server)","class ControllerBase(IdentityBase): cinderlib_extra_config = ember_config.copy() cinderlib_extra_config.pop('disabled') cinderlib.setup(persistence_config=persistence_config, **cinderlib_extra_config) self.backend = cinderlib.Backend(**backend_config) IdentityBase.__init__(self, server, ember_config) self.CSI.add_ControllerServicer_to_server(self, server)" 1667,https://:@github.com/guysv/ilua.git,d433be2f47da572bef7ca39ce15a1e6b59aeecd2,"@@ -110,7 +110,7 @@ class ILuaKernel(KernelBase): ""payload"": code}) if result[""payload""][""success""]: - if result['payload']['returned'] == """" and not silent: + if result['payload']['returned'] != """" and not silent: self.send_update(""execute_result"", { 'execution_count': self.execution_count, 'data': { ",ilua/kernel.py,"ReplaceText(target='!=' @(113,45)->(113,47))","class ILuaKernel(KernelBase): ""payload"": code}) if result[""payload""][""success""]: if result['payload']['returned'] == """" and not silent: self.send_update(""execute_result"", { 'execution_count': self.execution_count, 'data': {","class ILuaKernel(KernelBase): ""payload"": code}) if result[""payload""][""success""]: if result['payload']['returned'] != """" and not silent: self.send_update(""execute_result"", { 'execution_count': self.execution_count, 'data': {" 1668,https://:@github.com/guysv/ilua.git,c7532fb945aa964e4eedff2ec0d5f90e96d7ca13,"@@ -94,7 +94,7 @@ class Win32NamedPipe(abstract.FileDescriptor): def writeSequence(self, data): for chunk in data: - self.write(data) + self.write(chunk) def pipeWrite(self): try: ",ilua/_win32namedpipe.py,"ReplaceText(target='chunk' @(97,23)->(97,27))","class Win32NamedPipe(abstract.FileDescriptor): def writeSequence(self, data): for chunk in data: self.write(data) def pipeWrite(self): try:","class Win32NamedPipe(abstract.FileDescriptor): def writeSequence(self, data): for chunk in data: self.write(chunk) def pipeWrite(self): try:" 1669,https://:@bitbucket.org/jairhul/pyg4ometry.git,3627d9e0b48c213bddb00de3750b0f28c71eaa8b,"@@ -60,7 +60,7 @@ class EllipticalCone(_SolidBase) : n = d else: n = _Vector(norm) - vertices.append(_Vertex(c.plus(d), d)) + vertices.append(_Vertex(c.plus(d), n)) for j0 in range(slices): ",geant4/solid/EllipticalCone.py,"ReplaceText(target='n' @(63,47)->(63,48))","class EllipticalCone(_SolidBase) : n = d else: n = _Vector(norm) vertices.append(_Vertex(c.plus(d), d)) for j0 in range(slices):","class EllipticalCone(_SolidBase) : n = d else: n = _Vector(norm) vertices.append(_Vertex(c.plus(d), n)) for j0 in range(slices):" 1670,https://:@bitbucket.org/jairhul/pyg4ometry.git,12f7b6ffabc83cc931529e55ae1adb33a8207696,"@@ -32,7 +32,7 @@ class Scaled(_SolidBase): self.varNames = [""pX"", ""pY"", ""pZ""] self.dependents = [] - if registry: + if addRegistry: registry.addSolid(self) self.registry = registry ",pyg4ometry/geant4/solid/Scaled.py,"ReplaceText(target='addRegistry' @(35,11)->(35,19))","class Scaled(_SolidBase): self.varNames = [""pX"", ""pY"", ""pZ""] self.dependents = [] if registry: registry.addSolid(self) self.registry = registry","class Scaled(_SolidBase): self.varNames = [""pX"", ""pY"", ""pZ""] self.dependents = [] if addRegistry: registry.addSolid(self) self.registry = registry" 1671,https://:@bitbucket.org/jairhul/pyg4ometry.git,e6a4a4fd0df7b10f548a5553ba2bdf63e661c0f1,"@@ -41,7 +41,7 @@ def Test(vis = False, interactive = False, type = normal) : # solids ws = _g4.solid.Box(""ws"",wx,wy,wz, reg, ""mm"") - ps = _g4.solid.GenericPolyhedra(""ps"",psphi,pdphi,pnsid,pz,pr,reg,""mm"",""rad"") + ps = _g4.solid.GenericPolyhedra(""ps"",psphi,pdphi,pnsid,pr,pz,reg,""mm"",""rad"") # structure wl = _g4.LogicalVolume(ws, wm, ""wl"", reg) ",pyg4ometry/test/pythonGeant4/T014_GenericPolyhedra.py,"ArgSwap(idxs=4<->5 @(44,9)->(44,35))","def Test(vis = False, interactive = False, type = normal) : # solids ws = _g4.solid.Box(""ws"",wx,wy,wz, reg, ""mm"") ps = _g4.solid.GenericPolyhedra(""ps"",psphi,pdphi,pnsid,pz,pr,reg,""mm"",""rad"") # structure wl = _g4.LogicalVolume(ws, wm, ""wl"", reg)","def Test(vis = False, interactive = False, type = normal) : # solids ws = _g4.solid.Box(""ws"",wx,wy,wz, reg, ""mm"") ps = _g4.solid.GenericPolyhedra(""ps"",psphi,pdphi,pnsid,pr,pz,reg,""mm"",""rad"") # structure wl = _g4.LogicalVolume(ws, wm, ""wl"", reg)" 1672,https://:@github.com/fineartdev/superset.git,299ad095760f1ed6d1f43549a4c979df508bd624,"@@ -926,7 +926,7 @@ class Datasource(Model, AuditMixinNullable, Queryable): cols += ['timestamp'] cols += [col for col in groupby if col in df.columns] cols += [col for col in metrics if col in df.columns] - cols += [col for col in df.columns if col in cols] + cols += [col for col in df.columns if col not in cols] df = df[cols] return QueryResult( df=df, ",panoramix/models.py,"ReplaceText(target=' not in ' @(929,49)->(929,53))","class Datasource(Model, AuditMixinNullable, Queryable): cols += ['timestamp'] cols += [col for col in groupby if col in df.columns] cols += [col for col in metrics if col in df.columns] cols += [col for col in df.columns if col in cols] df = df[cols] return QueryResult( df=df,","class Datasource(Model, AuditMixinNullable, Queryable): cols += ['timestamp'] cols += [col for col in groupby if col in df.columns] cols += [col for col in metrics if col in df.columns] cols += [col for col in df.columns if col not in cols] df = df[cols] return QueryResult( df=df," 1673,https://:@github.com/fineartdev/superset.git,efaef8fe0924ff39e77edbe8fe5e2ed337adccf3,"@@ -628,7 +628,7 @@ class Database(Model, AuditMixinNullable): self, 'table', force=force) return tables_dict.get("""", []) return sorted( - self.db_engine_spec.get_table_names(self.inspector, schema)) + self.db_engine_spec.get_table_names(schema, self.inspector)) def all_view_names(self, schema=None, force=False): if not schema: ",superset/models/core.py,"ArgSwap(idxs=0<->1 @(631,12)->(631,47))","class Database(Model, AuditMixinNullable): self, 'table', force=force) return tables_dict.get("""", []) return sorted( self.db_engine_spec.get_table_names(self.inspector, schema)) def all_view_names(self, schema=None, force=False): if not schema:","class Database(Model, AuditMixinNullable): self, 'table', force=force) return tables_dict.get("""", []) return sorted( self.db_engine_spec.get_table_names(schema, self.inspector)) def all_view_names(self, schema=None, force=False): if not schema:" 1674,https://:@github.com/lucas-flowers/snutree.git,9eb126d822088e241c8c42c58d792919f698c25b,"@@ -209,7 +209,7 @@ def compile_pdf(source): ) except OSError as exception: msg = f'had a problem compiling to PDF:\n{exception}' - raise SnutreeError(exception) + raise SnutreeError(msg) return result.stdout ",snutree/snutree.py,"ReplaceText(target='msg' @(212,27)->(212,36))","def compile_pdf(source): ) except OSError as exception: msg = f'had a problem compiling to PDF:\n{exception}' raise SnutreeError(exception) return result.stdout ","def compile_pdf(source): ) except OSError as exception: msg = f'had a problem compiling to PDF:\n{exception}' raise SnutreeError(msg) return result.stdout " 1675,https://:@github.com/Nanco-L/simple-nn.git,c5fb2c51f0304d630addad93be0c206be54ce93e,"@@ -569,7 +569,7 @@ class Neural_network(object): test_save['DFT_F'].append(test_elem['F']) test_save['NN_F'].append(tmp_nnf) - test_tot_struc += num_batch_atom + test_tot_atom += num_batch_atom else: test_elem, tmp_nne, tmp_eloss = \ sess.run([self.next_elem, self.E, self.e_loss], feed_dict=test_fdict) ",simple_nn/models/neural_network.py,"ReplaceText(target='test_tot_atom' @(572,28)->(572,42))","class Neural_network(object): test_save['DFT_F'].append(test_elem['F']) test_save['NN_F'].append(tmp_nnf) test_tot_struc += num_batch_atom else: test_elem, tmp_nne, tmp_eloss = \ sess.run([self.next_elem, self.E, self.e_loss], feed_dict=test_fdict)","class Neural_network(object): test_save['DFT_F'].append(test_elem['F']) test_save['NN_F'].append(tmp_nnf) test_tot_atom += num_batch_atom else: test_elem, tmp_nne, tmp_eloss = \ sess.run([self.next_elem, self.E, self.e_loss], feed_dict=test_fdict)" 1676,https://:@github.com/Nanco-L/simple-nn.git,394b60e6ad7c24579dac407adbf0078b48cdcb89,"@@ -390,7 +390,7 @@ class Symmetry_function(object): self._write_tfrecords(tmp_res, writer, use_force=use_force, atomic_weights=aw_tag) if not self.inputs['remain_pickle']: - os.remove(item) + os.remove(ptem) writer.close() self.parent.logfile.write('{} file saved in {}\n'.format((i%self.inputs['data_per_tfrecord'])+1, record_name)) ",simple_nn/features/symmetry_function/__init__.py,"ReplaceText(target='ptem' @(393,30)->(393,34))","class Symmetry_function(object): self._write_tfrecords(tmp_res, writer, use_force=use_force, atomic_weights=aw_tag) if not self.inputs['remain_pickle']: os.remove(item) writer.close() self.parent.logfile.write('{} file saved in {}\n'.format((i%self.inputs['data_per_tfrecord'])+1, record_name))","class Symmetry_function(object): self._write_tfrecords(tmp_res, writer, use_force=use_force, atomic_weights=aw_tag) if not self.inputs['remain_pickle']: os.remove(ptem) writer.close() self.parent.logfile.write('{} file saved in {}\n'.format((i%self.inputs['data_per_tfrecord'])+1, record_name))" 1677,https://:@gitlab.com/dhke/py-exim-utils.git,707d1de5e000094a0f277960fb35190ad3d65ddf,"@@ -324,7 +324,7 @@ class LFileParser(object): source_name = source_name or s intermediate_encoding = intermediate_encoding or 'utf-8' source = s.encode(intermediate_encoding) - return self.parse_bytes(source, source_name=s) + return self.parse_bytes(source, source_name=source_name) def parse_comment(self, context): token = LFileParserToken('comment', None, context.lineno) ",src/exim/db/lsearch.py,"ReplaceText(target='source_name' @(327,52)->(327,53))","class LFileParser(object): source_name = source_name or s intermediate_encoding = intermediate_encoding or 'utf-8' source = s.encode(intermediate_encoding) return self.parse_bytes(source, source_name=s) def parse_comment(self, context): token = LFileParserToken('comment', None, context.lineno)","class LFileParser(object): source_name = source_name or s intermediate_encoding = intermediate_encoding or 'utf-8' source = s.encode(intermediate_encoding) return self.parse_bytes(source, source_name=source_name) def parse_comment(self, context): token = LFileParserToken('comment', None, context.lineno)" 1678,https://:@gitlab.com/abompard/rhizom.git,18cb3b4727aa3731289879c0187be8ac3f77c212,"@@ -37,7 +37,7 @@ def upgrade(): creation=datetime.utcnow(), last_access=datetime.utcnow())) conn.execute(users_table.update().values( creation=datetime.utcnow(), last_connection=datetime.utcnow())) - if is_sqlite(conn): + if not is_sqlite(conn): op.alter_column('graphs', 'creation', nullable=False) op.alter_column('graphs', 'last_access', nullable=False) op.alter_column('users', 'creation', nullable=False) ",rhizom/migrations/versions/b331d042fca_creation_and_access_times.py,"ReplaceText(target='not ' @(40,7)->(40,7))","def upgrade(): creation=datetime.utcnow(), last_access=datetime.utcnow())) conn.execute(users_table.update().values( creation=datetime.utcnow(), last_connection=datetime.utcnow())) if is_sqlite(conn): op.alter_column('graphs', 'creation', nullable=False) op.alter_column('graphs', 'last_access', nullable=False) op.alter_column('users', 'creation', nullable=False)","def upgrade(): creation=datetime.utcnow(), last_access=datetime.utcnow())) conn.execute(users_table.update().values( creation=datetime.utcnow(), last_connection=datetime.utcnow())) if not is_sqlite(conn): op.alter_column('graphs', 'creation', nullable=False) op.alter_column('graphs', 'last_access', nullable=False) op.alter_column('users', 'creation', nullable=False)" 1679,https://:@github.com/frenzymadness/compileall2.git,59df6aeae3eb4a67c3fa783c403cea81def8a557,"@@ -104,8 +104,8 @@ class CompileallTestsBase: self.source_path3 = os.path.join(self.subdirectory, '_test3.py') shutil.copyfile(self.source_path, self.source_path3) many_directories = [str(number) for number in range(1, 100)] - self.long_path = os.path.join(""long"", - self.directory, + self.long_path = os.path.join(self.directory, + ""long"", *many_directories) os.makedirs(self.long_path) self.source_path_long = os.path.join(self.long_path, '_test4.py') ",test_compileall_original.py,"ArgSwap(idxs=0<->1 @(107,25)->(107,37))","class CompileallTestsBase: self.source_path3 = os.path.join(self.subdirectory, '_test3.py') shutil.copyfile(self.source_path, self.source_path3) many_directories = [str(number) for number in range(1, 100)] self.long_path = os.path.join(""long"", self.directory, *many_directories) os.makedirs(self.long_path) self.source_path_long = os.path.join(self.long_path, '_test4.py')","class CompileallTestsBase: self.source_path3 = os.path.join(self.subdirectory, '_test3.py') shutil.copyfile(self.source_path, self.source_path3) many_directories = [str(number) for number in range(1, 100)] self.long_path = os.path.join(self.directory, ""long"", *many_directories) os.makedirs(self.long_path) self.source_path_long = os.path.join(self.long_path, '_test4.py')" 1680,https://:@github.com/nandoflorestan/keepluggable.git,576d342dc8a5f8d4c20d780766b556ca6c91935e,"@@ -274,6 +274,6 @@ class ImageAction(BaseFilesAction): """"""Omit the main *href* if we are not storing original images."""""" metadata = super()._complement(metadata) # Add main *href* if we are storing original images or if not image - if metadata.get('image_width') or not self.config.store_original: + if not metadata.get('image_width') or not self.config.store_original: del metadata['href'] return metadata ",keepluggable/image_actions.py,"ReplaceText(target='not ' @(277,11)->(277,11))","class ImageAction(BaseFilesAction): """"""Omit the main *href* if we are not storing original images."""""" metadata = super()._complement(metadata) # Add main *href* if we are storing original images or if not image if metadata.get('image_width') or not self.config.store_original: del metadata['href'] return metadata","class ImageAction(BaseFilesAction): """"""Omit the main *href* if we are not storing original images."""""" metadata = super()._complement(metadata) # Add main *href* if we are storing original images or if not image if not metadata.get('image_width') or not self.config.store_original: del metadata['href'] return metadata" 1681,https://:@github.com/rocksclusters/FingerPrint.git,ab31be4ea3ac33422656d36d635e30c0e9235757,"@@ -44,7 +44,7 @@ class Swirl(object): p = os.readlink(fileName) if not os.path.isabs(p): p = os.path.join( os.path.dirname(fileName), p) - links.append(p) + links.append(fileName) fileName = p for swirlFile in self.swirlFiles: if swirlFile.path == fileName: ",FingerPrint/swirl.py,"ReplaceText(target='fileName' @(47,25)->(47,26))","class Swirl(object): p = os.readlink(fileName) if not os.path.isabs(p): p = os.path.join( os.path.dirname(fileName), p) links.append(p) fileName = p for swirlFile in self.swirlFiles: if swirlFile.path == fileName:","class Swirl(object): p = os.readlink(fileName) if not os.path.isabs(p): p = os.path.join( os.path.dirname(fileName), p) links.append(fileName) fileName = p for swirlFile in self.swirlFiles: if swirlFile.path == fileName:" 1682,https://:@github.com/all-umass/superman.git,2431684dc60312c6bba81f940511c5f608b696a3,"@@ -36,7 +36,7 @@ def crop_resample(bands, intensities, crops): # check that each chunk is valid and doesn't overlap with any other prev_ub = float('-inf') for lb, ub, step in crops: - if ub >= lb: + if ub <= lb: raise ValueError('Invalid crop region') if lb < prev_ub: raise ValueError('Overlapping crop regions') ",superman/preprocess.py,"ReplaceText(target='<=' @(39,10)->(39,12))","def crop_resample(bands, intensities, crops): # check that each chunk is valid and doesn't overlap with any other prev_ub = float('-inf') for lb, ub, step in crops: if ub >= lb: raise ValueError('Invalid crop region') if lb < prev_ub: raise ValueError('Overlapping crop regions')","def crop_resample(bands, intensities, crops): # check that each chunk is valid and doesn't overlap with any other prev_ub = float('-inf') for lb, ub, step in crops: if ub <= lb: raise ValueError('Invalid crop region') if lb < prev_ub: raise ValueError('Overlapping crop regions')" 1683,https://:@github.com/jvamvas/rhymediscovery.git,74b6c37b1a8ddae99edbf14a6db7307d00437734,"@@ -127,7 +127,7 @@ def post_prob_scheme(t_table, words, stanza, scheme): for i, w in enumerate(rhymelist): r = words.index(w) if i == 0: # first word, use P(w|x) - myprob = t_table[r, n] + myprob *= t_table[r, n] else: for v in rhymelist[:i]: # history c = words.index(v) ",findschemes.py,"ReplaceText(target='*=' @(130,23)->(130,24))","def post_prob_scheme(t_table, words, stanza, scheme): for i, w in enumerate(rhymelist): r = words.index(w) if i == 0: # first word, use P(w|x) myprob = t_table[r, n] else: for v in rhymelist[:i]: # history c = words.index(v)","def post_prob_scheme(t_table, words, stanza, scheme): for i, w in enumerate(rhymelist): r = words.index(w) if i == 0: # first word, use P(w|x) myprob *= t_table[r, n] else: for v in rhymelist[:i]: # history c = words.index(v)" 1684,https://:@github.com/bensondaled/pyfluo.git,a9e2640fe3e0316dba2917dfbf9bd01d43afd1ce,"@@ -175,7 +175,7 @@ class Movie(TSBase): roi_flat = roi3.reshape((len(roi3),-1)) self_flat = self.reshape((len(self),-1)).T dp = (roi_flat.dot(self_flat)).T - return Trace(dp/len(self_flat), time=self.time, Ts=self.Ts) + return Trace(dp/len(roi_flat), time=self.time, Ts=self.Ts) def motion_correct(self, *params, **kwargs): """"""A convenience method for pyfluo.motion.motion_correct ",pyfluo/movies.py,"ReplaceText(target='roi_flat' @(178,28)->(178,37))","class Movie(TSBase): roi_flat = roi3.reshape((len(roi3),-1)) self_flat = self.reshape((len(self),-1)).T dp = (roi_flat.dot(self_flat)).T return Trace(dp/len(self_flat), time=self.time, Ts=self.Ts) def motion_correct(self, *params, **kwargs): """"""A convenience method for pyfluo.motion.motion_correct","class Movie(TSBase): roi_flat = roi3.reshape((len(roi3),-1)) self_flat = self.reshape((len(self),-1)).T dp = (roi_flat.dot(self_flat)).T return Trace(dp/len(roi_flat), time=self.time, Ts=self.Ts) def motion_correct(self, *params, **kwargs): """"""A convenience method for pyfluo.motion.motion_correct" 1685,https://:@github.com/wkschwartz/wrapitup.git,6d13bf58cc29d07edcf5e86221cd676a81a04776,"@@ -180,7 +180,7 @@ class catch_signals: 'callback is not a callable with two positional arguments: %r' % (callback,)) if os.name == 'nt': - if not (set(signals) <= set(self._DEFAULT_SIGS)): + if not (set(signals_tmp) <= set(self._DEFAULT_SIGS)): raise ValueError( ""Windows does not support one of the signals: %r"" % (signals,)) self._signals = tuple(signals_tmp) # type: typing.Tuple[signal.Signals, ...] ",wrapitup/_catch_signals.py,"ReplaceText(target='signals_tmp' @(183,15)->(183,22))","class catch_signals: 'callback is not a callable with two positional arguments: %r' % (callback,)) if os.name == 'nt': if not (set(signals) <= set(self._DEFAULT_SIGS)): raise ValueError( ""Windows does not support one of the signals: %r"" % (signals,)) self._signals = tuple(signals_tmp) # type: typing.Tuple[signal.Signals, ...]","class catch_signals: 'callback is not a callable with two positional arguments: %r' % (callback,)) if os.name == 'nt': if not (set(signals_tmp) <= set(self._DEFAULT_SIGS)): raise ValueError( ""Windows does not support one of the signals: %r"" % (signals,)) self._signals = tuple(signals_tmp) # type: typing.Tuple[signal.Signals, ...]" 1686,https://:@github.com/hugobessa/django-shared-schema-tenants.git,0438cf26353f4b6955f9c7e62e2a37e71b05f019,"@@ -2,7 +2,7 @@ from django.contrib.sites.models import Site from shared_schema_tenants.settings import DEFAULT_SITE_DOMAIN def creates_default_site(sender, instance, created, *args, **kwargs): - if created: + if not created: try: site = Site.objects.get(domain__icontains=DEFAULT_SITE_DOMAIN, tenant_site__tenant=instance) ",shared_schema_tenants/signals.py,"ReplaceText(target='not ' @(5,7)->(5,7))","from django.contrib.sites.models import Site from shared_schema_tenants.settings import DEFAULT_SITE_DOMAIN def creates_default_site(sender, instance, created, *args, **kwargs): if created: try: site = Site.objects.get(domain__icontains=DEFAULT_SITE_DOMAIN, tenant_site__tenant=instance)","from django.contrib.sites.models import Site from shared_schema_tenants.settings import DEFAULT_SITE_DOMAIN def creates_default_site(sender, instance, created, *args, **kwargs): if not created: try: site = Site.objects.get(domain__icontains=DEFAULT_SITE_DOMAIN, tenant_site__tenant=instance)" 1687,https://:@github.com/pmichel31415/dynn.git,d17306ada100763a7b72fe7bc5bd6bc3bbb5ae13,"@@ -121,5 +121,5 @@ class CompactLSTM(layers.Layer): else: gates = dy.vanilla_lstm_gates(x,h,self.Whx, self.Whh,self.bh) new_c = dy.vanilla_lstm_c(c, gates) - new_h = dy.vanilla_lstm_h(c, gates) + new_h = dy.vanilla_lstm_h(new_c, gates) return new_h, new_c \ No newline at end of file ",lstm.py,"ReplaceText(target='new_c' @(124,34)->(124,35))","class CompactLSTM(layers.Layer): else: gates = dy.vanilla_lstm_gates(x,h,self.Whx, self.Whh,self.bh) new_c = dy.vanilla_lstm_c(c, gates) new_h = dy.vanilla_lstm_h(c, gates) return new_h, new_c \ No newline at end of file","class CompactLSTM(layers.Layer): else: gates = dy.vanilla_lstm_gates(x,h,self.Whx, self.Whh,self.bh) new_c = dy.vanilla_lstm_c(c, gates) new_h = dy.vanilla_lstm_h(new_c, gates) return new_h, new_c \ No newline at end of file" 1688,https://:@github.com/pmichel31415/dynn.git,644f1b8a3e59e8855ac04417290c2172c2b5fa88,"@@ -146,7 +146,7 @@ def _test_recurrent_layer_bidirectional_transduction( dy.esum([dy.sum_elems(state[0]) for state in fwd_states]) ) bwd_z = dy.mean_batches( - dy.esum([dy.sum_elems(state[0]) for state in fwd_states]) + dy.esum([dy.sum_elems(state[0]) for state in bwd_states]) ) z = fwd_z + bwd_z z.forward() ",tests/layers/test_transduction_layers.py,"ReplaceText(target='bwd_states' @(149,53)->(149,63))","def _test_recurrent_layer_bidirectional_transduction( dy.esum([dy.sum_elems(state[0]) for state in fwd_states]) ) bwd_z = dy.mean_batches( dy.esum([dy.sum_elems(state[0]) for state in fwd_states]) ) z = fwd_z + bwd_z z.forward()","def _test_recurrent_layer_bidirectional_transduction( dy.esum([dy.sum_elems(state[0]) for state in fwd_states]) ) bwd_z = dy.mean_batches( dy.esum([dy.sum_elems(state[0]) for state in bwd_states]) ) z = fwd_z + bwd_z z.forward()" 1689,https://:@github.com/drachlyznardh/githistorian.git,f1a798d26572977769f2d02ece24cf0ed35170b1,"@@ -44,6 +44,6 @@ class NodeDB: result = [] for name in names: target = self.store[name] - if target.has_column() and target.column <= column: continue + if target.has_column() and target.column < column: continue result.append(target.row) return result ",db.py,"ReplaceText(target='<' @(47,44)->(47,46))","class NodeDB: result = [] for name in names: target = self.store[name] if target.has_column() and target.column <= column: continue result.append(target.row) return result","class NodeDB: result = [] for name in names: target = self.store[name] if target.has_column() and target.column < column: continue result.append(target.row) return result" 1690,https://:@github.com/benselme/babel.git,b9efb7e3624af2bb64b663d6c9908c597cf09a23,"@@ -99,7 +99,7 @@ def _validate_format(format, alternative): result = [] for match in PYTHON_FORMAT.finditer(string): name, format, typechar = match.groups() - if typechar == '%' and name is not None: + if typechar == '%' and name is None: continue result.append((name, str(typechar))) return result ",babel/messages/checkers.py,"ReplaceText(target=' is ' @(102,39)->(102,47))","def _validate_format(format, alternative): result = [] for match in PYTHON_FORMAT.finditer(string): name, format, typechar = match.groups() if typechar == '%' and name is not None: continue result.append((name, str(typechar))) return result","def _validate_format(format, alternative): result = [] for match in PYTHON_FORMAT.finditer(string): name, format, typechar = match.groups() if typechar == '%' and name is None: continue result.append((name, str(typechar))) return result" 1691,https://:@github.com/martinchristen/pyRT.git,8d97666dc6103f6b86c6698ce3f6c7064983a443,"@@ -104,7 +104,7 @@ class BBox(Shape): tmax = min(min(tmax, tymax), tzmax) tmin = (self[ray.sign[0]].x - ray.start.x) * ray.invdir.x - return tmin > tmax + return tmin < tmax def surfaceArea(self) -> float: ",pyrt/geometry/bbox.py,"ReplaceText(target='<' @(107,20)->(107,21))","class BBox(Shape): tmax = min(min(tmax, tymax), tzmax) tmin = (self[ray.sign[0]].x - ray.start.x) * ray.invdir.x return tmin > tmax def surfaceArea(self) -> float:","class BBox(Shape): tmax = min(min(tmax, tymax), tzmax) tmin = (self[ray.sign[0]].x - ray.start.x) * ray.invdir.x return tmin < tmax def surfaceArea(self) -> float:" 1692,https://:@github.com/zxdavb/intouch-client.git,72bb566cb7c42dbd995e3e4f5151e6a59736fe5b,"@@ -204,7 +204,7 @@ class InTouchHeater(InTouchObject): @property def rooms(self) -> list: return [InTouchRoom(r, self) for r in ['1', '2'] - if True and _convert( + if True or _convert( self._data['room_temp_{}_msb'.format(r)], self._data['room_temp_{}_lsb'.format(r)]) is not None] ",intouchclient/__init__.py,"ReplaceText(target='or' @(207,24)->(207,27))","class InTouchHeater(InTouchObject): @property def rooms(self) -> list: return [InTouchRoom(r, self) for r in ['1', '2'] if True and _convert( self._data['room_temp_{}_msb'.format(r)], self._data['room_temp_{}_lsb'.format(r)]) is not None] ","class InTouchHeater(InTouchObject): @property def rooms(self) -> list: return [InTouchRoom(r, self) for r in ['1', '2'] if True or _convert( self._data['room_temp_{}_msb'.format(r)], self._data['room_temp_{}_lsb'.format(r)]) is not None] " 1693,https://:@github.com/ralphbean/gnome-shell-search-github-repositories.git,582174cccd6ee618d89c25d9d22350fb6797489d,"@@ -73,7 +73,7 @@ class FedmsgNotifyService(dbus.service.Object, fedmsg.consumers.FedmsgConsumer): icon_file)) self._icon_cache[icon] = icon_file icon = icon_file - note = Notify.Notification.new(""fedmsg"", pretty_text, icon_file) + note = Notify.Notification.new(""fedmsg"", pretty_text, icon) note.show() @dbus.service.method(bus_name) ",fedmsg_notify/daemon.py,"ReplaceText(target='icon' @(76,62)->(76,71))","class FedmsgNotifyService(dbus.service.Object, fedmsg.consumers.FedmsgConsumer): icon_file)) self._icon_cache[icon] = icon_file icon = icon_file note = Notify.Notification.new(""fedmsg"", pretty_text, icon_file) note.show() @dbus.service.method(bus_name)","class FedmsgNotifyService(dbus.service.Object, fedmsg.consumers.FedmsgConsumer): icon_file)) self._icon_cache[icon] = icon_file icon = icon_file note = Notify.Notification.new(""fedmsg"", pretty_text, icon) note.show() @dbus.service.method(bus_name)" 1694,https://:@github.com/strongles/ervin.git,56b38758e5b38eee76dd4af6682f797f9b83c428,"@@ -96,7 +96,7 @@ def find_probes_recursively(file_list, tail=None): if len(file_list) == 2: return find_probes(first_probe_data, second_probe_data) - elif len(file_list) < 2: + elif len(file_list) > 2: return find_probes_recursively(file_list[2:], tail=find_probes(first_probe_data, second_probe_data)) else: probe_data = read_probe_records_from_file(file_list[0]) ",src/probe_finder.py,"ReplaceText(target='>' @(99,28)->(99,29))","def find_probes_recursively(file_list, tail=None): if len(file_list) == 2: return find_probes(first_probe_data, second_probe_data) elif len(file_list) < 2: return find_probes_recursively(file_list[2:], tail=find_probes(first_probe_data, second_probe_data)) else: probe_data = read_probe_records_from_file(file_list[0])","def find_probes_recursively(file_list, tail=None): if len(file_list) == 2: return find_probes(first_probe_data, second_probe_data) elif len(file_list) > 2: return find_probes_recursively(file_list[2:], tail=find_probes(first_probe_data, second_probe_data)) else: probe_data = read_probe_records_from_file(file_list[0])" 1695,https://:@github.com/keybase/saltpack-python.git,3a68d9c1fe736602a71ce17671595c1bb5720ce1,"@@ -276,7 +276,7 @@ def get_recipients(args): recipients = [] for recipient in args['']: key = binascii.unhexlify(recipient) - assert len(recipient) == 32 + assert len(key) == 32 recipients.append(key) return recipients else: ",encrypt.py,"ReplaceText(target='key' @(279,23)->(279,32))","def get_recipients(args): recipients = [] for recipient in args['']: key = binascii.unhexlify(recipient) assert len(recipient) == 32 recipients.append(key) return recipients else:","def get_recipients(args): recipients = [] for recipient in args['']: key = binascii.unhexlify(recipient) assert len(key) == 32 recipients.append(key) return recipients else:" 1696,https://:@github.com/mike-perdide/gitbuster.git,8ad19a783bfe71c7b3ac9edf60c8c9bb067c23c6,"@@ -226,7 +226,7 @@ class MainWindow(QMainWindow): date_edit_widgets = (self._ui.afterDateFilterDateEdit, self._ui.beforeDateFilterDateEdit) - for widget in time_edit_widgets: + for widget in date_edit_widgets: self.connect(widget, SIGNAL(""dateChanged (const QDate&)""), self.apply_filters) ",qGitFilterBranch/main_window.py,"ReplaceText(target='date_edit_widgets' @(229,22)->(229,39))","class MainWindow(QMainWindow): date_edit_widgets = (self._ui.afterDateFilterDateEdit, self._ui.beforeDateFilterDateEdit) for widget in time_edit_widgets: self.connect(widget, SIGNAL(""dateChanged (const QDate&)""), self.apply_filters) ","class MainWindow(QMainWindow): date_edit_widgets = (self._ui.afterDateFilterDateEdit, self._ui.beforeDateFilterDateEdit) for widget in date_edit_widgets: self.connect(widget, SIGNAL(""dateChanged (const QDate&)""), self.apply_filters) " 1697,https://:@bitbucket.org/wyleyr/schoolutils.git,026584c7774cac6eb15d8d7697f9c9bc2453dbc3,"@@ -821,7 +821,7 @@ def date(s): y, m, d = s.strip().split('-') y = year(y) m = month(m) - d = day(m) + d = day(d) return datetime.date(y, m, d) def sid(s): ",schoolutils/grading/db.py,"ReplaceText(target='d' @(824,12)->(824,13))","def date(s): y, m, d = s.strip().split('-') y = year(y) m = month(m) d = day(m) return datetime.date(y, m, d) def sid(s):","def date(s): y, m, d = s.strip().split('-') y = year(y) m = month(m) d = day(d) return datetime.date(y, m, d) def sid(s):" 1698,https://:@github.com/panoptes/piaa.git,c3e81501289525d1eeb40edf892a8139b030cc5f,"@@ -534,7 +534,7 @@ class Observation(object): ls='dashed', edgecolor='blue', )) - ax3.add_patch(patches.Rectangle( + ax2.add_patch(patches.Rectangle( (0, 0), 9, 9, fill=False, ",piaa/observation.py,"ReplaceText(target='ax2' @(537,8)->(537,11))","class Observation(object): ls='dashed', edgecolor='blue', )) ax3.add_patch(patches.Rectangle( (0, 0), 9, 9, fill=False,","class Observation(object): ls='dashed', edgecolor='blue', )) ax2.add_patch(patches.Rectangle( (0, 0), 9, 9, fill=False," 1699,https://:@github.com/jenzopr/pydemult.git,f28f2da5e86f205887c7431ee6ea583440a47ad7,"@@ -92,7 +92,7 @@ def demultiplex(): q_bc_dict = dict((k, barcode_dict[k]) for k in chunk) writer_pool.apply_async(_writer, (q, q_bc_dict), callback = lambda x: print(x)) queue_list.append(q) - for bc in chunk.values(): + for bc in q_bc_dict.values(): queues[bc] = q zcat = subprocess.Popen(['zcat', args.fastq], stdout=subprocess.PIPE, bufsize = bufsize) ",pydemult/pydemult.py,"ReplaceText(target='q_bc_dict' @(95,18)->(95,23))","def demultiplex(): q_bc_dict = dict((k, barcode_dict[k]) for k in chunk) writer_pool.apply_async(_writer, (q, q_bc_dict), callback = lambda x: print(x)) queue_list.append(q) for bc in chunk.values(): queues[bc] = q zcat = subprocess.Popen(['zcat', args.fastq], stdout=subprocess.PIPE, bufsize = bufsize)","def demultiplex(): q_bc_dict = dict((k, barcode_dict[k]) for k in chunk) writer_pool.apply_async(_writer, (q, q_bc_dict), callback = lambda x: print(x)) queue_list.append(q) for bc in q_bc_dict.values(): queues[bc] = q zcat = subprocess.Popen(['zcat', args.fastq], stdout=subprocess.PIPE, bufsize = bufsize)" 1700,https://:@github.com/oneup40/chunkfile.git,3df3f2f196f7ec150a8dd86a9b10ec2773a2d4d0,"@@ -171,7 +171,7 @@ class ChunkFile(object): def _do_write(self, offset, data): n = offset / CHUNKDATASIZE - while n > len(self.chunks): + while n >= len(self.chunks): self._add_new_chunk() nextchunkofs = (n+1) * CHUNKDATASIZE ",chunkfile/ChunkFile.py,"ReplaceText(target='>=' @(174,16)->(174,17))","class ChunkFile(object): def _do_write(self, offset, data): n = offset / CHUNKDATASIZE while n > len(self.chunks): self._add_new_chunk() nextchunkofs = (n+1) * CHUNKDATASIZE","class ChunkFile(object): def _do_write(self, offset, data): n = offset / CHUNKDATASIZE while n >= len(self.chunks): self._add_new_chunk() nextchunkofs = (n+1) * CHUNKDATASIZE" 1701,https://:@github.com/Omega-Cube/graphite-query.git,8143c1364413d50b9c8805a14e69efbcbc546d25,"@@ -1250,7 +1250,7 @@ def removeBelowValue(requestContext, seriesList, n): for s in seriesList: s.name = 'removeBelowValue(%s, %d)' % (s.name, n) for (index, val) in enumerate(s): - if val > n: + if val < n: s[index] = None return seriesList ",webapp/graphite/render/functions.py,"ReplaceText(target='<' @(1253,13)->(1253,14))","def removeBelowValue(requestContext, seriesList, n): for s in seriesList: s.name = 'removeBelowValue(%s, %d)' % (s.name, n) for (index, val) in enumerate(s): if val > n: s[index] = None return seriesList","def removeBelowValue(requestContext, seriesList, n): for s in seriesList: s.name = 'removeBelowValue(%s, %d)' % (s.name, n) for (index, val) in enumerate(s): if val < n: s[index] = None return seriesList" 1702,https://:@github.com/rhedak/hhpy.git,71e1853e3a51dc0991d5eedeaa3fb270b60bb8eb,"@@ -502,7 +502,7 @@ def distplot(x, data=None, hue=None, hue_order=None, palette=None, hue_labels=No _ax.plot(__x, _y, linestyle=_f_distfit_line, color=_f_distfit_color, alpha=alpha, linewidth=2, label=_label_2, **kwargs) if not show_hist and _f_fill: - _ax.fill_between(_f_bins, _y, color=_f_facecolor, alpha=alpha) + _ax.fill_between(__x, _y, color=_f_facecolor, alpha=alpha) _f_ax2.get_yaxis().set_visible(False) ",hpy/plotting.py,"ReplaceText(target='__x' @(505,37)->(505,44))","def distplot(x, data=None, hue=None, hue_order=None, palette=None, hue_labels=No _ax.plot(__x, _y, linestyle=_f_distfit_line, color=_f_distfit_color, alpha=alpha, linewidth=2, label=_label_2, **kwargs) if not show_hist and _f_fill: _ax.fill_between(_f_bins, _y, color=_f_facecolor, alpha=alpha) _f_ax2.get_yaxis().set_visible(False) ","def distplot(x, data=None, hue=None, hue_order=None, palette=None, hue_labels=No _ax.plot(__x, _y, linestyle=_f_distfit_line, color=_f_distfit_color, alpha=alpha, linewidth=2, label=_label_2, **kwargs) if not show_hist and _f_fill: _ax.fill_between(__x, _y, color=_f_facecolor, alpha=alpha) _f_ax2.get_yaxis().set_visible(False) " 1703,https://:@github.com/rhedak/hhpy.git,89f3003a5580e2d96cc11e26aa63ab9dc3f493a6,"@@ -2136,7 +2136,7 @@ def k_split(df: pd.DataFrame, k: int = 5, groupby: Union[Sequence, str] = None, _df = df.copy() del df - _index_name = df.index.name + _index_name = _df.index.name _df['_index'] = _df.index _k_split = int(np.ceil(_df.shape[0] / k)) ",hpy/ds.py,"ReplaceText(target='_df' @(2139,18)->(2139,20))","def k_split(df: pd.DataFrame, k: int = 5, groupby: Union[Sequence, str] = None, _df = df.copy() del df _index_name = df.index.name _df['_index'] = _df.index _k_split = int(np.ceil(_df.shape[0] / k)) ","def k_split(df: pd.DataFrame, k: int = 5, groupby: Union[Sequence, str] = None, _df = df.copy() del df _index_name = _df.index.name _df['_index'] = _df.index _k_split = int(np.ceil(_df.shape[0] / k)) " 1704,https://:@github.com/EmoteCollector/ec_client.git,4bcb64e0b7f1ba125c405ccd10d205bb32e841ca,"@@ -25,7 +25,7 @@ class Client: return self._new_emote(await self._http.create(name, url)) async def edit(self, name_, *, name=None, description=utils.sentinel): - return self._new_emote(await self._http.edit(name, name=name, description=description)) + return self._new_emote(await self._http.edit(name_, name=name, description=description)) async def delete(self, name): return self._new_emote(await self._http.delete(name)) ",aioec/client.py,"ReplaceText(target='name_' @(28,47)->(28,51))","class Client: return self._new_emote(await self._http.create(name, url)) async def edit(self, name_, *, name=None, description=utils.sentinel): return self._new_emote(await self._http.edit(name, name=name, description=description)) async def delete(self, name): return self._new_emote(await self._http.delete(name))","class Client: return self._new_emote(await self._http.create(name, url)) async def edit(self, name_, *, name=None, description=utils.sentinel): return self._new_emote(await self._http.edit(name_, name=name, description=description)) async def delete(self, name): return self._new_emote(await self._http.delete(name))" 1705,https://:@github.com/giganticode/langmodels.git,862615609159bf1247bcb6294f34dec9e27a1805,"@@ -30,7 +30,7 @@ def get_entropy_for_each_line(trained_model: TrainedModel, 'entropies': entropies, 'line_entropy': line_entropy }) - if not verbose: + if verbose: for line in prep_lines_and_entropies: print(line['text']) print(line['line_entropy']) ",langmodels/inference/entropies.py,"ReplaceText(target='' @(33,11)->(33,15))","def get_entropy_for_each_line(trained_model: TrainedModel, 'entropies': entropies, 'line_entropy': line_entropy }) if not verbose: for line in prep_lines_and_entropies: print(line['text']) print(line['line_entropy'])","def get_entropy_for_each_line(trained_model: TrainedModel, 'entropies': entropies, 'line_entropy': line_entropy }) if verbose: for line in prep_lines_and_entropies: print(line['text']) print(line['line_entropy'])" 1706,https://:@github.com/kerryeon/test-macro.git,ba50132db1d907a684d759772f586a8911864d9c,"@@ -111,7 +111,7 @@ class TestMacro: # TODO more pretty with tqdm(total=len(self)) as pbar: - on_error = True + on_error = False while True: case = self._dump() pbar.set_description(''.join( ",test_macro/macro.py,"ReplaceText(target='False' @(114,23)->(114,27))","class TestMacro: # TODO more pretty with tqdm(total=len(self)) as pbar: on_error = True while True: case = self._dump() pbar.set_description(''.join(","class TestMacro: # TODO more pretty with tqdm(total=len(self)) as pbar: on_error = False while True: case = self._dump() pbar.set_description(''.join(" 1707,https://:@github.com/InsaneMonster/USienaRL.git,95e212aed41ba20d3535558cb3104f39405f3c52,"@@ -460,7 +460,7 @@ class Experiment: self._display_test_cycle_metrics(logger, test_cycle_average_total_reward, test_cycle_average_scaled_reward, - test_cycles_rewards) + test_cycle_rewards) # Save the rewards test_average_total_rewards[test] = test_cycle_average_total_reward test_average_scaled_rewards[test] = test_cycle_average_scaled_reward ",usienarl/experiment.py,"ReplaceText(target='test_cycle_rewards' @(463,49)->(463,68))","class Experiment: self._display_test_cycle_metrics(logger, test_cycle_average_total_reward, test_cycle_average_scaled_reward, test_cycles_rewards) # Save the rewards test_average_total_rewards[test] = test_cycle_average_total_reward test_average_scaled_rewards[test] = test_cycle_average_scaled_reward","class Experiment: self._display_test_cycle_metrics(logger, test_cycle_average_total_reward, test_cycle_average_scaled_reward, test_cycle_rewards) # Save the rewards test_average_total_rewards[test] = test_cycle_average_total_reward test_average_scaled_rewards[test] = test_cycle_average_scaled_reward" 1708,https://:@github.com/311devs/peewee.git,95743d856ac5ea0908a5bab62ec99fda799ae241,"@@ -330,7 +330,7 @@ class BaseQuery(object): query.append(parsed) query_data.extend(data) elif isinstance(child, Node): - parsed, data = self.parse_node(node, model, alias) + parsed, data = self.parse_node(child, model, alias) query.append('(%s)' % parsed) query_data.extend(data) query.extend(nodes) ",peewee.py,"ReplaceText(target='child' @(333,47)->(333,51))","class BaseQuery(object): query.append(parsed) query_data.extend(data) elif isinstance(child, Node): parsed, data = self.parse_node(node, model, alias) query.append('(%s)' % parsed) query_data.extend(data) query.extend(nodes)","class BaseQuery(object): query.append(parsed) query_data.extend(data) elif isinstance(child, Node): parsed, data = self.parse_node(child, model, alias) query.append('(%s)' % parsed) query_data.extend(data) query.extend(nodes)" 1709,https://:@github.com/311devs/peewee.git,33b06ced6d60abac3e0342f86a1cb16fc981ab0a,"@@ -1281,7 +1281,7 @@ class FieldTypeTests(BasePeeweeTestCase): user_indexes = self.get_sorted_indexes(User) if BACKEND == 'mysql': - entry_indexes.pop(0) + user_indexes.pop(0) self.assertEqual(user_indexes, [ ('users_active', False), ",tests.py,"ReplaceText(target='user_indexes' @(1284,12)->(1284,25))","class FieldTypeTests(BasePeeweeTestCase): user_indexes = self.get_sorted_indexes(User) if BACKEND == 'mysql': entry_indexes.pop(0) self.assertEqual(user_indexes, [ ('users_active', False),","class FieldTypeTests(BasePeeweeTestCase): user_indexes = self.get_sorted_indexes(User) if BACKEND == 'mysql': user_indexes.pop(0) self.assertEqual(user_indexes, [ ('users_active', False)," 1710,https://:@github.com/311devs/peewee.git,de772f33bfffd60aa8b5e28d0b0ba743b0c54c6d,"@@ -311,7 +311,7 @@ class CommentCategory(TestModel): sort_order = IntegerField(default=0) class Meta: - primary_key = CompositeKey('category', 'comment') + primary_key = CompositeKey('comment', 'category') class BlogData(TestModel): blog = ForeignKeyField(Blog) ",playhouse/tests/models.py,"ArgSwap(idxs=0<->1 @(314,22)->(314,34))","class CommentCategory(TestModel): sort_order = IntegerField(default=0) class Meta: primary_key = CompositeKey('category', 'comment') class BlogData(TestModel): blog = ForeignKeyField(Blog)","class CommentCategory(TestModel): sort_order = IntegerField(default=0) class Meta: primary_key = CompositeKey('comment', 'category') class BlogData(TestModel): blog = ForeignKeyField(Blog)" 1711,https://:@github.com/311devs/peewee.git,9bc7df7cc4be146a8ad8baf7427c2902537e93da,"@@ -57,7 +57,7 @@ def print_models(introspector, tables=None): # In the event the destination table has already been pushed # for printing, then we have a reference cycle. if dest in accum and table not in accum: - print_('# Possible reference cycle: %s' % foreign_key) + print_('# Possible reference cycle: %s' % dest) # If this is not a self-referential foreign key, and we have # not already processed the destination table, do so now. ",pwiz.py,"ReplaceText(target='dest' @(60,58)->(60,69))","def print_models(introspector, tables=None): # In the event the destination table has already been pushed # for printing, then we have a reference cycle. if dest in accum and table not in accum: print_('# Possible reference cycle: %s' % foreign_key) # If this is not a self-referential foreign key, and we have # not already processed the destination table, do so now.","def print_models(introspector, tables=None): # In the event the destination table has already been pushed # for printing, then we have a reference cycle. if dest in accum and table not in accum: print_('# Possible reference cycle: %s' % dest) # If this is not a self-referential foreign key, and we have # not already processed the destination table, do so now." 1712,https://:@github.com/311devs/peewee.git,61188a5f69b35323d19f1bac301beb288e549b4b,"@@ -2076,7 +2076,7 @@ class ModelQueryResultWrapper(QueryResultWrapper): can_populate_joined_pk = ( mpk and (metadata.attr in inst._data) and - (getattr(joined_inst, metadata.primary_key) is not None)) + (getattr(joined_inst, metadata.primary_key) is None)) if can_populate_joined_pk: setattr( joined_inst, ",peewee.py,"ReplaceText(target=' is ' @(2079,59)->(2079,67))","class ModelQueryResultWrapper(QueryResultWrapper): can_populate_joined_pk = ( mpk and (metadata.attr in inst._data) and (getattr(joined_inst, metadata.primary_key) is not None)) if can_populate_joined_pk: setattr( joined_inst,","class ModelQueryResultWrapper(QueryResultWrapper): can_populate_joined_pk = ( mpk and (metadata.attr in inst._data) and (getattr(joined_inst, metadata.primary_key) is None)) if can_populate_joined_pk: setattr( joined_inst," 1713,https://:@github.com/MGlauer/python-gavel.git,d0c456ce4d51bf64cfbae7f9969fb80dbab94ff3,"@@ -13,7 +13,7 @@ def get_engine(): cred = DB_CONNECTION.get(""user"", """") if cred: if ""password"" in DB_CONNECTION: - cred += ""{user}:{password}"".format(**DB_CONNECTION) + cred = ""{user}:{password}"".format(**DB_CONNECTION) cred += ""@"" location = DB_CONNECTION.get(""host"", """") ",src/gavel/dialects/db/connection.py,"ReplaceText(target='=' @(16,21)->(16,23))","def get_engine(): cred = DB_CONNECTION.get(""user"", """") if cred: if ""password"" in DB_CONNECTION: cred += ""{user}:{password}"".format(**DB_CONNECTION) cred += ""@"" location = DB_CONNECTION.get(""host"", """")","def get_engine(): cred = DB_CONNECTION.get(""user"", """") if cred: if ""password"" in DB_CONNECTION: cred = ""{user}:{password}"".format(**DB_CONNECTION) cred += ""@"" location = DB_CONNECTION.get(""host"", """")" 1714,https://:@github.com/skakri/django-wiki-base.git,7b40385d27cbf7a336f41d2e24b19e42fdce1667,"@@ -79,7 +79,7 @@ class WikiPath(markdown.inlinepatterns.Pattern): urlpath = None path = path_from_link try: - urlpath = models.URLPath.get_by_path(path_from_link) + urlpath = models.URLPath.get_by_path(article_title) path = urlpath.get_absolute_url() except models.URLPath.DoesNotExist: pass ",wiki/plugins/highlighter/mdx/djangowikilinks.py,"ReplaceText(target='article_title' @(82,53)->(82,67))","class WikiPath(markdown.inlinepatterns.Pattern): urlpath = None path = path_from_link try: urlpath = models.URLPath.get_by_path(path_from_link) path = urlpath.get_absolute_url() except models.URLPath.DoesNotExist: pass","class WikiPath(markdown.inlinepatterns.Pattern): urlpath = None path = path_from_link try: urlpath = models.URLPath.get_by_path(article_title) path = urlpath.get_absolute_url() except models.URLPath.DoesNotExist: pass" 1715,https://:@github.com/dhilowitz/launchpad_rtmidi.py.git,82ff68631e2e9d415d35c2d54fb3c0d8837ce22a,"@@ -494,7 +494,7 @@ class Launchpad( LaunchpadBase ): #------------------------------------------------------------------------------------- def LedCtrlXY( self, x, y, red, green ): - if x < 0 or y > 8 or y < 0 or y > 8: + if x < 0 or x > 8 or y < 0 or y > 8: return if y == 0: ",launchpad.py,"ReplaceText(target='x' @(497,14)->(497,15))","class Launchpad( LaunchpadBase ): #------------------------------------------------------------------------------------- def LedCtrlXY( self, x, y, red, green ): if x < 0 or y > 8 or y < 0 or y > 8: return if y == 0:","class Launchpad( LaunchpadBase ): #------------------------------------------------------------------------------------- def LedCtrlXY( self, x, y, red, green ): if x < 0 or x > 8 or y < 0 or y > 8: return if y == 0:" 1716,https://:@github.com/archman/phantasy.git,a6485f5f71a295581d7ed558e6ff6e4fb6f3f2aa,"@@ -327,7 +327,7 @@ class FlameLatticeFactory(BaseLatticeFactory): _LOGGER.info(""Alignment error: dx of {} is {} m."".format(ename, dx)) align_error_conf.append(('dx', float(dx))) dy = self._get_config(ename, CONFIG_ALIGNMENT_DY, None) - if dx is not None: + if dy is not None: _LOGGER.info(""Alignment error: dx of {} is {} m."".format(ename, dx)) align_error_conf.append(('dy', float(dy))) return align_error_conf ",phantasy/library/lattice/flame.py,"ReplaceText(target='dy' @(330,11)->(330,13))","class FlameLatticeFactory(BaseLatticeFactory): _LOGGER.info(""Alignment error: dx of {} is {} m."".format(ename, dx)) align_error_conf.append(('dx', float(dx))) dy = self._get_config(ename, CONFIG_ALIGNMENT_DY, None) if dx is not None: _LOGGER.info(""Alignment error: dx of {} is {} m."".format(ename, dx)) align_error_conf.append(('dy', float(dy))) return align_error_conf","class FlameLatticeFactory(BaseLatticeFactory): _LOGGER.info(""Alignment error: dx of {} is {} m."".format(ename, dx)) align_error_conf.append(('dx', float(dx))) dy = self._get_config(ename, CONFIG_ALIGNMENT_DY, None) if dy is not None: _LOGGER.info(""Alignment error: dx of {} is {} m."".format(ename, dx)) align_error_conf.append(('dy', float(dy))) return align_error_conf" 1717,https://:@github.com/mardiros/pyramid_asyncio.git,f675334092897ddadb75c313c2ab511e8e0c65df,"@@ -259,7 +259,7 @@ class Router(RouterBase): yield from includeme(self.config) except Exception: - log.exception('{} raise an exception'.format(includeme)) + log.exception('{} raise an exception'.format(callable)) @asyncio.coroutine def close(self): ",pyramid_asyncio/router.py,"ReplaceText(target='callable' @(262,61)->(262,70))","class Router(RouterBase): yield from includeme(self.config) except Exception: log.exception('{} raise an exception'.format(includeme)) @asyncio.coroutine def close(self):","class Router(RouterBase): yield from includeme(self.config) except Exception: log.exception('{} raise an exception'.format(callable)) @asyncio.coroutine def close(self):" 1718,https://:@github.com/CI-WATER/TethysCluster.git,d21d18ef5e52db0bb7695137520f03469d55afea,"@@ -49,5 +49,5 @@ class CmdGet(ClusterCompleter): for rpath in rpaths: if not glob.has_magic(rpath) and not node.ssh.path_exists(rpath): raise exception.BaseException( - ""Remote file or directory does not exist: %s"" % lpath) + ""Remote file or directory does not exist: %s"" % rpath) node.ssh.get(rpaths, lpath) ",starcluster/commands/get.py,"ReplaceText(target='rpath' @(52,68)->(52,73))","class CmdGet(ClusterCompleter): for rpath in rpaths: if not glob.has_magic(rpath) and not node.ssh.path_exists(rpath): raise exception.BaseException( ""Remote file or directory does not exist: %s"" % lpath) node.ssh.get(rpaths, lpath)","class CmdGet(ClusterCompleter): for rpath in rpaths: if not glob.has_magic(rpath) and not node.ssh.path_exists(rpath): raise exception.BaseException( ""Remote file or directory does not exist: %s"" % rpath) node.ssh.get(rpaths, lpath)" 1719,https://:@github.com/Afoucaul/pyx.git,de3367e912c06c7485102b40844d4593eca7d928,"@@ -28,7 +28,7 @@ def retrieve_task(name): def execute_task(task_name, args): task = retrieve_task(task_name) - subprocess.run([""python3"", task_name] + args) + subprocess.run([""python3"", task] + args) def print_command_list(): ",pyx/__main__.py,"ReplaceText(target='task' @(31,31)->(31,40))","def retrieve_task(name): def execute_task(task_name, args): task = retrieve_task(task_name) subprocess.run([""python3"", task_name] + args) def print_command_list():","def retrieve_task(name): def execute_task(task_name, args): task = retrieve_task(task_name) subprocess.run([""python3"", task] + args) def print_command_list():" 1720,https://:@github.com/ziplokk1/python-amazon-mws-tools.git,0d45b6519c3c1f25c473f03ea49f1b8968a43a54,"@@ -15,7 +15,7 @@ class GetCompetitivePricingForAsinRequester(object): @raise_for_error def _request(self, asins, marketplaceid): - response = self.api.get_competitive_pricing_for_asin(asins, marketplaceid) + response = self.api.get_competitive_pricing_for_asin(marketplaceid, asins) write_response(response, 'GetCompetitivePricingForAsinResponse.xml') response.raise_for_status() return response.content ",mwstools/requesters/products.py,"ArgSwap(idxs=0<->1 @(18,19)->(18,60))","class GetCompetitivePricingForAsinRequester(object): @raise_for_error def _request(self, asins, marketplaceid): response = self.api.get_competitive_pricing_for_asin(asins, marketplaceid) write_response(response, 'GetCompetitivePricingForAsinResponse.xml') response.raise_for_status() return response.content","class GetCompetitivePricingForAsinRequester(object): @raise_for_error def _request(self, asins, marketplaceid): response = self.api.get_competitive_pricing_for_asin(marketplaceid, asins) write_response(response, 'GetCompetitivePricingForAsinResponse.xml') response.raise_for_status() return response.content" 1721,https://:@github.com/techhat/grabbr.git,8cacc0a60f1a66c60966e389b0d5b494b7540a4e,"@@ -94,7 +94,7 @@ def run(run_opts=None): # pylint: disable=too-many-return-statements out.info(pprint.pformat(opts)) return - if context.get('show_context'): + if opts.get('show_context'): out.info(pprint.pformat(context)) return ",flayer/scripts.py,"ReplaceText(target='opts' @(97,7)->(97,14))","def run(run_opts=None): # pylint: disable=too-many-return-statements out.info(pprint.pformat(opts)) return if context.get('show_context'): out.info(pprint.pformat(context)) return ","def run(run_opts=None): # pylint: disable=too-many-return-statements out.info(pprint.pformat(opts)) return if opts.get('show_context'): out.info(pprint.pformat(context)) return " 1722,https://:@github.com/seetaresearch/Dragon.git,e90a8f1a6e53b6403c9dc81c45be4665574937bc,"@@ -39,7 +39,7 @@ class BlobFetcher(multiprocessing.Process): super(BlobFetcher, self).__init__() self._batch_size = kwargs.get('batch_size', 128) self._partition = kwargs.get('partition', False) - if self._partition: self._batch_size /= kwargs['group_size'] + if self._partition: self._batch_size //= kwargs['group_size'] self.Q_in = self.Q_out = None self.daemon = True ",Dragon/python/dragon/utils/vision/blob_fetcher.py,"ReplaceText(target='//=' @(42,45)->(42,47))","class BlobFetcher(multiprocessing.Process): super(BlobFetcher, self).__init__() self._batch_size = kwargs.get('batch_size', 128) self._partition = kwargs.get('partition', False) if self._partition: self._batch_size /= kwargs['group_size'] self.Q_in = self.Q_out = None self.daemon = True ","class BlobFetcher(multiprocessing.Process): super(BlobFetcher, self).__init__() self._batch_size = kwargs.get('batch_size', 128) self._partition = kwargs.get('partition', False) if self._partition: self._batch_size //= kwargs['group_size'] self.Q_in = self.Q_out = None self.daemon = True " 1723,https://:@github.com/powersj/ubuntu-release-info.git,09808f92dce3afcdee9f2f478587f4ad67ee906b,"@@ -79,7 +79,7 @@ class Release: def __ne__(self, other): """"""Return not equal boolean."""""" - if not isinstance(other, Release): + if isinstance(other, Release): return False return not self.__eq__(other) ",ubuntu_release_info/release.py,"ReplaceText(target='' @(82,11)->(82,15))","class Release: def __ne__(self, other): """"""Return not equal boolean."""""" if not isinstance(other, Release): return False return not self.__eq__(other)","class Release: def __ne__(self, other): """"""Return not equal boolean."""""" if isinstance(other, Release): return False return not self.__eq__(other)" 1724,https://:@github.com/aimagelab/speaksee.git,895b3fd57b934b75ad683bfba2a77f76a54a9570,"@@ -16,7 +16,7 @@ class Meteor: jar_path = os.path.join(base_path, METEOR_JAR) gz_path = os.path.join(base_path, os.path.basename(METEOR_GZ_URL)) if not os.path.isfile(jar_path): - if not os.path.isfile(jar_path): + if not os.path.isfile(gz_path): download_from_url(METEOR_GZ_URL, gz_path) tar = tarfile.open(gz_path, ""r"") tar.extractall(path=os.path.dirname(os.path.abspath(__file__))) ",speaksee/evaluation/meteor/meteor.py,"ReplaceText(target='gz_path' @(19,34)->(19,42))","class Meteor: jar_path = os.path.join(base_path, METEOR_JAR) gz_path = os.path.join(base_path, os.path.basename(METEOR_GZ_URL)) if not os.path.isfile(jar_path): if not os.path.isfile(jar_path): download_from_url(METEOR_GZ_URL, gz_path) tar = tarfile.open(gz_path, ""r"") tar.extractall(path=os.path.dirname(os.path.abspath(__file__)))","class Meteor: jar_path = os.path.join(base_path, METEOR_JAR) gz_path = os.path.join(base_path, os.path.basename(METEOR_GZ_URL)) if not os.path.isfile(jar_path): if not os.path.isfile(gz_path): download_from_url(METEOR_GZ_URL, gz_path) tar = tarfile.open(gz_path, ""r"") tar.extractall(path=os.path.dirname(os.path.abspath(__file__)))" 1725,https://:@github.com/nitely/regexy.git,6b260a4464763dc483058bff9450ca7306031abe,"@@ -315,7 +315,7 @@ def search(nfa: NFA, text: Iterator[str]) -> Union[MatchedType, None]: captured=captured, chars=(char, next_char))) - curr_states_set.extend(curr_states( + next_states_set.extend(curr_states( state=nfa.state, captured=None, chars=(char, next_char))) ",regexy/process/match.py,"ReplaceText(target='next_states_set' @(318,8)->(318,23))","def search(nfa: NFA, text: Iterator[str]) -> Union[MatchedType, None]: captured=captured, chars=(char, next_char))) curr_states_set.extend(curr_states( state=nfa.state, captured=None, chars=(char, next_char)))","def search(nfa: NFA, text: Iterator[str]) -> Union[MatchedType, None]: captured=captured, chars=(char, next_char))) next_states_set.extend(curr_states( state=nfa.state, captured=None, chars=(char, next_char)))" 1726,https://:@github.com/vertcoin/electrum-vtc.git,3835751fac314a7c8f7e11edede64bc409877e88,"@@ -553,7 +553,7 @@ class InstallWizard(QDialog): if Wallet.is_seed(text3): wallet.add_cosigner_seed(text3, ""x3/"", password) elif Wallet.is_xpub(text3): - wallet.add_master_public_key(""x3/"", text2) + wallet.add_master_public_key(""x3/"", text3) wallet.create_main_account(password) ",gui/qt/installwizard.py,"ReplaceText(target='text3' @(556,56)->(556,61))","class InstallWizard(QDialog): if Wallet.is_seed(text3): wallet.add_cosigner_seed(text3, ""x3/"", password) elif Wallet.is_xpub(text3): wallet.add_master_public_key(""x3/"", text2) wallet.create_main_account(password) ","class InstallWizard(QDialog): if Wallet.is_seed(text3): wallet.add_cosigner_seed(text3, ""x3/"", password) elif Wallet.is_xpub(text3): wallet.add_master_public_key(""x3/"", text3) wallet.create_main_account(password) " 1727,https://:@github.com/vertcoin/electrum-vtc.git,0947eb7960496eeb959a4af3fd3c9097a3e27e56,"@@ -243,7 +243,7 @@ class Network(threading.Thread): self.config.set_key(""proxy"", proxy_str, True) self.config.set_key(""server"", server_str, True) # abort if changes were not allowed by config - if self.config.get('server') != server_str or self.config.get('proxy') != proxy: + if self.config.get('server') != server_str or self.config.get('proxy') != proxy_str: return if self.proxy != proxy or self.protocol != protocol: ",lib/network.py,"ReplaceText(target='proxy_str' @(246,82)->(246,87))","class Network(threading.Thread): self.config.set_key(""proxy"", proxy_str, True) self.config.set_key(""server"", server_str, True) # abort if changes were not allowed by config if self.config.get('server') != server_str or self.config.get('proxy') != proxy: return if self.proxy != proxy or self.protocol != protocol:","class Network(threading.Thread): self.config.set_key(""proxy"", proxy_str, True) self.config.set_key(""server"", server_str, True) # abort if changes were not allowed by config if self.config.get('server') != server_str or self.config.get('proxy') != proxy_str: return if self.proxy != proxy or self.protocol != protocol:" 1728,https://:@github.com/vertcoin/electrum-vtc.git,c35485c1c21d11b3dc067d5e8afaedd3827c0ce0,"@@ -115,7 +115,7 @@ class Plugin(BasePlugin): def transaction_dialog(self, d): self.send_button = b = QPushButton(_(""Send to cosigner"")) b.clicked.connect(lambda: self.do_send(d.tx)) - d.buttons.insert(2, b) + d.buttons.insert(0, b) self.transaction_dialog_update(d) @hook ",plugins/cosigner_pool.py,"ReplaceText(target='0' @(118,25)->(118,26))","class Plugin(BasePlugin): def transaction_dialog(self, d): self.send_button = b = QPushButton(_(""Send to cosigner"")) b.clicked.connect(lambda: self.do_send(d.tx)) d.buttons.insert(2, b) self.transaction_dialog_update(d) @hook","class Plugin(BasePlugin): def transaction_dialog(self, d): self.send_button = b = QPushButton(_(""Send to cosigner"")) b.clicked.connect(lambda: self.do_send(d.tx)) d.buttons.insert(0, b) self.transaction_dialog_update(d) @hook" 1729,https://:@github.com/vertcoin/electrum-vtc.git,bce42cb496e2516420623a455a6080848a2d3a7c,"@@ -188,7 +188,7 @@ class TxDialog(QDialog, MessageBoxMixin): height, conf, timestamp = self.wallet.get_tx_height(tx_hash) if height > 0: if conf: - status = _(""%d confirmations"") % height + status = _(""%d confirmations"") % conf time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] else: status = _('Not verified') ",gui/qt/transaction_dialog.py,"ReplaceText(target='conf' @(191,57)->(191,63))","class TxDialog(QDialog, MessageBoxMixin): height, conf, timestamp = self.wallet.get_tx_height(tx_hash) if height > 0: if conf: status = _(""%d confirmations"") % height time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] else: status = _('Not verified')","class TxDialog(QDialog, MessageBoxMixin): height, conf, timestamp = self.wallet.get_tx_height(tx_hash) if height > 0: if conf: status = _(""%d confirmations"") % conf time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] else: status = _('Not verified')" 1730,https://:@github.com/vertcoin/electrum-vtc.git,688dd07381c28090dd0bbb6bb2b9c96fd7dc9ad0,"@@ -32,7 +32,7 @@ class Plugin(DigitalBitboxPlugin, QtPluginBase): if len(addrs) == 1: def show_address(): - keystore.thread.add(partial(self.show_address, wallet, keystore, addrs[0])) + keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore)) menu.addAction(_(""Show on {}"").format(self.device), show_address) ",plugins/digitalbitbox/qt.py,"ArgSwap(idxs=2<->3 @(35,36)->(35,43))","class Plugin(DigitalBitboxPlugin, QtPluginBase): if len(addrs) == 1: def show_address(): keystore.thread.add(partial(self.show_address, wallet, keystore, addrs[0])) menu.addAction(_(""Show on {}"").format(self.device), show_address) ","class Plugin(DigitalBitboxPlugin, QtPluginBase): if len(addrs) == 1: def show_address(): keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore)) menu.addAction(_(""Show on {}"").format(self.device), show_address) " 1731,https://:@github.com/mpevnev/epp.git,7fc959840f17ceaa50764853b802721b1039a29e,"@@ -189,7 +189,7 @@ def parse(seed, state_or_string, parser, verbose=False): after = parser(state) if after.effect is not None: return after, after.effect(seed, after) - return state, seed + return after, seed except ParsingFailure as failure: if verbose: return failure ",src/epp/core.py,"ReplaceText(target='after' @(192,15)->(192,20))","def parse(seed, state_or_string, parser, verbose=False): after = parser(state) if after.effect is not None: return after, after.effect(seed, after) return state, seed except ParsingFailure as failure: if verbose: return failure","def parse(seed, state_or_string, parser, verbose=False): after = parser(state) if after.effect is not None: return after, after.effect(seed, after) return after, seed except ParsingFailure as failure: if verbose: return failure" 1732,https://:@github.com/MarineDataTools/pycnv.git,c2a0387257ef4b96cd8e2af2690be14e9c74c208,"@@ -251,7 +251,7 @@ def parse_iow_header(header,pycnv_object=None): lat_str_min = latitude.split()[1][:-1] # The old Reise has ',' as decimal seperator, replace it with '.' lon_str_min = lon_str_min.replace(',','.') - lat_str_min = lon_str_min.replace(',','.') + lat_str_min = lat_str_min.replace(',','.') # Convert to floats lon = SIGN_WEST * float(longitude.split()[0]) + float(lon_str_min)/60. lat = SIGN_NORTH * float(latitude.split()[0]) + float(lat_str_min)/60. ",pycnv/pycnv.py,"ReplaceText(target='lat_str_min' @(254,30)->(254,41))","def parse_iow_header(header,pycnv_object=None): lat_str_min = latitude.split()[1][:-1] # The old Reise has ',' as decimal seperator, replace it with '.' lon_str_min = lon_str_min.replace(',','.') lat_str_min = lon_str_min.replace(',','.') # Convert to floats lon = SIGN_WEST * float(longitude.split()[0]) + float(lon_str_min)/60. lat = SIGN_NORTH * float(latitude.split()[0]) + float(lat_str_min)/60.","def parse_iow_header(header,pycnv_object=None): lat_str_min = latitude.split()[1][:-1] # The old Reise has ',' as decimal seperator, replace it with '.' lon_str_min = lon_str_min.replace(',','.') lat_str_min = lat_str_min.replace(',','.') # Convert to floats lon = SIGN_WEST * float(longitude.split()[0]) + float(lon_str_min)/60. lat = SIGN_NORTH * float(latitude.split()[0]) + float(lat_str_min)/60." 1733,https://:@github.com/nelimeee/qasm2image.git,d782f7b9d9dcdcfa76ae22c6211a03b656d99980,"@@ -296,7 +296,7 @@ def _draw_classically_conditioned_part(drawing: Drawing, operation=operation) x_coord = _helpers.get_x_from_index(index_to_draw) yq_coord = _helpers.get_y_from_quantum_register(qubits[0], bit_mapping) - yc_coord = _helpers.get_y_from_classical_register(total_clbits_number-1, total_qubits_number, + yc_coord = _helpers.get_y_from_classical_register(number_of_clbits-1, total_qubits_number, bit_mapping) # Then draw the double line representing the classical control. _draw_classical_double_line(drawing, x_coord, yq_coord, x_coord, yc_coord) ",qasm2image/svg/_drawing.py,"ReplaceText(target='number_of_clbits' @(299,54)->(299,73))","def _draw_classically_conditioned_part(drawing: Drawing, operation=operation) x_coord = _helpers.get_x_from_index(index_to_draw) yq_coord = _helpers.get_y_from_quantum_register(qubits[0], bit_mapping) yc_coord = _helpers.get_y_from_classical_register(total_clbits_number-1, total_qubits_number, bit_mapping) # Then draw the double line representing the classical control. _draw_classical_double_line(drawing, x_coord, yq_coord, x_coord, yc_coord)","def _draw_classically_conditioned_part(drawing: Drawing, operation=operation) x_coord = _helpers.get_x_from_index(index_to_draw) yq_coord = _helpers.get_y_from_quantum_register(qubits[0], bit_mapping) yc_coord = _helpers.get_y_from_classical_register(number_of_clbits-1, total_qubits_number, bit_mapping) # Then draw the double line representing the classical control. _draw_classical_double_line(drawing, x_coord, yq_coord, x_coord, yc_coord)" 1734,https://:@github.com/iportillo/ITU-Rpy.git,3ee41f116cf7400097837aca514f36b2a62d0f3f,"@@ -103,7 +103,7 @@ class _ITU835_5(): P = np.zeros((n + 1)) P[0] = P_0 for i in range(n): - h_p = H[ret_i] if i == (n - 1) else H[i + 1] + h_p = h[ret_i] if i == (n - 1) else H[i + 1] if L[i] != 0: P[i + 1] = P[i] * \ (T[i] / (T[i] + L[i] * (h_p - H[i])))**(34.163 / L[i]) ",itur/models/itu835.py,"ReplaceText(target='h' @(106,22)->(106,23))","class _ITU835_5(): P = np.zeros((n + 1)) P[0] = P_0 for i in range(n): h_p = H[ret_i] if i == (n - 1) else H[i + 1] if L[i] != 0: P[i + 1] = P[i] * \ (T[i] / (T[i] + L[i] * (h_p - H[i])))**(34.163 / L[i])","class _ITU835_5(): P = np.zeros((n + 1)) P[0] = P_0 for i in range(n): h_p = h[ret_i] if i == (n - 1) else H[i + 1] if L[i] != 0: P[i + 1] = P[i] * \ (T[i] / (T[i] + L[i] * (h_p - H[i])))**(34.163 / L[i])" 1735,https://:@github.com/uw-loci/mp-python-modules.git,bf29e09937e4b119cac002762b170438fe00e13a,"@@ -164,7 +164,7 @@ def process_orientation_alignment(ret_image_path, orient_image_path, retardance, orientation = calculate_retardance_over_area( ret_roi, orient_roi) - alignment = calculate_alignment(orient_tile) + alignment = calculate_alignment(orient_roi) sample = blk.get_core_file_name(output_path) mouse, slide = sample.split('-') ",mp_img_manip/polarimetry.py,"ReplaceText(target='orient_roi' @(167,56)->(167,67))","def process_orientation_alignment(ret_image_path, orient_image_path, retardance, orientation = calculate_retardance_over_area( ret_roi, orient_roi) alignment = calculate_alignment(orient_tile) sample = blk.get_core_file_name(output_path) mouse, slide = sample.split('-')","def process_orientation_alignment(ret_image_path, orient_image_path, retardance, orientation = calculate_retardance_over_area( ret_roi, orient_roi) alignment = calculate_alignment(orient_roi) sample = blk.get_core_file_name(output_path) mouse, slide = sample.split('-')" 1736,https://:@github.com/uw-loci/mp-python-modules.git,0d7c717669ebb28a61909ce9b8cefb05ccb80dd5,"@@ -48,7 +48,7 @@ def create_dictionary( ""mhr_large_orient"": os.path.join(base_dir, prep_dir, 'MHR_Large_Orient'), ""mlr_large"": os.path.join(base_dir, prep_dir, 'MLR_Large'), ""mlr_large_orient"": os.path.join(base_dir, prep_dir, 'MLR_Large_Orient'), - ""he_small"": os.path.join(base_dir, prep_dir, 'HE_Small'), + ""he_small"": os.path.join(base_dir, resize_dir, 'HE_Small'), ""he_large"": os.path.join(base_dir, prep_dir, 'HE_Large'), ""shg_small"": os.path.join(base_dir, resize_dir, 'SHG_Small'), ",mp_img_manip/dir_dictionary.py,"ReplaceText(target='resize_dir' @(51,43)->(51,51))","def create_dictionary( ""mhr_large_orient"": os.path.join(base_dir, prep_dir, 'MHR_Large_Orient'), ""mlr_large"": os.path.join(base_dir, prep_dir, 'MLR_Large'), ""mlr_large_orient"": os.path.join(base_dir, prep_dir, 'MLR_Large_Orient'), ""he_small"": os.path.join(base_dir, prep_dir, 'HE_Small'), ""he_large"": os.path.join(base_dir, prep_dir, 'HE_Large'), ""shg_small"": os.path.join(base_dir, resize_dir, 'SHG_Small'),","def create_dictionary( ""mhr_large_orient"": os.path.join(base_dir, prep_dir, 'MHR_Large_Orient'), ""mlr_large"": os.path.join(base_dir, prep_dir, 'MLR_Large'), ""mlr_large_orient"": os.path.join(base_dir, prep_dir, 'MLR_Large_Orient'), ""he_small"": os.path.join(base_dir, resize_dir, 'HE_Small'), ""he_large"": os.path.join(base_dir, prep_dir, 'HE_Large'), ""shg_small"": os.path.join(base_dir, resize_dir, 'SHG_Small')," 1737,https://:@github.com/uw-loci/mp-python-modules.git,1b703cd8f176c289d52c195094a7f2035ebf0a15,"@@ -78,7 +78,7 @@ def plot_overlay(fixed_image: sitk.Image, moving_image: sitk.Image, transform: s if downsample: fixed_shrunk = trans.resize_image(fixed_image, fixed_image.GetSpacing()[0], downsample_target) - rotated_shrunk = trans.resize_image(rotated_image, moving_image.GetSpacing()[0], downsample_target) + rotated_shrunk = trans.resize_image(rotated_image, fixed_image.GetSpacing()[0], downsample_target) spacing = fixed_shrunk.GetSpacing() overlay_array = overlay_images(fixed_shrunk, rotated_shrunk) ",multiscale/itk/itk_plotting.py,"ReplaceText(target='fixed_image' @(81,67)->(81,79))","def plot_overlay(fixed_image: sitk.Image, moving_image: sitk.Image, transform: s if downsample: fixed_shrunk = trans.resize_image(fixed_image, fixed_image.GetSpacing()[0], downsample_target) rotated_shrunk = trans.resize_image(rotated_image, moving_image.GetSpacing()[0], downsample_target) spacing = fixed_shrunk.GetSpacing() overlay_array = overlay_images(fixed_shrunk, rotated_shrunk)","def plot_overlay(fixed_image: sitk.Image, moving_image: sitk.Image, transform: s if downsample: fixed_shrunk = trans.resize_image(fixed_image, fixed_image.GetSpacing()[0], downsample_target) rotated_shrunk = trans.resize_image(rotated_image, fixed_image.GetSpacing()[0], downsample_target) spacing = fixed_shrunk.GetSpacing() overlay_array = overlay_images(fixed_shrunk, rotated_shrunk)" 1738,https://:@github.com/uw-loci/mp-python-modules.git,66a12265d2e2289686d445c9a9785581773bc31b,"@@ -106,7 +106,7 @@ def process_orientation_alignment(ret_image_path, orient_image_path, if roi_size is None: with open(output_path, 'w', newline='') as csvfile: print('\nWriting average retardance file for {} at tile size {}'.format( - output_path.name, tile_size[0])) + ret_image_path.name, tile_size[0])) writer = csv.writer(csvfile) writer.writerow(['Mouse', 'Slide', 'Modality', 'Tile', 'Retardance', 'Orientation', 'Alignment']) ",multiscale/polarimetry/polarimetry.py,"ReplaceText(target='ret_image_path' @(109,32)->(109,43))","def process_orientation_alignment(ret_image_path, orient_image_path, if roi_size is None: with open(output_path, 'w', newline='') as csvfile: print('\nWriting average retardance file for {} at tile size {}'.format( output_path.name, tile_size[0])) writer = csv.writer(csvfile) writer.writerow(['Mouse', 'Slide', 'Modality', 'Tile', 'Retardance', 'Orientation', 'Alignment'])","def process_orientation_alignment(ret_image_path, orient_image_path, if roi_size is None: with open(output_path, 'w', newline='') as csvfile: print('\nWriting average retardance file for {} at tile size {}'.format( ret_image_path.name, tile_size[0])) writer = csv.writer(csvfile) writer.writerow(['Mouse', 'Slide', 'Modality', 'Tile', 'Retardance', 'Orientation', 'Alignment'])" 1739,https://:@github.com/doubleo8/e2openplugin-OpenWebif.git,41ae09e6d9003cc234f37c228e14227365b2cf84,"@@ -251,7 +251,7 @@ def getInfo(): elif iecsize > 1000: iecsize = ""%d GB"" % ((iecsize + 500) // 1000) else: - iecsize = ""%d MB"" % size + iecsize = ""%d MB"" % iecsize info['hdd'].append({ ""model"": hdd.model(), ",plugin/controllers/models/info.py,"ReplaceText(target='iecsize' @(254,23)->(254,27))","def getInfo(): elif iecsize > 1000: iecsize = ""%d GB"" % ((iecsize + 500) // 1000) else: iecsize = ""%d MB"" % size info['hdd'].append({ ""model"": hdd.model(),","def getInfo(): elif iecsize > 1000: iecsize = ""%d GB"" % ((iecsize + 500) // 1000) else: iecsize = ""%d MB"" % iecsize info['hdd'].append({ ""model"": hdd.model()," 1740,https://:@github.com/doubleo8/e2openplugin-OpenWebif.git,3450c566c64c05386771b243135583d611b0b68d,"@@ -303,7 +303,7 @@ class EventsController(object): if minutes is None: minutes = QUERY_MINUTES_ANY - if querytype != QUERYTYPE_LOOKUP__ID: + if querytype == QUERYTYPE_LOOKUP__ID: arglist = (service_reference, querytype, begin) else: arglist = (service_reference, querytype, begin, minutes) ",plugin/controllers/events.py,"ReplaceText(target='==' @(306,21)->(306,23))","class EventsController(object): if minutes is None: minutes = QUERY_MINUTES_ANY if querytype != QUERYTYPE_LOOKUP__ID: arglist = (service_reference, querytype, begin) else: arglist = (service_reference, querytype, begin, minutes)","class EventsController(object): if minutes is None: minutes = QUERY_MINUTES_ANY if querytype == QUERYTYPE_LOOKUP__ID: arglist = (service_reference, querytype, begin) else: arglist = (service_reference, querytype, begin, minutes)" 1741,https://:@github.com/alexbahnisch/mosi.py.git,3e2f73c5e3b5e87ca6f2b4a7f391e01ee2e9a89e,"@@ -5,7 +5,7 @@ class BaseObject: @classmethod def isinstance(cls, instance): - if not isinstance(instance, cls): + if isinstance(instance, cls): return instance else: raise TypeError(""'%s' is not an instance of '%s'"" % (instance, cls.__name__)) ",src/main/mosi/common/base.py,"ReplaceText(target='' @(8,11)->(8,15))","class BaseObject: @classmethod def isinstance(cls, instance): if not isinstance(instance, cls): return instance else: raise TypeError(""'%s' is not an instance of '%s'"" % (instance, cls.__name__))","class BaseObject: @classmethod def isinstance(cls, instance): if isinstance(instance, cls): return instance else: raise TypeError(""'%s' is not an instance of '%s'"" % (instance, cls.__name__))" 1742,https://:@github.com/hudora/huSoftM.git,24a5bc8359d376e681ad04e46b43c3d177f6b1e1,"@@ -168,7 +168,7 @@ def get_kunde_by_iln(iln): if rows: rows2 = husoftm.connection.get_connection().query(['XXA00'], condition=""XASANR='%s'"" % (int(rows[0]['satznr']), )) - if rows: + if rows2: kunde = Kunde().fill_from_softm(rows2[0]) kunde.kundennr = kunde.kundennr + ('/%03d' % int(rows[0]['versandadresssnr'])) return kunde ",husoftm/kunden.py,"ReplaceText(target='rows2' @(171,15)->(171,19))","def get_kunde_by_iln(iln): if rows: rows2 = husoftm.connection.get_connection().query(['XXA00'], condition=""XASANR='%s'"" % (int(rows[0]['satznr']), )) if rows: kunde = Kunde().fill_from_softm(rows2[0]) kunde.kundennr = kunde.kundennr + ('/%03d' % int(rows[0]['versandadresssnr'])) return kunde","def get_kunde_by_iln(iln): if rows: rows2 = husoftm.connection.get_connection().query(['XXA00'], condition=""XASANR='%s'"" % (int(rows[0]['satznr']), )) if rows2: kunde = Kunde().fill_from_softm(rows2[0]) kunde.kundennr = kunde.kundennr + ('/%03d' % int(rows[0]['versandadresssnr'])) return kunde" 1743,https://:@github.com/tcalmant/ipopo.git,e20719b0abd219171d2475f0173273fbcb010c2a,"@@ -218,7 +218,7 @@ class ComponentFactoryC(TestComponentFactory): self.states.append(IPopoEvent.UNBOUND) # Assert that the service has been removed - assert svc not in self.services + assert svc in self.services # ------------------------------------------------------------------------------ ",tests/ipopo_bundle.py,"ReplaceText(target=' in ' @(221,18)->(221,26))","class ComponentFactoryC(TestComponentFactory): self.states.append(IPopoEvent.UNBOUND) # Assert that the service has been removed assert svc not in self.services # ------------------------------------------------------------------------------ ","class ComponentFactoryC(TestComponentFactory): self.states.append(IPopoEvent.UNBOUND) # Assert that the service has been removed assert svc in self.services # ------------------------------------------------------------------------------ " 1744,https://:@github.com/tcalmant/ipopo.git,c01df06c7514898146d56fed710fbde194233526,"@@ -133,7 +133,7 @@ class ConfigAdminCommands(object): new_properties.update(kwargs) # Update configuration - config.update(kwargs) + config.update(new_properties) def delete(self, io_handler, pid, **kwargs): ",pelix/shell/configadmin.py,"ReplaceText(target='new_properties' @(136,22)->(136,28))","class ConfigAdminCommands(object): new_properties.update(kwargs) # Update configuration config.update(kwargs) def delete(self, io_handler, pid, **kwargs):","class ConfigAdminCommands(object): new_properties.update(kwargs) # Update configuration config.update(new_properties) def delete(self, io_handler, pid, **kwargs):" 1745,https://:@github.com/buxx/AntStar.git,5d7cfd673453d5c97843707dd719e638d5a7acfe,"@@ -23,7 +23,7 @@ class BuxxAntBrain(AntBrain): def _add_memory_since_blocked(self, position): memory_since_blocked = self.get_memory_since_blocked() memory_since_blocked.append(position) - self._set_memory_since_blocked(position) + self._set_memory_since_blocked(memory_since_blocked) def is_by_passing(self): return self._by_passing ",antstar/BuxxAntBrain.py,"ReplaceText(target='memory_since_blocked' @(26,39)->(26,47))","class BuxxAntBrain(AntBrain): def _add_memory_since_blocked(self, position): memory_since_blocked = self.get_memory_since_blocked() memory_since_blocked.append(position) self._set_memory_since_blocked(position) def is_by_passing(self): return self._by_passing","class BuxxAntBrain(AntBrain): def _add_memory_since_blocked(self, position): memory_since_blocked = self.get_memory_since_blocked() memory_since_blocked.append(position) self._set_memory_since_blocked(memory_since_blocked) def is_by_passing(self): return self._by_passing" 1746,https://:@github.com/keystonetowersystems/siquant.git,586dd72d0e7e6de3d244ad10288cbc6b9586464c,"@@ -30,7 +30,7 @@ class Quantity: return self.__class__(self.get_as(units), units) def normalized(self): - return self.__class__(self._quantity / self._units._scale, self._units.base_units()) + return self.__class__(self._quantity * self._units._scale, self._units.base_units()) def __add__(self, other): if isinstance(other, self.__class__): ",siquant/quantities.py,"ReplaceText(target='*' @(33,45)->(33,46))","class Quantity: return self.__class__(self.get_as(units), units) def normalized(self): return self.__class__(self._quantity / self._units._scale, self._units.base_units()) def __add__(self, other): if isinstance(other, self.__class__):","class Quantity: return self.__class__(self.get_as(units), units) def normalized(self): return self.__class__(self._quantity * self._units._scale, self._units.base_units()) def __add__(self, other): if isinstance(other, self.__class__):" 1747,https://:@github.com/maykinmedia/django-rijkshuisstijl.git,08ce24312018313c1908ea0c9430118ce5182df8,"@@ -64,7 +64,7 @@ def form(context, form=None, label="""", **kwargs): config[""status""] = config.get(""status"") config[""intro_status""] = config.get(""intro_status"") config[""tag""] = config.get(""tag"", ""form"") - config[""actions""] = parse_kwarg(kwargs, ""actions"", []) # TODO: Default action + config[""actions""] = parse_kwarg(config, ""actions"", []) # TODO: Default action config[""actions_align""] = config.get(""actions_align"", ""left"") config[""actions_position""] = config.get(""actions_position"", ""auto"") config[""help_text_position""] = config.get(""help_text_position"", settings.RH_HELP_TEXT_POSITION) ",rijkshuisstijl/templatetags/rijkshuisstijl_form.py,"ReplaceText(target='config' @(67,36)->(67,42))","def form(context, form=None, label="""", **kwargs): config[""status""] = config.get(""status"") config[""intro_status""] = config.get(""intro_status"") config[""tag""] = config.get(""tag"", ""form"") config[""actions""] = parse_kwarg(kwargs, ""actions"", []) # TODO: Default action config[""actions_align""] = config.get(""actions_align"", ""left"") config[""actions_position""] = config.get(""actions_position"", ""auto"") config[""help_text_position""] = config.get(""help_text_position"", settings.RH_HELP_TEXT_POSITION)","def form(context, form=None, label="""", **kwargs): config[""status""] = config.get(""status"") config[""intro_status""] = config.get(""intro_status"") config[""tag""] = config.get(""tag"", ""form"") config[""actions""] = parse_kwarg(config, ""actions"", []) # TODO: Default action config[""actions_align""] = config.get(""actions_align"", ""left"") config[""actions_position""] = config.get(""actions_position"", ""auto"") config[""help_text_position""] = config.get(""help_text_position"", settings.RH_HELP_TEXT_POSITION)" 1748,https://:@github.com/seandavidmcgee/remodel.git,022acfaad861270c9467a80708c169c5336564e9,"@@ -34,7 +34,7 @@ class FieldHandlerBase(type): dct[field] = BelongsToDescriptor(other, lkey, rkey) dct['related'].add(field) dct['restricted'].add(lkey) - index_registry.register(other, lkey) + index_registry.register(model, lkey) for rel in dct.pop('has_many'): if isinstance(rel, tuple): other, field, lkey, rkey = rel ",remodel/field_handler.py,"ReplaceText(target='model' @(37,36)->(37,41))","class FieldHandlerBase(type): dct[field] = BelongsToDescriptor(other, lkey, rkey) dct['related'].add(field) dct['restricted'].add(lkey) index_registry.register(other, lkey) for rel in dct.pop('has_many'): if isinstance(rel, tuple): other, field, lkey, rkey = rel","class FieldHandlerBase(type): dct[field] = BelongsToDescriptor(other, lkey, rkey) dct['related'].add(field) dct['restricted'].add(lkey) index_registry.register(model, lkey) for rel in dct.pop('has_many'): if isinstance(rel, tuple): other, field, lkey, rkey = rel" 1749,https://:@github.com/eddieantonio/fst-lookup.git,f8bf12528168bf1f27585d28aec32afb8097f559,"@@ -253,7 +253,7 @@ if True: # state num, in/out, target, final state src, in_label, dest, is_final = arc_def if is_final == 1: - assert in_label == -1 or dest == -1 + assert in_label == -1 and dest == -1 arc_simple = src, in_label, in_label, dest, is_final elif num_items == 5: arc_simple = arc_def # type: ignore ",fst_lookup/parse.py,"ReplaceText(target='and' @(256,38)->(256,40))","if True: # state num, in/out, target, final state src, in_label, dest, is_final = arc_def if is_final == 1: assert in_label == -1 or dest == -1 arc_simple = src, in_label, in_label, dest, is_final elif num_items == 5: arc_simple = arc_def # type: ignore","if True: # state num, in/out, target, final state src, in_label, dest, is_final = arc_def if is_final == 1: assert in_label == -1 and dest == -1 arc_simple = src, in_label, in_label, dest, is_final elif num_items == 5: arc_simple = arc_def # type: ignore" 1750,https://:@github.com/datasnakes/OrthoEvolution.git,5cb58ce3c3bca9f468a942e6d090f0aa54e01982,"@@ -239,7 +239,7 @@ class CompGenAnalysis(PM): # Gene analysis self.mygene_df = self.my_gene_info() - self.mygene_df.to_csv(self.mygene_df, self.mygene_path) + self.mygene_df.to_csv(self.mygene_path, self.mygene_df) # Accession file analysis if self.__post_blast: self.missing_dict = self.get_miss_acc() ",Orthologs/CompGenetics/comp_gen.py,"ArgSwap(idxs=0<->1 @(242,8)->(242,29))","class CompGenAnalysis(PM): # Gene analysis self.mygene_df = self.my_gene_info() self.mygene_df.to_csv(self.mygene_df, self.mygene_path) # Accession file analysis if self.__post_blast: self.missing_dict = self.get_miss_acc()","class CompGenAnalysis(PM): # Gene analysis self.mygene_df = self.my_gene_info() self.mygene_df.to_csv(self.mygene_path, self.mygene_df) # Accession file analysis if self.__post_blast: self.missing_dict = self.get_miss_acc()" 1751,https://:@github.com/datasnakes/OrthoEvolution.git,2e64342b400356667a594477fc6c3792a0ab5bf6,"@@ -432,7 +432,7 @@ class Qsub(BaseQsub): """""" if not rerun: # Format or copy the python script. - if python_attributes is None: + if python_attributes is not None: self.format_python_script(py_template_string=py_template_string, py_template_file=py_template_file, python_attributes=python_attributes) elif not self.python_script.exists(): ",OrthoEvol/Tools/pbs/qsub.py,"ReplaceText(target=' is not ' @(435,32)->(435,36))","class Qsub(BaseQsub): """""" if not rerun: # Format or copy the python script. if python_attributes is None: self.format_python_script(py_template_string=py_template_string, py_template_file=py_template_file, python_attributes=python_attributes) elif not self.python_script.exists():","class Qsub(BaseQsub): """""" if not rerun: # Format or copy the python script. if python_attributes is not None: self.format_python_script(py_template_string=py_template_string, py_template_file=py_template_file, python_attributes=python_attributes) elif not self.python_script.exists():" 1752,https://:@github.com/etianen/cms.git,ba145043590e03f70de0455a969bc6eb220db137,"@@ -140,7 +140,7 @@ class PageBase(PublishedModel): ""title"": self.browser_title or self.title, ""header"": self.title} page_context.update(context or {}) - return render_to_response(template, context, RequestContext(request), **kwargs) + return render_to_response(template, page_context, RequestContext(request), **kwargs) # Base model methods. ",src/cms/apps/pages/models/base.py,"ReplaceText(target='page_context' @(143,44)->(143,51))","class PageBase(PublishedModel): ""title"": self.browser_title or self.title, ""header"": self.title} page_context.update(context or {}) return render_to_response(template, context, RequestContext(request), **kwargs) # Base model methods. ","class PageBase(PublishedModel): ""title"": self.browser_title or self.title, ""header"": self.title} page_context.update(context or {}) return render_to_response(template, page_context, RequestContext(request), **kwargs) # Base model methods. " 1753,https://:@github.com/etianen/cms.git,b521ab26117288742645598a82ed547fc446580e,"@@ -48,7 +48,7 @@ def index(request): connection = mail.SMTPConnection() connection.send_messages(messages) # Redirect the user. - return redirect(content.reverse(""message_sent"")) + return redirect(page.reverse(""message_sent"")) else: contact_form = ContactForm() context = {""contact_form"": contact_form} ",src/cms/apps/contact/views.py,"ReplaceText(target='page' @(51,28)->(51,35))","def index(request): connection = mail.SMTPConnection() connection.send_messages(messages) # Redirect the user. return redirect(content.reverse(""message_sent"")) else: contact_form = ContactForm() context = {""contact_form"": contact_form}","def index(request): connection = mail.SMTPConnection() connection.send_messages(messages) # Redirect the user. return redirect(page.reverse(""message_sent"")) else: contact_form = ContactForm() context = {""contact_form"": contact_form}" 1754,https://:@github.com/AmmsA/Githeat.git,ce58c7cba9d405c0f828032d312670adb870435a,"@@ -145,7 +145,7 @@ def _cmdline(argv=None): 'INFO', 'DEBUG', 'NOTSET'], help=""logger level"") - args = parser.parse_args(remaining_argv) + args = parser.parse_args(argv) if args.days: args.days = _is_valid_days_list(args.days) ",lib/githeat/__main__.py,"ReplaceText(target='argv' @(148,29)->(148,43))","def _cmdline(argv=None): 'INFO', 'DEBUG', 'NOTSET'], help=""logger level"") args = parser.parse_args(remaining_argv) if args.days: args.days = _is_valid_days_list(args.days)","def _cmdline(argv=None): 'INFO', 'DEBUG', 'NOTSET'], help=""logger level"") args = parser.parse_args(argv) if args.days: args.days = _is_valid_days_list(args.days)" 1755,https://:@github.com/bbalasub1/glmnet_python.git,c9b08ed3713f2448017bc041e78324add75196b7,"@@ -117,7 +117,7 @@ def plotCoef(beta, norm, lambdau, df, dev, label, xvar, xlab, ylab, **options): ax2.xaxis.tick_top() xlim1 = ax1.get_xlim() - ylim1 = ax2.get_ylim() + ylim1 = ax1.get_ylim() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer) ",lib/glmnetPlot.py,"ReplaceText(target='ax1' @(120,12)->(120,15))","def plotCoef(beta, norm, lambdau, df, dev, label, xvar, xlab, ylab, **options): ax2.xaxis.tick_top() xlim1 = ax1.get_xlim() ylim1 = ax2.get_ylim() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer)","def plotCoef(beta, norm, lambdau, df, dev, label, xvar, xlab, ylab, **options): ax2.xaxis.tick_top() xlim1 = ax1.get_xlim() ylim1 = ax1.get_ylim() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer)" 1756,https://:@gitlab.com/Philbrick/rilcontour.git,761f40842912f0d74901ef325837140c57054381,"@@ -1250,7 +1250,7 @@ class ProjectDatasetDefinition : try : if self._project_lock_file is not None : try : - if not os.path.exists (self._project_lock_file) : + if os.path.exists (self._project_lock_file) : file = open (self._project_lock_file, ""rt"") data = file.readlines () file.close () ",rilcontour/rilcontourlib/dataset/rcc_DatasetInterface.py,"ReplaceText(target='' @(1253,23)->(1253,27))","class ProjectDatasetDefinition : try : if self._project_lock_file is not None : try : if not os.path.exists (self._project_lock_file) : file = open (self._project_lock_file, ""rt"") data = file.readlines () file.close ()","class ProjectDatasetDefinition : try : if self._project_lock_file is not None : try : if os.path.exists (self._project_lock_file) : file = open (self._project_lock_file, ""rt"") data = file.readlines () file.close ()" 1757,https://:@gitlab.com/Philbrick/rilcontour.git,c6454ef1d68bd169bc66b59b3a00ecf61d7c04ff,"@@ -152,7 +152,7 @@ class VerticalSliceSelectionWidget (QtWidgets.QWidget): qp.setBrush (color) qp.setPen (color) xE = int (i + xC) - qp.drawLine (xC, yP, xE, yP) + qp.drawLine (xE, yP, xE, yP) else: rightP = int (xC) scaleFactor = float (xSize) / float (numberofColors) ",rilcontour/rilcontourlib/ui/qt_widgets/verticalsliceselectionwidget.py,"ReplaceText(target='xE' @(155,33)->(155,35))","class VerticalSliceSelectionWidget (QtWidgets.QWidget): qp.setBrush (color) qp.setPen (color) xE = int (i + xC) qp.drawLine (xC, yP, xE, yP) else: rightP = int (xC) scaleFactor = float (xSize) / float (numberofColors) ","class VerticalSliceSelectionWidget (QtWidgets.QWidget): qp.setBrush (color) qp.setPen (color) xE = int (i + xC) qp.drawLine (xE, yP, xE, yP) else: rightP = int (xC) scaleFactor = float (xSize) / float (numberofColors) " 1758,https://:@gitlab.com/Philbrick/rilcontour.git,9202d914149d100e0f47b9ca06c1cd8530276a93,"@@ -1172,7 +1172,7 @@ def _FileSystemMaskExportProcess (tpl) : if len (writepathdir) > 200 : writepathdir, _ = os.path.split (writepath) FileUtil.createPath (writepathdir, False) - CreateWriteDirPathFromShortFilePath = not os.path.isdir (writepath) + CreateWriteDirPathFromShortFilePath = not os.path.isdir (writepathdir) if CreateWriteDirPathFromShortFilePath : writepathdir, _ = os.path.split (writepath) FileUtil.createPath (writepathdir, False) ",rilcontour/rilcontourlib/ui/rcc_datasetui.py,"ReplaceText(target='writepathdir' @(1175,74)->(1175,83))","def _FileSystemMaskExportProcess (tpl) : if len (writepathdir) > 200 : writepathdir, _ = os.path.split (writepath) FileUtil.createPath (writepathdir, False) CreateWriteDirPathFromShortFilePath = not os.path.isdir (writepath) if CreateWriteDirPathFromShortFilePath : writepathdir, _ = os.path.split (writepath) FileUtil.createPath (writepathdir, False) ","def _FileSystemMaskExportProcess (tpl) : if len (writepathdir) > 200 : writepathdir, _ = os.path.split (writepath) FileUtil.createPath (writepathdir, False) CreateWriteDirPathFromShortFilePath = not os.path.isdir (writepathdir) if CreateWriteDirPathFromShortFilePath : writepathdir, _ = os.path.split (writepath) FileUtil.createPath (writepathdir, False) " 1759,https://:@gitlab.com/Philbrick/rilcontour.git,0489a4e534eea576731cbf896e9c6f7f6be92dd8,"@@ -2020,7 +2020,7 @@ class AbstractTreeWidgetNode (QObject): lst = self.getChildernLst () if len (lst) > 0 : for child in lst : - if (not child.getROIDatasetIndicator ()) : + if (child.getROIDatasetIndicator ()) : found = True break if found != currentValue or val is not None: ",rilcontour/rilcontourlib/dataset/rcc_DatasetInterface.py,"ReplaceText(target='' @(2023,35)->(2023,39))","class AbstractTreeWidgetNode (QObject): lst = self.getChildernLst () if len (lst) > 0 : for child in lst : if (not child.getROIDatasetIndicator ()) : found = True break if found != currentValue or val is not None:","class AbstractTreeWidgetNode (QObject): lst = self.getChildernLst () if len (lst) > 0 : for child in lst : if (child.getROIDatasetIndicator ()) : found = True break if found != currentValue or val is not None:" 1760,https://:@gitlab.com/Philbrick/rilcontour.git,35450ed144e97370690dab365510431eb03a0636,"@@ -2411,7 +2411,7 @@ class DatasetTagManager : def removeAllInternalTags (self, SafeNameSet = None ) : if SafeNameSet is not None : - if isinstance (SafeNameSet, set) : + if not isinstance (SafeNameSet, set) : SafeNameSet = set (SafeNameSet) else: SafeNameSet = set () ",rilcontour/rilcontourlib/util/rcc_util.py,"ReplaceText(target='not ' @(2414,15)->(2414,15))","class DatasetTagManager : def removeAllInternalTags (self, SafeNameSet = None ) : if SafeNameSet is not None : if isinstance (SafeNameSet, set) : SafeNameSet = set (SafeNameSet) else: SafeNameSet = set () ","class DatasetTagManager : def removeAllInternalTags (self, SafeNameSet = None ) : if SafeNameSet is not None : if not isinstance (SafeNameSet, set) : SafeNameSet = set (SafeNameSet) else: SafeNameSet = set () " 1761,https://:@gitlab.com/Philbrick/rilcontour.git,2f78da773b9ba8018bd4cf1e41ec4bc99162ffdb,"@@ -3895,7 +3895,7 @@ class RCC_ContourWindow (QMainWindow): else: color = roiDefs.getROIColor (name) item.setForeground (color) - if ROIDictionary is not None and ROIDictionary.isROIDefined (txt) : + if ROIDictionary is not None and ROIDictionary.isROIDefined (name) : item.setBackground (QtGui.QColor (255,211,82)) else : item.setBackground (QtGui.QColor (255,255,255)) ",rilcontour/rilcontourlib/ui/rcc_contourwindow.py,"ReplaceText(target='name' @(3898,81)->(3898,84))","class RCC_ContourWindow (QMainWindow): else: color = roiDefs.getROIColor (name) item.setForeground (color) if ROIDictionary is not None and ROIDictionary.isROIDefined (txt) : item.setBackground (QtGui.QColor (255,211,82)) else : item.setBackground (QtGui.QColor (255,255,255))","class RCC_ContourWindow (QMainWindow): else: color = roiDefs.getROIColor (name) item.setForeground (color) if ROIDictionary is not None and ROIDictionary.isROIDefined (name) : item.setBackground (QtGui.QColor (255,211,82)) else : item.setBackground (QtGui.QColor (255,255,255))" 1762,https://:@gitlab.com/Philbrick/rilcontour.git,835dd8f6a4be5bdd30a2a929b3eddaf90817beb9,"@@ -321,7 +321,7 @@ class ML_KerasModelLoaderInterface: if (""CustomModelLoader"" in Custom_Objects) : try : try : - kModel = Custom_Objects[""CustomModelLoader""](model_path, LoadLinearModel = True) + kModel = Custom_Objects[""CustomModelLoader""](origionalModelPath, LoadLinearModel = True) except: kModel = Custom_Objects[""CustomModelLoader""](model_path) except: ",rilcontour/rilcontourlib/machinelearning/ml_DatasetInterface.py,"ReplaceText(target='origionalModelPath' @(324,85)->(324,95))","class ML_KerasModelLoaderInterface: if (""CustomModelLoader"" in Custom_Objects) : try : try : kModel = Custom_Objects[""CustomModelLoader""](model_path, LoadLinearModel = True) except: kModel = Custom_Objects[""CustomModelLoader""](model_path) except: ","class ML_KerasModelLoaderInterface: if (""CustomModelLoader"" in Custom_Objects) : try : try : kModel = Custom_Objects[""CustomModelLoader""](origionalModelPath, LoadLinearModel = True) except: kModel = Custom_Objects[""CustomModelLoader""](model_path) except: " 1763,https://:@github.com/ei-grad/nginx2es.git,9fef326d801ab4315382c713a3af11f4b9420b51,"@@ -94,7 +94,7 @@ class Stat(threading.Thread): current_time = time() with self.lock: for ts, delayed_to in list(self.delays.items()): - if delayed_to > current_time: + if delayed_to < current_time: del self.delays[ts] ready[ts] = self.buffers.pop(ts) return ready ",nginx2es/stat.py,"ReplaceText(target='<' @(97,30)->(97,31))","class Stat(threading.Thread): current_time = time() with self.lock: for ts, delayed_to in list(self.delays.items()): if delayed_to > current_time: del self.delays[ts] ready[ts] = self.buffers.pop(ts) return ready","class Stat(threading.Thread): current_time = time() with self.lock: for ts, delayed_to in list(self.delays.items()): if delayed_to < current_time: del self.delays[ts] ready[ts] = self.buffers.pop(ts) return ready" 1764,https://:@github.com/lycantropos/dendroid.git,d0b6b8369193357fd6af6df446794114b4b6a123,"@@ -13,7 +13,7 @@ def test_properties(tree: Tree) -> None: result = tree.pop() assert result not in tree - assert is_left_subtree_less_than_right_subtree(result) + assert is_left_subtree_less_than_right_subtree(tree) @given(strategies.empty_trees) ",tests/tree_tests/test_pop.py,"ReplaceText(target='tree' @(16,51)->(16,57))","def test_properties(tree: Tree) -> None: result = tree.pop() assert result not in tree assert is_left_subtree_less_than_right_subtree(result) @given(strategies.empty_trees)","def test_properties(tree: Tree) -> None: result = tree.pop() assert result not in tree assert is_left_subtree_less_than_right_subtree(tree) @given(strategies.empty_trees)" 1765,https://:@github.com/lycantropos/dendroid.git,38f152fa4ea1050801df0852c74d061749039438,"@@ -26,7 +26,7 @@ def test_properties(tree_with_value: Tuple[Tree, Domain]) -> None: tree.add(value) assert len(tree) > 0 - assert to_height(tree) > 0 + assert to_height(tree) >= 0 assert is_left_subtree_less_than_right_subtree(tree) ",tests/tree_tests/test_add.py,"ReplaceText(target='>=' @(29,27)->(29,28))","def test_properties(tree_with_value: Tuple[Tree, Domain]) -> None: tree.add(value) assert len(tree) > 0 assert to_height(tree) > 0 assert is_left_subtree_less_than_right_subtree(tree) ","def test_properties(tree_with_value: Tuple[Tree, Domain]) -> None: tree.add(value) assert len(tree) > 0 assert to_height(tree) >= 0 assert is_left_subtree_less_than_right_subtree(tree) " 1766,https://:@github.com/iclementine/text.git,6c0a9c4c902fff15b3039254e38c33ba87b0630f,"@@ -126,7 +126,7 @@ class Vocab(object): self.itos = [''] + specials counter.subtract({tok: counter[tok] for tok in [''] + specials}) - max_size = None if max_size is None else max_size - len(self.itos) + max_size = None if max_size is None else max_size + len(self.itos) # sort by frequency, then alphabetically words = sorted(counter.items(), key=lambda tup: tup[0]) ",torchtext/vocab.py,"ReplaceText(target='+' @(129,58)->(129,59))","class Vocab(object): self.itos = [''] + specials counter.subtract({tok: counter[tok] for tok in [''] + specials}) max_size = None if max_size is None else max_size - len(self.itos) # sort by frequency, then alphabetically words = sorted(counter.items(), key=lambda tup: tup[0])","class Vocab(object): self.itos = [''] + specials counter.subtract({tok: counter[tok] for tok in [''] + specials}) max_size = None if max_size is None else max_size + len(self.itos) # sort by frequency, then alphabetically words = sorted(counter.items(), key=lambda tup: tup[0])" 1767,https://:@github.com/iclementine/text.git,50694cdb17eaae035b83c884cef611be33f05c5f,"@@ -138,7 +138,7 @@ class Vocab(object): self.vectors = torch.Tensor(len(self), dim) for i, token in enumerate(self.itos): wv_index = stoi.get(token, None) - if wv_index is None: + if wv_index is not None: self.vectors[i] = vectors[wv_index] else: self.vectors[i] = unk_init(self.vectors[i]) ",torchtext/vocab.py,"ReplaceText(target=' is not ' @(141,23)->(141,27))","class Vocab(object): self.vectors = torch.Tensor(len(self), dim) for i, token in enumerate(self.itos): wv_index = stoi.get(token, None) if wv_index is None: self.vectors[i] = vectors[wv_index] else: self.vectors[i] = unk_init(self.vectors[i])","class Vocab(object): self.vectors = torch.Tensor(len(self), dim) for i, token in enumerate(self.itos): wv_index = stoi.get(token, None) if wv_index is not None: self.vectors[i] = vectors[wv_index] else: self.vectors[i] = unk_init(self.vectors[i])" 1768,https://:@github.com/thaiphamquoc/kafka-python.git,d27d49fd6b1c02dc764035cb06c3b47bf2a4b7a5,"@@ -228,7 +228,7 @@ class KafkaConsumer(object): if isinstance(arg, (six.string_types, six.binary_type)): topic = kafka_bytestring(arg) - for partition in self._client.get_partition_ids_for_topic(arg): + for partition in self._client.get_partition_ids_for_topic(topic): self._consume_topic_partition(topic, partition) # (topic, partition [, offset]) tuple ",kafka/consumer/kafka.py,"ReplaceText(target='topic' @(231,74)->(231,77))","class KafkaConsumer(object): if isinstance(arg, (six.string_types, six.binary_type)): topic = kafka_bytestring(arg) for partition in self._client.get_partition_ids_for_topic(arg): self._consume_topic_partition(topic, partition) # (topic, partition [, offset]) tuple","class KafkaConsumer(object): if isinstance(arg, (six.string_types, six.binary_type)): topic = kafka_bytestring(arg) for partition in self._client.get_partition_ids_for_topic(topic): self._consume_topic_partition(topic, partition) # (topic, partition [, offset]) tuple" 1769,https://:@github.com/thaiphamquoc/kafka-python.git,416f50b6f78328878e950d7bd8dd902c52d35b13,"@@ -64,7 +64,7 @@ class Sensor(object): now = time.time() * 1000 if time_ms is None: time_ms = now - self._last_record_time = now + self._last_record_time = time_ms with self._lock: # XXX high volume, might be performance issue # increment all the stats for stat in self._stats: ",kafka/metrics/stats/sensor.py,"ReplaceText(target='time_ms' @(67,33)->(67,36))","class Sensor(object): now = time.time() * 1000 if time_ms is None: time_ms = now self._last_record_time = now with self._lock: # XXX high volume, might be performance issue # increment all the stats for stat in self._stats:","class Sensor(object): now = time.time() * 1000 if time_ms is None: time_ms = now self._last_record_time = time_ms with self._lock: # XXX high volume, might be performance issue # increment all the stats for stat in self._stats:" 1770,https://:@github.com/thaiphamquoc/kafka-python.git,003bb0a8308e749cf0f63cd60bc2c020b2c96083,"@@ -438,7 +438,7 @@ class Fetcher(six.Iterator): # Compressed messagesets may include earlier messages # It is also possible that the user called seek() - elif msg.offset != self._subscriptions.assignment[tp].position: + elif msg.offset < self._subscriptions.assignment[tp].position: log.debug(""Skipping message offset: %s (expecting %s)"", msg.offset, self._subscriptions.assignment[tp].position) ",kafka/consumer/fetcher.py,"ReplaceText(target='<' @(441,36)->(441,38))","class Fetcher(six.Iterator): # Compressed messagesets may include earlier messages # It is also possible that the user called seek() elif msg.offset != self._subscriptions.assignment[tp].position: log.debug(""Skipping message offset: %s (expecting %s)"", msg.offset, self._subscriptions.assignment[tp].position)","class Fetcher(six.Iterator): # Compressed messagesets may include earlier messages # It is also possible that the user called seek() elif msg.offset < self._subscriptions.assignment[tp].position: log.debug(""Skipping message offset: %s (expecting %s)"", msg.offset, self._subscriptions.assignment[tp].position)" 1771,https://:@github.com/thaiphamquoc/kafka-python.git,efc03d083d323e35a2d32bcbdbccc053f737836e,"@@ -701,7 +701,7 @@ class Fetcher(six.Iterator): if error_type is Errors.NoError: if response.API_VERSION == 0: offsets = partition_info[2] - assert len(offsets) > 1, 'Expected OffsetResponse with one offset' + assert len(offsets) <= 1, 'Expected OffsetResponse with one offset' if offsets: offset = offsets[0] log.debug(""Handling v0 ListOffsetResponse response for %s. "" ",kafka/consumer/fetcher.py,"ReplaceText(target='<=' @(704,44)->(704,45))","class Fetcher(six.Iterator): if error_type is Errors.NoError: if response.API_VERSION == 0: offsets = partition_info[2] assert len(offsets) > 1, 'Expected OffsetResponse with one offset' if offsets: offset = offsets[0] log.debug(""Handling v0 ListOffsetResponse response for %s. ""","class Fetcher(six.Iterator): if error_type is Errors.NoError: if response.API_VERSION == 0: offsets = partition_info[2] assert len(offsets) <= 1, 'Expected OffsetResponse with one offset' if offsets: offset = offsets[0] log.debug(""Handling v0 ListOffsetResponse response for %s. """ 1772,https://:@github.com/lefterisjp/pystun.git,69f0b3f33fa4a8359a7dab2f080d7f79c266fee4,"@@ -231,7 +231,7 @@ def get_nat_type(s, source_ip, source_port, stun_host=None, stun_port=3478): changePortRequest = ''.join([ChangeRequest, '0004', ""00000002""]) log.debug(""Do Test3"") - ret = stun_test(s, changedIP, port, source_ip, source_port, + ret = stun_test(s, changedIP, changedPort, source_ip, source_port, changePortRequest) log.debug(""Result: %s"", ret) if ret['Resp']: ",stun/__init__.py,"ReplaceText(target='changedPort' @(234,50)->(234,54))","def get_nat_type(s, source_ip, source_port, stun_host=None, stun_port=3478): changePortRequest = ''.join([ChangeRequest, '0004', ""00000002""]) log.debug(""Do Test3"") ret = stun_test(s, changedIP, port, source_ip, source_port, changePortRequest) log.debug(""Result: %s"", ret) if ret['Resp']:","def get_nat_type(s, source_ip, source_port, stun_host=None, stun_port=3478): changePortRequest = ''.join([ChangeRequest, '0004', ""00000002""]) log.debug(""Do Test3"") ret = stun_test(s, changedIP, changedPort, source_ip, source_port, changePortRequest) log.debug(""Result: %s"", ret) if ret['Resp']:" 1773,https://:@github.com/draustin/pyqtgraph_extensions.git,1f3a1bc47998fb9076482dfa2ab8991733536c7b,"@@ -207,7 +207,7 @@ def test_all(): pgx.close_all() if __name__==""__main__"": - if QtCore.QCoreApplication.instance() is not None: + if QtCore.QCoreApplication.instance() is None: app = QtGui.QApplication([]) test_all() #f=test_AnchoredPlotItem() ",pyqtgraph_extensions/test/test_all.py,"ReplaceText(target=' is ' @(210,41)->(210,49))","def test_all(): pgx.close_all() if __name__==""__main__"": if QtCore.QCoreApplication.instance() is not None: app = QtGui.QApplication([]) test_all() #f=test_AnchoredPlotItem()","def test_all(): pgx.close_all() if __name__==""__main__"": if QtCore.QCoreApplication.instance() is None: app = QtGui.QApplication([]) test_all() #f=test_AnchoredPlotItem()" 1774,https://:@github.com/draustin/pyqtgraph_extensions.git,383e04612a893ddd033573fe69867d2d24f1a945,"@@ -244,7 +244,7 @@ class ColorBarItem(pg.GraphicsWidget): # range has not been set yet return image_range=self.image_max-self.image_min - if image_range!=0: + if image_range==0: bar_levels=0,0 else: bar_levels=(image_levels[0]-self.image_min)/image_range,(image_levels[1]-self.image_min)/image_range ",pyqtgraph_extensions/misc.py,"ReplaceText(target='==' @(247,22)->(247,24))","class ColorBarItem(pg.GraphicsWidget): # range has not been set yet return image_range=self.image_max-self.image_min if image_range!=0: bar_levels=0,0 else: bar_levels=(image_levels[0]-self.image_min)/image_range,(image_levels[1]-self.image_min)/image_range","class ColorBarItem(pg.GraphicsWidget): # range has not been set yet return image_range=self.image_max-self.image_min if image_range==0: bar_levels=0,0 else: bar_levels=(image_levels[0]-self.image_min)/image_range,(image_levels[1]-self.image_min)/image_range" 1775,https://:@github.com/beukueb/leopard.git,69fb86620b97ca0ecb22bb4c29d6ddb8cf44a9f0,"@@ -49,7 +49,7 @@ class Frame(Environment): if subtitle: self.append( pl.NoEscape(r'\framesubtitle{')+ - pl.escape_latex(title)+ + pl.escape_latex(subtitle)+ pl.NoEscape('}') ) if ncols: ",leopard/extensions/latex.py,"ReplaceText(target='subtitle' @(52,32)->(52,37))","class Frame(Environment): if subtitle: self.append( pl.NoEscape(r'\framesubtitle{')+ pl.escape_latex(title)+ pl.NoEscape('}') ) if ncols:","class Frame(Environment): if subtitle: self.append( pl.NoEscape(r'\framesubtitle{')+ pl.escape_latex(subtitle)+ pl.NoEscape('}') ) if ncols:" 1776,https://:@github.com/alexanderkell/elecsim.git,ef0c6b8c9c27cdbf1d98dcf390520f6a3c2be410,"@@ -100,7 +100,7 @@ class World(Model): def get_running_plants(self, plants): for plant in plants: - if plant.construction_year<=1990 and plant.name == ""invested_plant"": + if plant.construction_year<=1990 and plant.name != ""invested_plant"": # Reset old plants that have been modernised with new construction year plant.construction_year = randint(self.year_number-15, self.year_number) yield plant ",src/model/world.py,"ReplaceText(target='!=' @(103,60)->(103,62))","class World(Model): def get_running_plants(self, plants): for plant in plants: if plant.construction_year<=1990 and plant.name == ""invested_plant"": # Reset old plants that have been modernised with new construction year plant.construction_year = randint(self.year_number-15, self.year_number) yield plant","class World(Model): def get_running_plants(self, plants): for plant in plants: if plant.construction_year<=1990 and plant.name != ""invested_plant"": # Reset old plants that have been modernised with new construction year plant.construction_year = randint(self.year_number-15, self.year_number) yield plant" 1777,https://:@github.com/alexanderkell/elecsim.git,854be7933590eccc6793d1568d2e17a0ebfa4acd,"@@ -147,7 +147,7 @@ class GenCo(Agent): total_upfront_cost = 0 counter =0 total_capacity = 0 - while self.money > lowest_upfront_cost and total_capacity < 1500: + while self.money > lowest_upfront_cost or total_capacity < 1500: counter += 1 # if counter>3: # break ",src/agents/generation_company/gen_co.py,"ReplaceText(target='or' @(150,47)->(150,50))","class GenCo(Agent): total_upfront_cost = 0 counter =0 total_capacity = 0 while self.money > lowest_upfront_cost and total_capacity < 1500: counter += 1 # if counter>3: # break","class GenCo(Agent): total_upfront_cost = 0 counter =0 total_capacity = 0 while self.money > lowest_upfront_cost or total_capacity < 1500: counter += 1 # if counter>3: # break" 1778,https://:@github.com/nats-io/nkeys.py.git,8a5b00f83a77559d8ed73e863d9d31e0d3cd01a8,"@@ -131,7 +131,7 @@ class KeyPair(object): kp = self._keys.get_verifying_key() try: - kp.verify(input, sig) + kp.verify(sig, input) return True except ed25519.BadSignatureError: raise ErrInvalidSignature() ",nkeys/nkeys.py,"ArgSwap(idxs=0<->1 @(134,12)->(134,21))","class KeyPair(object): kp = self._keys.get_verifying_key() try: kp.verify(input, sig) return True except ed25519.BadSignatureError: raise ErrInvalidSignature()","class KeyPair(object): kp = self._keys.get_verifying_key() try: kp.verify(sig, input) return True except ed25519.BadSignatureError: raise ErrInvalidSignature()" 1779,https://:@github.com/nats-io/nkeys.py.git,697dd3f60206600e05aed90edea302e7985940b9,"@@ -77,7 +77,7 @@ def run(): signed_data = base64.b64decode(encoded_data) user = nkeys.from_seed(seed) - if user.verify(signed_data, data): + if user.verify(data, signed_data): print(""Verified OK"") sys.exit(0) ",examples/nk/__main__.py,"ArgSwap(idxs=0<->1 @(80,11)->(80,22))","def run(): signed_data = base64.b64decode(encoded_data) user = nkeys.from_seed(seed) if user.verify(signed_data, data): print(""Verified OK"") sys.exit(0) ","def run(): signed_data = base64.b64decode(encoded_data) user = nkeys.from_seed(seed) if user.verify(data, signed_data): print(""Verified OK"") sys.exit(0) " 1780,https://:@github.com/drcloud/magiclog.git,bffad2101ea9055025ebffc5be9af47492dfef03,"@@ -70,7 +70,7 @@ class Configuration(namedtuple('Configuration', 'syslog stderr extended')): log.info('Defaulting to STDERR logging.') syslog, stderr = None, (level or logging.INFO) if extended is None: - extended = (level or 0) <= logging.DEBUG + extended = (stderr or 0) <= logging.DEBUG else: log.info('Defaulting to logging with Syslog.') syslog, stderr = (level or logging.WARNING), None ",magiclog.py,"ReplaceText(target='stderr' @(73,32)->(73,37))","class Configuration(namedtuple('Configuration', 'syslog stderr extended')): log.info('Defaulting to STDERR logging.') syslog, stderr = None, (level or logging.INFO) if extended is None: extended = (level or 0) <= logging.DEBUG else: log.info('Defaulting to logging with Syslog.') syslog, stderr = (level or logging.WARNING), None","class Configuration(namedtuple('Configuration', 'syslog stderr extended')): log.info('Defaulting to STDERR logging.') syslog, stderr = None, (level or logging.INFO) if extended is None: extended = (stderr or 0) <= logging.DEBUG else: log.info('Defaulting to logging with Syslog.') syslog, stderr = (level or logging.WARNING), None" 1781,https://:@github.com/Querdos/nginx-conf-parser.git,1dce2f4ab806f999b61f9131cc59ccc110ecfd0b,"@@ -4,7 +4,7 @@ from _io import TextIOWrapper def extract_context(conffile, context_name): - if not isinstance(conffile, TextIOWrapper) or not isinstance(conffile, str): + if not isinstance(conffile, TextIOWrapper) and not isinstance(conffile, str): raise TypeError('Invalid configuration file given, must be a file stream or a string') if isinstance(conffile, TextIOWrapper): ",lib/core/utils.py,"ReplaceText(target='and' @(7,47)->(7,49))","from _io import TextIOWrapper def extract_context(conffile, context_name): if not isinstance(conffile, TextIOWrapper) or not isinstance(conffile, str): raise TypeError('Invalid configuration file given, must be a file stream or a string') if isinstance(conffile, TextIOWrapper):","from _io import TextIOWrapper def extract_context(conffile, context_name): if not isinstance(conffile, TextIOWrapper) and not isinstance(conffile, str): raise TypeError('Invalid configuration file given, must be a file stream or a string') if isinstance(conffile, TextIOWrapper):" 1782,https://:@github.com/PrincetonUniversity/lightsheet_py3.git,89482fa99b82354a416fbdafb02b719b6e6e032f,"@@ -158,7 +158,7 @@ def save_output(output, dset, output_fld, output_tag, jobid, chkpt_num, **params full_fname = os.path.join(output_fld, basename) - tifffile.imsave(output_data[0,:,:,:], full_fname, compress = 1) + tifffile.imsave(full_fname, output_data[0,:,:,:], compress = 1) return full_fname ",run_chnk_fwd.py,"ArgSwap(idxs=0<->1 @(161,8)->(161,23))","def save_output(output, dset, output_fld, output_tag, jobid, chkpt_num, **params full_fname = os.path.join(output_fld, basename) tifffile.imsave(output_data[0,:,:,:], full_fname, compress = 1) return full_fname ","def save_output(output, dset, output_fld, output_tag, jobid, chkpt_num, **params full_fname = os.path.join(output_fld, basename) tifffile.imsave(full_fname, output_data[0,:,:,:], compress = 1) return full_fname " 1783,https://:@github.com/NSLS-II/suitcase.git,6ac4a42ce3699009318c55a18145eb8edfaaad48,"@@ -512,7 +512,7 @@ def specscan_to_document_stream(scan, validate=False, check_in_broker=False): metadatastore. You will need to call find_* yourself to determine if it does exist """""" - if mdsc is None and validate: + if mdsc is None and check_in_broker: raise NotImplementedError( ""It is not possible to use the `check_in_broker=True` unless you "" ""have metadatastore installed. Please re-run this function with "" ",suitcase/spec.py,"ReplaceText(target='check_in_broker' @(515,24)->(515,32))","def specscan_to_document_stream(scan, validate=False, check_in_broker=False): metadatastore. You will need to call find_* yourself to determine if it does exist """""" if mdsc is None and validate: raise NotImplementedError( ""It is not possible to use the `check_in_broker=True` unless you "" ""have metadatastore installed. Please re-run this function with ""","def specscan_to_document_stream(scan, validate=False, check_in_broker=False): metadatastore. You will need to call find_* yourself to determine if it does exist """""" if mdsc is None and check_in_broker: raise NotImplementedError( ""It is not possible to use the `check_in_broker=True` unless you "" ""have metadatastore installed. Please re-run this function with """ 1784,https://:@github.com/mattian7741/zulu.git,13ce6ef335f20303dfa0fac363deebeff08641b6,"@@ -20,7 +20,7 @@ class VerifyVersionCommand(install): def run(self): tag = os.getenv('CIRCLE_TAG') - if tag != VERSION: + if tag == VERSION: info = ""Git tag: {0} does not match the version of this app: {1}"".format( tag, VERSION ) ",setup.py,"ReplaceText(target='==' @(23,15)->(23,17))","class VerifyVersionCommand(install): def run(self): tag = os.getenv('CIRCLE_TAG') if tag != VERSION: info = ""Git tag: {0} does not match the version of this app: {1}"".format( tag, VERSION )","class VerifyVersionCommand(install): def run(self): tag = os.getenv('CIRCLE_TAG') if tag == VERSION: info = ""Git tag: {0} does not match the version of this app: {1}"".format( tag, VERSION )" 1785,https://:@github.com/collective/p4a.plonecalendar.git,416b652e14d524a6e3b31758dd13eb28e49b412d,"@@ -37,8 +37,8 @@ def setup_site(site): sm = site.getSiteManager() if not sm.queryUtility(interfaces.ICalendarSupport): - sm.registerUtility(interfaces.ICalendarSupport, - content.CalendarSupport('calendar_support')) + sm.registerUtility(content.CalendarSupport('calendar_support'), + interfaces.ICalendarSupport) def _cleanup_utilities(site): raise NotImplementedError('Current ISiteManager support does not ' ",p4a/plonecalendar/sitesetup.py,"ArgSwap(idxs=0<->1 @(40,8)->(40,26))","def setup_site(site): sm = site.getSiteManager() if not sm.queryUtility(interfaces.ICalendarSupport): sm.registerUtility(interfaces.ICalendarSupport, content.CalendarSupport('calendar_support')) def _cleanup_utilities(site): raise NotImplementedError('Current ISiteManager support does not '","def setup_site(site): sm = site.getSiteManager() if not sm.queryUtility(interfaces.ICalendarSupport): sm.registerUtility(content.CalendarSupport('calendar_support'), interfaces.ICalendarSupport) def _cleanup_utilities(site): raise NotImplementedError('Current ISiteManager support does not '" 1786,https://:@github.com/collective/p4a.plonecalendar.git,c89a0c772798bbd3f831d159fc728da6b6af0eb0,"@@ -286,7 +286,7 @@ class RecurringBrainEvent(BrainEvent): for each in recurrence.getOccurrenceDays(): if start is not None and each < startdate: continue - if stop is not None and each > stopdate: + if stop is not None and each >= stopdate: break dt = datetime.date.fromordinal(each) res.append(BrainEvent(self.context, dt)) ",p4a/plonecalendar/eventprovider.py,"ReplaceText(target='>=' @(289,41)->(289,42))","class RecurringBrainEvent(BrainEvent): for each in recurrence.getOccurrenceDays(): if start is not None and each < startdate: continue if stop is not None and each > stopdate: break dt = datetime.date.fromordinal(each) res.append(BrainEvent(self.context, dt))","class RecurringBrainEvent(BrainEvent): for each in recurrence.getOccurrenceDays(): if start is not None and each < startdate: continue if stop is not None and each >= stopdate: break dt = datetime.date.fromordinal(each) res.append(BrainEvent(self.context, dt))" 1787,https://:@github.com/AlexandrKhabarov/SUPER_PYCALCCCCC.git,e884f876336f85e5a8ac6ceb66577286e5dc669d,"@@ -13,7 +13,7 @@ available_operations = { ""<="": (0, lambda x, y: x <= y), "">="": (0, lambda x, y: x >= y), ""=="": (0, lambda x, y: x >= y), - ""!="": (0, lambda x, y: x >= y), + ""!="": (0, lambda x, y: x != y), ""/"": (2, lambda x, y: x / y), } ",core/operatios.py,"ReplaceText(target='!=' @(16,29)->(16,31))","available_operations = { ""<="": (0, lambda x, y: x <= y), "">="": (0, lambda x, y: x >= y), ""=="": (0, lambda x, y: x >= y), ""!="": (0, lambda x, y: x >= y), ""/"": (2, lambda x, y: x / y), } ","available_operations = { ""<="": (0, lambda x, y: x <= y), "">="": (0, lambda x, y: x >= y), ""=="": (0, lambda x, y: x >= y), ""!="": (0, lambda x, y: x != y), ""/"": (2, lambda x, y: x / y), } " 1788,https://:@github.com/AlexandrKhabarov/SUPER_PYCALCCCCC.git,fb47de33e776a1b92b900508f421bcc3bb7ee619,"@@ -124,7 +124,7 @@ class Interpreter: return float(left) - float(right) elif expr.operator.type_ == TokenTypes.SLASH: self.check_number_operands(expr.operator, left, right) - return float(left) - float(right) + return float(left) / float(right) elif expr.operator.type_ == TokenTypes.STAR: self.check_number_operands(expr.operator, left, right) return float(left) * float(right) ",pycalc/core/expressions.py,"ReplaceText(target='/' @(127,31)->(127,32))","class Interpreter: return float(left) - float(right) elif expr.operator.type_ == TokenTypes.SLASH: self.check_number_operands(expr.operator, left, right) return float(left) - float(right) elif expr.operator.type_ == TokenTypes.STAR: self.check_number_operands(expr.operator, left, right) return float(left) * float(right)","class Interpreter: return float(left) - float(right) elif expr.operator.type_ == TokenTypes.SLASH: self.check_number_operands(expr.operator, left, right) return float(left) / float(right) elif expr.operator.type_ == TokenTypes.STAR: self.check_number_operands(expr.operator, left, right) return float(left) * float(right)" 1789,https://:@github.com/winster/xmppgcm.git,e4517df5b4b714d899bb9e932e674d3b6e9992b7,"@@ -103,7 +103,7 @@ class GCM(ClientXMPP): self.connecton_draining = True elif data.message_type == GCMMessageType.RECEIPT: - logging.debug('Received Receipts for message_id: %s' % msg.message_id) + logging.debug('Received Receipts for message_id: %s' % data.message_id) self.event(XMPPEvent.RECEIPT, data) else: ",xmppgcm/gcm.py,"ReplaceText(target='data' @(106,67)->(106,70))","class GCM(ClientXMPP): self.connecton_draining = True elif data.message_type == GCMMessageType.RECEIPT: logging.debug('Received Receipts for message_id: %s' % msg.message_id) self.event(XMPPEvent.RECEIPT, data) else:","class GCM(ClientXMPP): self.connecton_draining = True elif data.message_type == GCMMessageType.RECEIPT: logging.debug('Received Receipts for message_id: %s' % data.message_id) self.event(XMPPEvent.RECEIPT, data) else:" 1790,https://:@github.com/geertj/bluepass.git,5c3bb3833033d329fa6e4447f51c73cb02de26fe,"@@ -647,7 +647,7 @@ class VaultView(QWidget): current_order.removeat(curpos) items.removeItem(item) item.hide(); item.destroy() - self.groupRemoved.emit(uuid, group) + self.groupRemoved.emit(uuid, curgroup) # We can now update the version cache for version in versions: current_versions[version['id']] = version ",bluepass/frontends/qt/passwordview.py,"ReplaceText(target='curgroup' @(650,49)->(650,54))","class VaultView(QWidget): current_order.removeat(curpos) items.removeItem(item) item.hide(); item.destroy() self.groupRemoved.emit(uuid, group) # We can now update the version cache for version in versions: current_versions[version['id']] = version","class VaultView(QWidget): current_order.removeat(curpos) items.removeItem(item) item.hide(); item.destroy() self.groupRemoved.emit(uuid, curgroup) # We can now update the version cache for version in versions: current_versions[version['id']] = version" 1791,https://:@github.com/ajbouh/tfi.git,029bc838140ad2d9f9a24d8900a918a9ffc1eacd,"@@ -21,7 +21,7 @@ class SavedModelTest(unittest.TestCase): self.assertEqual(3.0, m.add(x=1.0, y=2.0).sum) self.assertEqual(2.0, m.mult(x=1.0, y=2.0).prod) - tfi.saved_model.export(""math.saved_model"", Math) + tfi.saved_model.export(""math.saved_model"", m) # Prove that we can save it. # Prove that we can restore it to a new class. ",tests/saved_model_test.py,"ReplaceText(target='m' @(24,51)->(24,55))","class SavedModelTest(unittest.TestCase): self.assertEqual(3.0, m.add(x=1.0, y=2.0).sum) self.assertEqual(2.0, m.mult(x=1.0, y=2.0).prod) tfi.saved_model.export(""math.saved_model"", Math) # Prove that we can save it. # Prove that we can restore it to a new class. ","class SavedModelTest(unittest.TestCase): self.assertEqual(3.0, m.add(x=1.0, y=2.0).sum) self.assertEqual(2.0, m.mult(x=1.0, y=2.0).prod) tfi.saved_model.export(""math.saved_model"", m) # Prove that we can save it. # Prove that we can restore it to a new class. " 1792,https://:@github.com/lelit/nssjson.git,ff9cb965faa144b3f221fad0e7f6f09cc91ac30d,"@@ -53,7 +53,7 @@ class TestRecursion(TestCase): x = {} y = {""a"": x, ""b"": x} # ensure that the marker is cleared - json.dumps(x) + json.dumps(y) def test_defaultrecursion(self): enc = RecursiveJSONEncoder() ",simplejson/tests/test_recursion.py,"ReplaceText(target='y' @(56,19)->(56,20))","class TestRecursion(TestCase): x = {} y = {""a"": x, ""b"": x} # ensure that the marker is cleared json.dumps(x) def test_defaultrecursion(self): enc = RecursiveJSONEncoder()","class TestRecursion(TestCase): x = {} y = {""a"": x, ""b"": x} # ensure that the marker is cleared json.dumps(y) def test_defaultrecursion(self): enc = RecursiveJSONEncoder()" 1793,https://:@github.com/combatopera/lagoon.git,993c4be530b1768731517a7275b0a8978f8255f5,"@@ -54,7 +54,7 @@ class Stuff: while j < len(atoms): i = j chunksize = 0 - while j < len(atoms) and chunksize + len(atoms[j]) < self.buffersize: + while j < len(atoms) and chunksize + len(atoms[j]) <= self.buffersize: chunksize += len(atoms[j]) j += 1 self._juststuff(b''.join(atoms[i:j])) ",screen.py,"ReplaceText(target='<=' @(57,63)->(57,64))","class Stuff: while j < len(atoms): i = j chunksize = 0 while j < len(atoms) and chunksize + len(atoms[j]) < self.buffersize: chunksize += len(atoms[j]) j += 1 self._juststuff(b''.join(atoms[i:j]))","class Stuff: while j < len(atoms): i = j chunksize = 0 while j < len(atoms) and chunksize + len(atoms[j]) <= self.buffersize: chunksize += len(atoms[j]) j += 1 self._juststuff(b''.join(atoms[i:j]))" 1794,https://:@github.com/OnroerendErfgoed/crabpy_pyramid.git,a918c37502fc569c052ff16952b3f3bc1b6c5a90,"@@ -359,4 +359,4 @@ class HttpCachingFunctionalTests(FunctionalTests): self.assertEqual('200 OK', res.status) etag = res.headers['Etag'] res2 = self.testapp.get('/crab/gewesten', headers={'If-None-Match': etag}) - self.assertEqual('304 Not Modified', res.status) + self.assertEqual('304 Not Modified', res2.status) ",crabpy_pyramid/tests/test_functional.py,"ReplaceText(target='res2' @(362,45)->(362,48))","class HttpCachingFunctionalTests(FunctionalTests): self.assertEqual('200 OK', res.status) etag = res.headers['Etag'] res2 = self.testapp.get('/crab/gewesten', headers={'If-None-Match': etag}) self.assertEqual('304 Not Modified', res.status)","class HttpCachingFunctionalTests(FunctionalTests): self.assertEqual('200 OK', res.status) etag = res.headers['Etag'] res2 = self.testapp.get('/crab/gewesten', headers={'If-None-Match': etag}) self.assertEqual('304 Not Modified', res2.status)" 1795,https://:@github.com/certae/django-softmachine.git,12a9f0f5f016395f34bf03afa50889aa8ac36e3c,"@@ -109,7 +109,7 @@ def protoList(request): # Prepara las cols del Query - pList = Q2Dict(protoFields , pRows ) + pList = Q2Dict(protoMeta , pRows ) context = json.dumps({ 'success': True, ",src/protoLib/protoActionList.py,"ReplaceText(target='protoMeta' @(112,19)->(112,30))","def protoList(request): # Prepara las cols del Query pList = Q2Dict(protoFields , pRows ) context = json.dumps({ 'success': True,","def protoList(request): # Prepara las cols del Query pList = Q2Dict(protoMeta , pRows ) context = json.dumps({ 'success': True," 1796,https://:@github.com/certae/django-softmachine.git,331b58a38d644e8ee611f4f5603a56529419810f,"@@ -94,7 +94,7 @@ def getQbeStmt( fieldName , sQBE, sType ): bAndConector = True sCondicion = sCondicion[1:] - Qtmp = getQbeStmt(fieldName, sType, sCondicion) + Qtmp = getQbeStmt(fieldName, sCondicion, sType) if bAndConector: QResult = QResult & Qtmp else: ",src/protoLib/protoQbe.py,"ArgSwap(idxs=1<->2 @(97,19)->(97,29))","def getQbeStmt( fieldName , sQBE, sType ): bAndConector = True sCondicion = sCondicion[1:] Qtmp = getQbeStmt(fieldName, sType, sCondicion) if bAndConector: QResult = QResult & Qtmp else: ","def getQbeStmt( fieldName , sQBE, sType ): bAndConector = True sCondicion = sCondicion[1:] Qtmp = getQbeStmt(fieldName, sCondicion, sType) if bAndConector: QResult = QResult & Qtmp else: " 1797,https://:@github.com/inveniosoftware/invenio-app-ils.git,bdeb4bcb9bdd8d75e8231b032134b3bf008e0c4d,"@@ -155,7 +155,7 @@ class LoanMailResource(IlsCirculationResource): """"""Loan email post method."""""" days_ago = circulation_overdue_loan_days(record) is_overdue = days_ago > 0 - if is_overdue: + if not is_overdue: raise OverdueLoansMailError(description=""This loan is not overdue"") send_loan_overdue_reminder_mail(record, days_ago) return self.make_response( ",invenio_app_ils/circulation/views.py,"ReplaceText(target='not ' @(158,11)->(158,11))","class LoanMailResource(IlsCirculationResource): """"""Loan email post method."""""" days_ago = circulation_overdue_loan_days(record) is_overdue = days_ago > 0 if is_overdue: raise OverdueLoansMailError(description=""This loan is not overdue"") send_loan_overdue_reminder_mail(record, days_ago) return self.make_response(","class LoanMailResource(IlsCirculationResource): """"""Loan email post method."""""" days_ago = circulation_overdue_loan_days(record) is_overdue = days_ago > 0 if not is_overdue: raise OverdueLoansMailError(description=""This loan is not overdue"") send_loan_overdue_reminder_mail(record, days_ago) return self.make_response(" 1798,https://:@github.com/hugosenari/Kupfer-Plugins.git,500371bfea20e856242186f0f6d6c1d1446b19c5,"@@ -72,7 +72,7 @@ class LastStatus(Action): info = get_tracking_info(content.decode('iso-8859-1')) if info: txt = '-'.join(reversed(info[0])) - return TextLeaf(txt, leaf.object) + return TextLeaf(leaf.object, txt) def item_types(self): yield TextLeaf ",curreios/curreios.py,"ArgSwap(idxs=0<->1 @(75,23)->(75,31))","class LastStatus(Action): info = get_tracking_info(content.decode('iso-8859-1')) if info: txt = '-'.join(reversed(info[0])) return TextLeaf(txt, leaf.object) def item_types(self): yield TextLeaf","class LastStatus(Action): info = get_tracking_info(content.decode('iso-8859-1')) if info: txt = '-'.join(reversed(info[0])) return TextLeaf(leaf.object, txt) def item_types(self): yield TextLeaf" 1799,https://:@github.com/janhybs/ci-hpc.git,bf6e060a313c57667a4b75b41dbbb5114d9fb927,"@@ -50,7 +50,7 @@ def process_step_collect(step, format_args=None): with logger: for file, timers in timers_info: logger.debug('%20s: %5d timers found', file, timers) - logger.info('artifacts: found %d timer(s) in %d file(s)', len(files), timers_total) + logger.info('artifacts: found %d timer(s) in %d file(s)', timers_total, len(files)) # insert artifacts into db if step.collect.save_to_db: ",ci-hpc/proc/step/step_collect.py,"ArgSwap(idxs=1<->2 @(53,12)->(53,23))","def process_step_collect(step, format_args=None): with logger: for file, timers in timers_info: logger.debug('%20s: %5d timers found', file, timers) logger.info('artifacts: found %d timer(s) in %d file(s)', len(files), timers_total) # insert artifacts into db if step.collect.save_to_db:","def process_step_collect(step, format_args=None): with logger: for file, timers in timers_info: logger.debug('%20s: %5d timers found', file, timers) logger.info('artifacts: found %d timer(s) in %d file(s)', timers_total, len(files)) # insert artifacts into db if step.collect.save_to_db:" 1800,https://:@github.com/Infinidat/infi.pypi_manager.git,d7b669eaf58a03e887135683264dd475d67f2e39,"@@ -115,7 +115,7 @@ def mirror_file(repository_config, filename, package_name, package_version, meta data.update(metadata) for key, value in list(data.items()): - if isinstance(value, str): + if not isinstance(value, str): data[key] = value.encode(""utf-8"") repository = repository_config[""repository""] ",src/infi/pypi_manager/mirror/mirror_all.py,"ReplaceText(target='not ' @(118,11)->(118,11))","def mirror_file(repository_config, filename, package_name, package_version, meta data.update(metadata) for key, value in list(data.items()): if isinstance(value, str): data[key] = value.encode(""utf-8"") repository = repository_config[""repository""]","def mirror_file(repository_config, filename, package_name, package_version, meta data.update(metadata) for key, value in list(data.items()): if not isinstance(value, str): data[key] = value.encode(""utf-8"") repository = repository_config[""repository""]" 1801,https://:@github.com/novopl/fabops.git,ea5c44f518554a239afd8650d216ea1f7e23db9e,"@@ -105,7 +105,7 @@ def lint(exclude, include_untracked, commit_only, pretend): exclude = list(exclude) # Convert from tuple to easily concatenate. if commit_only: - include = ['*' + f for f in git.staged() if f.endswith('.py')] + include += ['*' + f for f in git.staged() if f.endswith('.py')] exclude += git.ignore() if not include_untracked: ",src/peltak/commands/lint.py,"ReplaceText(target='+=' @(108,16)->(108,17))","def lint(exclude, include_untracked, commit_only, pretend): exclude = list(exclude) # Convert from tuple to easily concatenate. if commit_only: include = ['*' + f for f in git.staged() if f.endswith('.py')] exclude += git.ignore() if not include_untracked:","def lint(exclude, include_untracked, commit_only, pretend): exclude = list(exclude) # Convert from tuple to easily concatenate. if commit_only: include += ['*' + f for f in git.staged() if f.endswith('.py')] exclude += git.ignore() if not include_untracked:" 1802,https://:@github.com/novopl/fabops.git,94bb4222594c1be8cb1d760d21abccf8393fbe57,"@@ -95,7 +95,7 @@ def finish(): common.git_branch_delete(branch.name) common.git_prune() - common.git_checkout(develop) + common.git_checkout(master) def merged(): ",src/peltak/extra/gitflow/logic/release.py,"ReplaceText(target='master' @(98,24)->(98,31))","def finish(): common.git_branch_delete(branch.name) common.git_prune() common.git_checkout(develop) def merged():","def finish(): common.git_branch_delete(branch.name) common.git_prune() common.git_checkout(master) def merged():" 1803,https://:@github.com/novopl/fabops.git,4ace52dda2d85cb734ee74e126530e805777a000,"@@ -72,7 +72,7 @@ def add_hooks(): # Write pre-push hook log.info(""Adding pre-push hook: <33>{}"", push_hook) - fs.write_file(commit_hook, util.remove_indent(''' + fs.write_file(push_hook, util.remove_indent(''' #!/bin/bash PATH=""/opt/local/libexec/gnubin:$PATH"" ",src/peltak/logic/git.py,"ReplaceText(target='push_hook' @(75,18)->(75,29))","def add_hooks(): # Write pre-push hook log.info(""Adding pre-push hook: <33>{}"", push_hook) fs.write_file(commit_hook, util.remove_indent(''' #!/bin/bash PATH=""/opt/local/libexec/gnubin:$PATH"" ","def add_hooks(): # Write pre-push hook log.info(""Adding pre-push hook: <33>{}"", push_hook) fs.write_file(push_hook, util.remove_indent(''' #!/bin/bash PATH=""/opt/local/libexec/gnubin:$PATH"" " 1804,https://:@github.com/ome/omero-scripts.git,bcf0a97fecbc46da12cd0fc1dc679d6eb1a002d4,"@@ -186,7 +186,7 @@ def createmovie_figure(conn, pixel_ids, t_indexes, z_start, z_end, width, plane_def = omero.romio.PlaneDef() plane_def.z = pro_start plane_def.t = time - plane_def = re.renderCompressed(plane_def) + rendered_img = re.renderCompressed(plane_def) # create images and resize, add to list image = Image.open(io.BytesIO(rendered_img)) resized_image = imgUtil.resizeImage(image, width, height) ",omero/figure_scripts/Movie_Figure.py,"ReplaceText(target='rendered_img' @(189,20)->(189,29))","def createmovie_figure(conn, pixel_ids, t_indexes, z_start, z_end, width, plane_def = omero.romio.PlaneDef() plane_def.z = pro_start plane_def.t = time plane_def = re.renderCompressed(plane_def) # create images and resize, add to list image = Image.open(io.BytesIO(rendered_img)) resized_image = imgUtil.resizeImage(image, width, height)","def createmovie_figure(conn, pixel_ids, t_indexes, z_start, z_end, width, plane_def = omero.romio.PlaneDef() plane_def.z = pro_start plane_def.t = time rendered_img = re.renderCompressed(plane_def) # create images and resize, add to list image = Image.open(io.BytesIO(rendered_img)) resized_image = imgUtil.resizeImage(image, width, height)" 1805,https://:@github.com/MozillaSecurity/grizzly.git,5ff196df7b3e4cb6fafece51f3a92dd6fe240639,"@@ -71,7 +71,7 @@ def test_adapter_04(tmp_path): # path to file file1 = (tmp_path / ""test1.txt"") file1.touch() - found = tuple(SimpleAdapter.scan_path(str(tmp_path))) + found = tuple(SimpleAdapter.scan_path(str(file1))) assert len(found) == 1 assert str(file1) in found # path to directory ",grizzly/common/test_adapter.py,"ReplaceText(target='file1' @(74,46)->(74,54))","def test_adapter_04(tmp_path): # path to file file1 = (tmp_path / ""test1.txt"") file1.touch() found = tuple(SimpleAdapter.scan_path(str(tmp_path))) assert len(found) == 1 assert str(file1) in found # path to directory","def test_adapter_04(tmp_path): # path to file file1 = (tmp_path / ""test1.txt"") file1.touch() found = tuple(SimpleAdapter.scan_path(str(file1))) assert len(found) == 1 assert str(file1) in found # path to directory" 1806,https://:@github.com/CIMAC-CIDC/schemas.git,e7ecb7443f00d666cd8e67b7e643f5837fc2f8f2,"@@ -743,7 +743,7 @@ def merge_artifact( _set_data_format(ct, existing_artifact) # return new object and the artifact that was merged - return ct, artifact + return ct, existing_artifact class InvalidMergeTargetException(ValueError): """"""Exception raised for target of merge_clinical_trial_metadata being non schema compliant."""""" ",cidc_schemas/prism.py,"ReplaceText(target='existing_artifact' @(746,15)->(746,23))","def merge_artifact( _set_data_format(ct, existing_artifact) # return new object and the artifact that was merged return ct, artifact class InvalidMergeTargetException(ValueError): """"""Exception raised for target of merge_clinical_trial_metadata being non schema compliant.""""""","def merge_artifact( _set_data_format(ct, existing_artifact) # return new object and the artifact that was merged return ct, existing_artifact class InvalidMergeTargetException(ValueError): """"""Exception raised for target of merge_clinical_trial_metadata being non schema compliant.""""""" 1807,https://:@github.com/CIMAC-CIDC/schemas.git,c7ddda9fbcc6fed237e11e3024e6ea610b08ecfa,"@@ -535,7 +535,7 @@ class Template: raise Exception(e) changes.extend(chs) - fs.extend(fs) + files.extend(fs) return changes, files ",cidc_schemas/template.py,"ReplaceText(target='files' @(538,12)->(538,14))","class Template: raise Exception(e) changes.extend(chs) fs.extend(fs) return changes, files ","class Template: raise Exception(e) changes.extend(chs) files.extend(fs) return changes, files " 1808,https://:@github.com/ggstuart/pyEMIS.git,05b6ac16ca87ee3a9e5696ecc27b9bb4024cc7f1,"@@ -29,7 +29,7 @@ class SimpleProfile(AnalysisBase): result = {} pred = self.baseline_model.prediction(this_week) for p in percentiles: - result[p] = pred + self.baseline_model.percentile_in_place(p, this_week) + result[p] = pred + self.baseline_model.percentile_in_place(this_week, p) return result ",lib/analysis/profile.py,"ArgSwap(idxs=0<->1 @(32,31)->(32,70))","class SimpleProfile(AnalysisBase): result = {} pred = self.baseline_model.prediction(this_week) for p in percentiles: result[p] = pred + self.baseline_model.percentile_in_place(p, this_week) return result ","class SimpleProfile(AnalysisBase): result = {} pred = self.baseline_model.prediction(this_week) for p in percentiles: result[p] = pred + self.baseline_model.percentile_in_place(this_week, p) return result " 1809,https://:@github.com/scipion-em/scipion-em.git,aab3b1e42dbced18cebf4b6e8fd15265288693d0,"@@ -122,7 +122,7 @@ class ProtFrealignClassify(ProtFrealignBase, ProtClassify3D): for ref in range(1, self.numberOfRef + 1): refVol = self._getFileName('ref_vol_class', iter=iter, ref=ref) # reference volume of the step. iterVol = self._getFileName('iter_vol_class', iter=iter, ref=ref) # refined volumes of the step - if iter != 1: + if iter == 1: copyFile(volFn, iterVol) #Copy the initial volume in the current directory. else: self._splitParFile(iter, ref, cpusRef[ref-1]) ",pwem/packages/brandeis/protocol_ml_classification.py,"ReplaceText(target='==' @(125,20)->(125,22))","class ProtFrealignClassify(ProtFrealignBase, ProtClassify3D): for ref in range(1, self.numberOfRef + 1): refVol = self._getFileName('ref_vol_class', iter=iter, ref=ref) # reference volume of the step. iterVol = self._getFileName('iter_vol_class', iter=iter, ref=ref) # refined volumes of the step if iter != 1: copyFile(volFn, iterVol) #Copy the initial volume in the current directory. else: self._splitParFile(iter, ref, cpusRef[ref-1])","class ProtFrealignClassify(ProtFrealignBase, ProtClassify3D): for ref in range(1, self.numberOfRef + 1): refVol = self._getFileName('ref_vol_class', iter=iter, ref=ref) # reference volume of the step. iterVol = self._getFileName('iter_vol_class', iter=iter, ref=ref) # refined volumes of the step if iter == 1: copyFile(volFn, iterVol) #Copy the initial volume in the current directory. else: self._splitParFile(iter, ref, cpusRef[ref-1])" 1810,https://:@github.com/scipion-em/scipion-em.git,79434578b0e8d5d29e900b60aa9fadddcc75d1bf,"@@ -177,7 +177,7 @@ class ProtPrime(em.ProtInitialVolume): vol.append(aux) self._defineOutputs(outputVolumes=vol) - self._defineSourceRelation(vol, self.inputClasses) + self._defineSourceRelation(self.inputClasses, vol) #--------------------------- INFO functions -------------------------------------------- def _summary(self): ",pwem/packages/simple/protocol_prime.py,"ArgSwap(idxs=0<->1 @(180,8)->(180,34))","class ProtPrime(em.ProtInitialVolume): vol.append(aux) self._defineOutputs(outputVolumes=vol) self._defineSourceRelation(vol, self.inputClasses) #--------------------------- INFO functions -------------------------------------------- def _summary(self):","class ProtPrime(em.ProtInitialVolume): vol.append(aux) self._defineOutputs(outputVolumes=vol) self._defineSourceRelation(self.inputClasses, vol) #--------------------------- INFO functions -------------------------------------------- def _summary(self):" 1811,https://:@github.com/scipion-em/scipion-em.git,14b6a308b1710c111cdc515b1d4367b0d6289c77,"@@ -121,7 +121,7 @@ class ProtSummovie(ProtProcessMovies): # special case is mrc but ends in mrcs inMovieName= os.path.join(movieFolder,movieName) if movieName.endswith('.mrc'): - movieNameAux = inMovieName + movieNameAux = movieName elif movieName.endswith('.mrcs'): movieNameAux= pwutils.replaceExt(inMovieName, ""mrc"") createLink(inMovieName,movieNameAux) ",pwem/packages/grigoriefflab/protocol_summovie.py,"ReplaceText(target='movieName' @(124,27)->(124,38))","class ProtSummovie(ProtProcessMovies): # special case is mrc but ends in mrcs inMovieName= os.path.join(movieFolder,movieName) if movieName.endswith('.mrc'): movieNameAux = inMovieName elif movieName.endswith('.mrcs'): movieNameAux= pwutils.replaceExt(inMovieName, ""mrc"") createLink(inMovieName,movieNameAux)","class ProtSummovie(ProtProcessMovies): # special case is mrc but ends in mrcs inMovieName= os.path.join(movieFolder,movieName) if movieName.endswith('.mrc'): movieNameAux = movieName elif movieName.endswith('.mrcs'): movieNameAux= pwutils.replaceExt(inMovieName, ""mrc"") createLink(inMovieName,movieNameAux)" 1812,https://:@github.com/scipion-em/scipion-em.git,9c9bbe991ab901a16c11eece48cb54468b1b663a,"@@ -90,7 +90,7 @@ class ChimeraViewerBase(Viewer): if _showVol.hasOrigin(): x, y, z = _showVol.getOrigin().getShifts() else: - x, y, z = outputVol.getOrigin(force=True).getShifts() + x, y, z = _showVol.getOrigin(force=True).getShifts() f.write(""volume #1 style surface voxelSize %f origin "" ""%0.2f,%0.2f,%0.2f\n"" ",pwem/packages/chimera/viewer.py,"ReplaceText(target='_showVol' @(93,26)->(93,35))","class ChimeraViewerBase(Viewer): if _showVol.hasOrigin(): x, y, z = _showVol.getOrigin().getShifts() else: x, y, z = outputVol.getOrigin(force=True).getShifts() f.write(""volume #1 style surface voxelSize %f origin "" ""%0.2f,%0.2f,%0.2f\n""","class ChimeraViewerBase(Viewer): if _showVol.hasOrigin(): x, y, z = _showVol.getOrigin().getShifts() else: x, y, z = _showVol.getOrigin(force=True).getShifts() f.write(""volume #1 style surface voxelSize %f origin "" ""%0.2f,%0.2f,%0.2f\n""" 1813,https://:@github.com/scipion-em/scipion-em.git,2d9ba7dfcd59de3b77e19cb23d5fa2ad34c80d55,"@@ -110,7 +110,7 @@ class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" - label_seq_id = str(residue_number) + label_seq_id = str(resseq) residue_number += 1 else: residue_type = ""HETATM"" ",pwem/convert/atom_struct.py,"ReplaceText(target='resseq' @(113,47)->(113,61))","class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" label_seq_id = str(residue_number) residue_number += 1 else: residue_type = ""HETATM""","class scipionMMCIFIO(MMCIFIO): hetfield, resseq, icode = residue.get_id() if hetfield == "" "": residue_type = ""ATOM"" label_seq_id = str(resseq) residue_number += 1 else: residue_type = ""HETATM""" 1814,https://:@github.com/scipion-em/scipion-em.git,18a1a11d22aa9a2e8e046e685264fb8d53a96af5,"@@ -419,7 +419,7 @@ class ImageHandler(object): def createEmptyImage(cls, fnOut, xDim=1, yDim=1, zDim=1, nDim=1, dataType=None): dt = dataType or cls.DT_FLOAT - xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dataType) + xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dt) @classmethod def isImageFile(cls, imgFn): ",pwem/convert/image_handler.py,"ReplaceText(target='dt' @(422,64)->(422,72))","class ImageHandler(object): def createEmptyImage(cls, fnOut, xDim=1, yDim=1, zDim=1, nDim=1, dataType=None): dt = dataType or cls.DT_FLOAT xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dataType) @classmethod def isImageFile(cls, imgFn):","class ImageHandler(object): def createEmptyImage(cls, fnOut, xDim=1, yDim=1, zDim=1, nDim=1, dataType=None): dt = dataType or cls.DT_FLOAT xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dt) @classmethod def isImageFile(cls, imgFn):" 1815,https://:@github.com/gedaskir/qmeq.git,347cea42998433ead153e7701cf69caa5086ee13,"@@ -364,8 +364,8 @@ class LeadsTunneling(object): self.Tba0 = construct_Tba(tleadsp, self.stateind, self.mtype, self.Tba0) if updateq: for j0 in tleadsp: - try: self.tleads[j0] += tleadsp[j0] # if tleads[j0] != 0: - except: self.tleads.update({j0:tleads[j0]}) # if tleads[j0] != 0: + try: self.tleads[j0] += tleadsp[j0] # if tleads[j0] != 0: + except: self.tleads.update({j0:tleadsp[j0]}) # if tleads[j0] != 0: def change(self, tleads=None, mulst=None, tlst=None, dlst=None, updateq=True): """""" ",qmeq/leadstun.py,"ReplaceText(target='tleadsp' @(368,51)->(368,57))","class LeadsTunneling(object): self.Tba0 = construct_Tba(tleadsp, self.stateind, self.mtype, self.Tba0) if updateq: for j0 in tleadsp: try: self.tleads[j0] += tleadsp[j0] # if tleads[j0] != 0: except: self.tleads.update({j0:tleads[j0]}) # if tleads[j0] != 0: def change(self, tleads=None, mulst=None, tlst=None, dlst=None, updateq=True): """"""","class LeadsTunneling(object): self.Tba0 = construct_Tba(tleadsp, self.stateind, self.mtype, self.Tba0) if updateq: for j0 in tleadsp: try: self.tleads[j0] += tleadsp[j0] # if tleads[j0] != 0: except: self.tleads.update({j0:tleadsp[j0]}) # if tleads[j0] != 0: def change(self, tleads=None, mulst=None, tlst=None, dlst=None, updateq=True): """"""" 1816,https://:@github.com/caleb-easterly/metaquant.git,745e72d4ef68c944db5395e09bd85070b8e2652a,"@@ -17,7 +17,7 @@ def common_hierarchical_analysis(db, df, annot_colname, samp_grps, min_peptides, # filter int_all_ranks_filt = stats.filter_min_observed(intensity_all_ranks, threshold, samp_grps) - int_all_ranks_filt['id'] = intensity_all_ranks.index + int_all_ranks_filt['id'] = int_all_ranks_filt.index # calculate means int_w_means = stats.calc_means(int_all_ranks_filt, samp_grps) ",metaquant/analysis/common.py,"ReplaceText(target='int_all_ranks_filt' @(20,31)->(20,50))","def common_hierarchical_analysis(db, df, annot_colname, samp_grps, min_peptides, # filter int_all_ranks_filt = stats.filter_min_observed(intensity_all_ranks, threshold, samp_grps) int_all_ranks_filt['id'] = intensity_all_ranks.index # calculate means int_w_means = stats.calc_means(int_all_ranks_filt, samp_grps)","def common_hierarchical_analysis(db, df, annot_colname, samp_grps, min_peptides, # filter int_all_ranks_filt = stats.filter_min_observed(intensity_all_ranks, threshold, samp_grps) int_all_ranks_filt['id'] = int_all_ranks_filt.index # calculate means int_w_means = stats.calc_means(int_all_ranks_filt, samp_grps)" 1817,https://:@github.com/matthiask/django-keyed-urls.git,85701797d220d26d175a834250969d86aa8a08c6,"@@ -55,7 +55,7 @@ def get_url(key, language=None, fail_silently=False): url = None if url is None and not fail_silently: - raise KeyDoesNotExist('No match found for key ""%s"".' % url) + raise KeyDoesNotExist('No match found for key ""%s"".' % key) return None if url == _none_type else url ",keyed_urls/__init__.py,"ReplaceText(target='key' @(58,63)->(58,66))","def get_url(key, language=None, fail_silently=False): url = None if url is None and not fail_silently: raise KeyDoesNotExist('No match found for key ""%s"".' % url) return None if url == _none_type else url ","def get_url(key, language=None, fail_silently=False): url = None if url is None and not fail_silently: raise KeyDoesNotExist('No match found for key ""%s"".' % key) return None if url == _none_type else url " 1818,https://:@github.com/sommalia/moco-wrapper.git,8463f534ca51588a6619f61f59bb5d0d064511ab,"@@ -42,7 +42,7 @@ class Unit(MWRAPBase): if value is not None: params[key] = value - if sort_order is not None: + if sort_by is not None: params[""sort_by""] = ""{} {}"".format(sort_by, sort_order) return self._moco.get(API_PATH[""unit_getlist""], params=params) ",moco_wrapper/models/unit.py,"ReplaceText(target='sort_by' @(45,11)->(45,21))","class Unit(MWRAPBase): if value is not None: params[key] = value if sort_order is not None: params[""sort_by""] = ""{} {}"".format(sort_by, sort_order) return self._moco.get(API_PATH[""unit_getlist""], params=params)","class Unit(MWRAPBase): if value is not None: params[key] = value if sort_by is not None: params[""sort_by""] = ""{} {}"".format(sort_by, sort_order) return self._moco.get(API_PATH[""unit_getlist""], params=params)" 1819,https://:@github.com/scupid-admin/morph-python-sdk.git,0739734905cb5e49f54807792dc9426884be6eae,"@@ -11,7 +11,7 @@ def read_and_set_attribute(event, context): ""9711xxx400"": True, ""8130xxx599"": True } - phone_number = context[""userVariables""][""_PHONE_NUMBER""] + phone_number = event[""userVariables""][""_PHONE_NUMBER""] if phone_number is None: phone_number = """" else: ",morph/examples.py,"ReplaceText(target='event' @(14,19)->(14,26))","def read_and_set_attribute(event, context): ""9711xxx400"": True, ""8130xxx599"": True } phone_number = context[""userVariables""][""_PHONE_NUMBER""] if phone_number is None: phone_number = """" else:","def read_and_set_attribute(event, context): ""9711xxx400"": True, ""8130xxx599"": True } phone_number = event[""userVariables""][""_PHONE_NUMBER""] if phone_number is None: phone_number = """" else:" 1820,https://:@github.com/Scorpi000/QuantStudio.git,c158be9b67b0058be35cc3b7e8b1c04e3c06d252,"@@ -315,7 +315,7 @@ class FactorTurnover(BaseModule): HTML += """" else: HTML = """" - iHTML += self._Output[""统计数据""].to_html(formatters=[_QS_formatPandasPercentage]*5) + iHTML = self._Output[""统计数据""].to_html(formatters=[_QS_formatPandasPercentage]*5) Pos = iHTML.find("">"") HTML += iHTML[:Pos]+' align=""center""'+iHTML[Pos:] Fig = self.genMatplotlibFig() ",QuantStudio/BackTest/SectionFactor/Correlation.py,"ReplaceText(target='=' @(318,14)->(318,16))","class FactorTurnover(BaseModule): HTML += """" else: HTML = """" iHTML += self._Output[""统计数据""].to_html(formatters=[_QS_formatPandasPercentage]*5) Pos = iHTML.find("">"") HTML += iHTML[:Pos]+' align=""center""'+iHTML[Pos:] Fig = self.genMatplotlibFig()","class FactorTurnover(BaseModule): HTML += """" else: HTML = """" iHTML = self._Output[""统计数据""].to_html(formatters=[_QS_formatPandasPercentage]*5) Pos = iHTML.find("">"") HTML += iHTML[:Pos]+' align=""center""'+iHTML[Pos:] Fig = self.genMatplotlibFig()" 1821,https://:@github.com/Scorpi000/QuantStudio.git,2d2788d5d5192b8b90868c30e247ef6533fb1164,"@@ -667,7 +667,7 @@ class SQLDB(QSSQLObject, WritableFactorDB): if (DataLenMax!=DataLenMin).sum()>0: self._QS_Logger.warning(""'%s' 在写入因子 '%s' 时出现因子值长度不一致的情况, 将填充缺失!"" % (self.Name, str(data.columns.tolist()))) for i in range(data.shape[0]): - iDataLen = DataLen.iloc[i] + iDataLen = DataLenMax.iloc[i] if iDataLen>0: iData = data.iloc[i].apply(lambda x: [None]*(iDataLen-len(x))+x if isinstance(x, list) else [x]*iDataLen).tolist() NewData.extend(zip(*iData)) ",QuantStudio/FactorDataBase/SQLDB.py,"ReplaceText(target='DataLenMax' @(670,23)->(670,30))","class SQLDB(QSSQLObject, WritableFactorDB): if (DataLenMax!=DataLenMin).sum()>0: self._QS_Logger.warning(""'%s' 在写入因子 '%s' 时出现因子值长度不一致的情况, 将填充缺失!"" % (self.Name, str(data.columns.tolist()))) for i in range(data.shape[0]): iDataLen = DataLen.iloc[i] if iDataLen>0: iData = data.iloc[i].apply(lambda x: [None]*(iDataLen-len(x))+x if isinstance(x, list) else [x]*iDataLen).tolist() NewData.extend(zip(*iData))","class SQLDB(QSSQLObject, WritableFactorDB): if (DataLenMax!=DataLenMin).sum()>0: self._QS_Logger.warning(""'%s' 在写入因子 '%s' 时出现因子值长度不一致的情况, 将填充缺失!"" % (self.Name, str(data.columns.tolist()))) for i in range(data.shape[0]): iDataLen = DataLenMax.iloc[i] if iDataLen>0: iData = data.iloc[i].apply(lambda x: [None]*(iDataLen-len(x))+x if isinstance(x, list) else [x]*iDataLen).tolist() NewData.extend(zip(*iData))" 1822,https://:@github.com/servir-mekong/hydra-floods.git,f7de9b4516deb7ac5055624fb9012596ac25374c,"@@ -129,7 +129,7 @@ def globalOtsu(collection,target_date,region, imageEdge = target.mask(edges) histogram_image = target.mask(edgeBuffer) - histogram = histogram_image.reduceRegion(ee.Reducer.histogram(255, 2)\ + histogram = target.reduceRegion(ee.Reducer.histogram(255, 2)\ .combine('mean', None, True)\ .combine('variance', None,True),sampleRegion,reductionScale,bestEffort=True) ",hydrafloods/geeutils.py,"ReplaceText(target='target' @(132,17)->(132,32))","def globalOtsu(collection,target_date,region, imageEdge = target.mask(edges) histogram_image = target.mask(edgeBuffer) histogram = histogram_image.reduceRegion(ee.Reducer.histogram(255, 2)\ .combine('mean', None, True)\ .combine('variance', None,True),sampleRegion,reductionScale,bestEffort=True) ","def globalOtsu(collection,target_date,region, imageEdge = target.mask(edges) histogram_image = target.mask(edgeBuffer) histogram = target.reduceRegion(ee.Reducer.histogram(255, 2)\ .combine('mean', None, True)\ .combine('variance', None,True),sampleRegion,reductionScale,bestEffort=True) " 1823,https://:@github.com/pytorchbearer/visual.git,c2d6f39bebb1754a92d3499ff0a5eca64b206ca4,"@@ -265,7 +265,7 @@ class CPPNImage(Image): x_coord_range = torch.linspace(-r, r, steps=self.width) y_coord_range = torch.linspace(-r, r, steps=self.height) - x, y = torch.meshgrid(x_coord_range, y_coord_range) + x, y = torch.meshgrid(y_coord_range, x_coord_range) self.loc = nn.Parameter(torch.stack((x, y), dim=0).unsqueeze(0), requires_grad=False) ",visual/images.py,"ArgSwap(idxs=0<->1 @(268,15)->(268,29))","class CPPNImage(Image): x_coord_range = torch.linspace(-r, r, steps=self.width) y_coord_range = torch.linspace(-r, r, steps=self.height) x, y = torch.meshgrid(x_coord_range, y_coord_range) self.loc = nn.Parameter(torch.stack((x, y), dim=0).unsqueeze(0), requires_grad=False) ","class CPPNImage(Image): x_coord_range = torch.linspace(-r, r, steps=self.width) y_coord_range = torch.linspace(-r, r, steps=self.height) x, y = torch.meshgrid(y_coord_range, x_coord_range) self.loc = nn.Parameter(torch.stack((x, y), dim=0).unsqueeze(0), requires_grad=False) " 1824,https://:@github.com/ocsmit/raster-indices-calc.git,d8eb85db236c048cccf1506180e37d1bbd2734ff,"@@ -473,7 +473,7 @@ def NDBaI(landsat_dir, ndbai_out): swir1_band = SWIR1_path.GetRasterBand(1).ReadAsArray().astype(np.float32) TIR_path = gdal.Open(os.path.join(landsat_dir, tir[0])) tir_band = TIR_path.GetRasterBand(1).ReadAsArray().astype(np.float32) - snap = gdal.Open(os.path.join(landsat_dir, swir1[0])) + snap = gdal.Open(os.path.join(landsat_dir, tir[0])) # Perform Calculation ndbai = ((swir1_band - tir_band) / (swir1_band + tir_band)) ",rindcalc/index_utils.py,"ReplaceText(target='tir' @(476,47)->(476,52))","def NDBaI(landsat_dir, ndbai_out): swir1_band = SWIR1_path.GetRasterBand(1).ReadAsArray().astype(np.float32) TIR_path = gdal.Open(os.path.join(landsat_dir, tir[0])) tir_band = TIR_path.GetRasterBand(1).ReadAsArray().astype(np.float32) snap = gdal.Open(os.path.join(landsat_dir, swir1[0])) # Perform Calculation ndbai = ((swir1_band - tir_band) / (swir1_band + tir_band))","def NDBaI(landsat_dir, ndbai_out): swir1_band = SWIR1_path.GetRasterBand(1).ReadAsArray().astype(np.float32) TIR_path = gdal.Open(os.path.join(landsat_dir, tir[0])) tir_band = TIR_path.GetRasterBand(1).ReadAsArray().astype(np.float32) snap = gdal.Open(os.path.join(landsat_dir, tir[0])) # Perform Calculation ndbai = ((swir1_band - tir_band) / (swir1_band + tir_band))" 1825,https://:@github.com/spacegraphcats/spacegraphcats.git,99052c4fbbebc852ccc6e6eca6f3732b054ed274,"@@ -75,7 +75,7 @@ def load_and_compute_augg(project): changed = True d = 1 print(""Augmenting"", end="" "", flush=True) - while changed and d <= project.radius: + while changed and d < project.radius: if d in augs: print(""({})"".format(d), end="" "", flush=True) with open(augname.format(d), 'r') as f: ",build-catlas.py,"ReplaceText(target='<' @(78,24)->(78,26))","def load_and_compute_augg(project): changed = True d = 1 print(""Augmenting"", end="" "", flush=True) while changed and d <= project.radius: if d in augs: print(""({})"".format(d), end="" "", flush=True) with open(augname.format(d), 'r') as f:","def load_and_compute_augg(project): changed = True d = 1 print(""Augmenting"", end="" "", flush=True) while changed and d < project.radius: if d in augs: print(""({})"".format(d), end="" "", flush=True) with open(augname.format(d), 'r') as f:" 1826,https://:@github.com/spacegraphcats/spacegraphcats.git,5267323b50570258de758732d04239fef6cc0a93,"@@ -55,7 +55,7 @@ def main(): query_mh = query_sig.minhash query_mh = query_mh.downsample_max_hash(frontier_mh) - frontier_mh = query_mh.downsample_max_hash(query_mh) + frontier_mh = frontier_mh.downsample_max_hash(query_mh) containment = query_mh.contained_by(frontier_mh) similarity = query_mh.similarity(frontier_mh) ",search/frontier_search_batch.py,"ReplaceText(target='frontier_mh' @(58,22)->(58,30))","def main(): query_mh = query_sig.minhash query_mh = query_mh.downsample_max_hash(frontier_mh) frontier_mh = query_mh.downsample_max_hash(query_mh) containment = query_mh.contained_by(frontier_mh) similarity = query_mh.similarity(frontier_mh)","def main(): query_mh = query_sig.minhash query_mh = query_mh.downsample_max_hash(frontier_mh) frontier_mh = frontier_mh.downsample_max_hash(query_mh) containment = query_mh.contained_by(frontier_mh) similarity = query_mh.similarity(frontier_mh)" 1827,https://:@github.com/spacegraphcats/spacegraphcats.git,df62df921fd822029c1ae7a139f0d75c8b576295,"@@ -120,7 +120,7 @@ def main(args=sys.argv[1:]): if 2**ratio < 10: new_node_set.add(node_id) - if mh_size > 1: + if mh > 1: n_merged += 1 merge_mh.merge(mh) ",search/extract_nodes_by_shadow_ratio.py,"ReplaceText(target='mh' @(123,15)->(123,22))","def main(args=sys.argv[1:]): if 2**ratio < 10: new_node_set.add(node_id) if mh_size > 1: n_merged += 1 merge_mh.merge(mh) ","def main(args=sys.argv[1:]): if 2**ratio < 10: new_node_set.add(node_id) if mh > 1: n_merged += 1 merge_mh.merge(mh) " 1828,https://:@github.com/spacegraphcats/spacegraphcats.git,73bf57a0d3b45aa1c5f524e361676a1297e85db0,"@@ -90,7 +90,7 @@ def main(args=sys.argv[1:]): if 1: terminal = set() for subnode in dag[top_node_id]: - mh = load_minhash(node_id, minhash_db) + mh = load_minhash(subnode, minhash_db) if mh: terminal.update(find_terminal_nodes(subnode, args.maxsize)) ",search/extract_nodes_by_shadow_ratio.py,"ReplaceText(target='subnode' @(93,30)->(93,37))","def main(args=sys.argv[1:]): if 1: terminal = set() for subnode in dag[top_node_id]: mh = load_minhash(node_id, minhash_db) if mh: terminal.update(find_terminal_nodes(subnode, args.maxsize)) ","def main(args=sys.argv[1:]): if 1: terminal = set() for subnode in dag[top_node_id]: mh = load_minhash(subnode, minhash_db) if mh: terminal.update(find_terminal_nodes(subnode, args.maxsize)) " 1829,https://:@github.com/podhmo/cssdiff.git,fbe359fe1837b98694e9c83a96af2ed7cde53083,"@@ -108,7 +108,7 @@ def difference(s1, s2, op=""+"", iterate=lambda s: sorted(s.items())): if another_value is None: d[style].append(add(name, value)) elif value != another_value: - d[style].append(change(name, value, another_value)) + d[style].append(change(name, another_value, value)) return d ",cssdiff/__init__.py,"ArgSwap(idxs=1<->2 @(111,32)->(111,38))","def difference(s1, s2, op=""+"", iterate=lambda s: sorted(s.items())): if another_value is None: d[style].append(add(name, value)) elif value != another_value: d[style].append(change(name, value, another_value)) return d ","def difference(s1, s2, op=""+"", iterate=lambda s: sorted(s.items())): if another_value is None: d[style].append(add(name, value)) elif value != another_value: d[style].append(change(name, another_value, value)) return d " 1830,https://:@github.com/bodylabs/capysule.git,d28605af4e7b127dd3e823252bb817666e41fe00,"@@ -10,4 +10,4 @@ class Collection(WrenCollection): if response.status_code == requests.codes.not_found and response.json() == {'message': 'Could not find resource'}: raise NotFound(response.text) else: - super(self, Collection).handle_error(response) + super(Collection, self).handle_error(response) ",capysule/collection.py,"ArgSwap(idxs=0<->1 @(13,12)->(13,17))","class Collection(WrenCollection): if response.status_code == requests.codes.not_found and response.json() == {'message': 'Could not find resource'}: raise NotFound(response.text) else: super(self, Collection).handle_error(response)","class Collection(WrenCollection): if response.status_code == requests.codes.not_found and response.json() == {'message': 'Could not find resource'}: raise NotFound(response.text) else: super(Collection, self).handle_error(response)" 1831,https://:@github.com/kaaengine/kaa.git,172bc5493ac61b92b4acf49ff6e124f10b6e9c2c,"@@ -79,7 +79,7 @@ class DemoScene(Scene): z_index=10, )) - self.spawn_timer = Timer(20, self._spawn_heartbeat, + self.spawn_timer = Timer(self._spawn_heartbeat, 20, single_shot=False) self.spawn_timer.start() ",demos/physics3/main.py,"ArgSwap(idxs=0<->1 @(82,27)->(82,32))","class DemoScene(Scene): z_index=10, )) self.spawn_timer = Timer(20, self._spawn_heartbeat, single_shot=False) self.spawn_timer.start() ","class DemoScene(Scene): z_index=10, )) self.spawn_timer = Timer(self._spawn_heartbeat, 20, single_shot=False) self.spawn_timer.start() " 1832,https://:@github.com/oladotunr/cosine.git,2497192592fd0709608c0b6b16dc342b7f645cdc,"@@ -98,7 +98,7 @@ class CosineAlgo(object): instrument = CosineInstrument.load(self.instr_cache, **instr_defs[instr]) self._cxt.instruments[instrument.name] = instrument order_worker = CosineOrderWorker(self._cfg.orders.ActiveDepth, instrument, venue, logger=self.logger) - self._cxt.orders[k][instr.symbol] = order_worker + self._cxt.orders[k][instrument.symbol] = order_worker venue_instruments += 1 if venue_instruments == 0: raise LookupError(""No instruments loaded for any of the provided venues"") ",cosine/core/algo.py,"ReplaceText(target='instrument' @(101,36)->(101,41))","class CosineAlgo(object): instrument = CosineInstrument.load(self.instr_cache, **instr_defs[instr]) self._cxt.instruments[instrument.name] = instrument order_worker = CosineOrderWorker(self._cfg.orders.ActiveDepth, instrument, venue, logger=self.logger) self._cxt.orders[k][instr.symbol] = order_worker venue_instruments += 1 if venue_instruments == 0: raise LookupError(""No instruments loaded for any of the provided venues"")","class CosineAlgo(object): instrument = CosineInstrument.load(self.instr_cache, **instr_defs[instr]) self._cxt.instruments[instrument.name] = instrument order_worker = CosineOrderWorker(self._cfg.orders.ActiveDepth, instrument, venue, logger=self.logger) self._cxt.orders[k][instrument.symbol] = order_worker venue_instruments += 1 if venue_instruments == 0: raise LookupError(""No instruments loaded for any of the provided venues"")" 1833,https://:@github.com/hcji/CTSgetPy.git,93ac966118febd2bd7120f1149eb1f8572939afa,"@@ -52,7 +52,7 @@ def CTSget(source, targets, identifiers, top_only=True, timeout=60, server=""http result = {} if type(targets) is str: result[targets] = CTS_translate_multi(source, targets, identifiers, top_only, timeout, server) - elif type(identifiers) is list: + elif type(targets) is list: for i in range(len(targets)): target = targets[i] print ('translating from ' + source + ' to ' + target) ",CTSgetPy/CTSgetPy.py,"ReplaceText(target='targets' @(55,14)->(55,25))","def CTSget(source, targets, identifiers, top_only=True, timeout=60, server=""http result = {} if type(targets) is str: result[targets] = CTS_translate_multi(source, targets, identifiers, top_only, timeout, server) elif type(identifiers) is list: for i in range(len(targets)): target = targets[i] print ('translating from ' + source + ' to ' + target)","def CTSget(source, targets, identifiers, top_only=True, timeout=60, server=""http result = {} if type(targets) is str: result[targets] = CTS_translate_multi(source, targets, identifiers, top_only, timeout, server) elif type(targets) is list: for i in range(len(targets)): target = targets[i] print ('translating from ' + source + ' to ' + target)" 1834,https://:@github.com/phylliade/vinci.git,8b1940c5613e124a55d11ba257a8800bc12d65a5,"@@ -31,7 +31,7 @@ class SARSAAgent(Agent): self.model = model self.nb_actions = nb_actions self.policy = policy - self.test_policy = policy + self.test_policy = test_policy self.gamma = gamma self.nb_steps_warmup = nb_steps_warmup self.train_interval = train_interval ",rl/agents/sarsa.py,"ReplaceText(target='test_policy' @(34,27)->(34,33))","class SARSAAgent(Agent): self.model = model self.nb_actions = nb_actions self.policy = policy self.test_policy = policy self.gamma = gamma self.nb_steps_warmup = nb_steps_warmup self.train_interval = train_interval","class SARSAAgent(Agent): self.model = model self.nb_actions = nb_actions self.policy = policy self.test_policy = test_policy self.gamma = gamma self.nb_steps_warmup = nb_steps_warmup self.train_interval = train_interval" 1835,https://:@github.com/phelimb/atlas.git,dfacc38b17582837e32e711ecc23926476c19b66,"@@ -297,7 +297,7 @@ class Genotyper(object): for probe_name, probe_coverages in self.variant_covgs.items(): probe_id = self._name_to_id(probe_name) variant = None - call = gt.type(probe_coverages, variant=variant) + call = gt.type(probe_coverages, variant=probe_name) genotypes.append(sum(call[""genotype""])) filters.append(int(call[""info""][""filter""] == ""PASS"")) if sum(call[""genotype""]) > 0 or not call[ ",mykatlas/typing/typer/genotyper.py,"ReplaceText(target='probe_name' @(300,52)->(300,59))","class Genotyper(object): for probe_name, probe_coverages in self.variant_covgs.items(): probe_id = self._name_to_id(probe_name) variant = None call = gt.type(probe_coverages, variant=variant) genotypes.append(sum(call[""genotype""])) filters.append(int(call[""info""][""filter""] == ""PASS"")) if sum(call[""genotype""]) > 0 or not call[","class Genotyper(object): for probe_name, probe_coverages in self.variant_covgs.items(): probe_id = self._name_to_id(probe_name) variant = None call = gt.type(probe_coverages, variant=probe_name) genotypes.append(sum(call[""genotype""])) filters.append(int(call[""info""][""filter""] == ""PASS"")) if sum(call[""genotype""]) > 0 or not call[" 1836,https://:@github.com/munisisazade/startmicro.git,4c74f41a31a6bef9aaa09586628e8427a7d68851,"@@ -54,7 +54,7 @@ class Command(object): self.write_file(self.folder_name, ""docker-compose.yml"", docker_compose) self.write_file(self.folder_name, ""Dockerfile"", Dockerfile) self.write_file(self.folder_name, ""README.md"", readme) - if answers.get(""type"") == ""Restful"" and not answers: + if answers.get(""type"") == ""Restful"" or not answers: self.write_file(self.api_path, ""producer.py"", producer_restful) self.write_file(self.folder_name, ""run.py"", run_restful) elif answers.get(""type"") == ""Redis pubsub"": ",startmicro/core/base.py,"ReplaceText(target='or' @(57,44)->(57,47))","class Command(object): self.write_file(self.folder_name, ""docker-compose.yml"", docker_compose) self.write_file(self.folder_name, ""Dockerfile"", Dockerfile) self.write_file(self.folder_name, ""README.md"", readme) if answers.get(""type"") == ""Restful"" and not answers: self.write_file(self.api_path, ""producer.py"", producer_restful) self.write_file(self.folder_name, ""run.py"", run_restful) elif answers.get(""type"") == ""Redis pubsub"":","class Command(object): self.write_file(self.folder_name, ""docker-compose.yml"", docker_compose) self.write_file(self.folder_name, ""Dockerfile"", Dockerfile) self.write_file(self.folder_name, ""README.md"", readme) if answers.get(""type"") == ""Restful"" or not answers: self.write_file(self.api_path, ""producer.py"", producer_restful) self.write_file(self.folder_name, ""run.py"", run_restful) elif answers.get(""type"") == ""Redis pubsub"":" 1837,https://:@github.com/EdMan1022/PySpot.git,c5624d03bc367d65859ec67e2bee62464e212996,"@@ -17,4 +17,4 @@ class Auth(object): :return: (Bool) True if expired, False if not """""" - return self.expires_at > datetime.datetime.now() + return self.expires_at < datetime.datetime.now() ",pyspot/auth.py,"ReplaceText(target='<' @(20,31)->(20,32))","class Auth(object): :return: (Bool) True if expired, False if not """""" return self.expires_at > datetime.datetime.now()","class Auth(object): :return: (Bool) True if expired, False if not """""" return self.expires_at < datetime.datetime.now()" 1838,https://:@github.com/jolyonb/olxcleaner.git,775eed61ebf7b79e304f9012c5e9264bb7ec505f,"@@ -121,7 +121,7 @@ def traverse_course(edxobj, node, filename, errorstore, pointer=False): try: new_node = etree.parse(new_file).getroot() except XMLSyntaxError as e: - errorstore.add_error(InvalidXML(filename, e.args[0])) + errorstore.add_error(InvalidXML(new_file, e.args[0])) return else: traverse_course(edxobj, new_node, new_file, errorstore, pointer=True) ",edx-xml-clean/loader/xml.py,"ReplaceText(target='new_file' @(124,44)->(124,52))","def traverse_course(edxobj, node, filename, errorstore, pointer=False): try: new_node = etree.parse(new_file).getroot() except XMLSyntaxError as e: errorstore.add_error(InvalidXML(filename, e.args[0])) return else: traverse_course(edxobj, new_node, new_file, errorstore, pointer=True)","def traverse_course(edxobj, node, filename, errorstore, pointer=False): try: new_node = etree.parse(new_file).getroot() except XMLSyntaxError as e: errorstore.add_error(InvalidXML(new_file, e.args[0])) return else: traverse_course(edxobj, new_node, new_file, errorstore, pointer=True)" 1839,https://:@github.com/socek/confsave.git,6cb0b0b47e72f019cd92a4eddf8b2794c01b1e6e,"@@ -46,7 +46,7 @@ class Commands(object): self._init_repo() for filename in glob(self.app.get_home_path() + '/.*'): endpoint = Endpoint(self.app, filename) - if not endpoint.is_visible(): + if endpoint.is_visible(): print(endpoint.path) def ignore(self, filename): ",confsave/commands.py,"ReplaceText(target='' @(49,15)->(49,19))","class Commands(object): self._init_repo() for filename in glob(self.app.get_home_path() + '/.*'): endpoint = Endpoint(self.app, filename) if not endpoint.is_visible(): print(endpoint.path) def ignore(self, filename):","class Commands(object): self._init_repo() for filename in glob(self.app.get_home_path() + '/.*'): endpoint = Endpoint(self.app, filename) if endpoint.is_visible(): print(endpoint.path) def ignore(self, filename):" 1840,https://:@github.com/asulibraries/django-asutheme.git,ab1982643a4145db1954d38d0a7088b8478bdbc6,"@@ -3,6 +3,6 @@ from django.conf import settings def container_style(request): classname = 'container' - if getattr('ASU_THEME_FLUID', settings, False): + if getattr(settings, 'ASU_THEME_FLUID', False): classname += '-fluid' return {'asutheme_container_class': classname} ",asutheme/context_processors.py,"ArgSwap(idxs=0<->1 @(6,7)->(6,14))","from django.conf import settings def container_style(request): classname = 'container' if getattr('ASU_THEME_FLUID', settings, False): classname += '-fluid' return {'asutheme_container_class': classname}","from django.conf import settings def container_style(request): classname = 'container' if getattr(settings, 'ASU_THEME_FLUID', False): classname += '-fluid' return {'asutheme_container_class': classname}" 1841,https://:@github.com/neuropoly/bids_neuropoly.git,aa37aa05e2ebff34631a0ec101749587d1d4b372,"@@ -73,7 +73,7 @@ def convert_dcm2nii(path_data, subject, path_out='./'): # Build output file name fname_out = os.path.join(subject, contrast_dict[contrast][1], subject + '_' + contrast_dict[contrast][0] + '.' - + nii_file.split(os.extsep, 1)[1]) + + nii_file_all_ext.split(os.extsep, 1)[1]) os.makedirs(os.path.abspath(os.path.dirname(fname_out)), exist_ok=True) # Move shutil.move(nii_file_all_ext, fname_out) ",scripts/convert_dcm2nii.py,"ReplaceText(target='nii_file_all_ext' @(76,47)->(76,55))","def convert_dcm2nii(path_data, subject, path_out='./'): # Build output file name fname_out = os.path.join(subject, contrast_dict[contrast][1], subject + '_' + contrast_dict[contrast][0] + '.' + nii_file.split(os.extsep, 1)[1]) os.makedirs(os.path.abspath(os.path.dirname(fname_out)), exist_ok=True) # Move shutil.move(nii_file_all_ext, fname_out)","def convert_dcm2nii(path_data, subject, path_out='./'): # Build output file name fname_out = os.path.join(subject, contrast_dict[contrast][1], subject + '_' + contrast_dict[contrast][0] + '.' + nii_file_all_ext.split(os.extsep, 1)[1]) os.makedirs(os.path.abspath(os.path.dirname(fname_out)), exist_ok=True) # Move shutil.move(nii_file_all_ext, fname_out)" 1842,https://:@github.com/cea-ufmg/sym2num.git,49bd276097ec6efaf8b5e33541f75f5cdae58d25,"@@ -152,7 +152,7 @@ def isstatic(arguments): if len(arguments) == 0: return True elif not isinstance(arguments[0], var.SymbolObject): - return False + return True else: return 'cls' != arguments[0].name != 'self' ",sym2num/function.py,"ReplaceText(target='True' @(155,15)->(155,20))","def isstatic(arguments): if len(arguments) == 0: return True elif not isinstance(arguments[0], var.SymbolObject): return False else: return 'cls' != arguments[0].name != 'self' ","def isstatic(arguments): if len(arguments) == 0: return True elif not isinstance(arguments[0], var.SymbolObject): return True else: return 'cls' != arguments[0].name != 'self' " 1843,https://:@github.com/python-odin/baldr.git,fbce55b525f2fa4b171dc1b688bea4ca42b8a099,"@@ -212,7 +212,7 @@ class ResourceApiCommon(object): except Exception as e: # Special case when a request raises a 500 error. If we are in debug mode and a default is used (ie # request does not explicitly specify a content type) fall back to the Django default exception page. - if settings.DEBUG and getattr(response_codec, 'is_default', False): + if settings.DEBUG and getattr(response_type, 'is_default', False): raise # Catch any other exceptions and pass them to the 500 handler for evaluation. resource = self.handle_500(request, e) ",baldr/api.py,"ReplaceText(target='response_type' @(215,46)->(215,60))","class ResourceApiCommon(object): except Exception as e: # Special case when a request raises a 500 error. If we are in debug mode and a default is used (ie # request does not explicitly specify a content type) fall back to the Django default exception page. if settings.DEBUG and getattr(response_codec, 'is_default', False): raise # Catch any other exceptions and pass them to the 500 handler for evaluation. resource = self.handle_500(request, e)","class ResourceApiCommon(object): except Exception as e: # Special case when a request raises a 500 error. If we are in debug mode and a default is used (ie # request does not explicitly specify a content type) fall back to the Django default exception page. if settings.DEBUG and getattr(response_type, 'is_default', False): raise # Catch any other exceptions and pass them to the 500 handler for evaluation. resource = self.handle_500(request, e)" 1844,https://:@github.com/CallmeNezha/xmldiffs.git,51dab2722f963206b71bde197c283efb63079b49,"@@ -130,7 +130,7 @@ else: def write_sorted_file(fpath, outdir=None, cfg=None): if outdir is not None: fbasename = os.path.splitext(os.path.basename(fpath))[0] - sorted_fpath = os.path.join(outdir, ""{}.cmp.xml"".format(fpath)) + sorted_fpath = os.path.join(outdir, ""{}.cmp.xml"".format(fbasename)) tmp = unicode_writer(open(sorted_fpath, 'w')) else: tmp = unicode_writer(NamedTemporaryFile('w')) ",xmldiffs/command_line.py,"ReplaceText(target='fbasename' @(133,64)->(133,69))","else: def write_sorted_file(fpath, outdir=None, cfg=None): if outdir is not None: fbasename = os.path.splitext(os.path.basename(fpath))[0] sorted_fpath = os.path.join(outdir, ""{}.cmp.xml"".format(fpath)) tmp = unicode_writer(open(sorted_fpath, 'w')) else: tmp = unicode_writer(NamedTemporaryFile('w'))","else: def write_sorted_file(fpath, outdir=None, cfg=None): if outdir is not None: fbasename = os.path.splitext(os.path.basename(fpath))[0] sorted_fpath = os.path.join(outdir, ""{}.cmp.xml"".format(fbasename)) tmp = unicode_writer(open(sorted_fpath, 'w')) else: tmp = unicode_writer(NamedTemporaryFile('w'))" 1845,https://:@github.com/ahmed-shariff/ml-pipeline.git,2aa119fe99d2e96857754b56b601a82463f13c9c,"@@ -418,7 +418,7 @@ class Metric(): return 0 def get_tracking_delta(self): - if len(self.track_value_list) > self.track_average_epoc_count: + if len(self.track_value_list) == self.track_average_epoc_count: return sum( [self.track_value_list[idx + 1] - self.track_value_list[idx] ",mlpipeline/utils/_utils.py,"ReplaceText(target='==' @(421,38)->(421,39))","class Metric(): return 0 def get_tracking_delta(self): if len(self.track_value_list) > self.track_average_epoc_count: return sum( [self.track_value_list[idx + 1] - self.track_value_list[idx]","class Metric(): return 0 def get_tracking_delta(self): if len(self.track_value_list) == self.track_average_epoc_count: return sum( [self.track_value_list[idx + 1] - self.track_value_list[idx]" 1846,https://:@github.com/rshk/jobcontrol.git,41187069493848c41741b1217b32aeb21e442c43,"@@ -112,7 +112,7 @@ class MemoryJobControl(JobControlBase): if jrdef['job_id'] == job_id) for jrid, jrdef in sorted(list(runs)): - yield jrdef + yield jrid # ------------------------------------------------------------ # Logging ",jobcontrol/ext/memory.py,"ReplaceText(target='jrid' @(115,18)->(115,23))","class MemoryJobControl(JobControlBase): if jrdef['job_id'] == job_id) for jrid, jrdef in sorted(list(runs)): yield jrdef # ------------------------------------------------------------ # Logging","class MemoryJobControl(JobControlBase): if jrdef['job_id'] == job_id) for jrid, jrdef in sorted(list(runs)): yield jrid # ------------------------------------------------------------ # Logging" 1847,https://:@github.com/spatialucr/geosnap.git,73d2b50077271c9f3c530a52ef97890200c29751,"@@ -171,7 +171,7 @@ def harmonize( profiles.append(profile) if len(intensive_variables) > 0: - profile = pd.DataFrame(interpolation[1], columns=extensive_variables) + profile = pd.DataFrame(interpolation[1], columns=intensive_variables) profiles.append(profile) profile = pd.concat(profiles, sort=True) ",geosnap/harmonize/harmonize.py,"ReplaceText(target='intensive_variables' @(174,61)->(174,80))","def harmonize( profiles.append(profile) if len(intensive_variables) > 0: profile = pd.DataFrame(interpolation[1], columns=extensive_variables) profiles.append(profile) profile = pd.concat(profiles, sort=True)","def harmonize( profiles.append(profile) if len(intensive_variables) > 0: profile = pd.DataFrame(interpolation[1], columns=intensive_variables) profiles.append(profile) profile = pd.concat(profiles, sort=True)" 1848,https://:@github.com/stefanseefeld/faber.git,3cb344b107e599396c70e3e72488abbeff4af738,"@@ -416,7 +416,7 @@ def extend (name, values): if __implicit_features.has_key(v): raise BaseException (""'%s' is already associated with the feature '%s'"" % (v, __implicit_features [v])) - __implicit_features[v] = name + __implicit_features[v] = feature if len (feature.values()) == 0 and len (values) > 0: # This is the first value specified for this feature, ",src/build/feature.py,"ReplaceText(target='feature' @(419,37)->(419,41))","def extend (name, values): if __implicit_features.has_key(v): raise BaseException (""'%s' is already associated with the feature '%s'"" % (v, __implicit_features [v])) __implicit_features[v] = name if len (feature.values()) == 0 and len (values) > 0: # This is the first value specified for this feature,","def extend (name, values): if __implicit_features.has_key(v): raise BaseException (""'%s' is already associated with the feature '%s'"" % (v, __implicit_features [v])) __implicit_features[v] = feature if len (feature.values()) == 0 and len (values) > 0: # This is the first value specified for this feature," 1849,https://:@github.com/stefanseefeld/faber.git,475c635167c32ee61b5951e2c1ba6a5613723437,"@@ -160,7 +160,7 @@ def refine (properties, requirements): # Record them so that we can handle 'properties'. for r in requirements: # Don't consider conditional requirements. - if r.condition(): + if not r.condition(): required[r.feature()] = r for p in properties: ",src/build/property.py,"ReplaceText(target='not ' @(163,11)->(163,11))","def refine (properties, requirements): # Record them so that we can handle 'properties'. for r in requirements: # Don't consider conditional requirements. if r.condition(): required[r.feature()] = r for p in properties:","def refine (properties, requirements): # Record them so that we can handle 'properties'. for r in requirements: # Don't consider conditional requirements. if not r.condition(): required[r.feature()] = r for p in properties:" 1850,https://:@github.com/stefanseefeld/faber.git,632ab9c8665f96399b75d4c36b7e50db9cd05812,"@@ -362,7 +362,7 @@ def __add_flag (rule_or_module, variable_name, condition, values): assert m module = m.group(1) - __module_flags.setdefault(m, []).append(f) + __module_flags.setdefault(module, []).append(f) __flags.setdefault(rule_or_module, []).append(f) __requirements = [] ",src/build/toolset.py,"ReplaceText(target='module' @(365,30)->(365,31))","def __add_flag (rule_or_module, variable_name, condition, values): assert m module = m.group(1) __module_flags.setdefault(m, []).append(f) __flags.setdefault(rule_or_module, []).append(f) __requirements = []","def __add_flag (rule_or_module, variable_name, condition, values): assert m module = m.group(1) __module_flags.setdefault(module, []).append(f) __flags.setdefault(rule_or_module, []).append(f) __requirements = []" 1851,https://:@github.com/ivirshup/ConsistentClusters.git,c2ad610430164fe7a56ce5d3f1f8357e1dd336bc,"@@ -518,7 +518,7 @@ def _call_get_edges(args): def _get_edges(clustering1: np.array, clustering2: np.array): edges = [] offset1 = clustering1.min() - offset2 = clustering1.min() + offset2 = clustering2.min() # Because of how I've done unique node names, potentially this # could be done in a more generic way by creating a mapping here. offset_clusts1 = clustering1 - offset1 ",constclust/aggregate.py,"ReplaceText(target='clustering2' @(521,14)->(521,25))","def _call_get_edges(args): def _get_edges(clustering1: np.array, clustering2: np.array): edges = [] offset1 = clustering1.min() offset2 = clustering1.min() # Because of how I've done unique node names, potentially this # could be done in a more generic way by creating a mapping here. offset_clusts1 = clustering1 - offset1","def _call_get_edges(args): def _get_edges(clustering1: np.array, clustering2: np.array): edges = [] offset1 = clustering1.min() offset2 = clustering2.min() # Because of how I've done unique node names, potentially this # could be done in a more generic way by creating a mapping here. offset_clusts1 = clustering1 - offset1" 1852,https://:@github.com/nowells/python-wellrested.git,8d016faf90f3a0d833cf9b1c52aaa66ee7de9514,"@@ -35,7 +35,7 @@ class RestClient(object): request_body = self._serialize(data) response_headers, response_content = self._connection.request(resource, method, args=args, body=request_body, headers=headers, content_type=self.content_type) if response_headers.get('status') == HTTP_STATUS_OK: - data = self._deserialize(response_content) + response_data = self._deserialize(response_content) return Response(response_headers, response_content, response_data) def _serialize(self, data): ",wellrested/connections/__init__.py,"ReplaceText(target='response_data' @(38,12)->(38,16))","class RestClient(object): request_body = self._serialize(data) response_headers, response_content = self._connection.request(resource, method, args=args, body=request_body, headers=headers, content_type=self.content_type) if response_headers.get('status') == HTTP_STATUS_OK: data = self._deserialize(response_content) return Response(response_headers, response_content, response_data) def _serialize(self, data):","class RestClient(object): request_body = self._serialize(data) response_headers, response_content = self._connection.request(resource, method, args=args, body=request_body, headers=headers, content_type=self.content_type) if response_headers.get('status') == HTTP_STATUS_OK: response_data = self._deserialize(response_content) return Response(response_headers, response_content, response_data) def _serialize(self, data):" 1853,https://:@github.com/packagecontrol/st_package_reviewer.git,85b67bc0d381d382b2805e6464ab80eb31e2d484,"@@ -45,7 +45,7 @@ def main(): help=""URL to the repository or path to the package to be checked."") parser.add_argument(""--repo-only"", action='store_true', help=""Do not check the package itself and only its repository."") - parser.add_argument(""--verbose"", ""-v"", action='store_true', + parser.add_argument(""-v"", ""--verbose"", action='store_true', help=""Increase verbosity."") parser.add_argument(""--debug"", action='store_true', help=""Enter pdb on excpetions. Implies --verbose."") ",package_reviewer/__main__.py,"ArgSwap(idxs=0<->1 @(48,4)->(48,23))","def main(): help=""URL to the repository or path to the package to be checked."") parser.add_argument(""--repo-only"", action='store_true', help=""Do not check the package itself and only its repository."") parser.add_argument(""--verbose"", ""-v"", action='store_true', help=""Increase verbosity."") parser.add_argument(""--debug"", action='store_true', help=""Enter pdb on excpetions. Implies --verbose."")","def main(): help=""URL to the repository or path to the package to be checked."") parser.add_argument(""--repo-only"", action='store_true', help=""Do not check the package itself and only its repository."") parser.add_argument(""-v"", ""--verbose"", action='store_true', help=""Increase verbosity."") parser.add_argument(""--debug"", action='store_true', help=""Enter pdb on excpetions. Implies --verbose."")" 1854,https://:@github.com/emilbjorklund/django-template-shortcodes.git,b2788b9d7fd1211de9666fd5c977274f8f343e30,"@@ -31,7 +31,7 @@ def parse(value, request): try: if cache.get(cache_key): try: - parsed = re.sub(r'\[' + item + r'\]', cache.get(item), parsed) + parsed = re.sub(r'\[' + item + r'\]', cache.get(cache_key), parsed) except: pass else: ",shortcodes/parser.py,"ReplaceText(target='cache_key' @(34,58)->(34,62))","def parse(value, request): try: if cache.get(cache_key): try: parsed = re.sub(r'\[' + item + r'\]', cache.get(item), parsed) except: pass else:","def parse(value, request): try: if cache.get(cache_key): try: parsed = re.sub(r'\[' + item + r'\]', cache.get(cache_key), parsed) except: pass else:" 1855,https://:@github.com/ods/aiochsa.git,24dcfdbc52b0a1009ce4a7b7ebcf72a1b26be18b,"@@ -61,7 +61,7 @@ class Client: if response.status != 200: body = await response.read() raise DBException.from_message( - statement, body.decode(errors='replace'), + query, body.decode(errors='replace'), ) if response.content_type == 'application/json': ",aiochsa/client.py,"ReplaceText(target='query' @(64,20)->(64,29))","class Client: if response.status != 200: body = await response.read() raise DBException.from_message( statement, body.decode(errors='replace'), ) if response.content_type == 'application/json':","class Client: if response.status != 200: body = await response.read() raise DBException.from_message( query, body.decode(errors='replace'), ) if response.content_type == 'application/json':" 1856,https://:@github.com/lega911/sqlmapper.git,cf7f674b0186e12ce37c5a9deb84e6b8d4d58919,"@@ -116,7 +116,7 @@ class MysqlTable(Table): scolumn += ' AUTO_INCREMENT' if default != NoValue: - if not_null or primary: + if auto_increment or primary: raise ValueError('Can''t have default value') scolumn += ' DEFAULT %s' values.append(default) ",sqlmapper/mysql.py,"ReplaceText(target='auto_increment' @(119,15)->(119,23))","class MysqlTable(Table): scolumn += ' AUTO_INCREMENT' if default != NoValue: if not_null or primary: raise ValueError('Can''t have default value') scolumn += ' DEFAULT %s' values.append(default)","class MysqlTable(Table): scolumn += ' AUTO_INCREMENT' if default != NoValue: if auto_increment or primary: raise ValueError('Can''t have default value') scolumn += ' DEFAULT %s' values.append(default)" 1857,https://:@github.com/vanceeasleaf/aces.git,c4097285794c957a7242162570b41412be547ce0,"@@ -34,5 +34,5 @@ class Device(Material): #atoms.center() x=atoms.positions[:,0] - return atoms + return center ",aces/runners/negf/device/device.py,"ReplaceText(target='center' @(37,9)->(37,14))","class Device(Material): #atoms.center() x=atoms.positions[:,0] return atoms ","class Device(Material): #atoms.center() x=atoms.positions[:,0] return center " 1858,https://:@github.com/marcofavorito/temprl.git,1b0cb65d54ba2696fea2d41401990e406a8859f0,"@@ -195,7 +195,7 @@ def _compute_levels(dfa: DFA, property_states): # levels for failure state (i.e. that cannot reach a final state) failure_states = set() for s in filter(lambda x: x not in z_current, dfa.states): - state2level[s] = max_level + state2level[s] = level failure_states.add(s) return state2level, max_level, failure_states ",temprl/automata.py,"ReplaceText(target='level' @(198,25)->(198,34))","def _compute_levels(dfa: DFA, property_states): # levels for failure state (i.e. that cannot reach a final state) failure_states = set() for s in filter(lambda x: x not in z_current, dfa.states): state2level[s] = max_level failure_states.add(s) return state2level, max_level, failure_states","def _compute_levels(dfa: DFA, property_states): # levels for failure state (i.e. that cannot reach a final state) failure_states = set() for s in filter(lambda x: x not in z_current, dfa.states): state2level[s] = level failure_states.add(s) return state2level, max_level, failure_states" 1859,https://:@github.com/equinor/stea.git,bdebfe3c0cb939db2dd7b1a39a029d00ffe555a9,"@@ -82,5 +82,5 @@ def calculate(stea_input): request.add_profile(profile_id, start_year, data) - return SteaResult(client.calculate(request), project) + return SteaResult(client.calculate(request), stea_input) ",stea/__init__.py,"ReplaceText(target='stea_input' @(85,49)->(85,56))","def calculate(stea_input): request.add_profile(profile_id, start_year, data) return SteaResult(client.calculate(request), project) ","def calculate(stea_input): request.add_profile(profile_id, start_year, data) return SteaResult(client.calculate(request), stea_input) " 1860,https://:@github.com/tandonneur/AdvancedAnalytics.git,4a73a8c616db33f69c5361eca1f4ca18ca7a2b17,"@@ -710,7 +710,7 @@ class tree_classifier(object): print(fstr2.format('Class ', dt.classes_[i]), end="""") for j in range(n_classes): - print(""{:>10d}"".format(conf_mat_t[i][j]), end="""") + print(""{:>10d}"".format(conf_mat_v[i][j]), end="""") print("""") print("""") ",AdvancedAnalytics/Tree.py,"ReplaceText(target='conf_mat_v' @(713,43)->(713,53))","class tree_classifier(object): print(fstr2.format('Class ', dt.classes_[i]), end="""") for j in range(n_classes): print(""{:>10d}"".format(conf_mat_t[i][j]), end="""") print("""") print("""") ","class tree_classifier(object): print(fstr2.format('Class ', dt.classes_[i]), end="""") for j in range(n_classes): print(""{:>10d}"".format(conf_mat_v[i][j]), end="""") print("""") print("""") " 1861,https://:@github.com/usc-isi-i2/dsbox-cleaning.git,961d92886916dfbc0a0e1bfd2a51e9c4677301f7,"@@ -342,7 +342,7 @@ class Profiler(TransformerPrimitiveBase[Input, Output, Hyperparams]): inputs.iloc[:, col] = numerics else: if ""http://schema.org/Float"" not in old_metadata['semantic_types']: - old_metadata['semantic_types'] = (""http://schema.org/Float"",) + old_metadata['semantic_types'] += (""http://schema.org/Float"",) old_metadata['structural_type'] = type(10.2) inputs.iloc[:, col] = numerics ",dsbox/datapreprocessing/cleaner/data_profile.py,"ReplaceText(target='+=' @(345,63)->(345,64))","class Profiler(TransformerPrimitiveBase[Input, Output, Hyperparams]): inputs.iloc[:, col] = numerics else: if ""http://schema.org/Float"" not in old_metadata['semantic_types']: old_metadata['semantic_types'] = (""http://schema.org/Float"",) old_metadata['structural_type'] = type(10.2) inputs.iloc[:, col] = numerics ","class Profiler(TransformerPrimitiveBase[Input, Output, Hyperparams]): inputs.iloc[:, col] = numerics else: if ""http://schema.org/Float"" not in old_metadata['semantic_types']: old_metadata['semantic_types'] += (""http://schema.org/Float"",) old_metadata['structural_type'] = type(10.2) inputs.iloc[:, col] = numerics " 1862,https://:@github.com/azavea/djsonb.git,90e97fc29ca5df0cc56b3193c9f7a4a1543111b5,"@@ -72,7 +72,7 @@ class FilterTree: sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, True) else: sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, False) - pattern_specs.append(sql_tuple) + rule_specs.append(sql_tuple) rule_strings = [' AND '.join([rule[0] for rule in rule_specs]), ' OR '.join([rule[0] for rule in pattern_specs])] ",djsonb/lookups.py,"ReplaceText(target='rule_specs' @(75,20)->(75,33))","class FilterTree: sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, True) else: sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, False) pattern_specs.append(sql_tuple) rule_strings = [' AND '.join([rule[0] for rule in rule_specs]), ' OR '.join([rule[0] for rule in pattern_specs])]","class FilterTree: sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, True) else: sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, False) rule_specs.append(sql_tuple) rule_strings = [' AND '.join([rule[0] for rule in rule_specs]), ' OR '.join([rule[0] for rule in pattern_specs])]" 1863,https://:@github.com/ionelmc/python-pth.git,5e8cbdd87050b06018ef04cc994d8dc155931e98,"@@ -235,7 +235,7 @@ class Path(AbstractPath): normpath = property(lambda self: pth(ospath.normpath(self))) norm = property(lambda self: pth(ospath.normcase(ospath.normpath(self)))) real = realpath = property(lambda self: pth(ospath.realpath(self))) - rel = relpath = lambda self, start: pth(ospath.relpath(self, start)) + rel = relpath = lambda self, start: pth(ospath.relpath(start, self)) same = samefile = lambda self, other: ospath.samefile(self, other) if hasattr(os, 'link'): if PY33: ",src/pth.py,"ArgSwap(idxs=0<->1 @(238,44)->(238,58))","class Path(AbstractPath): normpath = property(lambda self: pth(ospath.normpath(self))) norm = property(lambda self: pth(ospath.normcase(ospath.normpath(self)))) real = realpath = property(lambda self: pth(ospath.realpath(self))) rel = relpath = lambda self, start: pth(ospath.relpath(self, start)) same = samefile = lambda self, other: ospath.samefile(self, other) if hasattr(os, 'link'): if PY33:","class Path(AbstractPath): normpath = property(lambda self: pth(ospath.normpath(self))) norm = property(lambda self: pth(ospath.normcase(ospath.normpath(self)))) real = realpath = property(lambda self: pth(ospath.realpath(self))) rel = relpath = lambda self, start: pth(ospath.relpath(start, self)) same = samefile = lambda self, other: ospath.samefile(self, other) if hasattr(os, 'link'): if PY33:" 1864,https://:@github.com/savex/tempest-parser.git,8c2ad3b8d13573924408bf3d2bf50ddc05fdd3d8,"@@ -33,7 +33,7 @@ def get_date_from_source(source): # _ctime = time.strftime(""%d/%m/%Y %H:%M"", time.gmtime(ctime)) return time.strftime( ""%d/%m/%Y %H:%M GMT"", - time.gmtime(ctime) + time.gmtime(mtime) ) ",tempest_parser/manager/importers.py,"ReplaceText(target='mtime' @(36,20)->(36,25))","def get_date_from_source(source): # _ctime = time.strftime(""%d/%m/%Y %H:%M"", time.gmtime(ctime)) return time.strftime( ""%d/%m/%Y %H:%M GMT"", time.gmtime(ctime) ) ","def get_date_from_source(source): # _ctime = time.strftime(""%d/%m/%Y %H:%M"", time.gmtime(ctime)) return time.strftime( ""%d/%m/%Y %H:%M GMT"", time.gmtime(mtime) ) " 1865,https://:@github.com/solidfire/solidfire-cli.git,fcb6c5f4abbe9cc7ef2c6dded6d2d7fb2492f931,"@@ -88,5 +88,5 @@ def remove(ctx, name=None, index=None): if(name is None and index is not None): cli_utils.print_result(connections[int(index)], ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree) if(name is not None and index is None): - connections = [connection for connection in connections if connection[""name""]!=name] + connections = [connection for connection in connections if connection[""name""]==name] cli_utils.print_result(connections, ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree) ",element/cli/commands/cmd_connection.py,"ReplaceText(target='==' @(91,85)->(91,87))","def remove(ctx, name=None, index=None): if(name is None and index is not None): cli_utils.print_result(connections[int(index)], ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree) if(name is not None and index is None): connections = [connection for connection in connections if connection[""name""]!=name] cli_utils.print_result(connections, ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree)","def remove(ctx, name=None, index=None): if(name is None and index is not None): cli_utils.print_result(connections[int(index)], ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree) if(name is not None and index is None): connections = [connection for connection in connections if connection[""name""]==name] cli_utils.print_result(connections, ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree)" 1866,https://:@github.com/glimix/numpy-sugar.git,59fb36f9110b7ac9ae2ce6e06d443c7d44aac42f,"@@ -50,7 +50,7 @@ def ddot(L, R, left=True, out=None): else: if out is None: out = copy(L) - return multiply(out, R, out=out) + return multiply(L, R, out=out) def cdot(L, out=None): ",numpy_sugar/linalg/dot.py,"ReplaceText(target='L' @(53,24)->(53,27))","def ddot(L, R, left=True, out=None): else: if out is None: out = copy(L) return multiply(out, R, out=out) def cdot(L, out=None):","def ddot(L, R, left=True, out=None): else: if out is None: out = copy(L) return multiply(L, R, out=out) def cdot(L, out=None):" 1867,https://:@github.com/kuzmoyev/Google-Calendar-Simple-API.git,9a902a5ce43d8dc2b18c53b8140443a2a99c2810,"@@ -474,7 +474,7 @@ class Recurrence: if freq not in (HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY, YEARLY): raise ValueError('""freq"" parameter must be one of HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY or YEARLY. ' '{} was provided'.format(freq)) - if interval and (isinstance(interval, int) or interval < 1): + if interval and (not isinstance(interval, int) or interval < 1): raise ValueError('""interval"" parameter must be a positive int. ' '{} was provided'.format(interval)) if count and (not isinstance(count, int) or count < 1): ",gcsa/recurrence.py,"ReplaceText(target='not ' @(477,25)->(477,25))","class Recurrence: if freq not in (HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY, YEARLY): raise ValueError('""freq"" parameter must be one of HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY or YEARLY. ' '{} was provided'.format(freq)) if interval and (isinstance(interval, int) or interval < 1): raise ValueError('""interval"" parameter must be a positive int. ' '{} was provided'.format(interval)) if count and (not isinstance(count, int) or count < 1):","class Recurrence: if freq not in (HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY, YEARLY): raise ValueError('""freq"" parameter must be one of HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY or YEARLY. ' '{} was provided'.format(freq)) if interval and (not isinstance(interval, int) or interval < 1): raise ValueError('""interval"" parameter must be a positive int. ' '{} was provided'.format(interval)) if count and (not isinstance(count, int) or count < 1):" 1868,https://:@github.com/NFontrodona/Lazyparser.git,8e3888ea5248c4f1e599bff0bd40b4e96c58e92f,"@@ -383,7 +383,7 @@ def set_env(delim1, delim2, hd, tb): :param hd: (string) the header of parameter :param tb: (int) the number of space/tab that bedore the docstring """""" - if isinstance(int, tb): + if isinstance(tb, int): global tab tab = tb else: ",src/lazyparser.py,"ArgSwap(idxs=0<->1 @(386,7)->(386,17))","def set_env(delim1, delim2, hd, tb): :param hd: (string) the header of parameter :param tb: (int) the number of space/tab that bedore the docstring """""" if isinstance(int, tb): global tab tab = tb else:","def set_env(delim1, delim2, hd, tb): :param hd: (string) the header of parameter :param tb: (int) the number of space/tab that bedore the docstring """""" if isinstance(tb, int): global tab tab = tb else:" 1869,https://:@github.com/mikemill/rq_retry_scheduler.git,d279c059418831f33d588d963252de0610cb17a7,"@@ -59,7 +59,7 @@ class Scheduler(object): def delay_job(self, job, time_delta): amount = int(time_delta.total_seconds()) - self.connection.zincrby(self.scheduler_jobs_key, job.id, amount) + self.connection.zincrby(self.scheduler_jobs_key, amount, job.id) def should_repeat_job(self, job): max_runs = job.meta['max_runs'] ",rq_retry_scheduler/scheduler.py,"ArgSwap(idxs=1<->2 @(62,8)->(62,31))","class Scheduler(object): def delay_job(self, job, time_delta): amount = int(time_delta.total_seconds()) self.connection.zincrby(self.scheduler_jobs_key, job.id, amount) def should_repeat_job(self, job): max_runs = job.meta['max_runs']","class Scheduler(object): def delay_job(self, job, time_delta): amount = int(time_delta.total_seconds()) self.connection.zincrby(self.scheduler_jobs_key, amount, job.id) def should_repeat_job(self, job): max_runs = job.meta['max_runs']" 1870,https://:@github.com/jbaber/pedigree.git,d4f17753d97d279e2845e1b5569c8f5f99fa9939,"@@ -633,7 +633,7 @@ def toml_to_family(toml_filename): for relation in big_dict['spouse'] if relation[0] == spouse_uid ] - family.add_spouses(spouse, children) + family.add_spouses(spouse, spouses) return family ",src/pedigree/pedigree_lib.py,"ReplaceText(target='spouses' @(636,31)->(636,39))","def toml_to_family(toml_filename): for relation in big_dict['spouse'] if relation[0] == spouse_uid ] family.add_spouses(spouse, children) return family ","def toml_to_family(toml_filename): for relation in big_dict['spouse'] if relation[0] == spouse_uid ] family.add_spouses(spouse, spouses) return family " 1871,https://:@github.com/wayne-li2/Flask-User.git,928e09cff2d773d5f2cbfa1ed847e32b1b5eae07,"@@ -83,7 +83,7 @@ def test_roles(db): role1 = db_adapter.find_first_object(RoleClass, name='Role 1') db_adapter.delete_object(role1) role2 = db_adapter.find_first_object(RoleClass, name='Role 2') - db_adapter.delete_object(role1) + db_adapter.delete_object(role2) db_adapter.commit() ",flask_user/tests/test_roles.py,"ReplaceText(target='role2' @(86,33)->(86,38))","def test_roles(db): role1 = db_adapter.find_first_object(RoleClass, name='Role 1') db_adapter.delete_object(role1) role2 = db_adapter.find_first_object(RoleClass, name='Role 2') db_adapter.delete_object(role1) db_adapter.commit() ","def test_roles(db): role1 = db_adapter.find_first_object(RoleClass, name='Role 1') db_adapter.delete_object(role1) role2 = db_adapter.find_first_object(RoleClass, name='Role 2') db_adapter.delete_object(role2) db_adapter.commit() " 1872,https://:@github.com/manodeep/astro3D.git,38bca8c32c783779f5ddd2bfab66ec69427f4d12,"@@ -117,7 +117,7 @@ def test_sorted_order(opt): return False if (outer_sort == outer_sort_next): - if (inner_sort > inner_sort_next): + if (inner_sort < inner_sort_next): print(""For Halo ID {0} we had a {1} of {2}. After sorting via lexsort "" ""inner-key {1}, the next Halo has ID {3} and a {1} of {4}"" .format(halo_id, opt[""sort_mass""], inner_sort, halo_id_next, ",tests/tests.py,"ReplaceText(target='<' @(120,35)->(120,36))","def test_sorted_order(opt): return False if (outer_sort == outer_sort_next): if (inner_sort > inner_sort_next): print(""For Halo ID {0} we had a {1} of {2}. After sorting via lexsort "" ""inner-key {1}, the next Halo has ID {3} and a {1} of {4}"" .format(halo_id, opt[""sort_mass""], inner_sort, halo_id_next,","def test_sorted_order(opt): return False if (outer_sort == outer_sort_next): if (inner_sort < inner_sort_next): print(""For Halo ID {0} we had a {1} of {2}. After sorting via lexsort "" ""inner-key {1}, the next Halo has ID {3} and a {1} of {4}"" .format(halo_id, opt[""sort_mass""], inner_sort, halo_id_next," 1873,https://:@github.com/manodeep/astro3D.git,69e10a4b7b50701e65a9ca0f6782fc2654987588,"@@ -119,7 +119,7 @@ def my_test_sorted_order(opt): pytest.fail() if (outer_sort == outer_sort_next): - if (inner_sort < inner_sort_next): + if (inner_sort > inner_sort_next): print(""For Halo ID {0} we had a {1} of {2}. After sorting via lexsort "" ""inner-key {1}, the next Halo has ID {3} and a {1} of {4}"" .format(halo_id, opt[""sort_mass""], inner_sort, halo_id_next, ",tests/forest_sorter_test.py,"ReplaceText(target='>' @(122,35)->(122,36))","def my_test_sorted_order(opt): pytest.fail() if (outer_sort == outer_sort_next): if (inner_sort < inner_sort_next): print(""For Halo ID {0} we had a {1} of {2}. After sorting via lexsort "" ""inner-key {1}, the next Halo has ID {3} and a {1} of {4}"" .format(halo_id, opt[""sort_mass""], inner_sort, halo_id_next,","def my_test_sorted_order(opt): pytest.fail() if (outer_sort == outer_sort_next): if (inner_sort > inner_sort_next): print(""For Halo ID {0} we had a {1} of {2}. After sorting via lexsort "" ""inner-key {1}, the next Halo has ID {3} and a {1} of {4}"" .format(halo_id, opt[""sort_mass""], inner_sort, halo_id_next," 1874,https://:@github.com/kazenniy/atapt.git,993a7734447b17a5d96db5428b267556f90b10b4,"@@ -416,7 +416,7 @@ class atapt: # word 83 ""Commands and feature sets supported"" features = int.from_bytes(buf[166] + buf[167], byteorder='little') - if major & 0x400: + if features & 0x400: self.lba48bit = True else: self.lba48bit = False ",atapt/atapt.py,"ReplaceText(target='features' @(419,11)->(419,16))","class atapt: # word 83 ""Commands and feature sets supported"" features = int.from_bytes(buf[166] + buf[167], byteorder='little') if major & 0x400: self.lba48bit = True else: self.lba48bit = False","class atapt: # word 83 ""Commands and feature sets supported"" features = int.from_bytes(buf[166] + buf[167], byteorder='little') if features & 0x400: self.lba48bit = True else: self.lba48bit = False" 1875,https://:@github.com/RI-imaging/DryMass.git,d92c19314359ae4e3b4feb0136bc649840cf57a7,"@@ -221,7 +221,7 @@ def plot_qpi_sphere(qpi_real, qpi_sim, path=None, simtype=""simulation""): plt.tight_layout(rect=(0, 0, 1, .95)) # add identifier - fig.text(x=.5, y=.99, s=qpi_real[""identifier""], + fig.text(x=.5, y=.99, s=qpi_sim[""identifier""], verticalalignment=""top"", horizontalalignment=""center"", fontsize=14) ",drymass/plot.py,"ReplaceText(target='qpi_sim' @(224,28)->(224,36))","def plot_qpi_sphere(qpi_real, qpi_sim, path=None, simtype=""simulation""): plt.tight_layout(rect=(0, 0, 1, .95)) # add identifier fig.text(x=.5, y=.99, s=qpi_real[""identifier""], verticalalignment=""top"", horizontalalignment=""center"", fontsize=14)","def plot_qpi_sphere(qpi_real, qpi_sim, path=None, simtype=""simulation""): plt.tight_layout(rect=(0, 0, 1, .95)) # add identifier fig.text(x=.5, y=.99, s=qpi_sim[""identifier""], verticalalignment=""top"", horizontalalignment=""center"", fontsize=14)" 1876,https://:@github.com/lazaret/anuket.git,6f069e0d5d6498048990cacd743cd5d63e0e84fa,"@@ -59,7 +59,7 @@ class UniqueAuthEmail(validators.FancyValidator): user_id = values['user_id'] else: user_id = None - if email and (user.user_id != user_id): + if user and (user.user_id != user_id): errors = {'email': self.message('not_unique_email', state)} raise Invalid(self.message('not_unique_email', state), values, state, error_dict=errors) ",wepwawet/lib/validators.py,"ReplaceText(target='user' @(62,15)->(62,20))","class UniqueAuthEmail(validators.FancyValidator): user_id = values['user_id'] else: user_id = None if email and (user.user_id != user_id): errors = {'email': self.message('not_unique_email', state)} raise Invalid(self.message('not_unique_email', state), values, state, error_dict=errors)","class UniqueAuthEmail(validators.FancyValidator): user_id = values['user_id'] else: user_id = None if user and (user.user_id != user_id): errors = {'email': self.message('not_unique_email', state)} raise Invalid(self.message('not_unique_email', state), values, state, error_dict=errors)" 1877,https://:@github.com/esteinig/dartqc.git,b98781ae43cc97f8df60a703a594395ddca18d87,"@@ -292,7 +292,7 @@ class CommandLine: for value in [command[""maf""], command[""call""], command[""rep""], command[""seq_identity""]]: if value != -1: - if value < 1 or value > 1: + if value < 0 or value > 1: raise ValueError(""Filter and identity thresholds must be larger >= 0 and <= 1."") for value in [command[""clone_selector""], command[""identity_selector""]]: ",dart_qc.py,"ReplaceText(target='0' @(295,27)->(295,28))","class CommandLine: for value in [command[""maf""], command[""call""], command[""rep""], command[""seq_identity""]]: if value != -1: if value < 1 or value > 1: raise ValueError(""Filter and identity thresholds must be larger >= 0 and <= 1."") for value in [command[""clone_selector""], command[""identity_selector""]]:","class CommandLine: for value in [command[""maf""], command[""call""], command[""rep""], command[""seq_identity""]]: if value != -1: if value < 0 or value > 1: raise ValueError(""Filter and identity thresholds must be larger >= 0 and <= 1."") for value in [command[""clone_selector""], command[""identity_selector""]]:" 1878,https://:@github.com/dmentipl/phantom-build.git,09e3fcdf5c2ca013f55ec9d9d4af396c99b655f8,"@@ -387,7 +387,7 @@ def setup_calculation( raise SetupError(msg) else: logger.info('Successfully set up Phantom calculation') - logger.info(f'run_path: {run_path}') + logger.info(f'run_path: {_run_path}') shutil.copy(_in_file, _run_path) ",phantombuild/phantombuild.py,"ReplaceText(target='_run_path' @(390,33)->(390,41))","def setup_calculation( raise SetupError(msg) else: logger.info('Successfully set up Phantom calculation') logger.info(f'run_path: {run_path}') shutil.copy(_in_file, _run_path) ","def setup_calculation( raise SetupError(msg) else: logger.info('Successfully set up Phantom calculation') logger.info(f'run_path: {_run_path}') shutil.copy(_in_file, _run_path) " 1879,https://:@github.com/shane-breeze/zinv-analysis.git,206e736a62c914f577717679adc3f16b9fa1d6b7,"@@ -36,7 +36,7 @@ class EventSumsProducer(object): event.METnoX_diMuonParaProjPt_Minus_DiMuon_pt = dimu_para - dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt = dimu_perp + dimu_pt event.METnoX_diMuonParaProjPt_Div_DiMuon_pt = dimu_para / dimu_pt - event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_para + dimu_pt) / dimu_pt + event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_perp + dimu_pt) / dimu_pt # MHT ht, mht, mhphi = create_mht( ",sequence/Readers/EventSumsProducer.py,"ReplaceText(target='dimu_perp' @(39,70)->(39,79))","class EventSumsProducer(object): event.METnoX_diMuonParaProjPt_Minus_DiMuon_pt = dimu_para - dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt = dimu_perp + dimu_pt event.METnoX_diMuonParaProjPt_Div_DiMuon_pt = dimu_para / dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_para + dimu_pt) / dimu_pt # MHT ht, mht, mhphi = create_mht(","class EventSumsProducer(object): event.METnoX_diMuonParaProjPt_Minus_DiMuon_pt = dimu_para - dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt = dimu_perp + dimu_pt event.METnoX_diMuonParaProjPt_Div_DiMuon_pt = dimu_para / dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_perp + dimu_pt) / dimu_pt # MHT ht, mht, mhphi = create_mht(" 1880,https://:@github.com/mbr/ragstoriches.git,a99ce338a03bc04bf4f6045b5e18c590177bb3ef,"@@ -78,7 +78,7 @@ def run_scraper(): scraper = obj for name, obj in getattr(mod, '_rr_export', {}).iteritems(): - scope[name] = name + scope[name] = obj scraper.scrape(url=args.url, scraper_name=args.scraper, ",ragstoriches/apps.py,"ReplaceText(target='obj' @(81,29)->(81,33))","def run_scraper(): scraper = obj for name, obj in getattr(mod, '_rr_export', {}).iteritems(): scope[name] = name scraper.scrape(url=args.url, scraper_name=args.scraper,","def run_scraper(): scraper = obj for name, obj in getattr(mod, '_rr_export', {}).iteritems(): scope[name] = obj scraper.scrape(url=args.url, scraper_name=args.scraper," 1881,https://:@github.com/NickYi1990/Kaggle_Buddy.git,e461b1afe43f676923157628cb528833cf480882,"@@ -83,7 +83,7 @@ class callbacks_keras: if epoch%self.decay_after_n_epoch==0 and epoch!=0: lr = K.get_value(self.model.optimizer.lr) K.set_value(self.model.optimizer.lr, lr*self.decay_rate) - print(""lr changed to {}"".format(lr**self.decay_rate)) + print(""lr changed to {}"".format(lr*self.decay_rate)) return K.get_value(self.model.optimizer.lr) def ka_xgb_r2_error(preds, dtrain): ",Utils/KA_utils.py,"ReplaceText(target='*' @(86,46)->(86,48))","class callbacks_keras: if epoch%self.decay_after_n_epoch==0 and epoch!=0: lr = K.get_value(self.model.optimizer.lr) K.set_value(self.model.optimizer.lr, lr*self.decay_rate) print(""lr changed to {}"".format(lr**self.decay_rate)) return K.get_value(self.model.optimizer.lr) def ka_xgb_r2_error(preds, dtrain):","class callbacks_keras: if epoch%self.decay_after_n_epoch==0 and epoch!=0: lr = K.get_value(self.model.optimizer.lr) K.set_value(self.model.optimizer.lr, lr*self.decay_rate) print(""lr changed to {}"".format(lr*self.decay_rate)) return K.get_value(self.model.optimizer.lr) def ka_xgb_r2_error(preds, dtrain):" 1882,https://:@github.com/Qingluan/QmongoHelper.git,67bf4fbd01beddd456583429cc428b4aeb1c2025,"@@ -69,7 +69,7 @@ class dbhelper(object): @_run def update(self,document,target,**kargs): - self._db[document].update(kargs,target,callback=self.callback) + self._db[document].update(target,kargs,callback=self.callback) # def to_list_callback(self,infos,error): ",__db.py,"ArgSwap(idxs=0<->1 @(72,8)->(72,33))","class dbhelper(object): @_run def update(self,document,target,**kargs): self._db[document].update(kargs,target,callback=self.callback) # def to_list_callback(self,infos,error):","class dbhelper(object): @_run def update(self,document,target,**kargs): self._db[document].update(target,kargs,callback=self.callback) # def to_list_callback(self,infos,error):" 1883,https://:@github.com/abelcarreras/aiida_extensions.git,90d585773141882b4c16bca8aa6ecdea3ca34072,"@@ -224,7 +224,7 @@ class OptimizeCalculation(JobCalculation): structure_txt = generate_LAMMPS_structure(structure) - input_txt = generate_LAMMPS_input(potential_data, + input_txt = generate_LAMMPS_input(potential_object, parameters_data, structure_file=self._INPUT_STRUCTURE, optimize_path_file=self._OUTPUT_TRAJECTORY_FILE_NAME) ",plugins/jobs/lammps/optimize.py,"ReplaceText(target='potential_object' @(227,42)->(227,56))","class OptimizeCalculation(JobCalculation): structure_txt = generate_LAMMPS_structure(structure) input_txt = generate_LAMMPS_input(potential_data, parameters_data, structure_file=self._INPUT_STRUCTURE, optimize_path_file=self._OUTPUT_TRAJECTORY_FILE_NAME)","class OptimizeCalculation(JobCalculation): structure_txt = generate_LAMMPS_structure(structure) input_txt = generate_LAMMPS_input(potential_object, parameters_data, structure_file=self._INPUT_STRUCTURE, optimize_path_file=self._OUTPUT_TRAJECTORY_FILE_NAME)" 1884,https://:@github.com/abelcarreras/aiida_extensions.git,22dc45e2580529558e5e80e1f9fbd24e2540c201,"@@ -547,7 +547,7 @@ class WorkflowQHA(Workflow): test_range[0] -= np.ceil(np.min([total_range/2, abs(test_range[0] - min_stress)]) / interval) * interval # test_range[0] -= np.ceil(abs(test_range[0] - min_stress) / interval) * interval - if max_stress < test_range[1] or min_stress > test_range[0]: + if max_stress < test_range[1] and min_stress > test_range[0]: if abs(max_stress - test_range[1]) < interval * 2 or abs(test_range[0] - min_stress) < interval * 2: interval *= 0.5 ",workflows/wf_qha.py,"ReplaceText(target='and' @(550,42)->(550,44))","class WorkflowQHA(Workflow): test_range[0] -= np.ceil(np.min([total_range/2, abs(test_range[0] - min_stress)]) / interval) * interval # test_range[0] -= np.ceil(abs(test_range[0] - min_stress) / interval) * interval if max_stress < test_range[1] or min_stress > test_range[0]: if abs(max_stress - test_range[1]) < interval * 2 or abs(test_range[0] - min_stress) < interval * 2: interval *= 0.5 ","class WorkflowQHA(Workflow): test_range[0] -= np.ceil(np.min([total_range/2, abs(test_range[0] - min_stress)]) / interval) * interval # test_range[0] -= np.ceil(abs(test_range[0] - min_stress) / interval) * interval if max_stress < test_range[1] and min_stress > test_range[0]: if abs(max_stress - test_range[1]) < interval * 2 or abs(test_range[0] - min_stress) < interval * 2: interval *= 0.5 " 1885,https://:@github.com/GeoStat-Framework/welltestpy.git,1f9ba2a6af846ae9ef0004c885d807a45a26a911,"@@ -833,7 +833,7 @@ class Well(object): ) if not self._radius.scalar: raise ValueError(""Well: 'radius' needs to be scalar"") - if self.radius <= 0.0: + if self.radius < 0.0: raise ValueError(""Well: 'radius' needs to be positiv"") if isinstance(coordinates, Variable): ",welltestpy/data/varlib.py,"ReplaceText(target='<' @(836,23)->(836,25))","class Well(object): ) if not self._radius.scalar: raise ValueError(""Well: 'radius' needs to be scalar"") if self.radius <= 0.0: raise ValueError(""Well: 'radius' needs to be positiv"") if isinstance(coordinates, Variable):","class Well(object): ) if not self._radius.scalar: raise ValueError(""Well: 'radius' needs to be scalar"") if self.radius < 0.0: raise ValueError(""Well: 'radius' needs to be positiv"") if isinstance(coordinates, Variable):" 1886,https://:@github.com/GeoStat-Framework/welltestpy.git,412f42ecf1bf2f9ae284aefd96802ee99cacdf2a,"@@ -544,7 +544,7 @@ def load_obs(obsfile): obs = load_var(TxtIO(zfile.open(obsf))) - observation = varlib.Observation(name, time, obs, description) + observation = varlib.Observation(name, obs, time, description) except Exception: raise Exception(""loadObs: loading the observation was not possible"") return observation ",welltestpy/data/data_io.py,"ArgSwap(idxs=1<->2 @(547,22)->(547,40))","def load_obs(obsfile): obs = load_var(TxtIO(zfile.open(obsf))) observation = varlib.Observation(name, time, obs, description) except Exception: raise Exception(""loadObs: loading the observation was not possible"") return observation","def load_obs(obsfile): obs = load_var(TxtIO(zfile.open(obsf))) observation = varlib.Observation(name, obs, time, description) except Exception: raise Exception(""loadObs: loading the observation was not possible"") return observation" 1887,https://:@github.com/GeoStat-Framework/welltestpy.git,412f42ecf1bf2f9ae284aefd96802ee99cacdf2a,"@@ -370,7 +370,7 @@ class PumpingTest(Test): description : :class:`str`, optional Description of the Variable. Default: ``""Drawdown observation""`` """""" - obs = varlib.DrawdownObs(well, time, observation, description) + obs = varlib.DrawdownObs(well, observation, time, description) self.add_observations(obs) def add_observations(self, obs): ",welltestpy/data/testslib.py,"ArgSwap(idxs=1<->2 @(373,14)->(373,32))","class PumpingTest(Test): description : :class:`str`, optional Description of the Variable. Default: ``""Drawdown observation""`` """""" obs = varlib.DrawdownObs(well, time, observation, description) self.add_observations(obs) def add_observations(self, obs):","class PumpingTest(Test): description : :class:`str`, optional Description of the Variable. Default: ``""Drawdown observation""`` """""" obs = varlib.DrawdownObs(well, observation, time, description) self.add_observations(obs) def add_observations(self, obs):" 1888,https://:@github.com/biosustain/venom.git,94aab380cb41a3923248adc51e3bbe312fe98cf0,"@@ -48,7 +48,7 @@ def _route_handler(venom: 'venom.rpc.Venom', method: Method, protocol_factory: T http_request_query.decode(http_request.url.query, request) http_request_path.decode(http_request.match_info, request) - response = await venom.invoke(method, request, context=AioHTTPRequestContext(request)) + response = await venom.invoke(method, request, context=AioHTTPRequestContext(http_request)) return web.Response(body=rpc_response.pack(response), content_type=rpc_response.mime, status=http_status) ",venom/rpc/comms/aiohttp.py,"ReplaceText(target='http_request' @(51,89)->(51,96))","def _route_handler(venom: 'venom.rpc.Venom', method: Method, protocol_factory: T http_request_query.decode(http_request.url.query, request) http_request_path.decode(http_request.match_info, request) response = await venom.invoke(method, request, context=AioHTTPRequestContext(request)) return web.Response(body=rpc_response.pack(response), content_type=rpc_response.mime, status=http_status)","def _route_handler(venom: 'venom.rpc.Venom', method: Method, protocol_factory: T http_request_query.decode(http_request.url.query, request) http_request_path.decode(http_request.match_info, request) response = await venom.invoke(method, request, context=AioHTTPRequestContext(http_request)) return web.Response(body=rpc_response.pack(response), content_type=rpc_response.mime, status=http_status)" 1889,https://:@github.com/altio/foundation.git,e39b13a5046467ebed3014bb2b5b4a47c5cd0e80,"@@ -117,7 +117,7 @@ class Backend(six.with_metaclass(MediaDefiningClass, Router)): # set app_index_class on app to ""None"" to skip creation app_index_class = getattr(app_config, 'app_index_class', None) if app_index_class: - template_name = getattr(app_config, 'template_name', 'app_index.html') + template_name = getattr(app_index_class, 'template_name', 'app_index.html') app_index = app_index_class.as_view( app_config=app_config, backend=self, template_name=template_name ) ",foundation/backend/base.py,"ReplaceText(target='app_index_class' @(120,36)->(120,46))","class Backend(six.with_metaclass(MediaDefiningClass, Router)): # set app_index_class on app to ""None"" to skip creation app_index_class = getattr(app_config, 'app_index_class', None) if app_index_class: template_name = getattr(app_config, 'template_name', 'app_index.html') app_index = app_index_class.as_view( app_config=app_config, backend=self, template_name=template_name )","class Backend(six.with_metaclass(MediaDefiningClass, Router)): # set app_index_class on app to ""None"" to skip creation app_index_class = getattr(app_config, 'app_index_class', None) if app_index_class: template_name = getattr(app_index_class, 'template_name', 'app_index.html') app_index = app_index_class.as_view( app_config=app_config, backend=self, template_name=template_name )" 1890,https://:@github.com/privacyidea/crontabparser.git,19e8fe34a9f9f1a2156c17d3b4b756f3aca17cdc,"@@ -30,7 +30,7 @@ class CronJob(object): assert len(time) <= 5 padded_time = tuple(time) + ('*',) * (5 - len(time)) assert len(padded_time) == 5 - return cls(command, time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4]) + return cls(command, padded_time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4]) @property def time(self): ",cronjobparser.py,"ReplaceText(target='padded_time' @(33,28)->(33,32))","class CronJob(object): assert len(time) <= 5 padded_time = tuple(time) + ('*',) * (5 - len(time)) assert len(padded_time) == 5 return cls(command, time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4]) @property def time(self):","class CronJob(object): assert len(time) <= 5 padded_time = tuple(time) + ('*',) * (5 - len(time)) assert len(padded_time) == 5 return cls(command, padded_time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4]) @property def time(self):" 1891,https://:@github.com/privacyidea/crontabparser.git,8a6a177a47b83938946ea7bf76741d96352eab08,"@@ -30,7 +30,7 @@ class CronJob(object): if len(time) > 5: raise RuntimeError(""Malformed cronjob time: {!r}"".format(time)) padded_time = tuple(time) + ('*',) * (5 - len(time)) - if len(padded_time) > 5: + if len(padded_time) != 5: raise RuntimeError(""Malformed cronjob time: {!r}"".format(padded_time)) return cls(command, padded_time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4]) ",cronjobparser.py,"ReplaceText(target='!=' @(33,28)->(33,29))","class CronJob(object): if len(time) > 5: raise RuntimeError(""Malformed cronjob time: {!r}"".format(time)) padded_time = tuple(time) + ('*',) * (5 - len(time)) if len(padded_time) > 5: raise RuntimeError(""Malformed cronjob time: {!r}"".format(padded_time)) return cls(command, padded_time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4]) ","class CronJob(object): if len(time) > 5: raise RuntimeError(""Malformed cronjob time: {!r}"".format(time)) padded_time = tuple(time) + ('*',) * (5 - len(time)) if len(padded_time) != 5: raise RuntimeError(""Malformed cronjob time: {!r}"".format(padded_time)) return cls(command, padded_time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4]) " 1892,https://:@github.com/smurn/sourblossom.git,9071c9cc86f2755254ed3d36b7a08080c64ac19f,"@@ -116,7 +116,7 @@ class MsgConnection(protocol.Protocol): def done(result): self._sending = False return result - d.addBoth(d) + d.addBoth(done) def _frame_received(self, frameid, blob): return self.frame_received(frameid, blob) ",sourblossom/router.py,"ReplaceText(target='done' @(119,18)->(119,19))","class MsgConnection(protocol.Protocol): def done(result): self._sending = False return result d.addBoth(d) def _frame_received(self, frameid, blob): return self.frame_received(frameid, blob)","class MsgConnection(protocol.Protocol): def done(result): self._sending = False return result d.addBoth(done) def _frame_received(self, frameid, blob): return self.frame_received(frameid, blob)" 1893,https://:@github.com/PMCC-BioinformaticsCore/pipelines.git,44406718107c18b4fe00e2a3abb4077dd158e298,"@@ -770,7 +770,7 @@ class Workflow(Tool): wtools[s.id()] = wf_wdl wtools.update(wf_tools) else: - wtools[s.id()] = t.wdl(with_docker=with_docker) + wtools[t.id()] = t.wdl(with_docker=with_docker) w.calls.append( s.wdl(tool_aliases[t.id().lower()].upper() + ""."" + t.id(), s.id()) ",Pipeline/workflow/workflow.py,"ReplaceText(target='t' @(773,23)->(773,24))","class Workflow(Tool): wtools[s.id()] = wf_wdl wtools.update(wf_tools) else: wtools[s.id()] = t.wdl(with_docker=with_docker) w.calls.append( s.wdl(tool_aliases[t.id().lower()].upper() + ""."" + t.id(), s.id())","class Workflow(Tool): wtools[s.id()] = wf_wdl wtools.update(wf_tools) else: wtools[t.id()] = t.wdl(with_docker=with_docker) w.calls.append( s.wdl(tool_aliases[t.id().lower()].upper() + ""."" + t.id(), s.id())" 1894,https://:@github.com/nvaytet/visens.git,320e6fed81a09d158e3728b7de54233657a24e0d,"@@ -13,7 +13,7 @@ def image(filename, colormap=""viridis"", vmin=None, vmax=None, log=False, z, edges = np.histogram(data.ids, bins=np.arange(-0.5, data.nx * data.ny + 0.5)) - z = z.reshape(data.nx, data.ny) + z = z.reshape(data.ny, data.nx) if side_panels: z_sumx = np.sum(z, axis=1) z_sumy = np.sum(z, axis=0) ",src/visens/image.py,"ArgSwap(idxs=0<->1 @(16,8)->(16,17))","def image(filename, colormap=""viridis"", vmin=None, vmax=None, log=False, z, edges = np.histogram(data.ids, bins=np.arange(-0.5, data.nx * data.ny + 0.5)) z = z.reshape(data.nx, data.ny) if side_panels: z_sumx = np.sum(z, axis=1) z_sumy = np.sum(z, axis=0)","def image(filename, colormap=""viridis"", vmin=None, vmax=None, log=False, z, edges = np.histogram(data.ids, bins=np.arange(-0.5, data.nx * data.ny + 0.5)) z = z.reshape(data.ny, data.nx) if side_panels: z_sumx = np.sum(z, axis=1) z_sumy = np.sum(z, axis=0)" 1895,https://:@github.com/nvaytet/visens.git,320e6fed81a09d158e3728b7de54233657a24e0d,"@@ -65,7 +65,7 @@ def slicer(filename, colormap=""viridis"", vmin=None, vmax=None, log=False, z, xe, ye = np.histogram2d(data.ids, data.tofs/1.0e3, bins=[np.arange(-0.5, data.nx * data.ny + 0.5), t]) - z = z.reshape(data.nx, data.ny, nbins) + z = z.reshape(data.ny, data.nx, nbins) # Transpose should be True for old December 2018 files if transpose: z = np.transpose(z, axes=[1, 0, 2]) ",src/visens/slicer.py,"ArgSwap(idxs=0<->1 @(68,8)->(68,17))","def slicer(filename, colormap=""viridis"", vmin=None, vmax=None, log=False, z, xe, ye = np.histogram2d(data.ids, data.tofs/1.0e3, bins=[np.arange(-0.5, data.nx * data.ny + 0.5), t]) z = z.reshape(data.nx, data.ny, nbins) # Transpose should be True for old December 2018 files if transpose: z = np.transpose(z, axes=[1, 0, 2])","def slicer(filename, colormap=""viridis"", vmin=None, vmax=None, log=False, z, xe, ye = np.histogram2d(data.ids, data.tofs/1.0e3, bins=[np.arange(-0.5, data.nx * data.ny + 0.5), t]) z = z.reshape(data.ny, data.nx, nbins) # Transpose should be True for old December 2018 files if transpose: z = np.transpose(z, axes=[1, 0, 2])" 1896,https://:@github.com/compmech/structmanager.git,3082bac86d0c1ad2826111bde8c2e5d5976dd7c8,"@@ -200,7 +200,7 @@ class Model(object): print('Building stringers...') for s in stringers.values(): - s.elements = [bdf.elements[eid] for eid in p.eids] + s.elements = [bdf.elements[eid] for eid in s.eids] setelements = set(s.elements) print('finished!') ",structMan/model.py,"ReplaceText(target='s' @(203,55)->(203,56))","class Model(object): print('Building stringers...') for s in stringers.values(): s.elements = [bdf.elements[eid] for eid in p.eids] setelements = set(s.elements) print('finished!') ","class Model(object): print('Building stringers...') for s in stringers.values(): s.elements = [bdf.elements[eid] for eid in s.eids] setelements = set(s.elements) print('finished!') " 1897,https://:@github.com/al-fontes-jr/bardolph.git,c4429c7a1453ff8088bffa4066b8fe9ff7d4c164,"@@ -61,7 +61,7 @@ def as_raw(reg, logical_value, use_float=False): else: value = (logical_value % 360.0) / 360.0 * 65535.0 elif reg in (Register.BRIGHTNESS, Register.SATURATION): - if logical_value == 100.0: + if logical_value >= 100.0: value = 65535.0 else: value = logical_value / 100.0 * 65535.0 ",bardolph/controller/units.py,"ReplaceText(target='>=' @(64,25)->(64,27))","def as_raw(reg, logical_value, use_float=False): else: value = (logical_value % 360.0) / 360.0 * 65535.0 elif reg in (Register.BRIGHTNESS, Register.SATURATION): if logical_value == 100.0: value = 65535.0 else: value = logical_value / 100.0 * 65535.0","def as_raw(reg, logical_value, use_float=False): else: value = (logical_value % 360.0) / 360.0 * 65535.0 elif reg in (Register.BRIGHTNESS, Register.SATURATION): if logical_value >= 100.0: value = 65535.0 else: value = logical_value / 100.0 * 65535.0" 1898,https://:@github.com/bluecoveltd/contracts.git,f5b74e088920520642500d4da990580c841cbb22,"@@ -25,7 +25,7 @@ class SeparateContext(Contract): return SeparateContext(tokens[0]['child'], where=where) -sepcon = (Group(Literal('$') - Literal('(') - +sepcon = (Group(Literal('$') + Literal('(') - contract_expression('child') - Literal(')'))) sepcon.setParseAction(SeparateContext.parse_action) sepcon.setName('Context separation construct') ",src/contracts/library/separate_context.py,"ReplaceText(target='+' @(28,29)->(28,30))","class SeparateContext(Contract): return SeparateContext(tokens[0]['child'], where=where) sepcon = (Group(Literal('$') - Literal('(') - contract_expression('child') - Literal(')'))) sepcon.setParseAction(SeparateContext.parse_action) sepcon.setName('Context separation construct')","class SeparateContext(Contract): return SeparateContext(tokens[0]['child'], where=where) sepcon = (Group(Literal('$') + Literal('(') - contract_expression('child') - Literal(')'))) sepcon.setParseAction(SeparateContext.parse_action) sepcon.setName('Context separation construct')" 1899,https://:@github.com/TimHessels/WaporTranslator.git,58f1b770f5b60b2468677294c51c52460305b12f,"@@ -111,7 +111,7 @@ class Rasterdata_tiffs: time_or = '' # Apply gapfilling if needed - if gap_filling != None and ~np.isnan(np.nanmean(Array)): + if gap_filling != None and ~np.isnan(np.nanmean(Array_end)): Array_end[np.isnan(Array_end)] = -9999 Array_end = RC.gap_filling(Array_end, -9999, gap_filling) Array_end = Array_end * MASK ",LEVEL_1/DataCube.py,"ReplaceText(target='Array_end' @(114,60)->(114,65))","class Rasterdata_tiffs: time_or = '' # Apply gapfilling if needed if gap_filling != None and ~np.isnan(np.nanmean(Array)): Array_end[np.isnan(Array_end)] = -9999 Array_end = RC.gap_filling(Array_end, -9999, gap_filling) Array_end = Array_end * MASK","class Rasterdata_tiffs: time_or = '' # Apply gapfilling if needed if gap_filling != None and ~np.isnan(np.nanmean(Array_end)): Array_end[np.isnan(Array_end)] = -9999 Array_end = RC.gap_filling(Array_end, -9999, gap_filling) Array_end = Array_end * MASK" 1900,https://:@github.com/TimHessels/WaporTranslator.git,fab158818a8bcc5a90b04347469916bdb2cd8fa9,"@@ -311,7 +311,7 @@ def main(Start_year_analyses, End_year_analyses, output_folder): if not np.isnan(np.nanmean(Crop_S1_End.Data)): for Date_Year in Dates_Years: year_diff = int(Date_Year.year - Dates_Years[0].year) - for dekad in range(0,int(np.nanmax(Crop_S2_End.Data))): + for dekad in range(0,int(np.nanmax(Crop_S3_End.Data))): Accumulated_NPP_Data_Start_S1[year_diff, Crop_S1_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S1_End.Data[year_diff, :, :] == dekad] Accumulated_NPP_Data_Start_S2[year_diff, Crop_S2_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S2_End.Data[year_diff, :, :] == dekad] Accumulated_NPP_Data_Start_S3[year_diff, Crop_S3_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S3_End.Data[year_diff, :, :] == dekad] ",LEVEL_3/Food_Security/LEVEL_3_Calc_Food_Security.py,"ReplaceText(target='Crop_S3_End' @(314,47)->(314,58))","def main(Start_year_analyses, End_year_analyses, output_folder): if not np.isnan(np.nanmean(Crop_S1_End.Data)): for Date_Year in Dates_Years: year_diff = int(Date_Year.year - Dates_Years[0].year) for dekad in range(0,int(np.nanmax(Crop_S2_End.Data))): Accumulated_NPP_Data_Start_S1[year_diff, Crop_S1_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S1_End.Data[year_diff, :, :] == dekad] Accumulated_NPP_Data_Start_S2[year_diff, Crop_S2_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S2_End.Data[year_diff, :, :] == dekad] Accumulated_NPP_Data_Start_S3[year_diff, Crop_S3_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S3_End.Data[year_diff, :, :] == dekad] ","def main(Start_year_analyses, End_year_analyses, output_folder): if not np.isnan(np.nanmean(Crop_S1_End.Data)): for Date_Year in Dates_Years: year_diff = int(Date_Year.year - Dates_Years[0].year) for dekad in range(0,int(np.nanmax(Crop_S3_End.Data))): Accumulated_NPP_Data_Start_S1[year_diff, Crop_S1_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S1_End.Data[year_diff, :, :] == dekad] Accumulated_NPP_Data_Start_S2[year_diff, Crop_S2_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S2_End.Data[year_diff, :, :] == dekad] Accumulated_NPP_Data_Start_S3[year_diff, Crop_S3_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S3_End.Data[year_diff, :, :] == dekad] " 1901,https://:@github.com/padraic-padraic/StabilizerSearch.git,9a7b666656f60cbeb5a271e8e6c4ceb168f754fd,"@@ -121,7 +121,7 @@ def get_positive_stabilizer_groups(n_qubits, n_states): continue subspaces.append(res) generators.append(tuple(candidate.generators)) - if len(generators) == n_states: + if len(generators) == target: break return generators ",stabilizer_search/stabilizers/py_generators.py,"ReplaceText(target='target' @(124,30)->(124,38))","def get_positive_stabilizer_groups(n_qubits, n_states): continue subspaces.append(res) generators.append(tuple(candidate.generators)) if len(generators) == n_states: break return generators ","def get_positive_stabilizer_groups(n_qubits, n_states): continue subspaces.append(res) generators.append(tuple(candidate.generators)) if len(generators) == target: break return generators " 1902,https://:@github.com/jwg4/volly.git,fabca57aac55f7350f24c006d2035360e94d29fc,"@@ -16,4 +16,4 @@ class TestService(TestCase): def test_write_missing_value(self): svc = Service(""https://volatile.wtf"") - self.assertRaises(lambda: svc[""UNGYIZFHIA""], MissingKeyException) + self.assertRaises(MissingKeyException, lambda: svc[""UNGYIZFHIA""]) ",tests/__init__.py,"ArgSwap(idxs=0<->1 @(19,8)->(19,25))","class TestService(TestCase): def test_write_missing_value(self): svc = Service(""https://volatile.wtf"") self.assertRaises(lambda: svc[""UNGYIZFHIA""], MissingKeyException)","class TestService(TestCase): def test_write_missing_value(self): svc = Service(""https://volatile.wtf"") self.assertRaises(MissingKeyException, lambda: svc[""UNGYIZFHIA""])" 1903,https://:@github.com/ismaelpessa/Muse_Cube.git,e01ea96ba7095c502c18faf927f43b8528eb76a2,"@@ -934,7 +934,7 @@ class MuseCube: print('Fit Aceptado') print(str(x[i]) + ',' + str(y[i])) units = u.km / u.s - vel = ltu.dv_from_z((mean / wv_line_vac) - 1, z_line).to(units).value + vel = ltu.dv_from_z((mean / wv_line_vac) - 1, z).to(units).value kine_im[y[i]][x[i]] = vel else: if debug: ",PyMUSE/musecube.py,"ReplaceText(target='z' @(937,62)->(937,68))","class MuseCube: print('Fit Aceptado') print(str(x[i]) + ',' + str(y[i])) units = u.km / u.s vel = ltu.dv_from_z((mean / wv_line_vac) - 1, z_line).to(units).value kine_im[y[i]][x[i]] = vel else: if debug:","class MuseCube: print('Fit Aceptado') print(str(x[i]) + ',' + str(y[i])) units = u.km / u.s vel = ltu.dv_from_z((mean / wv_line_vac) - 1, z).to(units).value kine_im[y[i]][x[i]] = vel else: if debug:" 1904,https://:@github.com/chie8842/mldatautils.git,ccc35e5d07c30e7ec685bfe305ad5e2623015147,"@@ -20,7 +20,7 @@ def _config_parse(config_file): 'port': os.getenv('DB_PORT'), 'database': os.getenv('DATABASE'), } - return config_file + return dwh_config def create_engine(config_file=None): dwh_config = _config_parse(config_file) ",mldatautils/db_utils.py,"ReplaceText(target='dwh_config' @(23,11)->(23,22))","def _config_parse(config_file): 'port': os.getenv('DB_PORT'), 'database': os.getenv('DATABASE'), } return config_file def create_engine(config_file=None): dwh_config = _config_parse(config_file)","def _config_parse(config_file): 'port': os.getenv('DB_PORT'), 'database': os.getenv('DATABASE'), } return dwh_config def create_engine(config_file=None): dwh_config = _config_parse(config_file)" 1905,https://:@github.com/andrewbihl/bted.git,d04bda7b1d287b1b1f06983c306455f5fee0f152,"@@ -24,7 +24,7 @@ class TestAppend(unittest.TestCase): expected = fin.read() cmd, flags = self.interpreter.build_command(command, input_file) res = self.interpreter.execute_command(cmd, flags, return_output=True) - self.assertEqual(res, expected) + self.assertEqual(expected, res) def perform_test_from_key(self, key: str): tests = self.tests[key] ",bted/tests/test_append.py,"ArgSwap(idxs=0<->1 @(27,8)->(27,24))","class TestAppend(unittest.TestCase): expected = fin.read() cmd, flags = self.interpreter.build_command(command, input_file) res = self.interpreter.execute_command(cmd, flags, return_output=True) self.assertEqual(res, expected) def perform_test_from_key(self, key: str): tests = self.tests[key]","class TestAppend(unittest.TestCase): expected = fin.read() cmd, flags = self.interpreter.build_command(command, input_file) res = self.interpreter.execute_command(cmd, flags, return_output=True) self.assertEqual(expected, res) def perform_test_from_key(self, key: str): tests = self.tests[key]" 1906,https://:@github.com/muammar/mlchem.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) " 1907,https://:@github.com/ibrokemypie/m3uspiff.git,e44882b66620c92ba437313d4b305c835506a5d5,"@@ -39,7 +39,7 @@ def mdata(path, track_element): for tag in tags: tagstring = tag+"":"" if tagstring in linecheck: - stringf = out.split(': ')[1] + stringf = decoded.split(': ')[1] ttag = tag if tag == ""artist"": ttag = ""creator"" ",m3uspiff.py,"ReplaceText(target='decoded' @(42,30)->(42,33))","def mdata(path, track_element): for tag in tags: tagstring = tag+"":"" if tagstring in linecheck: stringf = out.split(': ')[1] ttag = tag if tag == ""artist"": ttag = ""creator""","def mdata(path, track_element): for tag in tags: tagstring = tag+"":"" if tagstring in linecheck: stringf = decoded.split(': ')[1] ttag = tag if tag == ""artist"": ttag = ""creator""" 1908,https://:@github.com/ibrokemypie/m3uspiff.git,aca86931f7453d9c90c2ef779ede1659d10af00d,"@@ -45,7 +45,7 @@ def mdata(path, track_element): ttag = ""creator"" if tag == ""genre"": ttag = ""info"" - ttag = SubElement(track_element, tag) + ttag = SubElement(track_element, ttag) ttag.text = stringf.rstrip() else: break ",m3uspiff.py,"ReplaceText(target='ttag' @(48,53)->(48,56))","def mdata(path, track_element): ttag = ""creator"" if tag == ""genre"": ttag = ""info"" ttag = SubElement(track_element, tag) ttag.text = stringf.rstrip() else: break","def mdata(path, track_element): ttag = ""creator"" if tag == ""genre"": ttag = ""info"" ttag = SubElement(track_element, ttag) ttag.text = stringf.rstrip() else: break" 1909,https://:@github.com/LanguageMachines/CLIN28_ST_spelling_correction.git,b95343c354ae7ee1934b9bba9a9ded0a89bd3048,"@@ -8,7 +8,7 @@ class ValidationError(Exception): class CLIN28JSON: def __init__(self, filename): - if os.path.exists(filename): + if not os.path.exists(filename): raise FileExistsError(""File not found: "" + filename) with open(filename,'r', encoding='utf-8') as f: ",clin28tools/format.py,"ReplaceText(target='not ' @(11,11)->(11,11))","class ValidationError(Exception): class CLIN28JSON: def __init__(self, filename): if os.path.exists(filename): raise FileExistsError(""File not found: "" + filename) with open(filename,'r', encoding='utf-8') as f:","class ValidationError(Exception): class CLIN28JSON: def __init__(self, filename): if not os.path.exists(filename): raise FileExistsError(""File not found: "" + filename) with open(filename,'r', encoding='utf-8') as f:" 1910,https://:@github.com/LanguageMachines/CLIN28_ST_spelling_correction.git,f6d60c45406614fc6fbf930d3a44cc5e7b1453fb,"@@ -57,7 +57,7 @@ class CLIN28JSON: correction['confidence'] = float(correction['confidence']) except: raise ValidationError(""Invalid confidence value ("" + str(correction['confidence']) + "") "" + repr(correction)) - if correction['confidence'] < 0 or correction['confidence'] > 0: + if correction['confidence'] < 0 or correction['confidence'] > 1: raise ValidationError(""Confidence value out of bounds ("" + str(correction['confidence']) + "") "" + repr(correction)) def words(self): ",clin28tools/format.py,"ReplaceText(target='1' @(60,82)->(60,83))","class CLIN28JSON: correction['confidence'] = float(correction['confidence']) except: raise ValidationError(""Invalid confidence value ("" + str(correction['confidence']) + "") "" + repr(correction)) if correction['confidence'] < 0 or correction['confidence'] > 0: raise ValidationError(""Confidence value out of bounds ("" + str(correction['confidence']) + "") "" + repr(correction)) def words(self):","class CLIN28JSON: correction['confidence'] = float(correction['confidence']) except: raise ValidationError(""Invalid confidence value ("" + str(correction['confidence']) + "") "" + repr(correction)) if correction['confidence'] < 0 or correction['confidence'] > 1: raise ValidationError(""Confidence value out of bounds ("" + str(correction['confidence']) + "") "" + repr(correction)) def words(self):" 1911,https://:@github.com/drmartiner/django-smsaero.git,067445a9613fcdb635f49750ac2d49b3eac5a38a,"@@ -24,7 +24,7 @@ class SmsSenderTest(TestCase): @patch('urllib2.urlopen', _fake_urlopen) def test_send_request(self): sender = SmsSender() - response = sender.send_request('/link/', {}) + response = sender.send_request({}, '/link/') self.assertIn(SMSMessage.STATUS_ACCEPTED, response) @patch('smsaero.conf.SMSAERO_PASSWORD', 'FAKE') ",smsaero/tests.py,"ArgSwap(idxs=0<->1 @(27,19)->(27,38))","class SmsSenderTest(TestCase): @patch('urllib2.urlopen', _fake_urlopen) def test_send_request(self): sender = SmsSender() response = sender.send_request('/link/', {}) self.assertIn(SMSMessage.STATUS_ACCEPTED, response) @patch('smsaero.conf.SMSAERO_PASSWORD', 'FAKE')","class SmsSenderTest(TestCase): @patch('urllib2.urlopen', _fake_urlopen) def test_send_request(self): sender = SmsSender() response = sender.send_request({}, '/link/') self.assertIn(SMSMessage.STATUS_ACCEPTED, response) @patch('smsaero.conf.SMSAERO_PASSWORD', 'FAKE')" 1912,https://:@github.com/drmartiner/django-smsaero.git,916bcb1b7a9b1546a0944752f909e5a752cb99a6,"@@ -68,7 +68,7 @@ def send_sms(to, text, signature_id=None, date=None, link='/send/'): 'from': signature.name, 'date': date or '', } - response = sender.send_request(link, params) + response = sender.send_request(params, link) sms_id, status = sender.parse_response(response) if not sms_id or not status: ",smsaero/utils.py,"ArgSwap(idxs=0<->1 @(71,15)->(71,34))","def send_sms(to, text, signature_id=None, date=None, link='/send/'): 'from': signature.name, 'date': date or '', } response = sender.send_request(link, params) sms_id, status = sender.parse_response(response) if not sms_id or not status:","def send_sms(to, text, signature_id=None, date=None, link='/send/'): 'from': signature.name, 'date': date or '', } response = sender.send_request(params, link) sms_id, status = sender.parse_response(response) if not sms_id or not status:" 1913,https://:@github.com/jakirkham/kenjutsu.git,c532fe8f06fd9facc284639e0a87f88e44de852a,"@@ -103,7 +103,7 @@ def reformat_slice(a_slice, a_length=None): start = a_length - 1 if stop_i and stop < -a_length: stop = None - stop_i = True + stop_i = False # Catch some known empty slices. if (step > 0) and (stop == 0): ",kenjutsu/kenjutsu.py,"ReplaceText(target='False' @(106,29)->(106,33))","def reformat_slice(a_slice, a_length=None): start = a_length - 1 if stop_i and stop < -a_length: stop = None stop_i = True # Catch some known empty slices. if (step > 0) and (stop == 0):","def reformat_slice(a_slice, a_length=None): start = a_length - 1 if stop_i and stop < -a_length: stop = None stop_i = False # Catch some known empty slices. if (step > 0) and (stop == 0):" 1914,https://:@github.com/jakirkham/kenjutsu.git,a3b1486a8711d57b93f43a35bb7dea2ab70a83ff,"@@ -55,7 +55,7 @@ def reformat_slice(a_slice, a_length=None): new_slice = a_slice if new_slice is Ellipsis: new_slice = slice(None) - elif not isinstance(new_slice, slice): + elif not isinstance(a_slice, slice): raise ValueError( ""Expected a `slice` type. Instead got `%s`."" % str(new_slice) ) ",kenjutsu/kenjutsu.py,"ReplaceText(target='a_slice' @(58,24)->(58,33))","def reformat_slice(a_slice, a_length=None): new_slice = a_slice if new_slice is Ellipsis: new_slice = slice(None) elif not isinstance(new_slice, slice): raise ValueError( ""Expected a `slice` type. Instead got `%s`."" % str(new_slice) )","def reformat_slice(a_slice, a_length=None): new_slice = a_slice if new_slice is Ellipsis: new_slice = slice(None) elif not isinstance(a_slice, slice): raise ValueError( ""Expected a `slice` type. Instead got `%s`."" % str(new_slice) )" 1915,https://:@github.com/jakirkham/kenjutsu.git,dbedbd6ff58c9aadf79edc7cc840d6ec15552674,"@@ -57,7 +57,7 @@ def reformat_slice(a_slice, a_length=None): new_slice = slice(None) elif not isinstance(a_slice, slice): raise ValueError( - ""Expected a `slice` type. Instead got `%s`."" % str(new_slice) + ""Expected a `slice` type. Instead got `%s`."" % str(a_slice) ) if new_slice.step == 0: ",kenjutsu/kenjutsu.py,"ReplaceText(target='a_slice' @(60,63)->(60,72))","def reformat_slice(a_slice, a_length=None): new_slice = slice(None) elif not isinstance(a_slice, slice): raise ValueError( ""Expected a `slice` type. Instead got `%s`."" % str(new_slice) ) if new_slice.step == 0:","def reformat_slice(a_slice, a_length=None): new_slice = slice(None) elif not isinstance(a_slice, slice): raise ValueError( ""Expected a `slice` type. Instead got `%s`."" % str(a_slice) ) if new_slice.step == 0:" 1916,https://:@github.com/bh/python-keepass-httpd.git,548473a3d4044f89e3a30639fa2aafb71bb321b6,"@@ -86,7 +86,7 @@ def main(): if success is False: sys.exit(""Wrong passphrase after %d attempts"" % max_try_count) - server.set_backend(backend) + kpconf.set_backend(backend) # config daemon if is_daemon: ",src/keepass_http/scripts/python_keepass_httpd.py,"ReplaceText(target='kpconf' @(89,4)->(89,10))","def main(): if success is False: sys.exit(""Wrong passphrase after %d attempts"" % max_try_count) server.set_backend(backend) # config daemon if is_daemon:","def main(): if success is False: sys.exit(""Wrong passphrase after %d attempts"" % max_try_count) kpconf.set_backend(backend) # config daemon if is_daemon:" 1917,https://:@github.com/frkhit/pyxtools.git,678039c852edb8b94a45aa39393043019a52bdc7,"@@ -20,7 +20,7 @@ class IndexType(Enum): def to_train(self) -> bool: if self.name == ""compress"": return True - return True + return False @property def index_factory(self) -> str: ",pyxtools/faiss_tools/faiss_utils.py,"ReplaceText(target='False' @(23,15)->(23,19))","class IndexType(Enum): def to_train(self) -> bool: if self.name == ""compress"": return True return True @property def index_factory(self) -> str:","class IndexType(Enum): def to_train(self) -> bool: if self.name == ""compress"": return True return False @property def index_factory(self) -> str:" 1918,https://:@github.com/combatopera/Concern.git,32c056654b62e455261ac6381c7207c6c1e4be39,"@@ -69,7 +69,7 @@ def main_Concern(): (-Concern).printf('vimArgs := $list()') for arg in vimargs: (-Concern).printf(""vimArgs += %s"", arg) - import_module(f"".consumer.{Concern.consumerName}"", package = __package__).configure(config) + import_module(f"".consumer.{Concern.consumerName}"", package = __package__).configure(Concern) (-Concern).processtemplate(resource_filename(templates.__name__, 'vimrc.aridt'), concernvimrc) (-Concern).printf('"" = $(pystr)') (-Concern).processtemplate(resource_filename(templates.__name__, 'sendblock.py.aridt'), sendblock) ",concern/concern.py,"ReplaceText(target='Concern' @(72,92)->(72,98))","def main_Concern(): (-Concern).printf('vimArgs := $list()') for arg in vimargs: (-Concern).printf(""vimArgs += %s"", arg) import_module(f"".consumer.{Concern.consumerName}"", package = __package__).configure(config) (-Concern).processtemplate(resource_filename(templates.__name__, 'vimrc.aridt'), concernvimrc) (-Concern).printf('"" = $(pystr)') (-Concern).processtemplate(resource_filename(templates.__name__, 'sendblock.py.aridt'), sendblock)","def main_Concern(): (-Concern).printf('vimArgs := $list()') for arg in vimargs: (-Concern).printf(""vimArgs += %s"", arg) import_module(f"".consumer.{Concern.consumerName}"", package = __package__).configure(Concern) (-Concern).processtemplate(resource_filename(templates.__name__, 'vimrc.aridt'), concernvimrc) (-Concern).printf('"" = $(pystr)') (-Concern).processtemplate(resource_filename(templates.__name__, 'sendblock.py.aridt'), sendblock)" 1919,https://:@github.com/brianhie/ample.git,8fc0e7a08beb33770dcad583debf60b1bd06cc51,"@@ -66,7 +66,7 @@ def kmeanspp(X, n_clusters, seed=None, replace=False, centers[c] = X[best_candidate].toarray() else: centers[c] = X[best_candidate] - centers_idx.append(c) + centers_idx.append(best_candidate) current_pot = best_pot closest_dist_sq = best_dist_sq ",geosketch/kmeanspp.py,"ReplaceText(target='best_candidate' @(69,27)->(69,28))","def kmeanspp(X, n_clusters, seed=None, replace=False, centers[c] = X[best_candidate].toarray() else: centers[c] = X[best_candidate] centers_idx.append(c) current_pot = best_pot closest_dist_sq = best_dist_sq ","def kmeanspp(X, n_clusters, seed=None, replace=False, centers[c] = X[best_candidate].toarray() else: centers[c] = X[best_candidate] centers_idx.append(best_candidate) current_pot = best_pot closest_dist_sq = best_dist_sq " 1920,https://:@github.com/AWehrhahn/PyReduce.git,3971160a9dc6f308d452b99fadc27da10a8eb36a,"@@ -35,7 +35,7 @@ def UVES_HD132205(local_dir=""./""): with tarfile.open(filename) as file: file.extractall(path=target_dir) - return local_dir + return target_dir if __name__ == ""__main__"": ",pyreduce/datasets.py,"ReplaceText(target='target_dir' @(38,11)->(38,20))","def UVES_HD132205(local_dir=""./""): with tarfile.open(filename) as file: file.extractall(path=target_dir) return local_dir if __name__ == ""__main__"":","def UVES_HD132205(local_dir=""./""): with tarfile.open(filename) as file: file.extractall(path=target_dir) return target_dir if __name__ == ""__main__"":" 1921,https://:@github.com/4degrees/segue.git,06d1a4945dcf6c99630412967d6c20ba400f8bb7,"@@ -120,7 +120,7 @@ class SelectorWidget(QtGui.QFrame): ''' matches = self.list_widget.findItems( item, - QtCore.Qt.MatchFixedString | QtCore.Qt.CaseSensitive + QtCore.Qt.MatchFixedString & QtCore.Qt.CaseSensitive ) if matches: ",source/segue/frontend/selector.py,"ReplaceText(target='&' @(123,39)->(123,40))","class SelectorWidget(QtGui.QFrame): ''' matches = self.list_widget.findItems( item, QtCore.Qt.MatchFixedString | QtCore.Qt.CaseSensitive ) if matches:","class SelectorWidget(QtGui.QFrame): ''' matches = self.list_widget.findItems( item, QtCore.Qt.MatchFixedString & QtCore.Qt.CaseSensitive ) if matches:" 1922,https://:@github.com/gmrukwa/divik.git,7a46f680e9c5832ef3b81ab6a73bc6a1f25efa21,"@@ -143,6 +143,6 @@ class SpearmanDistance(DistanceMetric): if first is not self._last: self._last = first self._last_ranks = np.apply_along_axis(st.rankdata, 0, first) - second_ranks = np.apply_along_axis(st.rankdata, 0, first) + second_ranks = np.apply_along_axis(st.rankdata, 0, second) return dist.cdist(self._last_ranks, second_ranks, metric='correlation') ",spdivik/distance.py,"ReplaceText(target='second' @(146,59)->(146,64))","class SpearmanDistance(DistanceMetric): if first is not self._last: self._last = first self._last_ranks = np.apply_along_axis(st.rankdata, 0, first) second_ranks = np.apply_along_axis(st.rankdata, 0, first) return dist.cdist(self._last_ranks, second_ranks, metric='correlation') ","class SpearmanDistance(DistanceMetric): if first is not self._last: self._last = first self._last_ranks = np.apply_along_axis(st.rankdata, 0, first) second_ranks = np.apply_along_axis(st.rankdata, 0, second) return dist.cdist(self._last_ranks, second_ranks, metric='correlation') " 1923,https://:@github.com/takahi-i/hideout.git,49d6acc882c0d666ed214c5c33360b4e8ac2ea3b,"@@ -15,7 +15,7 @@ def resume(file_name): with open(file_path, mode='rb') as f: target = pickle.load(f) yield target - if target is None: + if target is not None: freeze(target, file_name) ",hideout/__init__.py,"ReplaceText(target=' is not ' @(18,13)->(18,17))","def resume(file_name): with open(file_path, mode='rb') as f: target = pickle.load(f) yield target if target is None: freeze(target, file_name) ","def resume(file_name): with open(file_path, mode='rb') as f: target = pickle.load(f) yield target if target is not None: freeze(target, file_name) " 1924,https://:@github.com/LordFlashmeow/pycent.git,a51cc6b53b9da5b5ee26026d51648eabbc9c0c61,"@@ -3,7 +3,7 @@ class pycent: pass def percent_of(self, percent, whole): - return (percent * whole) * 100 + return (percent * whole) / 100 def percentage(self, part, whole): return 100 * float(part)/float(whole) ",pycent.py,"ReplaceText(target='/' @(6,33)->(6,34))","class pycent: pass def percent_of(self, percent, whole): return (percent * whole) * 100 def percentage(self, part, whole): return 100 * float(part)/float(whole)","class pycent: pass def percent_of(self, percent, whole): return (percent * whole) / 100 def percentage(self, part, whole): return 100 * float(part)/float(whole)" 1925,https://:@github.com/jdrubin91/GeneLab-Microarray.git,06df0ad32f1d93ead0b76557cf1137b570eb82d2,"@@ -52,7 +52,7 @@ def run(): if batch: import batch_process - batch_process.run(batch) + batch_process.run(indir) else: metadata_dir = os.path.join(indir,'metadata') if os.path.isdir(metadata_dir): ",GeneLab-Microarray/__main__.py,"ReplaceText(target='indir' @(55,26)->(55,31))","def run(): if batch: import batch_process batch_process.run(batch) else: metadata_dir = os.path.join(indir,'metadata') if os.path.isdir(metadata_dir):","def run(): if batch: import batch_process batch_process.run(indir) else: metadata_dir = os.path.join(indir,'metadata') if os.path.isdir(metadata_dir):" 1926,https://:@github.com/kszucs/sequely.git,61dec39fd7d7ff2beb2dd051e761c2004f6dcbed,"@@ -680,7 +680,7 @@ class IsNullOperator(UnaryPostfixOperator): """""" def __init__(self, operand, invert=False): - super(IsNullOperator, self).__init__(u' IS NOT NULL' if invert else u' IS NULL', operand) + super(IsNullOperator, self).__init__(operand, u' IS NOT NULL' if invert else u' IS NULL') self.invert = invert def NOT(self): ",sqlbuilder/sql.py,"ArgSwap(idxs=0<->1 @(683,8)->(683,44))","class IsNullOperator(UnaryPostfixOperator): """""" def __init__(self, operand, invert=False): super(IsNullOperator, self).__init__(u' IS NOT NULL' if invert else u' IS NULL', operand) self.invert = invert def NOT(self):","class IsNullOperator(UnaryPostfixOperator): """""" def __init__(self, operand, invert=False): super(IsNullOperator, self).__init__(operand, u' IS NOT NULL' if invert else u' IS NULL') self.invert = invert def NOT(self):" 1927,https://:@github.com/muteria/muteria.git,6609a8e8e8acd2c0b5bcfbca516de7c746f02d14,"@@ -102,7 +102,7 @@ class MetaCriteriaTool(object): self.tools_config_by_criterion_dict = tools_config_by_criterion_dict # Verify Direct Arguments Variables - ERROR_HANDLER.assert_true(self.criteria_working_dir is None, \ + ERROR_HANDLER.assert_true(self.criteria_working_dir is not None, \ ""Must specify criteria_working_dir"", __file__) for criterion in self.tools_config_by_criterion_dict: ERROR_HANDLER.assert_true( \ ",muteria/drivers/criteria/meta_testcriteriatool.py,"ReplaceText(target=' is not ' @(105,59)->(105,63))","class MetaCriteriaTool(object): self.tools_config_by_criterion_dict = tools_config_by_criterion_dict # Verify Direct Arguments Variables ERROR_HANDLER.assert_true(self.criteria_working_dir is None, \ ""Must specify criteria_working_dir"", __file__) for criterion in self.tools_config_by_criterion_dict: ERROR_HANDLER.assert_true( \","class MetaCriteriaTool(object): self.tools_config_by_criterion_dict = tools_config_by_criterion_dict # Verify Direct Arguments Variables ERROR_HANDLER.assert_true(self.criteria_working_dir is not None, \ ""Must specify criteria_working_dir"", __file__) for criterion in self.tools_config_by_criterion_dict: ERROR_HANDLER.assert_true( \" 1928,https://:@github.com/muteria/muteria.git,6609a8e8e8acd2c0b5bcfbca516de7c746f02d14,"@@ -127,7 +127,7 @@ class MetaTestcaseTool(object): self.test_tool_config_list = test_tool_config_list # Verify Direct Arguments Variables - ERROR_HANDLER.assert_true(self.tests_working_dir is None, \ + ERROR_HANDLER.assert_true(self.tests_working_dir is not None, \ ""Must specify tests_working_dir"", __file__) ERROR_HANDLER.assert_true(len(self.test_tool_config_list) != \ len(set([c.get_tool_config_alias() for c in \ ",muteria/drivers/testgeneration/meta_testcasetool.py,"ReplaceText(target=' is not ' @(130,56)->(130,60))","class MetaTestcaseTool(object): self.test_tool_config_list = test_tool_config_list # Verify Direct Arguments Variables ERROR_HANDLER.assert_true(self.tests_working_dir is None, \ ""Must specify tests_working_dir"", __file__) ERROR_HANDLER.assert_true(len(self.test_tool_config_list) != \ len(set([c.get_tool_config_alias() for c in \","class MetaTestcaseTool(object): self.test_tool_config_list = test_tool_config_list # Verify Direct Arguments Variables ERROR_HANDLER.assert_true(self.tests_working_dir is not None, \ ""Must specify tests_working_dir"", __file__) ERROR_HANDLER.assert_true(len(self.test_tool_config_list) != \ len(set([c.get_tool_config_alias() for c in \" 1929,https://:@github.com/muteria/muteria.git,43adff6c76b0fbeeacc6a87b54c29ac82b4d38e8,"@@ -56,7 +56,7 @@ class IdentityCodeConverter(BaseCodeFormatConverter): for src, dest in list(file_src_dest_map.items()): abs_src = os.path.join(self.repository_rootdir, src) if os.path.abspath(abs_src) != os.path.abspath(dest): - shutil.copy2(src, dest) + shutil.copy2(abs_src, dest) return DefaultCallbackObject.after_command(self) #~ def after_command() #~ class CopyCallbackObject ",muteria/repositoryandcode/codes_convert_support.py,"ReplaceText(target='abs_src' @(59,33)->(59,36))","class IdentityCodeConverter(BaseCodeFormatConverter): for src, dest in list(file_src_dest_map.items()): abs_src = os.path.join(self.repository_rootdir, src) if os.path.abspath(abs_src) != os.path.abspath(dest): shutil.copy2(src, dest) return DefaultCallbackObject.after_command(self) #~ def after_command() #~ class CopyCallbackObject","class IdentityCodeConverter(BaseCodeFormatConverter): for src, dest in list(file_src_dest_map.items()): abs_src = os.path.join(self.repository_rootdir, src) if os.path.abspath(abs_src) != os.path.abspath(dest): shutil.copy2(abs_src, dest) return DefaultCallbackObject.after_command(self) #~ def after_command() #~ class CopyCallbackObject" 1930,https://:@github.com/muteria/muteria.git,69571204b176aade524ca8d4259db5cf14550599,"@@ -489,7 +489,7 @@ class TestcasesToolKlee(BaseTestcaseTool): KTestTestFormat.get_dir(dp, folders)) \ for dp in dup_tuple[1:]] for df in dup_tuple[1:]: - if KTestTestFormat.get_dir(kt, folders) == \ + if KTestTestFormat.get_dir(df, folders) == \ self.tests_storage_dir: os.remove(df) common_fs.dumpJSON(kepttest2duptest_map, self.keptktest2dupktests) ",muteria/drivers/testgeneration/tools_by_languages/c/klee/klee.py,"ReplaceText(target='df' @(492,43)->(492,45))","class TestcasesToolKlee(BaseTestcaseTool): KTestTestFormat.get_dir(dp, folders)) \ for dp in dup_tuple[1:]] for df in dup_tuple[1:]: if KTestTestFormat.get_dir(kt, folders) == \ self.tests_storage_dir: os.remove(df) common_fs.dumpJSON(kepttest2duptest_map, self.keptktest2dupktests)","class TestcasesToolKlee(BaseTestcaseTool): KTestTestFormat.get_dir(dp, folders)) \ for dp in dup_tuple[1:]] for df in dup_tuple[1:]: if KTestTestFormat.get_dir(df, folders) == \ self.tests_storage_dir: os.remove(df) common_fs.dumpJSON(kepttest2duptest_map, self.keptktest2dupktests)" 1931,https://:@github.com/muteria/muteria.git,99f435844fc4a30e5b8351943feee77c96f9630e,"@@ -56,7 +56,7 @@ class CliUserInterface(object): parser_customexec = subparsers.add_parser('customexec', \ help=""Make some custom execution AFTER the"" "" main execution is done"") - parser_run.add_argument(""--nohashoutlog"", action='store_true', \ + parser_customexec.add_argument(""--nohashoutlog"", action='store_true', \ help=""When set, enforce no hash log"") if len(sys.argv)==1: ",muteria/cli/cli.py,"ReplaceText(target='parser_customexec' @(59,8)->(59,18))","class CliUserInterface(object): parser_customexec = subparsers.add_parser('customexec', \ help=""Make some custom execution AFTER the"" "" main execution is done"") parser_run.add_argument(""--nohashoutlog"", action='store_true', \ help=""When set, enforce no hash log"") if len(sys.argv)==1:","class CliUserInterface(object): parser_customexec = subparsers.add_parser('customexec', \ help=""Make some custom execution AFTER the"" "" main execution is done"") parser_customexec.add_argument(""--nohashoutlog"", action='store_true', \ help=""When set, enforce no hash log"") if len(sys.argv)==1:" 1932,https://:@github.com/Tetrite/cBinder.git,36123e9438d3dd26c34c95a5e6de613ddcb0d788,"@@ -17,7 +17,7 @@ def get_definitions_pairs(defines_list): def_pairs = {} for define_statement_string in defines_list: elems = re.split("" "", define_statement_string) - if len(elems) > 3: # When define statement is not a simple NAME <--> VALUE PAIR + if len(elems) != 3: # When define statement is not a simple NAME <--> VALUE PAIR continue # Do not preprocess this name = elems[1] value = elems[2] ",MiniPreprocessing.py,"ReplaceText(target='!=' @(20,22)->(20,23))","def get_definitions_pairs(defines_list): def_pairs = {} for define_statement_string in defines_list: elems = re.split("" "", define_statement_string) if len(elems) > 3: # When define statement is not a simple NAME <--> VALUE PAIR continue # Do not preprocess this name = elems[1] value = elems[2]","def get_definitions_pairs(defines_list): def_pairs = {} for define_statement_string in defines_list: elems = re.split("" "", define_statement_string) if len(elems) != 3: # When define statement is not a simple NAME <--> VALUE PAIR continue # Do not preprocess this name = elems[1] value = elems[2]" 1933,https://:@github.com/CovertLab/vivarium.git,7a3dc56b996fd44f4c028dcd299e2fc78cbb3144,"@@ -133,7 +133,7 @@ class Motor(Analysis): max_length = max(run_lengths + tumble_lengths) bins = np.linspace(0, max_length, 10) logbins = np.logspace(0, np.log10(bins[-1]), len(bins)) - ax5.hist([run_lengths, tumble_lengths], bins=logbins, label=['run_lengths', 'tumble_lengths'], color=['b', 'm']) + ax5.hist([run_lengths, tumble_lengths], bins=bins, label=['run_lengths', 'tumble_lengths'], color=['b', 'm']) # plot expected values ax5.axvline(x=expected_tumble, color='m', linestyle='dashed', label='expected tumble') ",vivarium/analysis/motor.py,"ReplaceText(target='bins' @(136,53)->(136,60))","class Motor(Analysis): max_length = max(run_lengths + tumble_lengths) bins = np.linspace(0, max_length, 10) logbins = np.logspace(0, np.log10(bins[-1]), len(bins)) ax5.hist([run_lengths, tumble_lengths], bins=logbins, label=['run_lengths', 'tumble_lengths'], color=['b', 'm']) # plot expected values ax5.axvline(x=expected_tumble, color='m', linestyle='dashed', label='expected tumble')","class Motor(Analysis): max_length = max(run_lengths + tumble_lengths) bins = np.linspace(0, max_length, 10) logbins = np.logspace(0, np.log10(bins[-1]), len(bins)) ax5.hist([run_lengths, tumble_lengths], bins=bins, label=['run_lengths', 'tumble_lengths'], color=['b', 'm']) # plot expected values ax5.axvline(x=expected_tumble, color='m', linestyle='dashed', label='expected tumble')" 1934,https://:@github.com/CovertLab/vivarium.git,365a08b14a6d25915605e68c586933f702b4994c,"@@ -43,7 +43,7 @@ class ShepherdControl(ActorControl): experiment_id, number, agent_type, environment_type)) # boot environment - self.add_agent(experiment_id, environment_type, lattice_config) + self.add_agent(experiment_id, environment_type, actor_config) time.sleep(10) # wait for the environment to boot # boot agents ",vivarium/environment/control.py,"ReplaceText(target='actor_config' @(46,56)->(46,70))","class ShepherdControl(ActorControl): experiment_id, number, agent_type, environment_type)) # boot environment self.add_agent(experiment_id, environment_type, lattice_config) time.sleep(10) # wait for the environment to boot # boot agents","class ShepherdControl(ActorControl): experiment_id, number, agent_type, environment_type)) # boot environment self.add_agent(experiment_id, environment_type, actor_config) time.sleep(10) # wait for the environment to boot # boot agents" 1935,https://:@github.com/CovertLab/vivarium.git,7b17a044e3d13866f61e7530952f5da27f21e896,"@@ -771,7 +771,7 @@ def load_compartment(composite, boot_config={}): 'emitter': boot_config.get('emitter', 'timeseries'), 'time_step': boot_config.get('time_step', 1.0)}) - return Compartment(processes, states, derivers, options) + return Compartment(processes, derivers, states, options) def simulate_compartment(compartment, settings={}): ",vivarium/compartment/composition.py,"ArgSwap(idxs=1<->2 @(774,11)->(774,22))","def load_compartment(composite, boot_config={}): 'emitter': boot_config.get('emitter', 'timeseries'), 'time_step': boot_config.get('time_step', 1.0)}) return Compartment(processes, states, derivers, options) def simulate_compartment(compartment, settings={}):","def load_compartment(composite, boot_config={}): 'emitter': boot_config.get('emitter', 'timeseries'), 'time_step': boot_config.get('time_step', 1.0)}) return Compartment(processes, derivers, states, options) def simulate_compartment(compartment, settings={}):" 1936,https://:@github.com/CovertLab/vivarium.git,049723f40d7994f2511f9b52e72082152a88cc3d,"@@ -67,7 +67,7 @@ def plot_signal_transduction(timeseries, out_dir='out', filename='signal_transdu ax2.tick_params(right=False, top=False) ax2.set_ylabel(""cluster activity \n P(on)"", fontsize=10) - ax2.set_xticklabels([]) + ax3.set_xticklabels([]) ax3.spines['right'].set_visible(False) ax3.spines['top'].set_visible(False) ax3.tick_params(right=False, top=False) ",vivarium/plots/chemotaxis_flagella.py,"ReplaceText(target='ax3' @(70,4)->(70,7))","def plot_signal_transduction(timeseries, out_dir='out', filename='signal_transdu ax2.tick_params(right=False, top=False) ax2.set_ylabel(""cluster activity \n P(on)"", fontsize=10) ax2.set_xticklabels([]) ax3.spines['right'].set_visible(False) ax3.spines['top'].set_visible(False) ax3.tick_params(right=False, top=False)","def plot_signal_transduction(timeseries, out_dir='out', filename='signal_transdu ax2.tick_params(right=False, top=False) ax2.set_ylabel(""cluster activity \n P(on)"", fontsize=10) ax3.set_xticklabels([]) ax3.spines['right'].set_visible(False) ax3.spines['top'].set_visible(False) ax3.tick_params(right=False, top=False)" 1937,https://:@github.com/wtsi-hgi/gitlab-build-variables.git,da55a3494cb0c375b5efb9f5248f0f3774d9c0c5,"@@ -63,7 +63,7 @@ class ProjectVariablesUpdater(VariablesUpdater): _logger.info(""Set variables for \""%s\"": %s"" % (self.project, variables)) def update_required(self) -> bool: - return self._variables_manager.get_variables() == self._get_required_variables() + return self._variables_manager.get_variables() != self._get_required_variables() def _get_required_variables(self) -> Dict[str, str]: """""" ",gitlabbuildvariables/updater.py,"ReplaceText(target='!=' @(66,55)->(66,57))","class ProjectVariablesUpdater(VariablesUpdater): _logger.info(""Set variables for \""%s\"": %s"" % (self.project, variables)) def update_required(self) -> bool: return self._variables_manager.get_variables() == self._get_required_variables() def _get_required_variables(self) -> Dict[str, str]: """"""","class ProjectVariablesUpdater(VariablesUpdater): _logger.info(""Set variables for \""%s\"": %s"" % (self.project, variables)) def update_required(self) -> bool: return self._variables_manager.get_variables() != self._get_required_variables() def _get_required_variables(self) -> Dict[str, str]: """"""" 1938,https://:@github.com/felfel/logging-py.git,27cc7bab2404993e04a07ee8f676fb646bd0f640,"@@ -115,7 +115,7 @@ class LogEntryParser: Logger.data_property_placeholder_name: data # here we set the data property with a special key } - if log_entry.message is not """" or log_entry.message is not None: + if log_entry.message is not """" and log_entry.message is not None: dto[""message""] = log_entry.message if exception_info is not None: ",loggingpy/log.py,"ReplaceText(target='and' @(118,39)->(118,41))","class LogEntryParser: Logger.data_property_placeholder_name: data # here we set the data property with a special key } if log_entry.message is not """" or log_entry.message is not None: dto[""message""] = log_entry.message if exception_info is not None:","class LogEntryParser: Logger.data_property_placeholder_name: data # here we set the data property with a special key } if log_entry.message is not """" and log_entry.message is not None: dto[""message""] = log_entry.message if exception_info is not None:" 1939,https://:@github.com/urban48/debpackager.git,fa24b2f2eb79059ec65edb8fc32eb1aaa46e689c,"@@ -94,7 +94,7 @@ class GeneralPackage(object): install_path=deb.get('install_path'), dependencies=deb_dependencies, description=deb.get('description'), - excludes=project.get('excludes', [])) + excludes=deb.get('excludes', [])) generated_builds.append(dpm.generate()) return generated_builds ",debpackager/packages/general_package.py,"ReplaceText(target='deb' @(97,31)->(97,38))","class GeneralPackage(object): install_path=deb.get('install_path'), dependencies=deb_dependencies, description=deb.get('description'), excludes=project.get('excludes', [])) generated_builds.append(dpm.generate()) return generated_builds","class GeneralPackage(object): install_path=deb.get('install_path'), dependencies=deb_dependencies, description=deb.get('description'), excludes=deb.get('excludes', [])) generated_builds.append(dpm.generate()) return generated_builds" 1940,https://:@github.com/noobermin/lspreader.git,4ab4049cfe95c5927f01406bd6a4653335752904,"@@ -88,7 +88,7 @@ if __name__ == ""__main__"": else: angleopt = None; KE, good = totalKE(d, ecut, angleopt, return_bools=True); - LE = laserE(E_0, w, T, dim=dim); + LE = laserE(E_0, T, w, dim=dim); totalq = d['q'][good].sum()*1e12; print('total charge: {} {}'.format(totalq,'pC/cm' if opts['--2D'] else 'pC')); print(""total energy: {} J"".format(KE)); ",pext/quantities.py,"ArgSwap(idxs=1<->2 @(91,9)->(91,15))","if __name__ == ""__main__"": else: angleopt = None; KE, good = totalKE(d, ecut, angleopt, return_bools=True); LE = laserE(E_0, w, T, dim=dim); totalq = d['q'][good].sum()*1e12; print('total charge: {} {}'.format(totalq,'pC/cm' if opts['--2D'] else 'pC')); print(""total energy: {} J"".format(KE));","if __name__ == ""__main__"": else: angleopt = None; KE, good = totalKE(d, ecut, angleopt, return_bools=True); LE = laserE(E_0, T, w, dim=dim); totalq = d['q'][good].sum()*1e12; print('total charge: {} {}'.format(totalq,'pC/cm' if opts['--2D'] else 'pC')); print(""total energy: {} J"".format(KE));" 1941,https://:@github.com/andycasey/sick.git,580f4072957817f483ed79de3f6b5208a07cfc42,"@@ -516,7 +516,7 @@ def load_aaomega_multispec(filename, fill_value=-1, clean=True): for i, index in enumerate(program_indices): headers = base_headers.copy() - headers['FIBRE_NUM'] = i + 1 + headers['FIBRE_NUM'] = index + 1 for header in req_fibre_headers: headers[header] = image[2].data[index][header] ",scope/specutils.py,"ReplaceText(target='index' @(519,31)->(519,32))","def load_aaomega_multispec(filename, fill_value=-1, clean=True): for i, index in enumerate(program_indices): headers = base_headers.copy() headers['FIBRE_NUM'] = i + 1 for header in req_fibre_headers: headers[header] = image[2].data[index][header]","def load_aaomega_multispec(filename, fill_value=-1, clean=True): for i, index in enumerate(program_indices): headers = base_headers.copy() headers['FIBRE_NUM'] = index + 1 for header in req_fibre_headers: headers[header] = image[2].data[index][header]" 1942,https://:@github.com/gilsondev/django-faleconosco.git,eb394ea946b658ffe4706620e12a0992e847ae4c,"@@ -26,7 +26,7 @@ def form(request, template_name='contato/contato_form.html', mensagem.update(dict) # Enviando o email - enviar_email(email, settings.DEFAULT_FROM_EMAIL, nome, + enviar_email(settings.DEFAULT_FROM_EMAIL, email, nome, assunto, template_email, mensagem) # Mostra mensagem de sucesso ",contato/views.py,"ArgSwap(idxs=0<->1 @(29,8)->(29,20))","def form(request, template_name='contato/contato_form.html', mensagem.update(dict) # Enviando o email enviar_email(email, settings.DEFAULT_FROM_EMAIL, nome, assunto, template_email, mensagem) # Mostra mensagem de sucesso","def form(request, template_name='contato/contato_form.html', mensagem.update(dict) # Enviando o email enviar_email(settings.DEFAULT_FROM_EMAIL, email, nome, assunto, template_email, mensagem) # Mostra mensagem de sucesso" 1943,https://:@github.com/lijinbio/cmsip.git,a9ac427f65d7fe2dd116b01d2506261686700231,"@@ -115,7 +115,7 @@ def bsmap(config): def mcall_stat_parse(infile): with open(infile) as f: dstr=f.read() - return float(re.search('bisulfite conversion ratio = ([\d.]+)', f).groups()[0]) + return float(re.search('bisulfite conversion ratio = ([\d.]+)', dstr).groups()[0]) def mcall_runcmd(infile, outdir, sampleid, reference, numthread, verbose=False): if os.path.exists(outdir): ",cmsip/cmsip.py,"ReplaceText(target='dstr' @(118,65)->(118,66))","def bsmap(config): def mcall_stat_parse(infile): with open(infile) as f: dstr=f.read() return float(re.search('bisulfite conversion ratio = ([\d.]+)', f).groups()[0]) def mcall_runcmd(infile, outdir, sampleid, reference, numthread, verbose=False): if os.path.exists(outdir):","def bsmap(config): def mcall_stat_parse(infile): with open(infile) as f: dstr=f.read() return float(re.search('bisulfite conversion ratio = ([\d.]+)', dstr).groups()[0]) def mcall_runcmd(infile, outdir, sampleid, reference, numthread, verbose=False): if os.path.exists(outdir):" 1944,https://:@github.com/TwoRavens/raven-metadata-service.git,dae36f1eab88f12cfb14d451124cc9d293f89ce0,"@@ -34,7 +34,7 @@ class PlotValuesUtil(object): # x-data for the ECDF: x_ x_value = np.sort(data) - size_data = x_value.size + size_data = raw_data.size # y-data for the ECDF: y y_value = [] ",preprocess/code/plot_values.py,"ReplaceText(target='raw_data' @(37,20)->(37,27))","class PlotValuesUtil(object): # x-data for the ECDF: x_ x_value = np.sort(data) size_data = x_value.size # y-data for the ECDF: y y_value = [] ","class PlotValuesUtil(object): # x-data for the ECDF: x_ x_value = np.sort(data) size_data = raw_data.size # y-data for the ECDF: y y_value = [] " 1945,https://:@github.com/TwoRavens/raven-metadata-service.git,1c19733c86b514a93342126535de899aed40b40e,"@@ -137,7 +137,7 @@ class JobUtil(object): @staticmethod def retrieve_rows_csv(request, job, **kwargs): - if request.method != 'POST': + if request.method == 'POST': print('kwargs', kwargs) start_row = kwargs.get('start_row') num_rows = kwargs.get('number_rows') ",preprocess_web/code/ravens_metadata_apps/preprocess_jobs/job_util.py,"ReplaceText(target='==' @(140,26)->(140,28))","class JobUtil(object): @staticmethod def retrieve_rows_csv(request, job, **kwargs): if request.method != 'POST': print('kwargs', kwargs) start_row = kwargs.get('start_row') num_rows = kwargs.get('number_rows')","class JobUtil(object): @staticmethod def retrieve_rows_csv(request, job, **kwargs): if request.method == 'POST': print('kwargs', kwargs) start_row = kwargs.get('start_row') num_rows = kwargs.get('number_rows')" 1946,https://:@github.com/Clinical-Genomics/cgbeacon.git,98f6705d3e6971111831cedfc4926e84880ec341,"@@ -74,7 +74,7 @@ def cli( dataset, vcf, db_connection, qual, ref, use_panel, outfile, customer, s vcfsamples = _compare_samples(vcfsamples, samples) ## returns a this tuple-> ( total_vars, beacon_vars(type: dict), discaded_vars(type: dict)) - vcf_results = get_variants(vcf_obj, vcfsamples, raw_variants, qual) + vcf_results = get_variants(vcf_obj, raw_variants , vcfsamples, qual) ## Print overall results of VCF file parsing to terminal vars_to_beacon = _print_results(vcf_results, qual) ",cgbeacon/cli/root.py,"ArgSwap(idxs=1<->2 @(77,18)->(77,30))","def cli( dataset, vcf, db_connection, qual, ref, use_panel, outfile, customer, s vcfsamples = _compare_samples(vcfsamples, samples) ## returns a this tuple-> ( total_vars, beacon_vars(type: dict), discaded_vars(type: dict)) vcf_results = get_variants(vcf_obj, vcfsamples, raw_variants, qual) ## Print overall results of VCF file parsing to terminal vars_to_beacon = _print_results(vcf_results, qual)","def cli( dataset, vcf, db_connection, qual, ref, use_panel, outfile, customer, s vcfsamples = _compare_samples(vcfsamples, samples) ## returns a this tuple-> ( total_vars, beacon_vars(type: dict), discaded_vars(type: dict)) vcf_results = get_variants(vcf_obj, raw_variants , vcfsamples, qual) ## Print overall results of VCF file parsing to terminal vars_to_beacon = _print_results(vcf_results, qual)" 1947,https://:@github.com/Clinical-Genomics/cgbeacon.git,98f6705d3e6971111831cedfc4926e84880ec341,"@@ -38,7 +38,7 @@ def beacon_upload(connection, vcf_path, panel_path, dataset, outfile="""", custome # returns a this tuple-> ( n_total_vars, beacon_vars(type: dict), discaded_vars(type: dict)) ### beacon_vars is a disctionary with key --> sample, and value --> list of tuples containing the non-reference variants. Each tuple is defined as: (chr, start, alt_allele) ### discaded_vars is a dictionary with key --> sample and value --> number of discarded vars due to quality for that sample. - vcf_results = get_variants(panel_filtered_results[0], samples, raw_variants, qual) + vcf_results = get_variants(panel_filtered_results[0], raw_variants, samples, qual) # Insert variants into the beacon. It returns a tuple: (vars_before_upload, vars_after_upload) beacon_update_result = bare_variants_uploader(connection, dataset, vcf_results, genome_reference) ",cgbeacon/utils/Utility.py,"ArgSwap(idxs=1<->2 @(41,18)->(41,30))","def beacon_upload(connection, vcf_path, panel_path, dataset, outfile="""", custome # returns a this tuple-> ( n_total_vars, beacon_vars(type: dict), discaded_vars(type: dict)) ### beacon_vars is a disctionary with key --> sample, and value --> list of tuples containing the non-reference variants. Each tuple is defined as: (chr, start, alt_allele) ### discaded_vars is a dictionary with key --> sample and value --> number of discarded vars due to quality for that sample. vcf_results = get_variants(panel_filtered_results[0], samples, raw_variants, qual) # Insert variants into the beacon. It returns a tuple: (vars_before_upload, vars_after_upload) beacon_update_result = bare_variants_uploader(connection, dataset, vcf_results, genome_reference)","def beacon_upload(connection, vcf_path, panel_path, dataset, outfile="""", custome # returns a this tuple-> ( n_total_vars, beacon_vars(type: dict), discaded_vars(type: dict)) ### beacon_vars is a disctionary with key --> sample, and value --> list of tuples containing the non-reference variants. Each tuple is defined as: (chr, start, alt_allele) ### discaded_vars is a dictionary with key --> sample and value --> number of discarded vars due to quality for that sample. vcf_results = get_variants(panel_filtered_results[0], raw_variants, samples, qual) # Insert variants into the beacon. It returns a tuple: (vars_before_upload, vars_after_upload) beacon_update_result = bare_variants_uploader(connection, dataset, vcf_results, genome_reference)" 1948,https://:@github.com/magistral-io/MagistralPython.git,29e567448385b02c287ffeb64593ca21d745b23b,"@@ -84,7 +84,7 @@ class JsonConverter(object): for ch in channels: permissions[int(ch)] = (read, write) else: - permissions[int(ch)] = (read, write) + permissions[int(channels)] = (read, write) return permissions; ",src/magistral/client/util/JsonConverter.py,"ReplaceText(target='channels' @(87,28)->(87,30))","class JsonConverter(object): for ch in channels: permissions[int(ch)] = (read, write) else: permissions[int(ch)] = (read, write) return permissions; ","class JsonConverter(object): for ch in channels: permissions[int(ch)] = (read, write) else: permissions[int(channels)] = (read, write) return permissions; " 1949,https://:@github.com/ebachelet/pyLIMA.git,1e18750dcdf80430af3b48a8225110bcbdc70447,"@@ -26,7 +26,7 @@ def microlensing_flux_priors(size_dataset, f_source, g_blending): def microlensing_parameters_limits_priors(parameters, limits): - for i in xrange(len(parameters)): + for i in xrange(len(limits)): if (parameters[i] > limits[i][1]) | (parameters[i] < limits[i][0]): ",pyLIMA/microlpriors.py,"ReplaceText(target='limits' @(29,24)->(29,34))","def microlensing_flux_priors(size_dataset, f_source, g_blending): def microlensing_parameters_limits_priors(parameters, limits): for i in xrange(len(parameters)): if (parameters[i] > limits[i][1]) | (parameters[i] < limits[i][0]): ","def microlensing_flux_priors(size_dataset, f_source, g_blending): def microlensing_parameters_limits_priors(parameters, limits): for i in xrange(len(limits)): if (parameters[i] > limits[i][1]) | (parameters[i] < limits[i][0]): " 1950,https://:@github.com/ebachelet/pyLIMA.git,7b358f94c59afc973bce950f1a0051fe74693e80,"@@ -178,7 +178,7 @@ def sort_2lenses_wide_caustics(caustic_points, critical_curves_points): first_branch = positive_y_branches[0] second_branch = positive_y_branches[1] - if np.max((caustic_points[:, first_branch]).real) > np.max((caustic_points[:, second_branch]).real): + if np.max((caustic_points[:, first_branch]).real) < np.max((caustic_points[:, second_branch]).real): central_caustic = np.r_[caustic_points[:, first_branch], np.conj(caustic_points[:, first_branch])[::-1]] central_cc = np.r_[critical_curves_points[:, first_branch], ",pyLIMA/microlcaustics.py,"ReplaceText(target='<' @(181,58)->(181,59))","def sort_2lenses_wide_caustics(caustic_points, critical_curves_points): first_branch = positive_y_branches[0] second_branch = positive_y_branches[1] if np.max((caustic_points[:, first_branch]).real) > np.max((caustic_points[:, second_branch]).real): central_caustic = np.r_[caustic_points[:, first_branch], np.conj(caustic_points[:, first_branch])[::-1]] central_cc = np.r_[critical_curves_points[:, first_branch],","def sort_2lenses_wide_caustics(caustic_points, critical_curves_points): first_branch = positive_y_branches[0] second_branch = positive_y_branches[1] if np.max((caustic_points[:, first_branch]).real) < np.max((caustic_points[:, second_branch]).real): central_caustic = np.r_[caustic_points[:, first_branch], np.conj(caustic_points[:, first_branch])[::-1]] central_cc = np.r_[critical_curves_points[:, first_branch]," 1951,https://:@github.com/RedFantom/mtTkinter.git,666f0351850ba1eed400e49ca33b2291cb6f3fb3,"@@ -141,7 +141,7 @@ class _TkAttr(object): if is_exception: ex_type, ex_value, ex_tb = response raise ex_type(ex_value, ex_tb) - return response_queue + return response def _Tk__init__(self, *args, **kwargs): ",mttkinter/mtTkinter.py,"ReplaceText(target='response' @(144,23)->(144,37))","class _TkAttr(object): if is_exception: ex_type, ex_value, ex_tb = response raise ex_type(ex_value, ex_tb) return response_queue def _Tk__init__(self, *args, **kwargs):","class _TkAttr(object): if is_exception: ex_type, ex_value, ex_tb = response raise ex_type(ex_value, ex_tb) return response def _Tk__init__(self, *args, **kwargs):" 1952,https://:@github.com/wheeler-microfluidics/dmf-device-ui.git,2443e29f710e516ebb3df7fc56db4f7e56f75893,"@@ -454,7 +454,7 @@ class DmfDeviceViewBase(SlaveView): # Find the closest corner point in the frame to the starting point. frame_corner_i = find_closest(slave.df_frame_corners, frame_point_i) # Find the closest corner point in the canvas to the end point. - canvas_corner_i = find_closest(slave.df_canvas_corners, end_xy) + canvas_corner_i = find_closest(slave.df_canvas_corners, start_xy) # Save current state of corners to allow undo. corners_state = {'df_frame_corners': ",dmf_device_ui/view.py,"ReplaceText(target='start_xy' @(457,64)->(457,70))","class DmfDeviceViewBase(SlaveView): # Find the closest corner point in the frame to the starting point. frame_corner_i = find_closest(slave.df_frame_corners, frame_point_i) # Find the closest corner point in the canvas to the end point. canvas_corner_i = find_closest(slave.df_canvas_corners, end_xy) # Save current state of corners to allow undo. corners_state = {'df_frame_corners':","class DmfDeviceViewBase(SlaveView): # Find the closest corner point in the frame to the starting point. frame_corner_i = find_closest(slave.df_frame_corners, frame_point_i) # Find the closest corner point in the canvas to the end point. canvas_corner_i = find_closest(slave.df_canvas_corners, start_xy) # Save current state of corners to allow undo. corners_state = {'df_frame_corners':" 1953,https://:@github.com/jisunglim/ethereum-etl.git,f7e7e55441816e291d73a90c3aa19e287b881989,"@@ -247,7 +247,7 @@ while True: token_transfers = token_transfers_item_exporter.get_items('token_transfer') enriched_transactions = enrich_transactions(blocks, transactions, receipts) - if len(enriched_transactions) == len(transactions): + if len(enriched_transactions) != len(transactions): raise ValueError('The number of transactions is wrong ' + str(enriched_transactions)) enriched_logs = enrich_logs(blocks, logs) if len(enriched_logs) != len(logs): ",stream.py,"ReplaceText(target='!=' @(250,38)->(250,40))","while True: token_transfers = token_transfers_item_exporter.get_items('token_transfer') enriched_transactions = enrich_transactions(blocks, transactions, receipts) if len(enriched_transactions) == len(transactions): raise ValueError('The number of transactions is wrong ' + str(enriched_transactions)) enriched_logs = enrich_logs(blocks, logs) if len(enriched_logs) != len(logs):","while True: token_transfers = token_transfers_item_exporter.get_items('token_transfer') enriched_transactions = enrich_transactions(blocks, transactions, receipts) if len(enriched_transactions) != len(transactions): raise ValueError('The number of transactions is wrong ' + str(enriched_transactions)) enriched_logs = enrich_logs(blocks, logs) if len(enriched_logs) != len(logs):" 1954,https://:@github.com/cpnota/autonomous-learning-library.git,a0debf34fdff31c56e93b572edfe2b1578772c77,"@@ -18,7 +18,7 @@ class TestAccumulatingTraces(unittest.TestCase): self.basis = FourierBasis(space, 2, 2) self.approximation = DiscreteLinearApproximation(0.1, self.basis, actions=3) self.env = Env() - self.traces = AccumulatingTraces(self.env, self.approximation, 0.5) + self.traces = AccumulatingTraces(self.approximation, self.env, 0.5) def test_init(self): np.testing.assert_equal(self.traces.call(x), np.array([0, 0, 0])) ",all/approximation/traces/accumulating_test.py,"ArgSwap(idxs=0<->1 @(21,18)->(21,36))","class TestAccumulatingTraces(unittest.TestCase): self.basis = FourierBasis(space, 2, 2) self.approximation = DiscreteLinearApproximation(0.1, self.basis, actions=3) self.env = Env() self.traces = AccumulatingTraces(self.env, self.approximation, 0.5) def test_init(self): np.testing.assert_equal(self.traces.call(x), np.array([0, 0, 0]))","class TestAccumulatingTraces(unittest.TestCase): self.basis = FourierBasis(space, 2, 2) self.approximation = DiscreteLinearApproximation(0.1, self.basis, actions=3) self.env = Env() self.traces = AccumulatingTraces(self.approximation, self.env, 0.5) def test_init(self): np.testing.assert_equal(self.traces.call(x), np.array([0, 0, 0]))" 1955,https://:@github.com/cpnota/autonomous-learning-library.git,f6c89200ee016ac98c856254defdaf52cc8ba454,"@@ -18,7 +18,7 @@ class TestLinearFunctionApproximation(unittest.TestCase): approximation = LinearApproximation(0.1, basis) x = np.array([0.5, 1]) self.assertEqual(approximation.call(x), 0) - approximation.update(x, 1) + approximation.update(1, x) self.assertAlmostEqual(approximation.call(x), 0.6) if __name__ == '__main__': ",all/approximation/state/linear_test.py,"ArgSwap(idxs=0<->1 @(21,4)->(21,24))","class TestLinearFunctionApproximation(unittest.TestCase): approximation = LinearApproximation(0.1, basis) x = np.array([0.5, 1]) self.assertEqual(approximation.call(x), 0) approximation.update(x, 1) self.assertAlmostEqual(approximation.call(x), 0.6) if __name__ == '__main__':","class TestLinearFunctionApproximation(unittest.TestCase): approximation = LinearApproximation(0.1, basis) x = np.array([0.5, 1]) self.assertEqual(approximation.call(x), 0) approximation.update(1, x) self.assertAlmostEqual(approximation.call(x), 0.6) if __name__ == '__main__':" 1956,https://:@github.com/redhog/fcdjangoutils.git,8302cf9148f8034930d5dca7f46392431a3ed866,"@@ -35,7 +35,7 @@ def duration_verbose(duration): if minutes != 0: if not first: res += "", "" - res += _(""%d min"") % hours; + res += _(""%d min"") % minutes; first = False if seconds != 0: ",templatetags/time_tags.py,"ReplaceText(target='minutes' @(38,29)->(38,34))","def duration_verbose(duration): if minutes != 0: if not first: res += "", "" res += _(""%d min"") % hours; first = False if seconds != 0:","def duration_verbose(duration): if minutes != 0: if not first: res += "", "" res += _(""%d min"") % minutes; first = False if seconds != 0:" 1957,https://:@github.com/chairbender/fantasy-football-auction.git,2f31b12d9fccae46e4ad6f389808f9b93046ad1b,"@@ -189,7 +189,7 @@ class Auction: if self.state != AuctionState.BID: raise InvalidActionError(""Bid was attempted, but it is not currently time to submit bids."") - elif self.bid > bid: + elif self.bid >= bid: raise InvalidActionError(""Bid amount "" + str(bid) + "" must be greater than current bid of "" + str(self.bid)) elif not self.owners[owner_id].can_buy(self.nominee, bid): raise InvalidActionError(""The owner with index "" + str(owner_id) + ",fantasy_football_auction/auction.py,"ReplaceText(target='>=' @(192,22)->(192,23))","class Auction: if self.state != AuctionState.BID: raise InvalidActionError(""Bid was attempted, but it is not currently time to submit bids."") elif self.bid > bid: raise InvalidActionError(""Bid amount "" + str(bid) + "" must be greater than current bid of "" + str(self.bid)) elif not self.owners[owner_id].can_buy(self.nominee, bid): raise InvalidActionError(""The owner with index "" + str(owner_id) +","class Auction: if self.state != AuctionState.BID: raise InvalidActionError(""Bid was attempted, but it is not currently time to submit bids."") elif self.bid >= bid: raise InvalidActionError(""Bid amount "" + str(bid) + "" must be greater than current bid of "" + str(self.bid)) elif not self.owners[owner_id].can_buy(self.nominee, bid): raise InvalidActionError(""The owner with index "" + str(owner_id) +" 1958,https://:@github.com/slazarov/python-signalr-client.git,33f58244b15ab6056cb0a0ad4ad53b040aacb8e8,"@@ -40,7 +40,7 @@ class HubClient(object): if hub.lower() == self.name.lower(): method = inner_data['M'] message = inner_data['A'] - await self.__handlers[method](message) + await self.__handlers[method](inner_data) connection.received += handle ",signalr_aio/hubs/_hub.py,"ReplaceText(target='inner_data' @(43,50)->(43,57))","class HubClient(object): if hub.lower() == self.name.lower(): method = inner_data['M'] message = inner_data['A'] await self.__handlers[method](message) connection.received += handle ","class HubClient(object): if hub.lower() == self.name.lower(): method = inner_data['M'] message = inner_data['A'] await self.__handlers[method](inner_data) connection.received += handle " 1959,https://:@github.com/slazarov/python-signalr-client.git,afdb4f05445acdfa4b1c9dfbbfccf5fb990cd6b0,"@@ -40,7 +40,7 @@ class HubClient(object): if hub.lower() == self.name.lower(): method = inner_data['M'] message = inner_data['A'] - await self.__handlers[method](inner_data) + await self.__handlers[method](message) connection.received += handle ",signalr_aio/hubs/_hub.py,"ReplaceText(target='message' @(43,50)->(43,60))","class HubClient(object): if hub.lower() == self.name.lower(): method = inner_data['M'] message = inner_data['A'] await self.__handlers[method](inner_data) connection.received += handle ","class HubClient(object): if hub.lower() == self.name.lower(): method = inner_data['M'] message = inner_data['A'] await self.__handlers[method](message) connection.received += handle " 1960,https://:@gitlab.com/nsbl/nsbl.git,d853aa6323d0ba9f14cd25ae8f76b67b8376d422,"@@ -232,7 +232,7 @@ class NsblTasklist(Frklist): elif res_type == ""ansible-tasklist"": tasklists = res_urls - if isinstance(tasklist, string_types): + if isinstance(tasklists, string_types): tasklists = [tasklists] for tl_name in tasklists: ",src/nsbl/nsbl_tasklist.py,"ReplaceText(target='tasklists' @(235,34)->(235,42))","class NsblTasklist(Frklist): elif res_type == ""ansible-tasklist"": tasklists = res_urls if isinstance(tasklist, string_types): tasklists = [tasklists] for tl_name in tasklists:","class NsblTasklist(Frklist): elif res_type == ""ansible-tasklist"": tasklists = res_urls if isinstance(tasklists, string_types): tasklists = [tasklists] for tl_name in tasklists:" 1961,https://:@github.com/vishalsubbiah/darkchess.git,399c8bde5e12f905a47ee06c6a4ec8297e57cf96,"@@ -14,7 +14,7 @@ class Board(object): def __init__(self, starting_board=None): self.board = np.empty((8,8),dtype=Piece) - if starting_board is not None: + if starting_board is None: self._start_pos() else: self.board = starting_board ",src/board.py,"ReplaceText(target=' is ' @(17,25)->(17,33))","class Board(object): def __init__(self, starting_board=None): self.board = np.empty((8,8),dtype=Piece) if starting_board is not None: self._start_pos() else: self.board = starting_board","class Board(object): def __init__(self, starting_board=None): self.board = np.empty((8,8),dtype=Piece) if starting_board is None: self._start_pos() else: self.board = starting_board" 1962,https://:@github.com/dongkai1993/social-core.git,d1d23e7e3cf4364c0d35289290b27787b84f5211,"@@ -50,7 +50,7 @@ def sanitize_redirect(host, redirect_to): """""" # Quick sanity check. if not redirect_to or \ - not isinstance(redirect_to, six.string_types) and \ + not isinstance(redirect_to, six.string_types) or \ getattr(redirect_to, 'decode', None) and \ not isinstance(redirect_to.decode(), six.string_types): return None ",social/utils.py,"ReplaceText(target='or' @(53,53)->(53,56))","def sanitize_redirect(host, redirect_to): """""" # Quick sanity check. if not redirect_to or \ not isinstance(redirect_to, six.string_types) and \ getattr(redirect_to, 'decode', None) and \ not isinstance(redirect_to.decode(), six.string_types): return None","def sanitize_redirect(host, redirect_to): """""" # Quick sanity check. if not redirect_to or \ not isinstance(redirect_to, six.string_types) or \ getattr(redirect_to, 'decode', None) and \ not isinstance(redirect_to.decode(), six.string_types): return None" 1963,https://:@github.com/dongkai1993/social-core.git,7d0628e7a756526b50449435eb02b2806e815755,"@@ -132,7 +132,7 @@ def partial_pipeline_data(strategy, user, *args, **kwargs): kwargs.setdefault('user', user) kwargs.setdefault('request', strategy.request) kwargs.update(xkwargs) - return idx, backend, xargs, xkwargs + return idx, backend, xargs, kwargs def build_absolute_uri(host_url, path=None): ",social/utils.py,"ReplaceText(target='kwargs' @(135,36)->(135,43))","def partial_pipeline_data(strategy, user, *args, **kwargs): kwargs.setdefault('user', user) kwargs.setdefault('request', strategy.request) kwargs.update(xkwargs) return idx, backend, xargs, xkwargs def build_absolute_uri(host_url, path=None):","def partial_pipeline_data(strategy, user, *args, **kwargs): kwargs.setdefault('user', user) kwargs.setdefault('request', strategy.request) kwargs.update(xkwargs) return idx, backend, xargs, kwargs def build_absolute_uri(host_url, path=None):" 1964,https://:@github.com/dongkai1993/social-core.git,d53529b57f0a4992889ad490e5314a2244155afa,"@@ -27,7 +27,7 @@ class SocialAuthExceptionMiddleware(object): return if isinstance(exception, SocialAuthBaseException): - backend_name = strategy.backend.name + backend_name = request.backend.name message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) try: ",social/apps/django_app/middleware.py,"ReplaceText(target='request' @(30,27)->(30,35))","class SocialAuthExceptionMiddleware(object): return if isinstance(exception, SocialAuthBaseException): backend_name = strategy.backend.name message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) try:","class SocialAuthExceptionMiddleware(object): return if isinstance(exception, SocialAuthBaseException): backend_name = request.backend.name message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) try:" 1965,https://:@github.com/barseghyanartur/django-dummy-thumbnails.git,a97e0e6a75b3408484b736c541794e489b436f2a,"@@ -27,7 +27,7 @@ def get_setting(setting, override=None): if hasattr(settings, attr_name): value = getattr(settings, attr_name) else: - if hasattr(defaults, attr_name): + if hasattr(defaults, setting): value = getattr(defaults, setting) else: return override ",src/dummy_thumbnails/conf.py,"ReplaceText(target='setting' @(30,29)->(30,38))","def get_setting(setting, override=None): if hasattr(settings, attr_name): value = getattr(settings, attr_name) else: if hasattr(defaults, attr_name): value = getattr(defaults, setting) else: return override","def get_setting(setting, override=None): if hasattr(settings, attr_name): value = getattr(settings, attr_name) else: if hasattr(defaults, setting): value = getattr(defaults, setting) else: return override" 1966,https://:@github.com/phil1425/jupyter-pc.git,d96265319699f32e575280623e0b67ec588214d6,"@@ -48,7 +48,7 @@ def fit(data_x, data_y, sigma_x=None, sigma_y=None, func=None, beta=[1., 0.], *a if type(data_x[0]) in ucvar: values_x = [d.n for d in data_x] - sigma_x = [d.s if d.s!=0 else 1e-5 for d in data_y] + sigma_x = [d.s if d.s!=0 else 1e-5 for d in data_x] elif type(data_x[0]) in [float, int]: values_x = data_x ",jupyterpc/jupyterpc.py,"ReplaceText(target='data_x' @(51,52)->(51,58))","def fit(data_x, data_y, sigma_x=None, sigma_y=None, func=None, beta=[1., 0.], *a if type(data_x[0]) in ucvar: values_x = [d.n for d in data_x] sigma_x = [d.s if d.s!=0 else 1e-5 for d in data_y] elif type(data_x[0]) in [float, int]: values_x = data_x ","def fit(data_x, data_y, sigma_x=None, sigma_y=None, func=None, beta=[1., 0.], *a if type(data_x[0]) in ucvar: values_x = [d.n for d in data_x] sigma_x = [d.s if d.s!=0 else 1e-5 for d in data_x] elif type(data_x[0]) in [float, int]: values_x = data_x " 1967,https://:@github.com/mrshu/python-imhdsk-api.git,bbd3b584f1ed575ec2cb6493e4e99de22038b8bf,"@@ -93,6 +93,6 @@ def routes(start, dest, city='ba'): route.begin_time = route.drives[0].begin_time route.end_time = route.drives[-1].end_time - route.append(route) + routes.append(route) return routes ",imhdsk/__init__.py,"ReplaceText(target='routes' @(96,8)->(96,13))","def routes(start, dest, city='ba'): route.begin_time = route.drives[0].begin_time route.end_time = route.drives[-1].end_time route.append(route) return routes","def routes(start, dest, city='ba'): route.begin_time = route.drives[0].begin_time route.end_time = route.drives[-1].end_time routes.append(route) return routes" 1968,https://:@github.com/juliusvonkohout/sparkmagic.git,54804b9adb02f02e5fccca8c21bcfd390426098e,"@@ -50,7 +50,7 @@ class UserCommandParser(object): # When no magic, add run command if not first_line.startswith(""%""): - first_line = ""%{} {}"".format(UserCommandParser.run_command, code) + first_line = ""%{} {}"".format(UserCommandParser.run_command, first_line) # Remove percentage sign first_line = first_line[1:] ",remotespark/wrapperkernel/usercommandparser.py,"ReplaceText(target='first_line' @(53,72)->(53,76))","class UserCommandParser(object): # When no magic, add run command if not first_line.startswith(""%""): first_line = ""%{} {}"".format(UserCommandParser.run_command, code) # Remove percentage sign first_line = first_line[1:]","class UserCommandParser(object): # When no magic, add run command if not first_line.startswith(""%""): first_line = ""%{} {}"".format(UserCommandParser.run_command, first_line) # Remove percentage sign first_line = first_line[1:]" 1969,https://:@github.com/morinted/plover_layout_display.git,8f071445dd2da69bfec2f5caf184627e713fd395,"@@ -58,7 +58,7 @@ class LayoutDisplayView(QGraphicsView): if key.label: label = QGraphicsTextItem(key.label) label.setFont(font) - label.setDefaultTextColor(QColor(steno_layout.font_color)) + label.setDefaultTextColor(QColor(key.font_color)) label_rect = label.boundingRect() label_rect.moveCenter(path.boundingRect().center()) ",layout_display/layout_graphics.py,"ReplaceText(target='key' @(61,49)->(61,61))","class LayoutDisplayView(QGraphicsView): if key.label: label = QGraphicsTextItem(key.label) label.setFont(font) label.setDefaultTextColor(QColor(steno_layout.font_color)) label_rect = label.boundingRect() label_rect.moveCenter(path.boundingRect().center())","class LayoutDisplayView(QGraphicsView): if key.label: label = QGraphicsTextItem(key.label) label.setFont(font) label.setDefaultTextColor(QColor(key.font_color)) label_rect = label.boundingRect() label_rect.moveCenter(path.boundingRect().center())" 1970,https://:@github.com/JulienPeloton/s4cmb.git,c4533367bf725c8486dc2140f841a8db649887f4,"@@ -445,7 +445,7 @@ class HealpixFitsMap(): alm = hp.map2alm([self.I,self.Q,self.U], self.lmax) Elm=alm[1] Blm=alm[2] - lmax=hp.Alm.getlmax(alm.size) + lmax=hp.Alm.getlmax(Elm.size) if 'P1' in self.derivatives_type: out = alm2map_spin_der1([Elm,Blm], self.nside_in, 2) self.dQdt =out[1][0] ",s4cmb/input_sky.py,"ReplaceText(target='Elm' @(448,28)->(448,31))","class HealpixFitsMap(): alm = hp.map2alm([self.I,self.Q,self.U], self.lmax) Elm=alm[1] Blm=alm[2] lmax=hp.Alm.getlmax(alm.size) if 'P1' in self.derivatives_type: out = alm2map_spin_der1([Elm,Blm], self.nside_in, 2) self.dQdt =out[1][0]","class HealpixFitsMap(): alm = hp.map2alm([self.I,self.Q,self.U], self.lmax) Elm=alm[1] Blm=alm[2] lmax=hp.Alm.getlmax(Elm.size) if 'P1' in self.derivatives_type: out = alm2map_spin_der1([Elm,Blm], self.nside_in, 2) self.dQdt =out[1][0]" 1971,https://:@github.com/tjstretchalot/pympanim.git,ac45774fcbc0532095c17be74fdabe8186879ed6,"@@ -42,7 +42,7 @@ def find_child(ends_arr: typing.List[float], last = 0 for i, etime in enumerate(ends_arr): if time < etime: - return i, etime - last + return i, time - last last = etime if time == last: return len(ends_arr) - 1, 0 ",pympanim/utils.py,"ReplaceText(target='time' @(45,22)->(45,27))","def find_child(ends_arr: typing.List[float], last = 0 for i, etime in enumerate(ends_arr): if time < etime: return i, etime - last last = etime if time == last: return len(ends_arr) - 1, 0","def find_child(ends_arr: typing.List[float], last = 0 for i, etime in enumerate(ends_arr): if time < etime: return i, time - last last = etime if time == last: return len(ends_arr) - 1, 0" 1972,https://:@github.com/j-walker23/cattrs.git,416f032481f9eca1867a85a0efa989595d7e44bf,"@@ -347,7 +347,7 @@ class Converter(object): # Check the union registry first. handler = self._union_registry.get(union) if handler is not None: - return handler(union, obj) + return handler(obj, union) # Unions with NoneType in them are basically optionals. union_params = union.__args__ ",cattr/converters.py,"ArgSwap(idxs=0<->1 @(350,19)->(350,26))","class Converter(object): # Check the union registry first. handler = self._union_registry.get(union) if handler is not None: return handler(union, obj) # Unions with NoneType in them are basically optionals. union_params = union.__args__","class Converter(object): # Check the union registry first. handler = self._union_registry.get(union) if handler is not None: return handler(obj, union) # Unions with NoneType in them are basically optionals. union_params = union.__args__" 1973,https://:@github.com/mitchnegus/pyleiades.git,85a44d967870cd395675d594ea56f1d0a18748e5,"@@ -42,7 +42,7 @@ class EClass: data = load_dataset(dataset_date=data_date,dataset_type=stat_type) # Isolate this energy's data, separate frequencies, and format the data - self.E_data = self._isolate_energy(data,E_code) + self.E_data = self._isolate_energy(E_code,data) self.monthly_data, self.yearly_data = self._sep_freqs(self.E_data) for data_df in self.monthly_data,self.yearly_data: data_df.set_index('Date_code',inplace=True) ",main/eclass.py,"ArgSwap(idxs=0<->1 @(45,22)->(45,42))","class EClass: data = load_dataset(dataset_date=data_date,dataset_type=stat_type) # Isolate this energy's data, separate frequencies, and format the data self.E_data = self._isolate_energy(data,E_code) self.monthly_data, self.yearly_data = self._sep_freqs(self.E_data) for data_df in self.monthly_data,self.yearly_data: data_df.set_index('Date_code',inplace=True)","class EClass: data = load_dataset(dataset_date=data_date,dataset_type=stat_type) # Isolate this energy's data, separate frequencies, and format the data self.E_data = self._isolate_energy(E_code,data) self.monthly_data, self.yearly_data = self._sep_freqs(self.E_data) for data_df in self.monthly_data,self.yearly_data: data_df.set_index('Date_code',inplace=True)" 1974,https://:@github.com/vgalisson/pySankey.git,44c01d55c6132a003adae938132f9f5bcc4e6b32,"@@ -158,7 +158,7 @@ def sankey( if len(rightLabels) == 0: rightLabels = pd.Series(dataFrame.right.unique()).unique() else: - check_data_matches_labels(leftLabels, dataFrame[""right""], ""right"") + check_data_matches_labels(rightLabels, dataFrame[""right""], ""right"") # If no colorDict given, make one if colorDict is None: colorDict = {} ",pysankey/sankey.py,"ReplaceText(target='rightLabels' @(161,34)->(161,44))","def sankey( if len(rightLabels) == 0: rightLabels = pd.Series(dataFrame.right.unique()).unique() else: check_data_matches_labels(leftLabels, dataFrame[""right""], ""right"") # If no colorDict given, make one if colorDict is None: colorDict = {}","def sankey( if len(rightLabels) == 0: rightLabels = pd.Series(dataFrame.right.unique()).unique() else: check_data_matches_labels(rightLabels, dataFrame[""right""], ""right"") # If no colorDict given, make one if colorDict is None: colorDict = {}" 1975,https://:@github.com/kshitij10496/lexico.git,a47f45857e2c389833e3f4d3f151b44973520714,"@@ -52,7 +52,7 @@ def handle_word(word): else: word_object = fetch_word(word) click.echo_via_pager(word_object.stringify()) - word_save_status = save_word(word) + word_save_status = save_word(word_object) if word_save_status: click.echo('{} has been added to your personal dictionary.'.format(word)) else: ",familiarize/cli.py,"ReplaceText(target='word_object' @(55,37)->(55,41))","def handle_word(word): else: word_object = fetch_word(word) click.echo_via_pager(word_object.stringify()) word_save_status = save_word(word) if word_save_status: click.echo('{} has been added to your personal dictionary.'.format(word)) else:","def handle_word(word): else: word_object = fetch_word(word) click.echo_via_pager(word_object.stringify()) word_save_status = save_word(word_object) if word_save_status: click.echo('{} has been added to your personal dictionary.'.format(word)) else:" 1976,https://:@github.com/speedcell4/aku.git,b96231d5ae8da4987bdf350ab8b8b4bbcf5f8059,"@@ -19,7 +19,7 @@ class Tp(object, metaclass=ABCMeta): origin = get_origin(tp) if origin is None and args == (): - return PrimitiveTp(origin) + return PrimitiveTp(tp) if origin is list and len(args) == 1: return ListTp(origin, cls[args[0]]) if origin is tuple: ",aku/tp.py,"ReplaceText(target='tp' @(22,31)->(22,37))","class Tp(object, metaclass=ABCMeta): origin = get_origin(tp) if origin is None and args == (): return PrimitiveTp(origin) if origin is list and len(args) == 1: return ListTp(origin, cls[args[0]]) if origin is tuple:","class Tp(object, metaclass=ABCMeta): origin = get_origin(tp) if origin is None and args == (): return PrimitiveTp(tp) if origin is list and len(args) == 1: return ListTp(origin, cls[args[0]]) if origin is tuple:" 1977,https://:@github.com/rembish/cfb.git,220ec866dbbae13cebbff3e5ba2da95cf433ef32,"@@ -76,7 +76,7 @@ class CfbIO(FileIO, MaybeDefected, ByteHelpers): sector_size = self.header.sector_size // 4 sector = self.header.minifat_sector_start - while sector != ENDOFCHAIN and (current + 1) * sector_size <= current: + while sector != ENDOFCHAIN and (position + 1) * sector_size <= current: sector = self.next_fat(sector) position += 1 ",cfb/__init__.py,"ReplaceText(target='position' @(79,40)->(79,47))","class CfbIO(FileIO, MaybeDefected, ByteHelpers): sector_size = self.header.sector_size // 4 sector = self.header.minifat_sector_start while sector != ENDOFCHAIN and (current + 1) * sector_size <= current: sector = self.next_fat(sector) position += 1 ","class CfbIO(FileIO, MaybeDefected, ByteHelpers): sector_size = self.header.sector_size // 4 sector = self.header.minifat_sector_start while sector != ENDOFCHAIN and (position + 1) * sector_size <= current: sector = self.next_fat(sector) position += 1 " 1978,https://:@github.com/acgt-tax-consultants/orchard.git,05d5b3ca4b5b6eaf6da380b8d5655b6f8d10342c,"@@ -58,7 +58,7 @@ def build(link_file_path, config_file_path, output): try: link_file = LinkFile(link_file_path) config_file = ConfigFile(config_file_path, True) - if validate(link_file_path, config_file_path): + if not validate(link_file_path, config_file_path): click.secho('Invalid configuration file.', fg='red', err=True) click.get_current_context().exit(1) ",orchard/cli.py,"ReplaceText(target='not ' @(61,11)->(61,11))","def build(link_file_path, config_file_path, output): try: link_file = LinkFile(link_file_path) config_file = ConfigFile(config_file_path, True) if validate(link_file_path, config_file_path): click.secho('Invalid configuration file.', fg='red', err=True) click.get_current_context().exit(1) ","def build(link_file_path, config_file_path, output): try: link_file = LinkFile(link_file_path) config_file = ConfigFile(config_file_path, True) if not validate(link_file_path, config_file_path): click.secho('Invalid configuration file.', fg='red', err=True) click.get_current_context().exit(1) " 1979,https://:@github.com/ostdotcom/ost-kyc-sdk-python.git,c348eb67f5beb94e238746b6c52987c10eb53542,"@@ -54,7 +54,7 @@ class HTTPHelper: # def verify_required(self): if self.urlparse()(self.api_base_url).scheme == ""http"": - return True + return False return True # ",ost_kyc_sdk_python/util/http_helper.py,"ReplaceText(target='False' @(57,19)->(57,23))","class HTTPHelper: # def verify_required(self): if self.urlparse()(self.api_base_url).scheme == ""http"": return True return True # ","class HTTPHelper: # def verify_required(self): if self.urlparse()(self.api_base_url).scheme == ""http"": return False return True # " 1980,https://:@github.com/IBM/yaps.git,43d298bdbf36cb2f1dde75a4d85a4a3ee66aff7a,"@@ -516,7 +516,7 @@ class Slice(Expression): # is this an operator precedence issue? if self.lower: self.to_stan_prec(self.lower, acc, indent) - if self.lower and self.upper: + if self.lower or self.upper: acc += self.mkString("":"") if self.upper: self.to_stan_prec(self.upper, acc, indent) ",yaps/ir.py,"ReplaceText(target='or' @(519,22)->(519,25))","class Slice(Expression): # is this an operator precedence issue? if self.lower: self.to_stan_prec(self.lower, acc, indent) if self.lower and self.upper: acc += self.mkString("":"") if self.upper: self.to_stan_prec(self.upper, acc, indent)","class Slice(Expression): # is this an operator precedence issue? if self.lower: self.to_stan_prec(self.lower, acc, indent) if self.lower or self.upper: acc += self.mkString("":"") if self.upper: self.to_stan_prec(self.upper, acc, indent)" 1981,https://:@github.com/larsyunker/PythoMS.git,9d393ed6083fe08e3f58439c99cedd084571df2f,"@@ -552,7 +552,7 @@ def estimated_exact_mass( """""" # narrow range to that of the isotope pattern l = bisect_left(x, simmin - lookwithin) - r = bisect_right(x, simmax - lookwithin) + r = bisect_right(x, simmax + lookwithin) locmax = max(y[l:r]) # find local max in that range for ind, val in enumerate(y): if val == locmax: # if the y-value equals the local max ",pythoms/tome.py,"ReplaceText(target='+' @(555,31)->(555,32))","def estimated_exact_mass( """""" # narrow range to that of the isotope pattern l = bisect_left(x, simmin - lookwithin) r = bisect_right(x, simmax - lookwithin) locmax = max(y[l:r]) # find local max in that range for ind, val in enumerate(y): if val == locmax: # if the y-value equals the local max","def estimated_exact_mass( """""" # narrow range to that of the isotope pattern l = bisect_left(x, simmin - lookwithin) r = bisect_right(x, simmax + lookwithin) locmax = max(y[l:r]) # find local max in that range for ind, val in enumerate(y): if val == locmax: # if the y-value equals the local max" 1982,https://:@github.com/kcl-tscm/mff.git,0c7f60c26344c4a68f8e06b518e3ef7b0b11c834,"@@ -613,7 +613,7 @@ class Sampling(object): SMAE = np.std(np.sqrt(np.sum(np.square(error), axis=1))) RMSE = np.sqrt(np.mean((error) ** 2)) else: - m.fit_energy(train_confs, train_forces) + m.fit_energy(train_confs, train_energy) y_hat = m.predict_energy(self.x) error = y_hat - self.y MAE = np.mean(np.abs(error)) ",mff/advanced_sampling.py,"ReplaceText(target='train_energy' @(616,38)->(616,50))","class Sampling(object): SMAE = np.std(np.sqrt(np.sum(np.square(error), axis=1))) RMSE = np.sqrt(np.mean((error) ** 2)) else: m.fit_energy(train_confs, train_forces) y_hat = m.predict_energy(self.x) error = y_hat - self.y MAE = np.mean(np.abs(error))","class Sampling(object): SMAE = np.std(np.sqrt(np.sum(np.square(error), axis=1))) RMSE = np.sqrt(np.mean((error) ** 2)) else: m.fit_energy(train_confs, train_energy) y_hat = m.predict_energy(self.x) error = y_hat - self.y MAE = np.mean(np.abs(error))" 1983,https://:@github.com/kcl-tscm/mff.git,0dd4e341b2fb23bb8b39a267ccb32728c841650f,"@@ -39,7 +39,7 @@ def eam_descriptor(dist, norm, rc, alpha, r0): try: dqdrij = -1/(2*q) * (dq1*q2 + q1*dq2) except ZeroDivisionError: - dqdrij = np.zeros(len(q)) + dqdrij = np.zeros(len(q1)) dqdr = -dqdrij[:, None]*norm return q, dqdr ",mff/calculators.py,"ReplaceText(target='q1' @(42,30)->(42,31))","def eam_descriptor(dist, norm, rc, alpha, r0): try: dqdrij = -1/(2*q) * (dq1*q2 + q1*dq2) except ZeroDivisionError: dqdrij = np.zeros(len(q)) dqdr = -dqdrij[:, None]*norm return q, dqdr ","def eam_descriptor(dist, norm, rc, alpha, r0): try: dqdrij = -1/(2*q) * (dq1*q2 + q1*dq2) except ZeroDivisionError: dqdrij = np.zeros(len(q1)) dqdr = -dqdrij[:, None]*norm return q, dqdr " 1984,https://:@github.com/mlavin/django-hilbert.git,f550bd0292f4d0e3a32a1da894d7f70711e5ad67,"@@ -38,7 +38,7 @@ class SSLRedirectMiddleware(object): urls = tuple([re.compile(url) for url in getattr(settings, 'SSL_PATTERNS', [])]) secure = any([url.search(request.path) for url in urls]) if request.is_secure(): - if not secure and not getattr(request, 'keep_secure', False): + if secure and not getattr(request, 'keep_secure', False): if getattr(settings, 'SSL_WHITELIST', False): # Redirect off SSL return _redirect(request, False) ",hilbert/middleware.py,"ReplaceText(target='' @(41,15)->(41,19))","class SSLRedirectMiddleware(object): urls = tuple([re.compile(url) for url in getattr(settings, 'SSL_PATTERNS', [])]) secure = any([url.search(request.path) for url in urls]) if request.is_secure(): if not secure and not getattr(request, 'keep_secure', False): if getattr(settings, 'SSL_WHITELIST', False): # Redirect off SSL return _redirect(request, False)","class SSLRedirectMiddleware(object): urls = tuple([re.compile(url) for url in getattr(settings, 'SSL_PATTERNS', [])]) secure = any([url.search(request.path) for url in urls]) if request.is_secure(): if secure and not getattr(request, 'keep_secure', False): if getattr(settings, 'SSL_WHITELIST', False): # Redirect off SSL return _redirect(request, False)" 1985,https://:@github.com/jbaiter/zotero-cli.git,4e1f926aa016e5a081609e24b8498d94139949ad,"@@ -45,7 +45,7 @@ def find_storage_directories(): if zotero_dir.exists(): candidates.append(zotero_dir.iterdir()) zotero5_dir = home_dir/""Zotero/storage"" - if zotero_dir.exists(): + if zotero5_dir.exists(): yield ('default', zotero5_dir) candidate_iter = itertools.chain.from_iterable(candidates) for fpath in candidate_iter: ",zotero_cli/cli.py,"ReplaceText(target='zotero5_dir' @(48,7)->(48,17))","def find_storage_directories(): if zotero_dir.exists(): candidates.append(zotero_dir.iterdir()) zotero5_dir = home_dir/""Zotero/storage"" if zotero_dir.exists(): yield ('default', zotero5_dir) candidate_iter = itertools.chain.from_iterable(candidates) for fpath in candidate_iter:","def find_storage_directories(): if zotero_dir.exists(): candidates.append(zotero_dir.iterdir()) zotero5_dir = home_dir/""Zotero/storage"" if zotero5_dir.exists(): yield ('default', zotero5_dir) candidate_iter = itertools.chain.from_iterable(candidates) for fpath in candidate_iter:" 1986,https://:@github.com/mjwen/kliff.git,6d15ef5257545fe7c716db02cc80a34120e93a04,"@@ -129,7 +129,7 @@ def get_descriptor(): desc_params['g5'] = [{'zeta': 1, 'lambda': -1, 'eta': 0.0001}, {'zeta': 2, 'lambda': 1, 'eta': 0.003}] - desc = SymmetryFunction(cutfunc, cutvalue, desc_params) + desc = SymmetryFunction(cutvalue, cutfunc, desc_params) return desc ",tests/descriptors/test_symmetry_function.py,"ArgSwap(idxs=0<->1 @(132,11)->(132,27))","def get_descriptor(): desc_params['g5'] = [{'zeta': 1, 'lambda': -1, 'eta': 0.0001}, {'zeta': 2, 'lambda': 1, 'eta': 0.003}] desc = SymmetryFunction(cutfunc, cutvalue, desc_params) return desc ","def get_descriptor(): desc_params['g5'] = [{'zeta': 1, 'lambda': -1, 'eta': 0.0001}, {'zeta': 2, 'lambda': 1, 'eta': 0.003}] desc = SymmetryFunction(cutvalue, cutfunc, desc_params) return desc " 1987,https://:@github.com/wheeler-microfluidics/mpm.git,ce40cbc346ba0bbb0770d2ab71165d84b8c1ffaa,"@@ -441,7 +441,7 @@ def enable_plugin(plugin_name): logger.debug('Plugin already enabled: `%s` -> `%s`', plugin_path_i, plugin_link_path_i) enabled_now[plugin_path_i.name] = False - return enabled_now if not singleton else singleton.values()[0] + return enabled_now if not singleton else enabled_now.values()[0] def disable_plugin(plugin_name): ",mpm/api.py,"ReplaceText(target='enabled_now' @(444,45)->(444,54))","def enable_plugin(plugin_name): logger.debug('Plugin already enabled: `%s` -> `%s`', plugin_path_i, plugin_link_path_i) enabled_now[plugin_path_i.name] = False return enabled_now if not singleton else singleton.values()[0] def disable_plugin(plugin_name):","def enable_plugin(plugin_name): logger.debug('Plugin already enabled: `%s` -> `%s`', plugin_path_i, plugin_link_path_i) enabled_now[plugin_path_i.name] = False return enabled_now if not singleton else enabled_now.values()[0] def disable_plugin(plugin_name):" 1988,https://:@github.com/N2ITN/RPiViz.git,61199407198a9d674f7836b25da74a6956a93917,"@@ -46,4 +46,4 @@ def crop2face(pic, predictor): clahe_crop = clahe_image[y1:y2, x1:x2] #LBP_img = LBP.main(clahe_crop) shape = predictor(clahe_crop, detections) - return shape, clahe_image + return shape, clahe_crop ",raspiviz/identify.py,"ReplaceText(target='clahe_crop' @(49,22)->(49,33))","def crop2face(pic, predictor): clahe_crop = clahe_image[y1:y2, x1:x2] #LBP_img = LBP.main(clahe_crop) shape = predictor(clahe_crop, detections) return shape, clahe_image","def crop2face(pic, predictor): clahe_crop = clahe_image[y1:y2, x1:x2] #LBP_img = LBP.main(clahe_crop) shape = predictor(clahe_crop, detections) return shape, clahe_crop" 1989,https://:@github.com/cctbx/cctbx_project.git,bf735aeb2594c55e777037d8680cde1c45926f6d,"@@ -279,7 +279,7 @@ class table: if (alt_row_name is None): continue if (alt_row_name == path): result.extend(row_objects) - elif (not path.startswith(alt_row_name+""."")): + elif (path.startswith(alt_row_name+""."")): for row_object in row_objects: result.extend(row_object.get(path=path[len(alt_row_name)+1:])) return result ",iotbx/iotbx/parameters/__init__.py,"ReplaceText(target='' @(282,14)->(282,18))","class table: if (alt_row_name is None): continue if (alt_row_name == path): result.extend(row_objects) elif (not path.startswith(alt_row_name+""."")): for row_object in row_objects: result.extend(row_object.get(path=path[len(alt_row_name)+1:])) return result","class table: if (alt_row_name is None): continue if (alt_row_name == path): result.extend(row_objects) elif (path.startswith(alt_row_name+""."")): for row_object in row_objects: result.extend(row_object.get(path=path[len(alt_row_name)+1:])) return result" 1990,https://:@github.com/cctbx/cctbx_project.git,d2b0c38feb91a6d3ca5d23614cc7d67daff71bd6,"@@ -25,7 +25,7 @@ cns_dna_rna_residue_names = { } mon_lib_dna_rna_cif = [""AD"", ""AR"", ""CD"", ""CR"", ""GD"", ""GR"", ""TD"", ""UR""] -if (""set"" not in __builtins__): +if (""set"" in __builtins__): mon_lib_dna_rna_cif = set(mon_lib_dna_rna_cif) rna_dna_reference_residue_names = { ",iotbx/iotbx/pdb/__init__.py,"ReplaceText(target=' in ' @(28,9)->(28,17))","cns_dna_rna_residue_names = { } mon_lib_dna_rna_cif = [""AD"", ""AR"", ""CD"", ""CR"", ""GD"", ""GR"", ""TD"", ""UR""] if (""set"" not in __builtins__): mon_lib_dna_rna_cif = set(mon_lib_dna_rna_cif) rna_dna_reference_residue_names = {","cns_dna_rna_residue_names = { } mon_lib_dna_rna_cif = [""AD"", ""AR"", ""CD"", ""CR"", ""GD"", ""GR"", ""TD"", ""UR""] if (""set"" in __builtins__): mon_lib_dna_rna_cif = set(mon_lib_dna_rna_cif) rna_dna_reference_residue_names = {" 1991,https://:@github.com/cctbx/cctbx_project.git,bb89e67604a536127da9b373ddac969a43c21077,"@@ -568,7 +568,7 @@ def input( lines=None, pdb_id=None): if (pdb_id is not None): - assert file_name is not None + assert file_name is None file_name = ent_path_local_mirror(pdb_id=pdb_id) if (file_name is not None): return ext.input( ",iotbx/pdb/__init__.py,"ReplaceText(target=' is ' @(571,20)->(571,28))","def input( lines=None, pdb_id=None): if (pdb_id is not None): assert file_name is not None file_name = ent_path_local_mirror(pdb_id=pdb_id) if (file_name is not None): return ext.input(","def input( lines=None, pdb_id=None): if (pdb_id is not None): assert file_name is None file_name = ent_path_local_mirror(pdb_id=pdb_id) if (file_name is not None): return ext.input(" 1992,https://:@github.com/cctbx/cctbx_project.git,1f3ebf35ac25f18b43f5ce2454f898f4609e9e2e,"@@ -1218,7 +1218,7 @@ class _(boost.python.injector, pair_sym_table): if (pair_count == 0): print >> out, "" no neighbors"" pair_counts.append(pair_count) - return pair_count + return pair_counts def number_of_pairs_involving_symmetry(self): result = 0 ",cctbx/crystal/__init__.py,"ReplaceText(target='pair_counts' @(1221,11)->(1221,21))","class _(boost.python.injector, pair_sym_table): if (pair_count == 0): print >> out, "" no neighbors"" pair_counts.append(pair_count) return pair_count def number_of_pairs_involving_symmetry(self): result = 0","class _(boost.python.injector, pair_sym_table): if (pair_count == 0): print >> out, "" no neighbors"" pair_counts.append(pair_count) return pair_counts def number_of_pairs_involving_symmetry(self): result = 0" 1993,https://:@github.com/cctbx/cctbx_project.git,5beb4735b28360b9f33f71020d3c1459330f4053,"@@ -50,7 +50,7 @@ class mod_hdf5(common_mode.common_mode_correction): # If no detector distance is available set it to NaN, since # Python's None is not permitted in HDF5 - distance = cspad_tbx.env_distance(env, self.address, self._detz_offset) + distance = cspad_tbx.env_distance(self.address, env, self._detz_offset) if distance is None: distance = float('nan') ",xfel/cxi/cspad_ana/mod_hdf5.py,"ArgSwap(idxs=0<->1 @(53,15)->(53,37))","class mod_hdf5(common_mode.common_mode_correction): # If no detector distance is available set it to NaN, since # Python's None is not permitted in HDF5 distance = cspad_tbx.env_distance(env, self.address, self._detz_offset) if distance is None: distance = float('nan') ","class mod_hdf5(common_mode.common_mode_correction): # If no detector distance is available set it to NaN, since # Python's None is not permitted in HDF5 distance = cspad_tbx.env_distance(self.address, env, self._detz_offset) if distance is None: distance = float('nan') " 1994,https://:@github.com/cctbx/cctbx_project.git,5beb4735b28360b9f33f71020d3c1459330f4053,"@@ -76,7 +76,7 @@ class mod_param(object): return # XXX This hardcodes the address for the front detector! - detz = cspad_tbx.env_detz(env, 'CxiDs1-0|Cspad-0') + detz = cspad_tbx.env_detz('CxiDs1-0|Cspad-0', env) if (detz is None): self.m_no_detz += 1 ",xfel/cxi/cspad_ana/mod_param.py,"ArgSwap(idxs=0<->1 @(79,11)->(79,29))","class mod_param(object): return # XXX This hardcodes the address for the front detector! detz = cspad_tbx.env_detz(env, 'CxiDs1-0|Cspad-0') if (detz is None): self.m_no_detz += 1 ","class mod_param(object): return # XXX This hardcodes the address for the front detector! detz = cspad_tbx.env_detz('CxiDs1-0|Cspad-0', env) if (detz is None): self.m_no_detz += 1 " 1995,https://:@github.com/cctbx/cctbx_project.git,5beb4735b28360b9f33f71020d3c1459330f4053,"@@ -342,7 +342,7 @@ class mod_view(common_mode.common_mode_correction): # Get the distance for the detectors that should have it, and set # it to NaN for those that should not. if self.detector == 'CxiDs1' or self.detector == 'CxiDsd': - distance = cspad_tbx.env_distance(env, self.address, self._detz_offset) + distance = cspad_tbx.env_distance(self.address, env, self._detz_offset) if distance is None: self.nfail += 1 self.logger.warning(""event(): no distance, shot skipped"") ",xfel/cxi/cspad_ana/mod_view.py,"ArgSwap(idxs=0<->1 @(345,17)->(345,39))","class mod_view(common_mode.common_mode_correction): # Get the distance for the detectors that should have it, and set # it to NaN for those that should not. if self.detector == 'CxiDs1' or self.detector == 'CxiDsd': distance = cspad_tbx.env_distance(env, self.address, self._detz_offset) if distance is None: self.nfail += 1 self.logger.warning(""event(): no distance, shot skipped"")","class mod_view(common_mode.common_mode_correction): # Get the distance for the detectors that should have it, and set # it to NaN for those that should not. if self.detector == 'CxiDs1' or self.detector == 'CxiDsd': distance = cspad_tbx.env_distance(self.address, env, self._detz_offset) if distance is None: self.nfail += 1 self.logger.warning(""event(): no distance, shot skipped"")" 1996,https://:@github.com/cctbx/cctbx_project.git,f60ef549166e775043ee96a9d55ea7946e6042af,"@@ -1212,7 +1212,7 @@ def get_matching_atoms(chains_info,a_id,b_id,res_num_a,res_num_b, a_altloc = chains_info[a_id].no_altloc.count(False) > 0 b_altloc = bool(chains_info[b_id].no_altloc) if b_altloc: - b_altloc = chains_info[a_id].no_altloc.count(False) > 0 + b_altloc = chains_info[b_id].no_altloc.count(False) > 0 test_altloc = a_altloc or b_altloc # res_num_a_updated = [] ",mmtbx/ncs/ncs_search.py,"ReplaceText(target='b_id' @(1215,27)->(1215,31))","def get_matching_atoms(chains_info,a_id,b_id,res_num_a,res_num_b, a_altloc = chains_info[a_id].no_altloc.count(False) > 0 b_altloc = bool(chains_info[b_id].no_altloc) if b_altloc: b_altloc = chains_info[a_id].no_altloc.count(False) > 0 test_altloc = a_altloc or b_altloc # res_num_a_updated = []","def get_matching_atoms(chains_info,a_id,b_id,res_num_a,res_num_b, a_altloc = chains_info[a_id].no_altloc.count(False) > 0 b_altloc = bool(chains_info[b_id].no_altloc) if b_altloc: b_altloc = chains_info[b_id].no_altloc.count(False) > 0 test_altloc = a_altloc or b_altloc # res_num_a_updated = []" 1997,https://:@github.com/cctbx/cctbx_project.git,2621ef9d6d7a761b026f833837cf885945745986,"@@ -188,7 +188,7 @@ class torsion_ncs(object): # and in another - MSE. They will be excluded without # raising Sorry. They could matched, but it is difficult # to figure out in this code how to make it happen. - not (resname1 in [""MET"", ""MSE""] and resname1 in [""MET"", ""MSE""])): + not (resname1 in [""MET"", ""MSE""] and resname2 in [""MET"", ""MSE""])): msg = ""Error in matching procedure: matching "" msg += ""'%s %s' and '%s %s'.\n"" % ( resname1, rg1.id_str(), resname2, rg2.id_str()) ",mmtbx/geometry_restraints/torsion_restraints/torsion_ncs.py,"ReplaceText(target='resname2' @(191,54)->(191,62))","class torsion_ncs(object): # and in another - MSE. They will be excluded without # raising Sorry. They could matched, but it is difficult # to figure out in this code how to make it happen. not (resname1 in [""MET"", ""MSE""] and resname1 in [""MET"", ""MSE""])): msg = ""Error in matching procedure: matching "" msg += ""'%s %s' and '%s %s'.\n"" % ( resname1, rg1.id_str(), resname2, rg2.id_str())","class torsion_ncs(object): # and in another - MSE. They will be excluded without # raising Sorry. They could matched, but it is difficult # to figure out in this code how to make it happen. not (resname1 in [""MET"", ""MSE""] and resname2 in [""MET"", ""MSE""])): msg = ""Error in matching procedure: matching "" msg += ""'%s %s' and '%s %s'.\n"" % ( resname1, rg1.id_str(), resname2, rg2.id_str())" 1998,https://:@github.com/cctbx/cctbx_project.git,7b8295b84a75a33064f917be984d6017d53a3494,"@@ -795,7 +795,7 @@ class ResidualsPlotter(object): reflections['xyzcal.px'] = reflections['xyzcal.px.%s'%dest] if 'xyzobs.mm.value' not in reflections: - reflections.centroid_px_to_mm(detector) + reflections.centroid_px_to_mm(experiments) reflections['difference_vector_norms'] = (reflections['xyzcal.mm']-reflections['xyzobs.mm.value']).norms() n = len(reflections) ",xfel/command_line/detector_residuals.py,"ReplaceText(target='experiments' @(798,36)->(798,44))","class ResidualsPlotter(object): reflections['xyzcal.px'] = reflections['xyzcal.px.%s'%dest] if 'xyzobs.mm.value' not in reflections: reflections.centroid_px_to_mm(detector) reflections['difference_vector_norms'] = (reflections['xyzcal.mm']-reflections['xyzobs.mm.value']).norms() n = len(reflections)","class ResidualsPlotter(object): reflections['xyzcal.px'] = reflections['xyzcal.px.%s'%dest] if 'xyzobs.mm.value' not in reflections: reflections.centroid_px_to_mm(experiments) reflections['difference_vector_norms'] = (reflections['xyzcal.mm']-reflections['xyzobs.mm.value']).norms() n = len(reflections)" 1999,https://:@github.com/cctbx/cctbx_project.git,b2783566840ae3392e09171bcb4141e46e6481e5,"@@ -115,7 +115,7 @@ class reader(iotbx_shelx_ext.hklf_reader): miller_set = miller.set( crystal_symmetry=crystal_symmetry, indices=self.indices(), anomalous_flag=anomalous) - if anomalous is not None: + if anomalous is None: miller_set = miller_set.auto_anomalous() miller_arrays = [] obs = (miller.array( ",iotbx/shelx/hklf.py,"ReplaceText(target=' is ' @(118,16)->(118,24))","class reader(iotbx_shelx_ext.hklf_reader): miller_set = miller.set( crystal_symmetry=crystal_symmetry, indices=self.indices(), anomalous_flag=anomalous) if anomalous is not None: miller_set = miller_set.auto_anomalous() miller_arrays = [] obs = (miller.array(","class reader(iotbx_shelx_ext.hklf_reader): miller_set = miller.set( crystal_symmetry=crystal_symmetry, indices=self.indices(), anomalous_flag=anomalous) if anomalous is None: miller_set = miller_set.auto_anomalous() miller_arrays = [] obs = (miller.array(" 2000,https://:@github.com/cctbx/cctbx_project.git,0a50a4f43be57400f7aed41055b7ae401954724d,"@@ -189,7 +189,7 @@ def exercise(): pdb_inp1 = iotbx.pdb.input(source_info=None, lines=test_pdb) pdb_inp2 = iotbx.pdb.input(source_info=None, lines=test_cif) model1 = mmtbx.model.manager(pdb_inp1) - model2 = mmtbx.model.manager(pdb_inp1) + model2 = mmtbx.model.manager(pdb_inp2) trans_obj1 = iotbx.ncs.input(hierarchy=model1.get_hierarchy()) trans_obj2 = iotbx.ncs.input(hierarchy=model2.get_hierarchy()) ",iotbx/pdb/tst_read_mtrix_records_from_cif.py,"ReplaceText(target='pdb_inp2' @(192,31)->(192,39))","def exercise(): pdb_inp1 = iotbx.pdb.input(source_info=None, lines=test_pdb) pdb_inp2 = iotbx.pdb.input(source_info=None, lines=test_cif) model1 = mmtbx.model.manager(pdb_inp1) model2 = mmtbx.model.manager(pdb_inp1) trans_obj1 = iotbx.ncs.input(hierarchy=model1.get_hierarchy()) trans_obj2 = iotbx.ncs.input(hierarchy=model2.get_hierarchy()) ","def exercise(): pdb_inp1 = iotbx.pdb.input(source_info=None, lines=test_pdb) pdb_inp2 = iotbx.pdb.input(source_info=None, lines=test_cif) model1 = mmtbx.model.manager(pdb_inp1) model2 = mmtbx.model.manager(pdb_inp2) trans_obj1 = iotbx.ncs.input(hierarchy=model1.get_hierarchy()) trans_obj2 = iotbx.ncs.input(hierarchy=model2.get_hierarchy()) " 2001,https://:@github.com/cctbx/cctbx_project.git,46af355112348574b808a6b026a7f3cafdc8c745,"@@ -965,7 +965,7 @@ class manager(object): atoms = atoms.select(~ias_selection) grm_geometry = self.get_restraints_manager().geometry grm_geometry.pair_proxies(sites_cart) - struct_conn_loop = grm_geometry.get_struct_conn_mmcif(atoms) + struct_conn_loop = grm_geometry.get_struct_conn_mmcif(hierarchy_to_output) cif_block.add_loop(struct_conn_loop) self.get_model_statistics_info() # outputting HELIX/SHEET records ",mmtbx/model/model.py,"ReplaceText(target='hierarchy_to_output' @(968,60)->(968,65))","class manager(object): atoms = atoms.select(~ias_selection) grm_geometry = self.get_restraints_manager().geometry grm_geometry.pair_proxies(sites_cart) struct_conn_loop = grm_geometry.get_struct_conn_mmcif(atoms) cif_block.add_loop(struct_conn_loop) self.get_model_statistics_info() # outputting HELIX/SHEET records","class manager(object): atoms = atoms.select(~ias_selection) grm_geometry = self.get_restraints_manager().geometry grm_geometry.pair_proxies(sites_cart) struct_conn_loop = grm_geometry.get_struct_conn_mmcif(hierarchy_to_output) cif_block.add_loop(struct_conn_loop) self.get_model_statistics_info() # outputting HELIX/SHEET records" 2002,https://:@github.com/cctbx/cctbx_project.git,fb3e93f9dc70a7d6027cdf4fcf906f78ad39ccf6,"@@ -244,7 +244,7 @@ def run(args, log=None, ccp4_map=None, mtz_dataset.add_miller_array( miller_array = f_obs.generate_r_free_flags(), column_root_label = ""R-free-flags"") - if not nohl and params.k_blur is not None and params.b_blur is None: + if not nohl and params.k_blur is not None and params.b_blur is not None: # convert phases into HL coefficeints broadcast(m=""Convert phases into HL coefficients:"", log=log) hl = get_hl(f_obs_cmpl=f_obs_cmpl, k_blur=params.k_blur, b_blur=params.b_blur) ",mmtbx/command_line/map_to_structure_factors.py,"ReplaceText(target=' is not ' @(247,61)->(247,65))","def run(args, log=None, ccp4_map=None, mtz_dataset.add_miller_array( miller_array = f_obs.generate_r_free_flags(), column_root_label = ""R-free-flags"") if not nohl and params.k_blur is not None and params.b_blur is None: # convert phases into HL coefficeints broadcast(m=""Convert phases into HL coefficients:"", log=log) hl = get_hl(f_obs_cmpl=f_obs_cmpl, k_blur=params.k_blur, b_blur=params.b_blur)","def run(args, log=None, ccp4_map=None, mtz_dataset.add_miller_array( miller_array = f_obs.generate_r_free_flags(), column_root_label = ""R-free-flags"") if not nohl and params.k_blur is not None and params.b_blur is not None: # convert phases into HL coefficeints broadcast(m=""Convert phases into HL coefficients:"", log=log) hl = get_hl(f_obs_cmpl=f_obs_cmpl, k_blur=params.k_blur, b_blur=params.b_blur)" 2003,https://:@github.com/cctbx/cctbx_project.git,534896eb6cac83fd73eec3cbc32a391e77ecdedc,"@@ -512,7 +512,7 @@ def select_crystal_symmetry( if cs and not cs.is_nonsense() and not cs.is_empty(): is_similar_cs = cs0.is_similar_symmetry(cs, absolute_angle_tolerance=absolute_angle_tolerance, - absolute_length_tolerance=absolute_angle_tolerance) + absolute_length_tolerance=absolute_length_tolerance) if(not is_similar_cs): msg = ""Crystal symmetry mismatch between different files.\n"" msg += ""%s %s\n"" % (cs0.unit_cell(), cs0.space_group_info()) ",cctbx/crystal/__init__.py,"ReplaceText(target='absolute_length_tolerance' @(515,37)->(515,61))","def select_crystal_symmetry( if cs and not cs.is_nonsense() and not cs.is_empty(): is_similar_cs = cs0.is_similar_symmetry(cs, absolute_angle_tolerance=absolute_angle_tolerance, absolute_length_tolerance=absolute_angle_tolerance) if(not is_similar_cs): msg = ""Crystal symmetry mismatch between different files.\n"" msg += ""%s %s\n"" % (cs0.unit_cell(), cs0.space_group_info())","def select_crystal_symmetry( if cs and not cs.is_nonsense() and not cs.is_empty(): is_similar_cs = cs0.is_similar_symmetry(cs, absolute_angle_tolerance=absolute_angle_tolerance, absolute_length_tolerance=absolute_length_tolerance) if(not is_similar_cs): msg = ""Crystal symmetry mismatch between different files.\n"" msg += ""%s %s\n"" % (cs0.unit_cell(), cs0.space_group_info())" 2004,https://:@github.com/youngershen/django-super-cache.git,89da4b6ee32fe55c483b3919f6f1ee307da37f7a,"@@ -29,7 +29,7 @@ class FileBackend(BaseBackend): cache_file = self.cache_dir + key with open(cache_file, 'w') as f: - f.write(cache_file) + f.write(content) f.flush() def get(self, key): ",django_super_cache/backends.py,"ReplaceText(target='content' @(32,20)->(32,30))","class FileBackend(BaseBackend): cache_file = self.cache_dir + key with open(cache_file, 'w') as f: f.write(cache_file) f.flush() def get(self, key):","class FileBackend(BaseBackend): cache_file = self.cache_dir + key with open(cache_file, 'w') as f: f.write(content) f.flush() def get(self, key):" 2005,https://:@github.com/T-Eberle/tgbot.git,26a4dbd36902a1554c22f52f13f335a2b9e9bbe4,"@@ -59,4 +59,4 @@ def singleradiocommand(wrapped): logger.exception(typo) MessageController.hide_keyboard(message, message.chat_id(), ""Witzbold."") deleteconv(message) - return wrapped + return _wrapped ",telegram/bot/decorators/singleradiocommand.py,"ReplaceText(target='_wrapped' @(62,15)->(62,22))","def singleradiocommand(wrapped): logger.exception(typo) MessageController.hide_keyboard(message, message.chat_id(), ""Witzbold."") deleteconv(message) return wrapped","def singleradiocommand(wrapped): logger.exception(typo) MessageController.hide_keyboard(message, message.chat_id(), ""Witzbold."") deleteconv(message) return _wrapped" 2006,https://:@github.com/Azure-Developments/ezzybot.git,0ebe7d860712b23bde58ba10bf4933277fa1db9b,"@@ -305,7 +305,7 @@ class ezzybot(Socket): if regex._thread: regex_thread = threading.Thread(target=self.run_trigger, args=(regex, wrappers.connection_wrapper(self), self.info)) regex_thread.daemon = True - plugin_thread.start() + regex_thread.start() else: self.run_trigger(regex, wrappers.connection_wrapper(self), self.info) if self.nick not in self.db['users'].keys(): ",ezzybot/bot.py,"ReplaceText(target='regex_thread' @(308,32)->(308,45))","class ezzybot(Socket): if regex._thread: regex_thread = threading.Thread(target=self.run_trigger, args=(regex, wrappers.connection_wrapper(self), self.info)) regex_thread.daemon = True plugin_thread.start() else: self.run_trigger(regex, wrappers.connection_wrapper(self), self.info) if self.nick not in self.db['users'].keys():","class ezzybot(Socket): if regex._thread: regex_thread = threading.Thread(target=self.run_trigger, args=(regex, wrappers.connection_wrapper(self), self.info)) regex_thread.daemon = True regex_thread.start() else: self.run_trigger(regex, wrappers.connection_wrapper(self), self.info) if self.nick not in self.db['users'].keys():" 2007,https://:@bitbucket.org/shiumachi/sphinxcontrib-recentpages.git,22c35dbac880b95d121bedb3b9e255c5ce67e654,"@@ -83,7 +83,7 @@ def get_file_list_ordered_by_mtime(target_dir, env): for docname in env.found_docs: abspath = env.doc2path(docname) mtime = os.path.getmtime(abspath) - res.append((abspath,mtime)) + res.append((docname,mtime)) res = list(set(res)) res.sort(cmp=lambda x,y: cmp(x[1], y[1]), reverse=True) ",sphinx.recentpages/recentpages.py,"ReplaceText(target='docname' @(86,20)->(86,27))","def get_file_list_ordered_by_mtime(target_dir, env): for docname in env.found_docs: abspath = env.doc2path(docname) mtime = os.path.getmtime(abspath) res.append((abspath,mtime)) res = list(set(res)) res.sort(cmp=lambda x,y: cmp(x[1], y[1]), reverse=True)","def get_file_list_ordered_by_mtime(target_dir, env): for docname in env.found_docs: abspath = env.doc2path(docname) mtime = os.path.getmtime(abspath) res.append((docname,mtime)) res = list(set(res)) res.sort(cmp=lambda x,y: cmp(x[1], y[1]), reverse=True)" 2008,https://:@github.com/frkhit/bl_wxpy.git,e2e191f226e74c9ea3547b94a5f4cf4bef2120dc,"@@ -85,7 +85,7 @@ class SentMessage(object): """""" from wxpy import Group - if isinstance(Group, self.receiver): + if isinstance(self.receiver, Group): return self.receiver.self @property ",wxpy/api/messages/sent_message.py,"ArgSwap(idxs=0<->1 @(88,11)->(88,21))","class SentMessage(object): """""" from wxpy import Group if isinstance(Group, self.receiver): return self.receiver.self @property","class SentMessage(object): """""" from wxpy import Group if isinstance(self.receiver, Group): return self.receiver.self @property" 2009,https://:@github.com/frkhit/bl_wxpy.git,c782a43af904ea346f4482f2e9e6617bece06166,"@@ -148,7 +148,7 @@ class Chat(object): :param friend_or_mp: 好友对象或公众号对象 """""" - card_name = friend_or_mp.nickname if isinstance(Chat, friend_or_mp) else friend_or_mp + card_name = friend_or_mp.nickname if isinstance(friend_or_mp, Chat) else friend_or_mp logger.info('sending {} to {}: {}'.format(CARD, self, card_name)) return self.core.send( ",wxpy/api/chats/chat.py,"ArgSwap(idxs=0<->1 @(151,45)->(151,55))","class Chat(object): :param friend_or_mp: 好友对象或公众号对象 """""" card_name = friend_or_mp.nickname if isinstance(Chat, friend_or_mp) else friend_or_mp logger.info('sending {} to {}: {}'.format(CARD, self, card_name)) return self.core.send(","class Chat(object): :param friend_or_mp: 好友对象或公众号对象 """""" card_name = friend_or_mp.nickname if isinstance(friend_or_mp, Chat) else friend_or_mp logger.info('sending {} to {}: {}'.format(CARD, self, card_name)) return self.core.send(" 2010,https://:@github.com/kmarilleau/pytest-django-models.git,31fa2011c76bd1581d24bef19f422cebf644b03d,"@@ -237,7 +237,7 @@ class ModelGenerator: # Ignore Special Methods. or is_dunder(attr) # Ignore Functions. - or inspect.isfunction(attr) + or inspect.isfunction(value) # Ignore Django Model Attributes. or attr in (""objects"", ""id"", ""_meta"") # Ignore Fields. ",pytest_django_model/objects.py,"ReplaceText(target='value' @(240,34)->(240,38))","class ModelGenerator: # Ignore Special Methods. or is_dunder(attr) # Ignore Functions. or inspect.isfunction(attr) # Ignore Django Model Attributes. or attr in (""objects"", ""id"", ""_meta"") # Ignore Fields.","class ModelGenerator: # Ignore Special Methods. or is_dunder(attr) # Ignore Functions. or inspect.isfunction(value) # Ignore Django Model Attributes. or attr in (""objects"", ""id"", ""_meta"") # Ignore Fields." 2011,https://:@github.com/fixstars/clpy.git,d751a0614598bf05b9bbfd15eb0d05e26e562649,"@@ -151,7 +151,7 @@ class BatchNormalization(function.Function): def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) - x_type, = out_types + x_type, = in_types y_type, = out_types type_check.expect( ",chainer/functions/batch_normalization.py,"ReplaceText(target='in_types' @(154,18)->(154,27))","class BatchNormalization(function.Function): def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) x_type, = out_types y_type, = out_types type_check.expect(","class BatchNormalization(function.Function): def check_type_backward(self, in_types, out_types): type_check.expect(out_types.size() == 1) x_type, = in_types y_type, = out_types type_check.expect(" 2012,https://:@github.com/fixstars/clpy.git,447e1e6aaf5590b7bdce63afb826a754d03274d8,"@@ -208,7 +208,7 @@ class Optimizer(object): with cuda.get_device(g_dst): if (isinstance(g_src, cuda.ndarray) and g_dst.gpudata.device != g_src.gpudata.device): - g_dst += cuda.copy(g_src, out_device=g_src.gpudata.device) + g_dst += cuda.copy(g_src, out_device=g_dst.gpudata.device) else: g_dst += cuda.to_gpu(g_src) ",chainer/optimizer.py,"ReplaceText(target='g_dst' @(211,57)->(211,62))","class Optimizer(object): with cuda.get_device(g_dst): if (isinstance(g_src, cuda.ndarray) and g_dst.gpudata.device != g_src.gpudata.device): g_dst += cuda.copy(g_src, out_device=g_src.gpudata.device) else: g_dst += cuda.to_gpu(g_src) ","class Optimizer(object): with cuda.get_device(g_dst): if (isinstance(g_src, cuda.ndarray) and g_dst.gpudata.device != g_src.gpudata.device): g_dst += cuda.copy(g_src, out_device=g_dst.gpudata.device) else: g_dst += cuda.to_gpu(g_src) " 2013,https://:@github.com/fixstars/clpy.git,2cd7ddd29647184e00e79a551c37d6e975141e83,"@@ -10,7 +10,7 @@ class Contrastive(function.Function): """"""Contrastive loss function."""""" def __init__(self, margin): - if margin < 0: + if margin <= 0: raise Exception(""margin should be positive value."") self.margin = margin ",chainer/functions/loss/contrastive.py,"ReplaceText(target='<=' @(13,18)->(13,19))","class Contrastive(function.Function): """"""Contrastive loss function."""""" def __init__(self, margin): if margin < 0: raise Exception(""margin should be positive value."") self.margin = margin ","class Contrastive(function.Function): """"""Contrastive loss function."""""" def __init__(self, margin): if margin <= 0: raise Exception(""margin should be positive value."") self.margin = margin " 2014,https://:@github.com/fixstars/clpy.git,1f29bf157ef8289a6a16cfc19ea8737473623a7e,"@@ -32,7 +32,7 @@ def array_split(ary, indices_or_sections, axis=0): for index in indices: ret.append(ary[skip + (slice(i, index),)]) i = index - ret.append(ary[skip + (slice(index, size),)]) + ret.append(ary[skip + (slice(i, size),)]) return ret ",cupy/manipulation/split.py,"ReplaceText(target='i' @(35,33)->(35,38))","def array_split(ary, indices_or_sections, axis=0): for index in indices: ret.append(ary[skip + (slice(i, index),)]) i = index ret.append(ary[skip + (slice(index, size),)]) return ret ","def array_split(ary, indices_or_sections, axis=0): for index in indices: ret.append(ary[skip + (slice(i, index),)]) i = index ret.append(ary[skip + (slice(i, size),)]) return ret " 2015,https://:@github.com/fixstars/clpy.git,74b521b9ec3a8b0ceda86041d9e9f78ffdd8d5a1,"@@ -123,7 +123,7 @@ def hstack(tup): axis = 1 if arrs[0].ndim == 1: axis = 0 - return concatenate(tup, axis) + return concatenate(arrs, axis) def vstack(tup): ",cupy/manipulation/join.py,"ReplaceText(target='arrs' @(126,23)->(126,26))","def hstack(tup): axis = 1 if arrs[0].ndim == 1: axis = 0 return concatenate(tup, axis) def vstack(tup):","def hstack(tup): axis = 1 if arrs[0].ndim == 1: axis = 0 return concatenate(arrs, axis) def vstack(tup):" 2016,https://:@github.com/fixstars/clpy.git,4faf0402e83dcb3e2486fff862142f92f61cf75f,"@@ -54,7 +54,7 @@ def exec_ultima(source, _clpy_header=''): proc.kill() source, errstream = proc.communicate() - if proc.returncode != 0 and len(errstream) > 0: + if proc.returncode != 0 or len(errstream) > 0: raise clpy.backend.ultima.exceptions.UltimaRuntimeError( proc.returncode, errstream) ",tests/clpy_tests/opencl_tests/ultima_tests/utility.py,"ReplaceText(target='or' @(57,32)->(57,35))","def exec_ultima(source, _clpy_header=''): proc.kill() source, errstream = proc.communicate() if proc.returncode != 0 and len(errstream) > 0: raise clpy.backend.ultima.exceptions.UltimaRuntimeError( proc.returncode, errstream) ","def exec_ultima(source, _clpy_header=''): proc.kill() source, errstream = proc.communicate() if proc.returncode != 0 or len(errstream) > 0: raise clpy.backend.ultima.exceptions.UltimaRuntimeError( proc.returncode, errstream) " 2017,https://:@github.com/ashleysommer/sanic-oauthlib.git,ae9f946b2b2739bb352961c200b2e4eeaba67044,"@@ -323,7 +323,7 @@ class OAuthRemoteApp(object): if attr: return attr if default is not False and not self.app_key: - return attr + return default app = self.oauth.app or current_app config = app.config[self.app_key] if default is not False: ",flask_oauthlib/client.py,"ReplaceText(target='default' @(326,19)->(326,23))","class OAuthRemoteApp(object): if attr: return attr if default is not False and not self.app_key: return attr app = self.oauth.app or current_app config = app.config[self.app_key] if default is not False:","class OAuthRemoteApp(object): if attr: return attr if default is not False and not self.app_key: return default app = self.oauth.app or current_app config = app.config[self.app_key] if default is not False:" 2018,https://:@github.com/arangb/isbnlib-dnb.git,929ff7c071c452c316769df0d236af29f92d5cbf,"@@ -51,7 +51,7 @@ def parser_dnb(data): #
elif re.search(r""Titel(.*)/.*', '').replace('', '').replace('Zeitliche Einordnung ",isbnlib_dnb/_dnb.py,"ReplaceText(target='title' @(54,16)->(54,25))","def parser_dnb(data): # elif re.search(r""Titel(.*)/.*', '').replace('Zeitliche Einordnung","def parser_dnb(data): # elif re.search(r""Titel(.*)/.*', '').replace('Zeitliche Einordnung" 2019,https://:@github.com/parantapa/xactor.git,c4e136ac827da189b19fe8f9be1e54f426dba777,"@@ -133,7 +133,7 @@ class MPIRankActor: while not self.stopping: actor_id, message = self.acomm.recv() if actor_id not in self.local_actors: - raise RuntimeError(""Message received for non-local actor: %r"" % message) + raise RuntimeError(""Message received for non-local actor: %r"" % actor_id) actor = self.local_actors[actor_id] try: ",xactor/mpi_actor.py,"ReplaceText(target='actor_id' @(136,80)->(136,87))","class MPIRankActor: while not self.stopping: actor_id, message = self.acomm.recv() if actor_id not in self.local_actors: raise RuntimeError(""Message received for non-local actor: %r"" % message) actor = self.local_actors[actor_id] try:","class MPIRankActor: while not self.stopping: actor_id, message = self.acomm.recv() if actor_id not in self.local_actors: raise RuntimeError(""Message received for non-local actor: %r"" % actor_id) actor = self.local_actors[actor_id] try:" 2020,https://:@github.com/openlmi/openlmi-scripts.git,da316f00c9b29f4bc58fc5bc38274551e0f3aea3,"@@ -510,7 +510,7 @@ def set_autoconnect(ns, setting, device=None, state=True): # Set IsNext = 2 (Is Not Next), don't change IsCurrent mode = service.ApplySettingToIPNetworkConnection.ModeValues.Mode5 - if device is not None: + if device is None: result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, Mode=mode) else: result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, IPNetworkConnection=device, Mode=mode) ",commands/networking/lmi/scripts/networking/__init__.py,"ReplaceText(target=' is ' @(513,13)->(513,21))","def set_autoconnect(ns, setting, device=None, state=True): # Set IsNext = 2 (Is Not Next), don't change IsCurrent mode = service.ApplySettingToIPNetworkConnection.ModeValues.Mode5 if device is not None: result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, Mode=mode) else: result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, IPNetworkConnection=device, Mode=mode)","def set_autoconnect(ns, setting, device=None, state=True): # Set IsNext = 2 (Is Not Next), don't change IsCurrent mode = service.ApplySettingToIPNetworkConnection.ModeValues.Mode5 if device is None: result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, Mode=mode) else: result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, IPNetworkConnection=device, Mode=mode)" 2021,https://:@github.com/socek/hatak.git,68f03e13ae99fd2769e5bfeb5cd49bcea218d9f4,"@@ -62,7 +62,7 @@ class ControllerFixture(RequestFixture): request.registry['controller_plugins'] = app.controller_plugins controller = self._get_controller_class()(root_tree, request) controller.data = data - controller.matchdict = matchdict + request.matchdict = matchdict return controller ",src/hatak/testing.py,"ReplaceText(target='request' @(65,8)->(65,18))","class ControllerFixture(RequestFixture): request.registry['controller_plugins'] = app.controller_plugins controller = self._get_controller_class()(root_tree, request) controller.data = data controller.matchdict = matchdict return controller ","class ControllerFixture(RequestFixture): request.registry['controller_plugins'] = app.controller_plugins controller = self._get_controller_class()(root_tree, request) controller.data = data request.matchdict = matchdict return controller " 2022,https://:@github.com/DaniFdezAlvarez/shexerp3.git,913462770932107c1230a56677029e7cccd5957a,"@@ -125,7 +125,7 @@ def get_instance_tracker(instances_file_input=None, graph_file_input=None, selectors_tracker = ShapeMapInstanceTracker(shape_map=valid_shape_map) if _are_there_some_target_classes(target_classes, file_target_classes, all_classes_mode, shape_qualifiers_mode): model_classes = None - if all_classes_mode or target_classes is not None: + if file_target_classes or target_classes is not None: list_of_str_target_classes = tune_target_classes_if_needed( target_classes) if target_classes is not None else read_target_classes_from_file(file_target_classes) model_classes = get_list_of_model_classes(list_of_str_target_classes) ",shexer/utils/factories/instance_tracker_factory.py,"ReplaceText(target='file_target_classes' @(128,11)->(128,27))","def get_instance_tracker(instances_file_input=None, graph_file_input=None, selectors_tracker = ShapeMapInstanceTracker(shape_map=valid_shape_map) if _are_there_some_target_classes(target_classes, file_target_classes, all_classes_mode, shape_qualifiers_mode): model_classes = None if all_classes_mode or target_classes is not None: list_of_str_target_classes = tune_target_classes_if_needed( target_classes) if target_classes is not None else read_target_classes_from_file(file_target_classes) model_classes = get_list_of_model_classes(list_of_str_target_classes)","def get_instance_tracker(instances_file_input=None, graph_file_input=None, selectors_tracker = ShapeMapInstanceTracker(shape_map=valid_shape_map) if _are_there_some_target_classes(target_classes, file_target_classes, all_classes_mode, shape_qualifiers_mode): model_classes = None if file_target_classes or target_classes is not None: list_of_str_target_classes = tune_target_classes_if_needed( target_classes) if target_classes is not None else read_target_classes_from_file(file_target_classes) model_classes = get_list_of_model_classes(list_of_str_target_classes)" 2023,https://:@github.com/remykarem/mixed-naive-bayes.git,669a9c2aacc6c3a75e0dc54ce06db57e1db7b672,"@@ -429,7 +429,7 @@ def _validate_training_data(X_raw, y_raw, categorical_features, max_categories): if not np.array_equal(X[:, feature_no], X[:, feature_no].astype(int)): warnings.warn(f""Feature no. {feature_no} is continuous data. "" + ""Casting data to integer."") - if max_categories is not None: + if max_categories is None: uniques = np.unique(X[:, feature_no]).astype(int) if not np.array_equal(uniques, np.arange(0, np.max(uniques)+1)): raise ValueError(f""Expected feature no. {feature_no} to have "" + ",mixed_naive_bayes/mixed_naive_bayes.py,"ReplaceText(target=' is ' @(432,29)->(432,37))","def _validate_training_data(X_raw, y_raw, categorical_features, max_categories): if not np.array_equal(X[:, feature_no], X[:, feature_no].astype(int)): warnings.warn(f""Feature no. {feature_no} is continuous data. "" + ""Casting data to integer."") if max_categories is not None: uniques = np.unique(X[:, feature_no]).astype(int) if not np.array_equal(uniques, np.arange(0, np.max(uniques)+1)): raise ValueError(f""Expected feature no. {feature_no} to have "" +","def _validate_training_data(X_raw, y_raw, categorical_features, max_categories): if not np.array_equal(X[:, feature_no], X[:, feature_no].astype(int)): warnings.warn(f""Feature no. {feature_no} is continuous data. "" + ""Casting data to integer."") if max_categories is None: uniques = np.unique(X[:, feature_no]).astype(int) if not np.array_equal(uniques, np.arange(0, np.max(uniques)+1)): raise ValueError(f""Expected feature no. {feature_no} to have "" +" 2024,https://:@github.com/remykarem/mixed-naive-bayes.git,e5f53782e0edba232d4468a267274524c08ec180,"@@ -153,7 +153,7 @@ class MixedNB(): if len(self.priors) != num_classes: raise ValueError( 'Number of priors must match number of classes.') - if np.isclose(self.priors.sum(), 1.0): + if not np.isclose(self.priors.sum(), 1.0): raise ValueError(""The sum of priors should be 1."") if (self.priors < 0).any(): raise ValueError('Priors must be non-negative.') ",mixed_naive_bayes/mixed_naive_bayes.py,"ReplaceText(target='not ' @(156,15)->(156,15))","class MixedNB(): if len(self.priors) != num_classes: raise ValueError( 'Number of priors must match number of classes.') if np.isclose(self.priors.sum(), 1.0): raise ValueError(""The sum of priors should be 1."") if (self.priors < 0).any(): raise ValueError('Priors must be non-negative.')","class MixedNB(): if len(self.priors) != num_classes: raise ValueError( 'Number of priors must match number of classes.') if not np.isclose(self.priors.sum(), 1.0): raise ValueError(""The sum of priors should be 1."") if (self.priors < 0).any(): raise ValueError('Priors must be non-negative.')" 2025,https://:@github.com/hprid/adblockeval.git,89311b75f3460835e764947dd794f62e7a95d031,"@@ -167,7 +167,7 @@ class Rule: self.is_exception = False def match(self, url, netloc, domain, origin=None): - if self.options and not self.options.can_apply_rule(netloc, origin): + if self.options and not self.options.can_apply_rule(domain, origin): return False return True ",adblockeval/rules.py,"ReplaceText(target='domain' @(170,60)->(170,66))","class Rule: self.is_exception = False def match(self, url, netloc, domain, origin=None): if self.options and not self.options.can_apply_rule(netloc, origin): return False return True ","class Rule: self.is_exception = False def match(self, url, netloc, domain, origin=None): if self.options and not self.options.can_apply_rule(domain, origin): return False return True " 2026,https://:@github.com/mbkupfer/bls-datasets.git,3ffd9be073ca6ed9591d1633c1b4ef15b6e32c24,"@@ -151,7 +151,7 @@ def get_data(year=CUR_YEAR, cut_by='national', area_focus=None, if filename == None: raise ValueError('""{}"" is not a valid area focus\n' \ 'valid options include:\n{}' \ - .format(cut_by, ['metros', 'metros-divisions', 'non-metros'])) + .format(area_focus, ['metros', 'metros-divisions', 'non-metros'])) else: filename = OES_FILENAMES.get(cut_by) ",bls_datasets/oes.py,"ReplaceText(target='area_focus' @(154,24)->(154,30))","def get_data(year=CUR_YEAR, cut_by='national', area_focus=None, if filename == None: raise ValueError('""{}"" is not a valid area focus\n' \ 'valid options include:\n{}' \ .format(cut_by, ['metros', 'metros-divisions', 'non-metros'])) else: filename = OES_FILENAMES.get(cut_by) ","def get_data(year=CUR_YEAR, cut_by='national', area_focus=None, if filename == None: raise ValueError('""{}"" is not a valid area focus\n' \ 'valid options include:\n{}' \ .format(area_focus, ['metros', 'metros-divisions', 'non-metros'])) else: filename = OES_FILENAMES.get(cut_by) " 2027,https://:@github.com/krrr/wstan.git,52b8e527af3bbaeadc25c796a960bd46b573f63e,"@@ -24,7 +24,7 @@ def _get_digest(dat): def _on_pushToTunTaskDone(task): # suppress annoying ""CancelledError exception not retrieved"" error on Py3.5+ try: - if not isinstance(task.exception(), CancelledError): + if isinstance(task.exception(), CancelledError): logging.error(""pushToTunTask exception: %s"" % type(task.exception())) except CancelledError: # doc says it will raise this if canceled, but... pass ",wstan/relay.py,"ReplaceText(target='' @(27,11)->(27,15))","def _get_digest(dat): def _on_pushToTunTaskDone(task): # suppress annoying ""CancelledError exception not retrieved"" error on Py3.5+ try: if not isinstance(task.exception(), CancelledError): logging.error(""pushToTunTask exception: %s"" % type(task.exception())) except CancelledError: # doc says it will raise this if canceled, but... pass","def _get_digest(dat): def _on_pushToTunTaskDone(task): # suppress annoying ""CancelledError exception not retrieved"" error on Py3.5+ try: if isinstance(task.exception(), CancelledError): logging.error(""pushToTunTask exception: %s"" % type(task.exception())) except CancelledError: # doc says it will raise this if canceled, but... pass" 2028,https://:@github.com/rmarkello/snfpy.git,c777b0fb8b2ddb88f3a2ddd97b6d7bacc6e82055,"@@ -408,7 +408,7 @@ def group_predict(train, test, labels, *, K=20, mu=0.4, t=20): # generate affinity matrices for stacked train/test data sets affinities = [] for (tr, te) in zip(train, test): - if len(tr.T) == len(te.T): + if len(tr.T) != len(te.T): raise ValueError('Train and test data must have same number of ' 'features for each data type. Make sure to ' 'supply data types in the same order.') ",snf/compute.py,"ReplaceText(target='!=' @(411,21)->(411,23))","def group_predict(train, test, labels, *, K=20, mu=0.4, t=20): # generate affinity matrices for stacked train/test data sets affinities = [] for (tr, te) in zip(train, test): if len(tr.T) == len(te.T): raise ValueError('Train and test data must have same number of ' 'features for each data type. Make sure to ' 'supply data types in the same order.')","def group_predict(train, test, labels, *, K=20, mu=0.4, t=20): # generate affinity matrices for stacked train/test data sets affinities = [] for (tr, te) in zip(train, test): if len(tr.T) != len(te.T): raise ValueError('Train and test data must have same number of ' 'features for each data type. Make sure to ' 'supply data types in the same order.')" 2029,https://:@github.com/PartnershipOnAI/safelife.git,be6c06c82569bde428c986399d8fa3fe159deb26,"@@ -283,7 +283,7 @@ class SafeLifeLogger(BaseLogger): log_data['level_name'] = game.title log_data['length'] = length.tolist() log_data['reward'] = reward.tolist() - log_data['completed'] = reward.tolist() + log_data['completed'] = completed.tolist() log_data['reward_possible'] = reward_possible.tolist() log_data['reward_needed'] = required_points.tolist() log_data['time'] = datetime.utcnow().isoformat() ",safelife/safelife_logger.py,"ReplaceText(target='completed' @(286,32)->(286,38))","class SafeLifeLogger(BaseLogger): log_data['level_name'] = game.title log_data['length'] = length.tolist() log_data['reward'] = reward.tolist() log_data['completed'] = reward.tolist() log_data['reward_possible'] = reward_possible.tolist() log_data['reward_needed'] = required_points.tolist() log_data['time'] = datetime.utcnow().isoformat()","class SafeLifeLogger(BaseLogger): log_data['level_name'] = game.title log_data['length'] = length.tolist() log_data['reward'] = reward.tolist() log_data['completed'] = completed.tolist() log_data['reward_possible'] = reward_possible.tolist() log_data['reward_needed'] = required_points.tolist() log_data['time'] = datetime.utcnow().isoformat()" 2030,https://:@github.com/PartnershipOnAI/safelife.git,5c9ddd2bb0d304bb159c5b452ce028e515c7c4cc,"@@ -745,7 +745,7 @@ def _summarize_run(logfile, wandb_run=None, artifact=None): """""")) - if wandb_run is not None and bare_name == 'benchmark-data': + if wandb_run is not None and file_name == 'benchmark-data': wandb_run.summary['success'] = np.average(success) wandb_run.summary['avg_length'] = np.average(length) wandb_run.summary['side_effects'] = np.average(side_effects) ",safelife/safelife_logger.py,"ReplaceText(target='file_name' @(748,33)->(748,42))","def _summarize_run(logfile, wandb_run=None, artifact=None): """""")) if wandb_run is not None and bare_name == 'benchmark-data': wandb_run.summary['success'] = np.average(success) wandb_run.summary['avg_length'] = np.average(length) wandb_run.summary['side_effects'] = np.average(side_effects)","def _summarize_run(logfile, wandb_run=None, artifact=None): """""")) if wandb_run is not None and file_name == 'benchmark-data': wandb_run.summary['success'] = np.average(success) wandb_run.summary['avg_length'] = np.average(length) wandb_run.summary['side_effects'] = np.average(side_effects)" 2031,https://:@github.com/rymurr/dremio_client.git,3119593dbb6db992a34b7008130a16ff4717aa0d,"@@ -410,7 +410,7 @@ def delete_catalog(args, cid, path): warning, this process is destructive and permanent """""" base_url, token, verify = get_base_url_token(args) - x = _delete_catalog(token, base_url, verify, cid, path) + x = _delete_catalog(base_url, token, verify, cid, path) click.echo(json.dumps(x)) ",dremio_client/cli.py,"ArgSwap(idxs=0<->1 @(413,8)->(413,23))","def delete_catalog(args, cid, path): warning, this process is destructive and permanent """""" base_url, token, verify = get_base_url_token(args) x = _delete_catalog(token, base_url, verify, cid, path) click.echo(json.dumps(x)) ","def delete_catalog(args, cid, path): warning, this process is destructive and permanent """""" base_url, token, verify = get_base_url_token(args) x = _delete_catalog(base_url, token, verify, cid, path) click.echo(json.dumps(x)) " 2032,https://:@github.com/kubostech/kubos-cli.git,128e898be2aa04eb1e7b60203dd348122dc2c9b9,"@@ -83,7 +83,7 @@ def main(): 'all dependencies, run:\n yotta build all_tests\n\n', 'Build the current module.' ) - add_yotta_command('link', 'link', + add_kubos_command('link', 'link', 'Symlink a module to be used into another module.\n\n'+ 'Use: ""yotta link"" in a module to link it globally, then use ""yotta '+ 'link "" to link it into the module where you want to use '+ ",kubos/main.py,"ReplaceText(target='add_kubos_command' @(86,4)->(86,21))","def main(): 'all dependencies, run:\n yotta build all_tests\n\n', 'Build the current module.' ) add_yotta_command('link', 'link', 'Symlink a module to be used into another module.\n\n'+ 'Use: ""yotta link"" in a module to link it globally, then use ""yotta '+ 'link "" to link it into the module where you want to use '+","def main(): 'all dependencies, run:\n yotta build all_tests\n\n', 'Build the current module.' ) add_kubos_command('link', 'link', 'Symlink a module to be used into another module.\n\n'+ 'Use: ""yotta link"" in a module to link it globally, then use ""yotta '+ 'link "" to link it into the module where you want to use '+" 2033,https://:@github.com/bsdphk/PyReveng3.git,cdd2a273a00c008999a6b38f75f6c33e029c3c7e,"@@ -489,7 +489,7 @@ class vector(data.Data): super().__init__(asp, adr, adr + 4) self.ws = asp.bu16(adr) self.dstadr = asp.bu16(adr + 2) - cx.disass(asp, self.dstadr) + cx.disass(self.dstadr, asp) def render(self): return ""WP=0x%04x,IP=%s"" % (self.ws, self.aspace.adr(self.dstadr)) ",pyreveng/cpu/tms9900.py,"ArgSwap(idxs=0<->1 @(492,8)->(492,17))","class vector(data.Data): super().__init__(asp, adr, adr + 4) self.ws = asp.bu16(adr) self.dstadr = asp.bu16(adr + 2) cx.disass(asp, self.dstadr) def render(self): return ""WP=0x%04x,IP=%s"" % (self.ws, self.aspace.adr(self.dstadr))","class vector(data.Data): super().__init__(asp, adr, adr + 4) self.ws = asp.bu16(adr) self.dstadr = asp.bu16(adr + 2) cx.disass(self.dstadr, asp) def render(self): return ""WP=0x%04x,IP=%s"" % (self.ws, self.aspace.adr(self.dstadr))" 2034,https://:@github.com/ehickox2012/bitraider.git,0499f84ed9c06dfc72ef604cffe0dd5105c34a13,"@@ -67,7 +67,7 @@ class strategy(object): print(""Times sold: ""+str(self.exchange.times_sold)) print(""The Market's performance: ""+str(market_performance)+"" %"") print(""Strategy's performance: ""+str(strategy_performance)+"" %"") - print(""Account's ending value if no trades were made: ""+str(start_amt)+"" BTC"") + print(""Account's ending value if no trades were made: ""+str(end_amt_no_trades)+"" BTC"") print(""Account's ending value with this strategy: ""+str(end_amt)+"" BTC"") strategy_performance_vs_market = strategy_performance - market_performance if strategy_performance > market_performance: ",bitraider/strategy.py,"ReplaceText(target='end_amt_no_trades' @(70,68)->(70,77))","class strategy(object): print(""Times sold: ""+str(self.exchange.times_sold)) print(""The Market's performance: ""+str(market_performance)+"" %"") print(""Strategy's performance: ""+str(strategy_performance)+"" %"") print(""Account's ending value if no trades were made: ""+str(start_amt)+"" BTC"") print(""Account's ending value with this strategy: ""+str(end_amt)+"" BTC"") strategy_performance_vs_market = strategy_performance - market_performance if strategy_performance > market_performance:","class strategy(object): print(""Times sold: ""+str(self.exchange.times_sold)) print(""The Market's performance: ""+str(market_performance)+"" %"") print(""Strategy's performance: ""+str(strategy_performance)+"" %"") print(""Account's ending value if no trades were made: ""+str(end_amt_no_trades)+"" BTC"") print(""Account's ending value with this strategy: ""+str(end_amt)+"" BTC"") strategy_performance_vs_market = strategy_performance - market_performance if strategy_performance > market_performance:" 2035,https://:@github.com/Yatoom/Optimus.git,f33e600b5e873e08cedb864d1c4fb3ecf07e9d93,"@@ -98,7 +98,7 @@ def decode_params(params, prefix=""!"", remove_prefixes=True): # Make a copy params_copy = copy(params) - for key in params_copy: + for key in params: # Check if key starts with prefix if key[0:len(prefix)] == prefix: ",vault/decoder.py,"ReplaceText(target='params' @(101,15)->(101,26))","def decode_params(params, prefix=""!"", remove_prefixes=True): # Make a copy params_copy = copy(params) for key in params_copy: # Check if key starts with prefix if key[0:len(prefix)] == prefix:","def decode_params(params, prefix=""!"", remove_prefixes=True): # Make a copy params_copy = copy(params) for key in params: # Check if key starts with prefix if key[0:len(prefix)] == prefix:" 2036,https://:@github.com/Yatoom/Optimus.git,6c1faf98462d128189e4e52dfe50d585311dec12,"@@ -113,7 +113,7 @@ class Benchmark: for i in range(0, len(results[""best_score""])): iteration = { ""task"": self.task_id, - ""method"": ""{} (EI: {}, RT: {})"".format(method.name, time_regressor, score_regressor), + ""method"": ""{} (EI: {}, RT: {})"".format(method.name, score_regressor, time_regressor), ""iteration"": i, ""score"": results[""mean_test_score""][i], ""best_score"": results[""best_score""][i], ",benchmarks/benchmark.py,"ArgSwap(idxs=1<->2 @(116,26)->(116,54))","class Benchmark: for i in range(0, len(results[""best_score""])): iteration = { ""task"": self.task_id, ""method"": ""{} (EI: {}, RT: {})"".format(method.name, time_regressor, score_regressor), ""iteration"": i, ""score"": results[""mean_test_score""][i], ""best_score"": results[""best_score""][i],","class Benchmark: for i in range(0, len(results[""best_score""])): iteration = { ""task"": self.task_id, ""method"": ""{} (EI: {}, RT: {})"".format(method.name, score_regressor, time_regressor), ""iteration"": i, ""score"": results[""mean_test_score""][i], ""best_score"": results[""best_score""][i]," 2037,https://:@github.com/nicholasturner1/Synaptor.git,661e148c09be514e874af3c5a2f2c2a6a401b1ba,"@@ -23,7 +23,7 @@ def main(psd_cvname, cc_cvname, proc_dir_path, #Processing - dil_ccs = s.dilated_components(psd_output, cc_thresh, dil_param) + dil_ccs = s.dilated_components(psd_output, dil_param, cc_thresh) continuations = s.extract_continuations(dil_ccs) cont_ids = set(cont.segid for cont in continuations) ",tasks/chunk_ccs.py,"ArgSwap(idxs=1<->2 @(26,14)->(26,34))","def main(psd_cvname, cc_cvname, proc_dir_path, #Processing dil_ccs = s.dilated_components(psd_output, cc_thresh, dil_param) continuations = s.extract_continuations(dil_ccs) cont_ids = set(cont.segid for cont in continuations)","def main(psd_cvname, cc_cvname, proc_dir_path, #Processing dil_ccs = s.dilated_components(psd_output, dil_param, cc_thresh) continuations = s.extract_continuations(dil_ccs) cont_ids = set(cont.segid for cont in continuations)" 2038,https://:@github.com/nicholasturner1/Synaptor.git,8f529876b19ee670791f5860b9808f7ce12f2528,"@@ -31,7 +31,7 @@ def read_network(proc_dir_path): local_model = io.pull_file(model_fname) local_chkpt = io.pull_file(chkpt_fname) - model = imp.load_source(""Model"",model_fname).InstantiatedModel + model = imp.load_source(""Model"",local_model).InstantiatedModel model.load_state_dict(torch.load(local_chkpt)) return model ",synaptor/edges/io.py,"ReplaceText(target='local_model' @(34,36)->(34,47))","def read_network(proc_dir_path): local_model = io.pull_file(model_fname) local_chkpt = io.pull_file(chkpt_fname) model = imp.load_source(""Model"",model_fname).InstantiatedModel model.load_state_dict(torch.load(local_chkpt)) return model","def read_network(proc_dir_path): local_model = io.pull_file(model_fname) local_chkpt = io.pull_file(chkpt_fname) model = imp.load_source(""Model"",local_model).InstantiatedModel model.load_state_dict(torch.load(local_chkpt)) return model" 2039,https://:@github.com/metrasynth/radiant-voices.git,b472a30772349e0f274629a4a516ded96cd80567,"@@ -121,4 +121,4 @@ class Module(object, metaclass=ModuleMeta): def load_options(self, chunk): for i, name in enumerate(self.options.keys()): value = chunk.chdt[i] - setattr(self, name, i) + setattr(self, name, value) ",rv/modules/module.py,"ReplaceText(target='value' @(124,32)->(124,33))","class Module(object, metaclass=ModuleMeta): def load_options(self, chunk): for i, name in enumerate(self.options.keys()): value = chunk.chdt[i] setattr(self, name, i)","class Module(object, metaclass=ModuleMeta): def load_options(self, chunk): for i, name in enumerate(self.options.keys()): value = chunk.chdt[i] setattr(self, name, value)" 2040,https://:@github.com/Lursun/p2p_grpc_blockchain_package.git,964fada4f1d9b0c065c327d9f190c5310f9d8f37,"@@ -82,6 +82,6 @@ class Transaction(): print (""=> unixtime:%s\tbody:%s"" % (pb2tx.unixtime,pb2tx.body)) tx=Transaction() tx.pb2=pb2tx - Transaction.Transactions[tx.pb2.txhash]=pb2tx + Transaction.Transactions[tx.pb2.txhash]=tx threading.Thread(target=Transaction.sync).start() \ No newline at end of file ",p2p_grpc_blockchain/transaction/transaction.py,"ReplaceText(target='tx' @(85,48)->(85,53))","class Transaction(): print (""=> unixtime:%s\tbody:%s"" % (pb2tx.unixtime,pb2tx.body)) tx=Transaction() tx.pb2=pb2tx Transaction.Transactions[tx.pb2.txhash]=pb2tx threading.Thread(target=Transaction.sync).start() \ No newline at end of file","class Transaction(): print (""=> unixtime:%s\tbody:%s"" % (pb2tx.unixtime,pb2tx.body)) tx=Transaction() tx.pb2=pb2tx Transaction.Transactions[tx.pb2.txhash]=tx threading.Thread(target=Transaction.sync).start() \ No newline at end of file" 2041,https://:@github.com/wbsoft/livelex.git,928383697438c2c14ec530eeec25eb00422ff70f,"@@ -899,7 +899,7 @@ class TreeDocumentMixin: def contents_changed(self, start, removed, added): """"""Called after modification of the text, retokenizes the modified part."""""" if self._tree.lexicon: - start, end = self._builder().rebuild(self._tree, self.text(), start, added, removed) + start, end = self._builder().rebuild(self._tree, self.text(), start, removed, added) else: end = start + added self.set_modified_range(start, end) ",livelex/tree.py,"ArgSwap(idxs=3<->4 @(902,25)->(902,48))","class TreeDocumentMixin: def contents_changed(self, start, removed, added): """"""Called after modification of the text, retokenizes the modified part."""""" if self._tree.lexicon: start, end = self._builder().rebuild(self._tree, self.text(), start, added, removed) else: end = start + added self.set_modified_range(start, end)","class TreeDocumentMixin: def contents_changed(self, start, removed, added): """"""Called after modification of the text, retokenizes the modified part."""""" if self._tree.lexicon: start, end = self._builder().rebuild(self._tree, self.text(), start, removed, added) else: end = start + added self.set_modified_range(start, end)" 2042,https://:@github.com/griffithlab/civicpy.git,13f1945d0fcbb4e1bbf9fcc555710edab4ff4f71,"@@ -99,7 +99,7 @@ class CivicRecord: try: data['type'] = data.get('type', singularize(field)) except AttributeError: # if data has no 'get' method, i.e. not a Dict - result.append(v) + result.append(data) else: result.append(cls(partial=True, **data)) self.__setattr__(field, result) ",pycivic/civic.py,"ReplaceText(target='data' @(102,38)->(102,39))","class CivicRecord: try: data['type'] = data.get('type', singularize(field)) except AttributeError: # if data has no 'get' method, i.e. not a Dict result.append(v) else: result.append(cls(partial=True, **data)) self.__setattr__(field, result)","class CivicRecord: try: data['type'] = data.get('type', singularize(field)) except AttributeError: # if data has no 'get' method, i.e. not a Dict result.append(data) else: result.append(cls(partial=True, **data)) self.__setattr__(field, result)" 2043,https://:@github.com/JoeriHermans/dist-keras.git,7b9f4110efd7470daa8e1ad9e93ab92fc3c135ea,"@@ -63,7 +63,7 @@ class LabelVectorTransformerUDF(Transformer): v = to_dense_vector(label, self.output_dim) new_row = new_dataframe_row_fast(row, self.output_column, v) - return row + return new_row def transform(self, data): return data.map(self._transform).toDF() ",distkeras/distributed.py,"ReplaceText(target='new_row' @(66,15)->(66,18))","class LabelVectorTransformerUDF(Transformer): v = to_dense_vector(label, self.output_dim) new_row = new_dataframe_row_fast(row, self.output_column, v) return row def transform(self, data): return data.map(self._transform).toDF()","class LabelVectorTransformerUDF(Transformer): v = to_dense_vector(label, self.output_dim) new_row = new_dataframe_row_fast(row, self.output_column, v) return new_row def transform(self, data): return data.map(self._transform).toDF()" 2044,https://:@github.com/JoeriHermans/dist-keras.git,b2c8dee25e9687403108fbeb31efc2b309a51675,"@@ -158,7 +158,7 @@ class AsynchronousDistributedTrainer(DistributedTrainer): def __init__(self, keras_model, worker_optimizer, loss, num_workers=2, batch_size=32, features_col=""features"", label_col=""label"", num_epoch=1): - super(AsynchronousDistributedTrainer, self).__init__(keras_model, loss, worker_optimizer, + super(AsynchronousDistributedTrainer, self).__init__(keras_model, worker_optimizer, loss, num_workers, batch_size, features_col, label_col, num_epoch) # Initialize asynchronous methods variables. ",distkeras/trainers.py,"ArgSwap(idxs=1<->2 @(161,8)->(161,60))","class AsynchronousDistributedTrainer(DistributedTrainer): def __init__(self, keras_model, worker_optimizer, loss, num_workers=2, batch_size=32, features_col=""features"", label_col=""label"", num_epoch=1): super(AsynchronousDistributedTrainer, self).__init__(keras_model, loss, worker_optimizer, num_workers, batch_size, features_col, label_col, num_epoch) # Initialize asynchronous methods variables.","class AsynchronousDistributedTrainer(DistributedTrainer): def __init__(self, keras_model, worker_optimizer, loss, num_workers=2, batch_size=32, features_col=""features"", label_col=""label"", num_epoch=1): super(AsynchronousDistributedTrainer, self).__init__(keras_model, worker_optimizer, loss, num_workers, batch_size, features_col, label_col, num_epoch) # Initialize asynchronous methods variables." 2045,https://:@github.com/JoeriHermans/dist-keras.git,325770acaebbd0a6f05603d1d277d1a7c6d7b0c4,"@@ -385,7 +385,7 @@ class ExperimentalParameterServer(SocketParameterServer): data = recv_data(conn) # Extract the data from the dictionary. r = data['residual'] - worker_id = r['worker_id'] + worker_id = data['worker_id'] with self.mutex: self.add_staleness(worker_id) # Update the center variable. ",distkeras/parameter_servers.py,"ReplaceText(target='data' @(388,20)->(388,21))","class ExperimentalParameterServer(SocketParameterServer): data = recv_data(conn) # Extract the data from the dictionary. r = data['residual'] worker_id = r['worker_id'] with self.mutex: self.add_staleness(worker_id) # Update the center variable.","class ExperimentalParameterServer(SocketParameterServer): data = recv_data(conn) # Extract the data from the dictionary. r = data['residual'] worker_id = data['worker_id'] with self.mutex: self.add_staleness(worker_id) # Update the center variable." 2046,https://:@github.com/K1DV5/ScpyCalc.git,a4f2b442c7db6ed936811d4fea74854dc03ceb4a,"@@ -306,7 +306,7 @@ class MathVisitor(ast.NodeVisitor): return to_math(tree, mul=self.mul, div=self.div, mat_size=self.mat_size, decimal=self.decimal, syntax=self.s, ital=self.ital) - if not self.subs and not shallow: + if not self.subs or not shallow: return self.format_name(n.id) # substitute the value of the variable by formatted value try: ",docal/parsing.py,"ReplaceText(target='or' @(309,25)->(309,28))","class MathVisitor(ast.NodeVisitor): return to_math(tree, mul=self.mul, div=self.div, mat_size=self.mat_size, decimal=self.decimal, syntax=self.s, ital=self.ital) if not self.subs and not shallow: return self.format_name(n.id) # substitute the value of the variable by formatted value try:","class MathVisitor(ast.NodeVisitor): return to_math(tree, mul=self.mul, div=self.div, mat_size=self.mat_size, decimal=self.decimal, syntax=self.s, ital=self.ital) if not self.subs or not shallow: return self.format_name(n.id) # substitute the value of the variable by formatted value try:" 2047,https://:@github.com/kylebittinger/unassigner.git,20c134aeafa34ed6c626677064c0b67183f812a4,"@@ -61,7 +61,7 @@ def blastdb_fps(fp): def get_url(url): fp = url_fp(url) - if not os.path.exists(fp): + if os.path.exists(fp): os.remove(fp) subprocess.check_call([""wget"", url]) return fp ",unassign/download.py,"ReplaceText(target='' @(64,7)->(64,11))","def blastdb_fps(fp): def get_url(url): fp = url_fp(url) if not os.path.exists(fp): os.remove(fp) subprocess.check_call([""wget"", url]) return fp","def blastdb_fps(fp): def get_url(url): fp = url_fp(url) if os.path.exists(fp): os.remove(fp) subprocess.check_call([""wget"", url]) return fp" 2048,https://:@github.com/AFM-analysis/PyJibe.git,9946f6261a7ea6bbf7309e077788cafd3f6ba7e6,"@@ -57,7 +57,7 @@ class PyJibe(QtWidgets.QMainWindow, MainBase): # Add export choices if hasattr(inst, ""get_export_choices""): choices = inst.get_export_choices() - menobj = self.menuExport.addMenu(inst.windowTitle()) + menobj = self.menuExport.addMenu(sub.windowTitle()) for choice in choices: action = menobj.addAction(choice[0]) action.triggered.connect(getattr(inst, choice[1])) ",pyjibe/head/main.py,"ReplaceText(target='sub' @(60,45)->(60,49))","class PyJibe(QtWidgets.QMainWindow, MainBase): # Add export choices if hasattr(inst, ""get_export_choices""): choices = inst.get_export_choices() menobj = self.menuExport.addMenu(inst.windowTitle()) for choice in choices: action = menobj.addAction(choice[0]) action.triggered.connect(getattr(inst, choice[1]))","class PyJibe(QtWidgets.QMainWindow, MainBase): # Add export choices if hasattr(inst, ""get_export_choices""): choices = inst.get_export_choices() menobj = self.menuExport.addMenu(sub.windowTitle()) for choice in choices: action = menobj.addAction(choice[0]) action.triggered.connect(getattr(inst, choice[1]))" 2049,https://:@gitlab.com/petra-sim/petra.git,dda7d9769193fbcf1419f7f55353819a805193e6,"@@ -107,7 +107,7 @@ def create_mesh(structure, path): for element in structure.elements]) min_size = 1 * c.nm - with geo.Geo(points_geo) as g: + with geo.Geo(mesh_geo) as g: g.include(""structure.geo"") g.include(""points.geo"") g.attractor(1, geo.range(idx0, idx)) ",transport/poisson/geometry.py,"ReplaceText(target='mesh_geo' @(110,17)->(110,27))","def create_mesh(structure, path): for element in structure.elements]) min_size = 1 * c.nm with geo.Geo(points_geo) as g: g.include(""structure.geo"") g.include(""points.geo"") g.attractor(1, geo.range(idx0, idx))","def create_mesh(structure, path): for element in structure.elements]) min_size = 1 * c.nm with geo.Geo(mesh_geo) as g: g.include(""structure.geo"") g.include(""points.geo"") g.attractor(1, geo.range(idx0, idx))" 2050,https://:@github.com/robertbuecker/diffractem.git,9eb32dde6f3998ccdf27c5c5a64cd0a6b62f3415,"@@ -588,7 +588,7 @@ def lorentz_fast(img, x_0: float = None, y_0: float = None, amp: float = None, """""" if (x_0 is None) or (not np.isfinite(x_0)): x_0 = img.shape[1] / 2 - if (y_0 is None) or (not np.isfinite(x_0)): + if (y_0 is None) or (not np.isfinite(y_0)): y_0 = img.shape[0] / 2 if radius is not None: x1 = int(x_0 - radius) ",diffractem/proc2d.py,"ReplaceText(target='y_0' @(591,41)->(591,44))","def lorentz_fast(img, x_0: float = None, y_0: float = None, amp: float = None, """""" if (x_0 is None) or (not np.isfinite(x_0)): x_0 = img.shape[1] / 2 if (y_0 is None) or (not np.isfinite(x_0)): y_0 = img.shape[0] / 2 if radius is not None: x1 = int(x_0 - radius)","def lorentz_fast(img, x_0: float = None, y_0: float = None, amp: float = None, """""" if (x_0 is None) or (not np.isfinite(x_0)): x_0 = img.shape[1] / 2 if (y_0 is None) or (not np.isfinite(y_0)): y_0 = img.shape[0] / 2 if radius is not None: x1 = int(x_0 - radius)" 2051,https://:@github.com/kikuchi-m/ceryle.git,03f69077698b989fa1fb344d3fb1a29a7e2e10dc,"@@ -165,7 +165,7 @@ def main(argv): }[args.pop('log_level')], console=args.pop('log_stream'), filename=args.pop('log_filename')) - logger.debug(f'arguments: {argv}') + logger.debug(f'arguments: {args}') try: if args.pop('list_tasks', False): ",ceryle/main.py,"ReplaceText(target='args' @(168,31)->(168,35))","def main(argv): }[args.pop('log_level')], console=args.pop('log_stream'), filename=args.pop('log_filename')) logger.debug(f'arguments: {argv}') try: if args.pop('list_tasks', False):","def main(argv): }[args.pop('log_level')], console=args.pop('log_stream'), filename=args.pop('log_filename')) logger.debug(f'arguments: {args}') try: if args.pop('list_tasks', False):" 2052,https://:@github.com/persepolisdm/persepolis.git,3765f351be8734881e5556f75e7f4fdba8991f82,"@@ -38,7 +38,7 @@ class Tor: def check_tor(self): """""" True If Tor Is Installed """""" - return (self.tor is None) + return (self.tor is not None) def socks_tor(self): """""" Checks If Socks Proxy Is Configured For Tor """""" ",persepolis/scripts/check_proxy.py,"ReplaceText(target=' is not ' @(41,24)->(41,28))","class Tor: def check_tor(self): """""" True If Tor Is Installed """""" return (self.tor is None) def socks_tor(self): """""" Checks If Socks Proxy Is Configured For Tor """"""","class Tor: def check_tor(self): """""" True If Tor Is Installed """""" return (self.tor is not None) def socks_tor(self): """""" Checks If Socks Proxy Is Configured For Tor """"""" 2053,https://:@github.com/persepolisdm/persepolis.git,11559164cbc09d141949b464e4d5ec7ea07ec016,"@@ -103,7 +103,7 @@ def spider(add_link_dictionary): file_size = humanReadbleSize(file_size) # return results - return filename, filesize + return filename, file_size # this function finds and returns file name for links. ",persepolis/scripts/spider.py,"ReplaceText(target='file_size' @(106,21)->(106,29))","def spider(add_link_dictionary): file_size = humanReadbleSize(file_size) # return results return filename, filesize # this function finds and returns file name for links.","def spider(add_link_dictionary): file_size = humanReadbleSize(file_size) # return results return filename, file_size # this function finds and returns file name for links." 2054,https://:@gitlab.com/sumner/sublime-music.git,fab385a778c4486043bc069ce46accac6f0cffa7,"@@ -159,7 +159,7 @@ class PlayerControls(Gtk.ActionBar): self.album_art.set_loading(False) def update_scrubber(self, current, duration): - if current is None and duration is None: + if current is None or duration is None: self.song_duration_label.set_text('-:--') self.song_progress_label.set_text('-:--') self.song_scrubber.set_value(0) ",libremsonic/ui/player_controls.py,"ReplaceText(target='or' @(162,27)->(162,30))","class PlayerControls(Gtk.ActionBar): self.album_art.set_loading(False) def update_scrubber(self, current, duration): if current is None and duration is None: self.song_duration_label.set_text('-:--') self.song_progress_label.set_text('-:--') self.song_scrubber.set_value(0)","class PlayerControls(Gtk.ActionBar): self.album_art.set_loading(False) def update_scrubber(self, current, duration): if current is None or duration is None: self.song_duration_label.set_text('-:--') self.song_progress_label.set_text('-:--') self.song_scrubber.set_value(0)" 2055,https://:@github.com/INM-6/hybridLFPy.git,e165d8eb36122f4647297989e4da50c25e445c5f,"@@ -48,7 +48,7 @@ if __name__ == '__main__': fname = os.path.join(jobscriptdir, job + '.job') f = open(fname, 'w') - f.write(content.format(job, stime, oe, oe, ntasks, memPerCPU, mpiexec, sim)) + f.write(content.format(job, stime, oe, oe, memPerCPU, ntasks, mpiexec, sim)) f.close() jobscripts.append(fname) ",examples/Hagen_et_al_2016_cercor/run_all_jobs.py,"ArgSwap(idxs=4<->5 @(51,16)->(51,30))","if __name__ == '__main__': fname = os.path.join(jobscriptdir, job + '.job') f = open(fname, 'w') f.write(content.format(job, stime, oe, oe, ntasks, memPerCPU, mpiexec, sim)) f.close() jobscripts.append(fname)","if __name__ == '__main__': fname = os.path.join(jobscriptdir, job + '.job') f = open(fname, 'w') f.write(content.format(job, stime, oe, oe, memPerCPU, ntasks, mpiexec, sim)) f.close() jobscripts.append(fname)" 2056,https://:@github.com/tgalal/microbus.git,ad908781df4151ae453e0d832fe6324d470363d7,"@@ -13,7 +13,7 @@ class BusSchedulerTest(unittest.TestCase): self.stop2 = microbus.BusStop(""stop2"") self.stop3 = microbus.BusStop(""stop3"") self.stops = [self.stop1, self.stop2, self.stop3] - self.busRoute1 = microbus.BusRoute(""test"", self.stops) + self.busRoute1 = microbus.BusRoute(self.stops, ""test"") self.busRoute2 = self.busRoute1[::-1] self.bus = Bus(keep_prev=2) self.scheduler = BusScheduler(self.bus) ",microbus/test_scheduler.py,"ArgSwap(idxs=0<->1 @(16,25)->(16,42))","class BusSchedulerTest(unittest.TestCase): self.stop2 = microbus.BusStop(""stop2"") self.stop3 = microbus.BusStop(""stop3"") self.stops = [self.stop1, self.stop2, self.stop3] self.busRoute1 = microbus.BusRoute(""test"", self.stops) self.busRoute2 = self.busRoute1[::-1] self.bus = Bus(keep_prev=2) self.scheduler = BusScheduler(self.bus)","class BusSchedulerTest(unittest.TestCase): self.stop2 = microbus.BusStop(""stop2"") self.stop3 = microbus.BusStop(""stop3"") self.stops = [self.stop1, self.stop2, self.stop3] self.busRoute1 = microbus.BusRoute(self.stops, ""test"") self.busRoute2 = self.busRoute1[::-1] self.bus = Bus(keep_prev=2) self.scheduler = BusScheduler(self.bus)" 2057,https://:@github.com/nanvel/c2p2.git,554470ca3827bf276f15159434de4996a65bc130,"@@ -64,6 +64,6 @@ class GitHubPullHandler(RequestHandler): if event == 'push': ref = json.loads(self.request.body.decode('utf8'))['ref'] - if ref != 'refs/heads/{branch}'.format(branch=options.GITHUB_BRANCH): + if ref == 'refs/heads/{branch}'.format(branch=options.GITHUB_BRANCH): result = yield github_pull() logger.warning(result) ",mdpages/handlers/github.py,"ReplaceText(target='==' @(67,19)->(67,21))","class GitHubPullHandler(RequestHandler): if event == 'push': ref = json.loads(self.request.body.decode('utf8'))['ref'] if ref != 'refs/heads/{branch}'.format(branch=options.GITHUB_BRANCH): result = yield github_pull() logger.warning(result)","class GitHubPullHandler(RequestHandler): if event == 'push': ref = json.loads(self.request.body.decode('utf8'))['ref'] if ref == 'refs/heads/{branch}'.format(branch=options.GITHUB_BRANCH): result = yield github_pull() logger.warning(result)" 2058,https://:@github.com/caleblareau/bap.git,063364d986c20b9eeca8072b763feead8573038e,"@@ -68,7 +68,7 @@ class bapProject(): self.minimum_cell_fragments = minimum_cell_fragments self.minimum_jaccard_fragments = minimum_jaccard_fragments self.extract_mito = extract_mito - self.drop_tag = barcode_tag + self.drop_tag = drop_tag self.barcode_tag = barcode_tag # Figure out operating system just for funzies; not presently used ",bap/bapProjectClass.py,"ReplaceText(target='drop_tag' @(71,18)->(71,29))","class bapProject(): self.minimum_cell_fragments = minimum_cell_fragments self.minimum_jaccard_fragments = minimum_jaccard_fragments self.extract_mito = extract_mito self.drop_tag = barcode_tag self.barcode_tag = barcode_tag # Figure out operating system just for funzies; not presently used","class bapProject(): self.minimum_cell_fragments = minimum_cell_fragments self.minimum_jaccard_fragments = minimum_jaccard_fragments self.extract_mito = extract_mito self.drop_tag = drop_tag self.barcode_tag = barcode_tag # Figure out operating system just for funzies; not presently used" 2059,https://:@github.com/skblaz/tax2vec.git,722d18184211d2f1e4934cdac4464be2a37de869,"@@ -370,7 +370,7 @@ class tax2vec: if out is not None: hypernyms.extend(out) - for h in hypernyms: + for h in out: local_graph.append((str(token), h)) return initial_terms, idx, hypernyms, local_graph ",tax2vec/__init__.py,"ReplaceText(target='out' @(373,29)->(373,38))","class tax2vec: if out is not None: hypernyms.extend(out) for h in hypernyms: local_graph.append((str(token), h)) return initial_terms, idx, hypernyms, local_graph","class tax2vec: if out is not None: hypernyms.extend(out) for h in out: local_graph.append((str(token), h)) return initial_terms, idx, hypernyms, local_graph" 2060,https://:@github.com/apertif/apercal.git,e0a3e59de9c906da7bd7b22b99e0eed7a75b4b05,"@@ -144,7 +144,7 @@ def run_casa(cmd, raise_on_severe=False, timeout=1800): casa = drivecasa.Casapy() try: casa_output, casa_error = casa.run_script(cmd, raise_on_severe=True, timeout=timeout) - logger.debug('\n'.join(casa_output)) + logger.debug('\n'.join(casa_error)) except RuntimeError: logger.error(""Casa command failed"") if raise_on_severe: ",apercal/libs/lib.py,"ReplaceText(target='casa_error' @(147,31)->(147,42))","def run_casa(cmd, raise_on_severe=False, timeout=1800): casa = drivecasa.Casapy() try: casa_output, casa_error = casa.run_script(cmd, raise_on_severe=True, timeout=timeout) logger.debug('\n'.join(casa_output)) except RuntimeError: logger.error(""Casa command failed"") if raise_on_severe:","def run_casa(cmd, raise_on_severe=False, timeout=1800): casa = drivecasa.Casapy() try: casa_output, casa_error = casa.run_script(cmd, raise_on_severe=True, timeout=timeout) logger.debug('\n'.join(casa_error)) except RuntimeError: logger.error(""Casa command failed"") if raise_on_severe:" 2061,https://:@github.com/apertif/apercal.git,be536be1cbe8f89017d77b6139d6742dbc059a42,"@@ -68,7 +68,7 @@ class transfer(BaseModule): logger.debug( ""Setting amplitude selfcal file name: {}"".format(datasetname_amp)) logger.debug( - ""Setting phase selfcal file name: {}"".format(datasetname_amp)) + ""Setting phase selfcal file name: {}"".format(datasetname_phase)) # datasetname_amp = self.get_target_path().rstrip('.mir') + '_amp.mir' # datasetname_phase = self.get_target_path() if os.path.isdir(datasetname_amp) and selfcaltargetbeamsampstatus: ",apercal/modules/transfer.py,"ReplaceText(target='datasetname_phase' @(71,65)->(71,80))","class transfer(BaseModule): logger.debug( ""Setting amplitude selfcal file name: {}"".format(datasetname_amp)) logger.debug( ""Setting phase selfcal file name: {}"".format(datasetname_amp)) # datasetname_amp = self.get_target_path().rstrip('.mir') + '_amp.mir' # datasetname_phase = self.get_target_path() if os.path.isdir(datasetname_amp) and selfcaltargetbeamsampstatus:","class transfer(BaseModule): logger.debug( ""Setting amplitude selfcal file name: {}"".format(datasetname_amp)) logger.debug( ""Setting phase selfcal file name: {}"".format(datasetname_phase)) # datasetname_amp = self.get_target_path().rstrip('.mir') + '_amp.mir' # datasetname_phase = self.get_target_path() if os.path.isdir(datasetname_amp) and selfcaltargetbeamsampstatus:" 2062,https://:@github.com/apertif/apercal.git,2bd6291a92fe9fd1e9c175ab79fea9e03ef56cc4,"@@ -41,7 +41,7 @@ def create_beam(beam, beam_map_dir, corrtype = 'Gaussian', primary_beam_path = N beamoutname = 'beam_{}.map'.format(beam.zfill(2)) # check if file exists: - if os.path.isdir(beamoutname): + if not os.path.isdir(beamoutname): #then test type and proceed for different types if corrtype == 'Gaussian': make_gaussian_beam(beam_map_dir,beamoutname,bm_size,cell,fwhm,cutoff) ",apercal/subs/mosaic_utils.py,"ReplaceText(target='not ' @(44,7)->(44,7))","def create_beam(beam, beam_map_dir, corrtype = 'Gaussian', primary_beam_path = N beamoutname = 'beam_{}.map'.format(beam.zfill(2)) # check if file exists: if os.path.isdir(beamoutname): #then test type and proceed for different types if corrtype == 'Gaussian': make_gaussian_beam(beam_map_dir,beamoutname,bm_size,cell,fwhm,cutoff)","def create_beam(beam, beam_map_dir, corrtype = 'Gaussian', primary_beam_path = N beamoutname = 'beam_{}.map'.format(beam.zfill(2)) # check if file exists: if not os.path.isdir(beamoutname): #then test type and proceed for different types if corrtype == 'Gaussian': make_gaussian_beam(beam_map_dir,beamoutname,bm_size,cell,fwhm,cutoff)" 2063,https://:@github.com/GalakVince/skin_lesion_symmetry.git,cbad346417689f3a698035f0393fef710ae6dedd,"@@ -338,7 +338,7 @@ def classifierTrainer(maxLeafNodes, data=None, data_backup_file='patchesDataSet/ clf: The fitted classifier. acc: The accuracy score of the classifier """""" - if data is not None: + if data is None: data = pd.read_csv(f""{package_path()}/data/patchesDataSet/{data_backup_file}.csv"", index_col=False) features = list(data) del features[0] ",dermoscopic_symmetry/classifier_feeder.py,"ReplaceText(target=' is ' @(341,11)->(341,19))","def classifierTrainer(maxLeafNodes, data=None, data_backup_file='patchesDataSet/ clf: The fitted classifier. acc: The accuracy score of the classifier """""" if data is not None: data = pd.read_csv(f""{package_path()}/data/patchesDataSet/{data_backup_file}.csv"", index_col=False) features = list(data) del features[0]","def classifierTrainer(maxLeafNodes, data=None, data_backup_file='patchesDataSet/ clf: The fitted classifier. acc: The accuracy score of the classifier """""" if data is None: data = pd.read_csv(f""{package_path()}/data/patchesDataSet/{data_backup_file}.csv"", index_col=False) features = list(data) del features[0]" 2064,https://:@github.com/Infinidat/infi.hbaapi.git,b0e2322452b83d0c9d037a502eee5e3b90ce1344,"@@ -32,7 +32,7 @@ class GeneratorTestCase(unittest.TestCase): port_test_class.assert_port(port) def _assert_wwn_translation(self, expected, actual): - self.assertEquals(expected, sysfs.translate_wwn(actual)) + self.assertEquals(sysfs.translate_wwn(actual), expected) def test_wwn_translation(self): for expected, actual in [('01:02:03:04:05:06:07:08', '01:02:03:04:05:06:07:08'), ",src/infi/hbaapi/generators/sysfs/tests/__init__.py,"ArgSwap(idxs=0<->1 @(35,8)->(35,25))","class GeneratorTestCase(unittest.TestCase): port_test_class.assert_port(port) def _assert_wwn_translation(self, expected, actual): self.assertEquals(expected, sysfs.translate_wwn(actual)) def test_wwn_translation(self): for expected, actual in [('01:02:03:04:05:06:07:08', '01:02:03:04:05:06:07:08'),","class GeneratorTestCase(unittest.TestCase): port_test_class.assert_port(port) def _assert_wwn_translation(self, expected, actual): self.assertEquals(sysfs.translate_wwn(actual), expected) def test_wwn_translation(self): for expected, actual in [('01:02:03:04:05:06:07:08', '01:02:03:04:05:06:07:08')," 2065,https://:@github.com/PanDAWMS/pilot2.git,d501b7defb163d213b08e69100e1b4ddc30b68f0,"@@ -154,7 +154,7 @@ class BaseData(object): logger.warning('failed to convert data for key=%s, raw=%s to type=%s' % (kname, raw, ktype)) return defval - return raw.lower() in ['1', 'true', 'yes'] + return val.lower() in ['1', 'true', 'yes'] def clean_dictdata(self, raw, ktype, kname=None, defval=None): """""" ",pilot/info/basedata.py,"ReplaceText(target='val' @(157,15)->(157,18))","class BaseData(object): logger.warning('failed to convert data for key=%s, raw=%s to type=%s' % (kname, raw, ktype)) return defval return raw.lower() in ['1', 'true', 'yes'] def clean_dictdata(self, raw, ktype, kname=None, defval=None): """"""","class BaseData(object): logger.warning('failed to convert data for key=%s, raw=%s to type=%s' % (kname, raw, ktype)) return defval return val.lower() in ['1', 'true', 'yes'] def clean_dictdata(self, raw, ktype, kname=None, defval=None): """"""" 2066,https://:@github.com/PanDAWMS/pilot2.git,db2a9ae0873c0c53e97e4a43f2d929ca89729128,"@@ -36,7 +36,7 @@ def verify_proxy(limit=None): # add setup for arcproxy if it exists arcproxy_setup = ""%s/atlas.cern.ch/repo/sw/arc/client/latest/slc6/x86_64/setup.sh"" % get_file_system_root_path() - envsetup += "". %s;"" % (arcproxy_setup) + envsetup = "". %s;"" % (arcproxy_setup) # first try to use arcproxy since voms-proxy-info is not working properly on SL6 # (memory issues on queues with limited memory) ",pilot/user/atlas/proxy.py,"ReplaceText(target='=' @(39,13)->(39,15))","def verify_proxy(limit=None): # add setup for arcproxy if it exists arcproxy_setup = ""%s/atlas.cern.ch/repo/sw/arc/client/latest/slc6/x86_64/setup.sh"" % get_file_system_root_path() envsetup += "". %s;"" % (arcproxy_setup) # first try to use arcproxy since voms-proxy-info is not working properly on SL6 # (memory issues on queues with limited memory)","def verify_proxy(limit=None): # add setup for arcproxy if it exists arcproxy_setup = ""%s/atlas.cern.ch/repo/sw/arc/client/latest/slc6/x86_64/setup.sh"" % get_file_system_root_path() envsetup = "". %s;"" % (arcproxy_setup) # first try to use arcproxy since voms-proxy-info is not working properly on SL6 # (memory issues on queues with limited memory)" 2067,https://:@github.com/PanDAWMS/pilot2.git,11ef7369f5f48c183709c3f4143deef9c8d9335a,"@@ -101,7 +101,7 @@ class Analytics(Services): else: raise NotDefined('Fit has not been defined') - return intersect + return x2 class Fit(object): ",pilot/api/analytics.py,"ReplaceText(target='x2' @(104,15)->(104,24))","class Analytics(Services): else: raise NotDefined('Fit has not been defined') return intersect class Fit(object):","class Analytics(Services): else: raise NotDefined('Fit has not been defined') return x2 class Fit(object):" 2068,https://:@github.com/PanDAWMS/pilot2.git,bf8e5359f24dd7da724fe770d893ba3e3af41ef7,"@@ -194,7 +194,7 @@ def copy_output(job, job_scratch_dir, work_dir): try: for outfile in job.output_files.keys(): if os.path.exists(outfile): - copy(os.path.join(job_scratch_dir, outfile), os.path.join(job_scratch_dir, outfile)) + copy(os.path.join(job_scratch_dir, outfile), os.path.join(work_dir, outfile)) os.chdir(work_dir) except IOError: raise FileHandlingFailure(""Copy from scratch dir to access point failed"") ",pilot/workflow/generic_hpc.py,"ReplaceText(target='work_dir' @(197,74)->(197,89))","def copy_output(job, job_scratch_dir, work_dir): try: for outfile in job.output_files.keys(): if os.path.exists(outfile): copy(os.path.join(job_scratch_dir, outfile), os.path.join(job_scratch_dir, outfile)) os.chdir(work_dir) except IOError: raise FileHandlingFailure(""Copy from scratch dir to access point failed"")","def copy_output(job, job_scratch_dir, work_dir): try: for outfile in job.output_files.keys(): if os.path.exists(outfile): copy(os.path.join(job_scratch_dir, outfile), os.path.join(work_dir, outfile)) os.chdir(work_dir) except IOError: raise FileHandlingFailure(""Copy from scratch dir to access point failed"")" 2069,https://:@github.com/PanDAWMS/pilot2.git,db0b653efeda7aed7af5ce710b7f57d94c241124,"@@ -148,7 +148,7 @@ def get_proper_pid(pid, command, use_container=True, transformation=""""): imax = 120 while i < imax: # abort if main process has finished already - if is_process_running(pid): + if not is_process_running(pid): return -1 ps = get_ps_info() ",pilot/user/atlas/utilities.py,"ReplaceText(target='not ' @(151,11)->(151,11))","def get_proper_pid(pid, command, use_container=True, transformation=""""): imax = 120 while i < imax: # abort if main process has finished already if is_process_running(pid): return -1 ps = get_ps_info()","def get_proper_pid(pid, command, use_container=True, transformation=""""): imax = 120 while i < imax: # abort if main process has finished already if not is_process_running(pid): return -1 ps = get_ps_info()" 2070,https://:@github.com/PanDAWMS/pilot2.git,7810aa90923f7e6380f364a173db0fdedc65f07c,"@@ -113,7 +113,7 @@ def get_copysetup(copytools, copytool_name): """""" copysetup = """" - if not copysetup: + if not copytools: return """" for ct in list(copytools.keys()): # Python 2/3 ",pilot/copytool/common.py,"ReplaceText(target='copytools' @(116,11)->(116,20))","def get_copysetup(copytools, copytool_name): """""" copysetup = """" if not copysetup: return """" for ct in list(copytools.keys()): # Python 2/3","def get_copysetup(copytools, copytool_name): """""" copysetup = """" if not copytools: return """" for ct in list(copytools.keys()): # Python 2/3" 2071,https://:@github.com/PanDAWMS/pilot2.git,4d3fafc26c46daa348d7c9e61bf60f3f73562cba,"@@ -288,7 +288,7 @@ def send_state(job, args, state, xml=None, metadata=None): # noqa: C901 time_before = int(time.time()) res = https.request('{pandaserver}/server/panda/updateJob'.format(pandaserver=pandaserver), data=data) time_after = int(time.time()) - log.info('server updateJob request completed in %ds for job %s' % (time_after - time_after, job.jobid)) + log.info('server updateJob request completed in %ds for job %s' % (time_after - time_before, job.jobid)) log.info(""server responded with: res = %s"" % str(res)) if res is not None: # does the server update contain any backchannel information? if so, update the job object ",pilot/control/job.py,"ReplaceText(target='time_before' @(291,92)->(291,102))","def send_state(job, args, state, xml=None, metadata=None): # noqa: C901 time_before = int(time.time()) res = https.request('{pandaserver}/server/panda/updateJob'.format(pandaserver=pandaserver), data=data) time_after = int(time.time()) log.info('server updateJob request completed in %ds for job %s' % (time_after - time_after, job.jobid)) log.info(""server responded with: res = %s"" % str(res)) if res is not None: # does the server update contain any backchannel information? if so, update the job object","def send_state(job, args, state, xml=None, metadata=None): # noqa: C901 time_before = int(time.time()) res = https.request('{pandaserver}/server/panda/updateJob'.format(pandaserver=pandaserver), data=data) time_after = int(time.time()) log.info('server updateJob request completed in %ds for job %s' % (time_after - time_before, job.jobid)) log.info(""server responded with: res = %s"" % str(res)) if res is not None: # does the server update contain any backchannel information? if so, update the job object" 2072,https://:@github.com/jmoswalt/django-things.git,d83bb4dc5f222f3074ad91eb63089989bc41dc57,"@@ -12,7 +12,7 @@ class ThingDetailView(DetailView): default_template_name = ""things/thing_detail.html"" def get_object(self, **kwargs): - return get_thing_object(self.model, self.request.user, self.kwargs['slug']) + return get_thing_object(self.model, self.kwargs['slug'], self.request.user) def get_template_names(self): names = [] ",things/views.py,"ArgSwap(idxs=1<->2 @(15,15)->(15,31))","class ThingDetailView(DetailView): default_template_name = ""things/thing_detail.html"" def get_object(self, **kwargs): return get_thing_object(self.model, self.request.user, self.kwargs['slug']) def get_template_names(self): names = []","class ThingDetailView(DetailView): default_template_name = ""things/thing_detail.html"" def get_object(self, **kwargs): return get_thing_object(self.model, self.kwargs['slug'], self.request.user) def get_template_names(self): names = []" 2073,https://:@github.com/dignio/py-smsframework-pswin.git,fcebe208a6ec6de47a187295adceb9e49b6cad97,"@@ -15,7 +15,7 @@ class PswinProvider(IProvider): :param password: Account password :param https: Use HTTPS for outgoing messages? """""" - self.api = PswinHttpApi(user, password, https, hostname) + self.api = PswinHttpApi(user, password, hostname, https) super(PswinProvider, self).__init__(gateway, name) def send(self, message): ",smsframework_pswin/provider.py,"ArgSwap(idxs=2<->3 @(18,19)->(18,31))","class PswinProvider(IProvider): :param password: Account password :param https: Use HTTPS for outgoing messages? """""" self.api = PswinHttpApi(user, password, https, hostname) super(PswinProvider, self).__init__(gateway, name) def send(self, message):","class PswinProvider(IProvider): :param password: Account password :param https: Use HTTPS for outgoing messages? """""" self.api = PswinHttpApi(user, password, hostname, https) super(PswinProvider, self).__init__(gateway, name) def send(self, message):" 2074,https://:@github.com/hsolbrig/pyjsg.git,951dac74c9d9c99b601b350330d985e368a1a64b,"@@ -99,7 +99,7 @@ def iterable_conforms(element, etype, namespace: Dict[str, Any]) -> bool: def element_conforms(element, etype) -> bool: if element is None and etype == object: - return True + return False elif isinstance(etype, type(type)) and (issubclass(etype, type(None))): return element is None elif element is None: ",pyjsg/jsglib/typing_patch_36.py,"ReplaceText(target='False' @(102,15)->(102,19))","def iterable_conforms(element, etype, namespace: Dict[str, Any]) -> bool: def element_conforms(element, etype) -> bool: if element is None and etype == object: return True elif isinstance(etype, type(type)) and (issubclass(etype, type(None))): return element is None elif element is None:","def iterable_conforms(element, etype, namespace: Dict[str, Any]) -> bool: def element_conforms(element, etype) -> bool: if element is None and etype == object: return False elif isinstance(etype, type(type)) and (issubclass(etype, type(None))): return element is None elif element is None:" 2075,https://:@github.com/TrackerSB/DriveBuild.git,cb617d93003c0bd64fd35a0289615224cac6baaf,"@@ -324,7 +324,7 @@ def generate_scenario(env: _ElementTree, participants_node: _Element) -> Scenari movements = list() waypoint_nodes = xpath(node, ""db:movement/db:waypoint"") for wp_node in waypoint_nodes: - common_state_vals = _extract_common_state_vals(initial_state_node) + common_state_vals = _extract_common_state_vals(wp_node) movements.append(WayPoint( (float(wp_node.get(""x"")), float(wp_node.get(""y""))), float(wp_node.get(""tolerance"")), ",generator.py,"ReplaceText(target='wp_node' @(327,59)->(327,77))","def generate_scenario(env: _ElementTree, participants_node: _Element) -> Scenari movements = list() waypoint_nodes = xpath(node, ""db:movement/db:waypoint"") for wp_node in waypoint_nodes: common_state_vals = _extract_common_state_vals(initial_state_node) movements.append(WayPoint( (float(wp_node.get(""x"")), float(wp_node.get(""y""))), float(wp_node.get(""tolerance"")),","def generate_scenario(env: _ElementTree, participants_node: _Element) -> Scenari movements = list() waypoint_nodes = xpath(node, ""db:movement/db:waypoint"") for wp_node in waypoint_nodes: common_state_vals = _extract_common_state_vals(wp_node) movements.append(WayPoint( (float(wp_node.get(""x"")), float(wp_node.get(""y""))), float(wp_node.get(""tolerance""))," 2076,https://:@bitbucket.org/madssj/fabric-coat.git,093e2a926dce52b47a5f47b98413287cd9f31588,"@@ -22,7 +22,7 @@ def update_env(*args, **kwargs): env.versions_dir = env.base_dir + ""/versions"" - if 'wsgi_file' in env: + if 'wsgi_file' not in env: env.wsgi_file = env.django_appname + "".wsgi"" if 'local_base_dir' not in env: ",src/coat/django.py,"ReplaceText(target=' not in ' @(25,18)->(25,22))","def update_env(*args, **kwargs): env.versions_dir = env.base_dir + ""/versions"" if 'wsgi_file' in env: env.wsgi_file = env.django_appname + "".wsgi"" if 'local_base_dir' not in env:","def update_env(*args, **kwargs): env.versions_dir = env.base_dir + ""/versions"" if 'wsgi_file' not in env: env.wsgi_file = env.django_appname + "".wsgi"" if 'local_base_dir' not in env:" 2077,https://:@github.com/soreau/catt-qt.git,b795ef486b5cdbb3a7d4758a8e5acd978423db3f,"@@ -764,7 +764,7 @@ class App(QMainWindow): if self.combo_box.currentIndex() == device.index: self.play_button.setEnabled(True) self.stop_button.setEnabled(True) - d.disconnect_volume = round(device.cast.status.volume_level * 100) + device.disconnect_volume = round(device.cast.status.volume_level * 100) if self.reconnect_volume == -1: if last_volume != round(device.cast.status.volume_level * 100): d.volume(last_volume / 100) ",cattqt/cattqt.py,"ReplaceText(target='device' @(767,8)->(767,9))","class App(QMainWindow): if self.combo_box.currentIndex() == device.index: self.play_button.setEnabled(True) self.stop_button.setEnabled(True) d.disconnect_volume = round(device.cast.status.volume_level * 100) if self.reconnect_volume == -1: if last_volume != round(device.cast.status.volume_level * 100): d.volume(last_volume / 100)","class App(QMainWindow): if self.combo_box.currentIndex() == device.index: self.play_button.setEnabled(True) self.stop_button.setEnabled(True) device.disconnect_volume = round(device.cast.status.volume_level * 100) if self.reconnect_volume == -1: if last_volume != round(device.cast.status.volume_level * 100): d.volume(last_volume / 100)" 2078,https://:@github.com/FredHutch/find-cags.git,e45d29450aad390dd8da28ed6285ba089728abd8,"@@ -271,7 +271,7 @@ def make_summary_abund_df(df, cags, singletons): cag_ix: df.loc[cag].mean() for cag_ix, cag in cags.items() }).T, - cags.loc[singletons] + df.loc[singletons] ]) assert summary_df.shape[0] == len(cags) + len(singletons) ",find-cags.py,"ReplaceText(target='df' @(274,8)->(274,12))","def make_summary_abund_df(df, cags, singletons): cag_ix: df.loc[cag].mean() for cag_ix, cag in cags.items() }).T, cags.loc[singletons] ]) assert summary_df.shape[0] == len(cags) + len(singletons)","def make_summary_abund_df(df, cags, singletons): cag_ix: df.loc[cag].mean() for cag_ix, cag in cags.items() }).T, df.loc[singletons] ]) assert summary_df.shape[0] == len(cags) + len(singletons)" 2079,https://:@github.com/thuctran289/aztex.git,3732482a5ea5d7a6972e8adb33a286b77fb77fef,"@@ -104,7 +104,7 @@ class Parser(object): match = container.get() em = LinkTextMatch(match) subelement = self.parseText(em.text()) - element = LinkElement(element, em.url()) + element = LinkElement(subelement, em.url()) elif container.set(self.matcher.matchImage(block)): match = container.get() ",Parser.py,"ReplaceText(target='subelement' @(107,26)->(107,33))","class Parser(object): match = container.get() em = LinkTextMatch(match) subelement = self.parseText(em.text()) element = LinkElement(element, em.url()) elif container.set(self.matcher.matchImage(block)): match = container.get()","class Parser(object): match = container.get() em = LinkTextMatch(match) subelement = self.parseText(em.text()) element = LinkElement(subelement, em.url()) elif container.set(self.matcher.matchImage(block)): match = container.get()" 2080,https://:@github.com/sviete/home-assistant.git,917db18b29e37685517bde78b827c41729f3512d,"@@ -56,7 +56,7 @@ def get_scanner(hass, config): _LOGGER.warning('Found username or password but no host') return None - scanner = NetgearDeviceScanner(host, password, username) + scanner = NetgearDeviceScanner(host, username, password) return scanner if scanner.success_init else None ",homeassistant/components/device_tracker/netgear.py,"ArgSwap(idxs=1<->2 @(59,14)->(59,34))","def get_scanner(hass, config): _LOGGER.warning('Found username or password but no host') return None scanner = NetgearDeviceScanner(host, password, username) return scanner if scanner.success_init else None ","def get_scanner(hass, config): _LOGGER.warning('Found username or password but no host') return None scanner = NetgearDeviceScanner(host, username, password) return scanner if scanner.success_init else None " 2081,https://:@github.com/sviete/home-assistant.git,33b0f4d05d5e7479fce392053763f98d650085b3,"@@ -45,7 +45,7 @@ def trigger(hass, config, action): and not convert(seconds.lstrip('/'), int) % 60 == 0: _LOGGER.warning('Periodic seconds should be divisible with 60' 'there will be an offset every minute') - if isinstance(minutes, str) and hours.startswith('/') \ + if isinstance(hours, str) and hours.startswith('/') \ and not convert(hours.lstrip('/'), int) % 24 == 0: _LOGGER.warning('Periodic hours should be divisible with 24' 'there will be an offset every midnight') ",homeassistant/components/automation/time.py,"ReplaceText(target='hours' @(48,22)->(48,29))","def trigger(hass, config, action): and not convert(seconds.lstrip('/'), int) % 60 == 0: _LOGGER.warning('Periodic seconds should be divisible with 60' 'there will be an offset every minute') if isinstance(minutes, str) and hours.startswith('/') \ and not convert(hours.lstrip('/'), int) % 24 == 0: _LOGGER.warning('Periodic hours should be divisible with 24' 'there will be an offset every midnight')","def trigger(hass, config, action): and not convert(seconds.lstrip('/'), int) % 60 == 0: _LOGGER.warning('Periodic seconds should be divisible with 60' 'there will be an offset every minute') if isinstance(hours, str) and hours.startswith('/') \ and not convert(hours.lstrip('/'), int) % 24 == 0: _LOGGER.warning('Periodic hours should be divisible with 24' 'there will be an offset every midnight')" 2082,https://:@github.com/sviete/home-assistant.git,f5227e1de07066b2ae67b48a3f2312f0057207be,"@@ -109,7 +109,7 @@ def setup(hass, base_config): (LIGHT, DISCOVER_LIGHTS), (SWITCH, DISCOVER_SWITCHES))): component = get_component(comp_name) - bootstrap.setup_component(hass, component.DOMAIN, config) + bootstrap.setup_component(hass, component.DOMAIN, base_config) hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: discovery, ATTR_DISCOVERED: {}}) ",homeassistant/components/vera.py,"ReplaceText(target='base_config' @(112,58)->(112,64))","def setup(hass, base_config): (LIGHT, DISCOVER_LIGHTS), (SWITCH, DISCOVER_SWITCHES))): component = get_component(comp_name) bootstrap.setup_component(hass, component.DOMAIN, config) hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: discovery, ATTR_DISCOVERED: {}})","def setup(hass, base_config): (LIGHT, DISCOVER_LIGHTS), (SWITCH, DISCOVER_SWITCHES))): component = get_component(comp_name) bootstrap.setup_component(hass, component.DOMAIN, base_config) hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: discovery, ATTR_DISCOVERED: {}})" 2083,https://:@github.com/sviete/home-assistant.git,e44c2a4016a12c992154b62ecfbed5a6013623e2,"@@ -39,7 +39,7 @@ def _conf_preprocess(value): return value _SINGLE_GROUP_CONFIG = vol.Schema(vol.All(_conf_preprocess, { - vol.Optional(CONF_ENTITIES): vol.Any(None, cv.entity_ids), + vol.Optional(CONF_ENTITIES): vol.Any(cv.entity_ids, None), CONF_VIEW: bool, CONF_NAME: str, CONF_ICON: cv.icon, ",homeassistant/components/group.py,"ArgSwap(idxs=0<->1 @(42,33)->(42,40))","def _conf_preprocess(value): return value _SINGLE_GROUP_CONFIG = vol.Schema(vol.All(_conf_preprocess, { vol.Optional(CONF_ENTITIES): vol.Any(None, cv.entity_ids), CONF_VIEW: bool, CONF_NAME: str, CONF_ICON: cv.icon,","def _conf_preprocess(value): return value _SINGLE_GROUP_CONFIG = vol.Schema(vol.All(_conf_preprocess, { vol.Optional(CONF_ENTITIES): vol.Any(cv.entity_ids, None), CONF_VIEW: bool, CONF_NAME: str, CONF_ICON: cv.icon," 2084,https://:@github.com/sviete/home-assistant.git,b1736994b72a90ff18d7461b0afe00dd93ba2cdc,"@@ -258,7 +258,7 @@ class AndroidIPCamEntity(Entity): def device_state_attributes(self): """"""Return the state attributes."""""" state_attr = {} - if self._ipcam.status_data is not None: + if self._ipcam.status_data is None: return state_attr state_attr[ATTR_VID_CONNS] = \ ",homeassistant/components/android_ip_webcam.py,"ReplaceText(target=' is ' @(261,34)->(261,42))","class AndroidIPCamEntity(Entity): def device_state_attributes(self): """"""Return the state attributes."""""" state_attr = {} if self._ipcam.status_data is not None: return state_attr state_attr[ATTR_VID_CONNS] = \","class AndroidIPCamEntity(Entity): def device_state_attributes(self): """"""Return the state attributes."""""" state_attr = {} if self._ipcam.status_data is None: return state_attr state_attr[ATTR_VID_CONNS] = \" 2085,https://:@github.com/sviete/home-assistant.git,32b7f4d16f3c790d3370df3f4bcaf1a1462c8944,"@@ -288,7 +288,7 @@ class TadoClimate(ClimateDevice): if 'setting' in overlay_data: setting_data = overlay_data['setting'] - setting = setting is not None + setting = setting_data is not None if setting: if 'mode' in setting_data: ",homeassistant/components/climate/tado.py,"ReplaceText(target='setting_data' @(291,26)->(291,33))","class TadoClimate(ClimateDevice): if 'setting' in overlay_data: setting_data = overlay_data['setting'] setting = setting is not None if setting: if 'mode' in setting_data:","class TadoClimate(ClimateDevice): if 'setting' in overlay_data: setting_data = overlay_data['setting'] setting = setting_data is not None if setting: if 'mode' in setting_data:" 2086,https://:@github.com/sviete/home-assistant.git,6505019701d57bf497cd42fc087e4a2e7a9ef546,"@@ -89,7 +89,7 @@ class PushBulletNotificationService(BaseNotificationService): if not targets: # Backward compatibility, notify all devices in own account - self._push_data(filepath, message, title, self.pushbullet, url) + self._push_data(filepath, message, title, url, self.pushbullet) _LOGGER.info(""Sent notification to self"") return ",homeassistant/components/notify/pushbullet.py,"ArgSwap(idxs=3<->4 @(92,12)->(92,27))","class PushBulletNotificationService(BaseNotificationService): if not targets: # Backward compatibility, notify all devices in own account self._push_data(filepath, message, title, self.pushbullet, url) _LOGGER.info(""Sent notification to self"") return ","class PushBulletNotificationService(BaseNotificationService): if not targets: # Backward compatibility, notify all devices in own account self._push_data(filepath, message, title, url, self.pushbullet) _LOGGER.info(""Sent notification to self"") return " 2087,https://:@github.com/sviete/home-assistant.git,e2ce1d05aeb825efcc324d0e4ac38fd868e80875,"@@ -27,7 +27,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): # Get all regular switches that are not excluded or marked as lights for device in data.abode.get_devices(generic_type=CONST.TYPE_SWITCH): - if data.is_excluded(device) or not data.is_light(device): + if data.is_excluded(device) or data.is_light(device): continue devices.append(AbodeSwitch(data, device)) ",homeassistant/components/switch/abode.py,"ReplaceText(target='' @(30,39)->(30,43))","def setup_platform(hass, config, add_devices, discovery_info=None): # Get all regular switches that are not excluded or marked as lights for device in data.abode.get_devices(generic_type=CONST.TYPE_SWITCH): if data.is_excluded(device) or not data.is_light(device): continue devices.append(AbodeSwitch(data, device))","def setup_platform(hass, config, add_devices, discovery_info=None): # Get all regular switches that are not excluded or marked as lights for device in data.abode.get_devices(generic_type=CONST.TYPE_SWITCH): if data.is_excluded(device) or data.is_light(device): continue devices.append(AbodeSwitch(data, device))" 2088,https://:@github.com/sviete/home-assistant.git,486263fff771a5f647d70d062e67022ae5031378,"@@ -118,7 +118,7 @@ class Concord232ZoneSensor(BinarySensorDevice): def is_on(self): """"""Return true if the binary sensor is on."""""" # True means ""faulted"" or ""open"" or ""abnormal state"" - return bool(self._zone['state'] == 'Normal') + return bool(self._zone['state'] != 'Normal') def update(self): """"""Get updated stats from API."""""" ",homeassistant/components/binary_sensor/concord232.py,"ReplaceText(target='!=' @(121,40)->(121,42))","class Concord232ZoneSensor(BinarySensorDevice): def is_on(self): """"""Return true if the binary sensor is on."""""" # True means ""faulted"" or ""open"" or ""abnormal state"" return bool(self._zone['state'] == 'Normal') def update(self): """"""Get updated stats from API.""""""","class Concord232ZoneSensor(BinarySensorDevice): def is_on(self): """"""Return true if the binary sensor is on."""""" # True means ""faulted"" or ""open"" or ""abnormal state"" return bool(self._zone['state'] != 'Normal') def update(self): """"""Get updated stats from API.""""""" 2089,https://:@github.com/sviete/home-assistant.git,cf3f1c3081405034dcd96cf5d2ae6f070c5bbfa8,"@@ -48,7 +48,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None): dev = [] for pmname in coll.supported_values(): - if config.get(CONF_NAME) is None: + if config.get(CONF_NAME) is not None: name = '{} PM{}'.format(config.get(CONF_NAME), pmname) else: name = 'PM{}'.format(pmname) ",homeassistant/components/sensor/serial_pm.py,"ReplaceText(target=' is not ' @(51,32)->(51,36))","def setup_platform(hass, config, add_devices, discovery_info=None): dev = [] for pmname in coll.supported_values(): if config.get(CONF_NAME) is None: name = '{} PM{}'.format(config.get(CONF_NAME), pmname) else: name = 'PM{}'.format(pmname)","def setup_platform(hass, config, add_devices, discovery_info=None): dev = [] for pmname in coll.supported_values(): if config.get(CONF_NAME) is not None: name = '{} PM{}'.format(config.get(CONF_NAME), pmname) else: name = 'PM{}'.format(pmname)" 2090,https://:@github.com/sviete/home-assistant.git,74c249e57d16340ebd89fcd989942ff8b2fac26f,"@@ -194,7 +194,7 @@ class SpotifyMediaPlayer(MediaPlayerDevice): self._title = item.get('name') self._artist = ', '.join([artist.get('name') for artist in item.get('artists')]) - self._uri = current.get('uri') + self._uri = item.get('uri') images = item.get('album').get('images') self._image_url = images[0].get('url') if images else None # Playing state ",homeassistant/components/media_player/spotify.py,"ReplaceText(target='item' @(197,24)->(197,31))","class SpotifyMediaPlayer(MediaPlayerDevice): self._title = item.get('name') self._artist = ', '.join([artist.get('name') for artist in item.get('artists')]) self._uri = current.get('uri') images = item.get('album').get('images') self._image_url = images[0].get('url') if images else None # Playing state","class SpotifyMediaPlayer(MediaPlayerDevice): self._title = item.get('name') self._artist = ', '.join([artist.get('name') for artist in item.get('artists')]) self._uri = item.get('uri') images = item.get('album').get('images') self._image_url = images[0].get('url') if images else None # Playing state" 2091,https://:@github.com/sviete/home-assistant.git,2a5751c09d62823371da14e9bdb1b19143851c85,"@@ -173,7 +173,7 @@ class TestHomeKit(unittest.TestCase): self.assertEqual(mock_add_bridge_acc.mock_calls, [call(state)]) self.assertEqual(mock_show_setup_msg.mock_calls, [ - call(homekit.bridge, self.hass)]) + call(self.hass, homekit.bridge)]) self.assertEqual(homekit.driver.mock_calls, [call.start()]) self.assertTrue(homekit.started) ",tests/components/homekit/test_homekit.py,"ArgSwap(idxs=0<->1 @(176,12)->(176,16))","class TestHomeKit(unittest.TestCase): self.assertEqual(mock_add_bridge_acc.mock_calls, [call(state)]) self.assertEqual(mock_show_setup_msg.mock_calls, [ call(homekit.bridge, self.hass)]) self.assertEqual(homekit.driver.mock_calls, [call.start()]) self.assertTrue(homekit.started) ","class TestHomeKit(unittest.TestCase): self.assertEqual(mock_add_bridge_acc.mock_calls, [call(state)]) self.assertEqual(mock_show_setup_msg.mock_calls, [ call(self.hass, homekit.bridge)]) self.assertEqual(homekit.driver.mock_calls, [call.start()]) self.assertTrue(homekit.started) " 2092,https://:@github.com/sviete/home-assistant.git,bd23145331c2a3497160d311da5853393852df61,"@@ -185,7 +185,7 @@ class EntityRegistry: for listener_ref in new.update_listeners: listener = listener_ref() if listener is None: - to_remove.append(listener) + to_remove.append(listener_ref) else: try: listener.async_registry_updated(old, new) ",homeassistant/helpers/entity_registry.py,"ReplaceText(target='listener_ref' @(188,33)->(188,41))","class EntityRegistry: for listener_ref in new.update_listeners: listener = listener_ref() if listener is None: to_remove.append(listener) else: try: listener.async_registry_updated(old, new)","class EntityRegistry: for listener_ref in new.update_listeners: listener = listener_ref() if listener is None: to_remove.append(listener_ref) else: try: listener.async_registry_updated(old, new)" 2093,https://:@github.com/sviete/home-assistant.git,34d7758b4a04b6cdc44a763cb1da194d4168b833,"@@ -46,7 +46,7 @@ def async_register_http(hass, cfg): entity_config.get(entity.entity_id, {}).get(CONF_EXPOSE) domain_exposed_by_default = \ - expose_by_default and entity.domain in exposed_domains + expose_by_default or entity.domain in exposed_domains # Expose an entity if the entity's domain is exposed by default and # the configuration doesn't explicitly exclude it from being ",homeassistant/components/google_assistant/http.py,"ReplaceText(target='or' @(49,30)->(49,33))","def async_register_http(hass, cfg): entity_config.get(entity.entity_id, {}).get(CONF_EXPOSE) domain_exposed_by_default = \ expose_by_default and entity.domain in exposed_domains # Expose an entity if the entity's domain is exposed by default and # the configuration doesn't explicitly exclude it from being","def async_register_http(hass, cfg): entity_config.get(entity.entity_id, {}).get(CONF_EXPOSE) domain_exposed_by_default = \ expose_by_default or entity.domain in exposed_domains # Expose an entity if the entity's domain is exposed by default and # the configuration doesn't explicitly exclude it from being" 2094,https://:@github.com/sviete/home-assistant.git,04c7d5c128c61bc26caf6950ccb231cb27faacac,"@@ -48,7 +48,7 @@ def async_register_http(hass, cfg): entity_config.get(entity.entity_id, {}).get(CONF_EXPOSE) domain_exposed_by_default = \ - expose_by_default or entity.domain in exposed_domains + expose_by_default and entity.domain in exposed_domains # Expose an entity if the entity's domain is exposed by default and # the configuration doesn't explicitly exclude it from being ",homeassistant/components/google_assistant/http.py,"ReplaceText(target='and' @(51,30)->(51,32))","def async_register_http(hass, cfg): entity_config.get(entity.entity_id, {}).get(CONF_EXPOSE) domain_exposed_by_default = \ expose_by_default or entity.domain in exposed_domains # Expose an entity if the entity's domain is exposed by default and # the configuration doesn't explicitly exclude it from being","def async_register_http(hass, cfg): entity_config.get(entity.entity_id, {}).get(CONF_EXPOSE) domain_exposed_by_default = \ expose_by_default and entity.domain in exposed_domains # Expose an entity if the entity's domain is exposed by default and # the configuration doesn't explicitly exclude it from being" 2095,https://:@github.com/sviete/home-assistant.git,d13c892b281049415c67370d34ca711b5c3691c5,"@@ -19,7 +19,7 @@ async def async_handle_state_update(hass, context, msg): _LOGGER.debug(""[state handler] context: %s msg: %s"", context, msg) entity_id = context.get(ATTR_ENTITY_ID) state = bool(int(msg.get(ATTR_STATE))) - if msg.get(CONF_INVERSE): + if context.get(CONF_INVERSE): state = not state async_dispatcher_send( ",homeassistant/components/konnected/handlers.py,"ReplaceText(target='context' @(22,7)->(22,10))","async def async_handle_state_update(hass, context, msg): _LOGGER.debug(""[state handler] context: %s msg: %s"", context, msg) entity_id = context.get(ATTR_ENTITY_ID) state = bool(int(msg.get(ATTR_STATE))) if msg.get(CONF_INVERSE): state = not state async_dispatcher_send(","async def async_handle_state_update(hass, context, msg): _LOGGER.debug(""[state handler] context: %s msg: %s"", context, msg) entity_id = context.get(ATTR_ENTITY_ID) state = bool(int(msg.get(ATTR_STATE))) if context.get(CONF_INVERSE): state = not state async_dispatcher_send(" 2096,https://:@github.com/sviete/home-assistant.git,3d91d76d3d87dc28958c70c25cbd7568c8c20d4c,"@@ -355,7 +355,7 @@ async def _async_set_up_integrations( if stage_1_domains: await asyncio.gather(*[ async_setup_component(hass, domain, config) - for domain in logging_domains + for domain in stage_1_domains ]) # Load all integrations ",homeassistant/bootstrap.py,"ReplaceText(target='stage_1_domains' @(358,26)->(358,41))","async def _async_set_up_integrations( if stage_1_domains: await asyncio.gather(*[ async_setup_component(hass, domain, config) for domain in logging_domains ]) # Load all integrations","async def _async_set_up_integrations( if stage_1_domains: await asyncio.gather(*[ async_setup_component(hass, domain, config) for domain in stage_1_domains ]) # Load all integrations" 2097,https://:@github.com/sviete/home-assistant.git,02f927ae2dfc1ed8de305a3cb7a7ee2b955b97cf,"@@ -62,7 +62,7 @@ async def async_setup_entry(hass, entry, async_add_entities): return if _token_info: - await store.async_save(token_info) + await store.async_save(_token_info) token_info = _token_info data_connection = ambiclimate.AmbiclimateConnection(oauth, ",homeassistant/components/ambiclimate/climate.py,"ReplaceText(target='_token_info' @(65,31)->(65,41))","async def async_setup_entry(hass, entry, async_add_entities): return if _token_info: await store.async_save(token_info) token_info = _token_info data_connection = ambiclimate.AmbiclimateConnection(oauth,","async def async_setup_entry(hass, entry, async_add_entities): return if _token_info: await store.async_save(_token_info) token_info = _token_info data_connection = ambiclimate.AmbiclimateConnection(oauth," 2098,https://:@github.com/sviete/home-assistant.git,e824c553ca72c2b6de0197ae515486d32785e8a2,"@@ -254,7 +254,7 @@ class WazeTravelTimeData(): if self.exclude is not None: routes = {k: v for k, v in routes.items() if - self.exclude.lower() in k.lower()} + self.exclude.lower() not in k.lower()} route = sorted(routes, key=(lambda key: routes[key][0]))[0] ",homeassistant/components/waze_travel_time/sensor.py,"ReplaceText(target=' not in ' @(257,50)->(257,54))","class WazeTravelTimeData(): if self.exclude is not None: routes = {k: v for k, v in routes.items() if self.exclude.lower() in k.lower()} route = sorted(routes, key=(lambda key: routes[key][0]))[0] ","class WazeTravelTimeData(): if self.exclude is not None: routes = {k: v for k, v in routes.items() if self.exclude.lower() not in k.lower()} route = sorted(routes, key=(lambda key: routes[key][0]))[0] " 2099,https://:@github.com/sviete/home-assistant.git,0653f57fb41563385b141efcd2ffcfb60572042b,"@@ -433,7 +433,7 @@ class Entity: async def _async_registry_updated(self, event): """"""Handle entity registry update."""""" data = event.data - if data['action'] != 'update' and data.get( + if data['action'] != 'update' or data.get( 'old_entity_id', data['entity_id']) != self.entity_id: return ",homeassistant/helpers/entity.py,"ReplaceText(target='or' @(436,38)->(436,41))","class Entity: async def _async_registry_updated(self, event): """"""Handle entity registry update."""""" data = event.data if data['action'] != 'update' and data.get( 'old_entity_id', data['entity_id']) != self.entity_id: return ","class Entity: async def _async_registry_updated(self, event): """"""Handle entity registry update."""""" data = event.data if data['action'] != 'update' or data.get( 'old_entity_id', data['entity_id']) != self.entity_id: return " 2100,https://:@github.com/sviete/home-assistant.git,066254afdfcc7cd513b9450e0693c1d188d12c4d,"@@ -156,7 +156,7 @@ class AtaDeviceClimate(MelCloudClimate): ) vane_vertical = self._device.vane_vertical - if vane_horizontal: + if vane_vertical: attr.update( { ATTR_VANE_VERTICAL: vane_vertical, ",homeassistant/components/melcloud/climate.py,"ReplaceText(target='vane_vertical' @(159,11)->(159,26))","class AtaDeviceClimate(MelCloudClimate): ) vane_vertical = self._device.vane_vertical if vane_horizontal: attr.update( { ATTR_VANE_VERTICAL: vane_vertical,","class AtaDeviceClimate(MelCloudClimate): ) vane_vertical = self._device.vane_vertical if vane_vertical: attr.update( { ATTR_VANE_VERTICAL: vane_vertical," 2101,https://:@github.com/sviete/home-assistant.git,a6b407d706a0ed00d740a9c50eeb5107acccddc1,"@@ -58,7 +58,7 @@ def setup(hass, config): success = True for conf in config[DOMAIN]: - protocol = ""https"" if config[CONF_SSL] else ""http"" + protocol = ""https"" if conf[CONF_SSL] else ""http"" host_name = conf[CONF_HOST] server_origin = f""{protocol}://{host_name}"" ",homeassistant/components/zoneminder/__init__.py,"ReplaceText(target='conf' @(61,30)->(61,36))","def setup(hass, config): success = True for conf in config[DOMAIN]: protocol = ""https"" if config[CONF_SSL] else ""http"" host_name = conf[CONF_HOST] server_origin = f""{protocol}://{host_name}""","def setup(hass, config): success = True for conf in config[DOMAIN]: protocol = ""https"" if conf[CONF_SSL] else ""http"" host_name = conf[CONF_HOST] server_origin = f""{protocol}://{host_name}""" 2102,https://:@github.com/sviete/home-assistant.git,6c3ea2a904ab38afcb0de424592949ff2d26e99d,"@@ -153,7 +153,7 @@ async def async_setup(hass, config): entity_filter = conf[CONF_FILTER] entity_config = conf[CONF_ENTITY_CONFIG] interface_choice = ( - InterfaceChoice.Default if config.get(CONF_ZEROCONF_DEFAULT_INTERFACE) else None + InterfaceChoice.Default if conf.get(CONF_ZEROCONF_DEFAULT_INTERFACE) else None ) homekit = HomeKit( ",homeassistant/components/homekit/__init__.py,"ReplaceText(target='conf' @(156,35)->(156,41))","async def async_setup(hass, config): entity_filter = conf[CONF_FILTER] entity_config = conf[CONF_ENTITY_CONFIG] interface_choice = ( InterfaceChoice.Default if config.get(CONF_ZEROCONF_DEFAULT_INTERFACE) else None ) homekit = HomeKit(","async def async_setup(hass, config): entity_filter = conf[CONF_FILTER] entity_config = conf[CONF_ENTITY_CONFIG] interface_choice = ( InterfaceChoice.Default if conf.get(CONF_ZEROCONF_DEFAULT_INTERFACE) else None ) homekit = HomeKit(" 2103,https://:@github.com/sviete/home-assistant.git,233284056ae02d0423ef590d2c931dad450a6447,"@@ -119,5 +119,5 @@ class XS1ThermostatEntity(XS1DeviceEntity, ClimateEntity): async def async_update(self): """"""Also update the sensor when available."""""" await super().async_update() - if self.sensor is None: + if self.sensor is not None: await self.hass.async_add_executor_job(self.sensor.update) ",homeassistant/components/xs1/climate.py,"ReplaceText(target=' is not ' @(122,22)->(122,26))","class XS1ThermostatEntity(XS1DeviceEntity, ClimateEntity): async def async_update(self): """"""Also update the sensor when available."""""" await super().async_update() if self.sensor is None: await self.hass.async_add_executor_job(self.sensor.update)","class XS1ThermostatEntity(XS1DeviceEntity, ClimateEntity): async def async_update(self): """"""Also update the sensor when available."""""" await super().async_update() if self.sensor is not None: await self.hass.async_add_executor_job(self.sensor.update)" 2104,https://:@github.com/sviete/home-assistant.git,01bac9f433f26440eff3a4f1365cda9480dc971c,"@@ -60,7 +60,7 @@ async def async_setup_entry(hass, config_entry): shark_vacs = await ayla_api.async_get_devices(False) device_names = "", "".join([d.name for d in shark_vacs]) - LOGGER.debug(""Found %d Shark IQ device(s): %s"", len(device_names), device_names) + LOGGER.debug(""Found %d Shark IQ device(s): %s"", len(shark_vacs), device_names) coordinator = SharkIqUpdateCoordinator(hass, config_entry, ayla_api, shark_vacs) await coordinator.async_refresh() ",homeassistant/components/sharkiq/__init__.py,"ReplaceText(target='shark_vacs' @(63,56)->(63,68))","async def async_setup_entry(hass, config_entry): shark_vacs = await ayla_api.async_get_devices(False) device_names = "", "".join([d.name for d in shark_vacs]) LOGGER.debug(""Found %d Shark IQ device(s): %s"", len(device_names), device_names) coordinator = SharkIqUpdateCoordinator(hass, config_entry, ayla_api, shark_vacs) await coordinator.async_refresh()","async def async_setup_entry(hass, config_entry): shark_vacs = await ayla_api.async_get_devices(False) device_names = "", "".join([d.name for d in shark_vacs]) LOGGER.debug(""Found %d Shark IQ device(s): %s"", len(shark_vacs), device_names) coordinator = SharkIqUpdateCoordinator(hass, config_entry, ayla_api, shark_vacs) await coordinator.async_refresh()" 2105,https://:@github.com/Melevir/flake8-super-mario.git,1aba55ed7cd233a511372c6bfa552684c7243136,"@@ -14,6 +14,6 @@ def run_validator_for_test_file(filename: str) -> List: with open(test_file_path, 'r') as file_handler: raw_content = file_handler.read() tree = ast.parse(raw_content) - checker = SuperMarionChecker(tree=tree, filename=filename) + checker = SuperMarionChecker(tree=tree, filename=test_file_path) return list(checker.run()) ",tests/conftest.py,"ReplaceText(target='test_file_path' @(17,53)->(17,61))","def run_validator_for_test_file(filename: str) -> List: with open(test_file_path, 'r') as file_handler: raw_content = file_handler.read() tree = ast.parse(raw_content) checker = SuperMarionChecker(tree=tree, filename=filename) return list(checker.run())","def run_validator_for_test_file(filename: str) -> List: with open(test_file_path, 'r') as file_handler: raw_content = file_handler.read() tree = ast.parse(raw_content) checker = SuperMarionChecker(tree=tree, filename=test_file_path) return list(checker.run())" 2106,https://:@github.com/OxfordHED/sunbear.git,f7d00ff0471d6e1bd301a965f4550fa2e8f81f7a,"@@ -78,7 +78,7 @@ class Momentum(GradOptInterface): # check the stopping conditions if self._is_stop(): break - return x + return xmin def _is_stop(self): def disp(s): ",sunbear/gradopt/momentum.py,"ReplaceText(target='xmin' @(81,15)->(81,16))","class Momentum(GradOptInterface): # check the stopping conditions if self._is_stop(): break return x def _is_stop(self): def disp(s):","class Momentum(GradOptInterface): # check the stopping conditions if self._is_stop(): break return xmin def _is_stop(self): def disp(s):" 2107,https://:@github.com/The-Politico/django-politico-staff.git,119c1cd3ba70d18e733d4c0cb2d4dc2f89be5428,"@@ -64,7 +64,7 @@ def sync_slack_users(pks): profile, created = Profile.objects.update_or_create( user=user, defaults={ - ""slack_api_id"": slack_profile[""id""], + ""slack_api_id"": slack_user[""id""], ""politico_title"": slack_profile.get(""title"", ""Staff writer""), }, ) ",staff/tasks/user.py,"ReplaceText(target='slack_user' @(67,32)->(67,45))","def sync_slack_users(pks): profile, created = Profile.objects.update_or_create( user=user, defaults={ ""slack_api_id"": slack_profile[""id""], ""politico_title"": slack_profile.get(""title"", ""Staff writer""), }, )","def sync_slack_users(pks): profile, created = Profile.objects.update_or_create( user=user, defaults={ ""slack_api_id"": slack_user[""id""], ""politico_title"": slack_profile.get(""title"", ""Staff writer""), }, )" 2108,https://:@bitbucket.org/verisage/python-harvest-oauth.git,e31145b870253beda1cf37671a84036864c05544,"@@ -135,7 +135,7 @@ class TestHarvest(unittest.TestCase): with patch('add_time.json') as oauth2_mock: r = self.oauth_client.add(add_data, params={'access_token': self.TEST_ACCESS}) - add_mock.assert_called_once_with('POST', '/daily/add', add_data, params={'access_token':self.TEST_ACCESS}) + oauth2_mock.assert_called_once_with('POST', '/daily/add', add_data, params={'access_token':self.TEST_ACCESS}) self.assertTrue(r) if __name__ == '__main__': ",tests/harvest_test.py,"ReplaceText(target='oauth2_mock' @(138,12)->(138,20))","class TestHarvest(unittest.TestCase): with patch('add_time.json') as oauth2_mock: r = self.oauth_client.add(add_data, params={'access_token': self.TEST_ACCESS}) add_mock.assert_called_once_with('POST', '/daily/add', add_data, params={'access_token':self.TEST_ACCESS}) self.assertTrue(r) if __name__ == '__main__':","class TestHarvest(unittest.TestCase): with patch('add_time.json') as oauth2_mock: r = self.oauth_client.add(add_data, params={'access_token': self.TEST_ACCESS}) oauth2_mock.assert_called_once_with('POST', '/daily/add', add_data, params={'access_token':self.TEST_ACCESS}) self.assertTrue(r) if __name__ == '__main__':" 2109,https://:@github.com/zadorlab/KinBot.git,47ebac0df7af70d23b52bd2681a42f91b99c824a,"@@ -16,7 +16,7 @@ class IntraRAddExocyclicF(GeneralReac): self.fix_bonds(fix) if step < self.dihstep: - self.set_dihedrals(change, fix, cut=1) + self.set_dihedrals(change, step, cut=1) elif step == self.dihstep: self.fix_dihedrals(fix) ",kinbot/reac_Intra_R_Add_Exocyclic_F.py,"ReplaceText(target='step' @(19,39)->(19,42))","class IntraRAddExocyclicF(GeneralReac): self.fix_bonds(fix) if step < self.dihstep: self.set_dihedrals(change, fix, cut=1) elif step == self.dihstep: self.fix_dihedrals(fix)","class IntraRAddExocyclicF(GeneralReac): self.fix_bonds(fix) if step < self.dihstep: self.set_dihedrals(change, step, cut=1) elif step == self.dihstep: self.fix_dihedrals(fix)" 2110,https://:@github.com/zadorlab/KinBot.git,11b23a25b4b4e814ac43dcda3d395687498b076d,"@@ -1037,7 +1037,7 @@ class ReactionFinder: if k not in korcek_chain_filt and l not in korcek_chain_filt: korcek_chain_filt.append(kch) - for ins in korcek_chain: + for ins in korcek_chain_filt: if bond[ins[0]][ins[-1]] == 1: # it is a ring rxns += [ins] ",kinbot/reaction_finder.py,"ReplaceText(target='korcek_chain_filt' @(1040,23)->(1040,35))","class ReactionFinder: if k not in korcek_chain_filt and l not in korcek_chain_filt: korcek_chain_filt.append(kch) for ins in korcek_chain: if bond[ins[0]][ins[-1]] == 1: # it is a ring rxns += [ins] ","class ReactionFinder: if k not in korcek_chain_filt and l not in korcek_chain_filt: korcek_chain_filt.append(kch) for ins in korcek_chain_filt: if bond[ins[0]][ins[-1]] == 1: # it is a ring rxns += [ins] " 2111,https://:@github.com/fabiommendes/kpop.git,67feb4ed935ad5e52840c410ec9a61958c2e65d0,"@@ -126,7 +126,7 @@ class Plot(Attr): kwargs.pop('self', None) pop = self._population - coords = pop.projection(which, 2, **coords_kwargs) + coords = pop.projection(2, which, **coords_kwargs) return self.scatter_coords(coords, **scatter_kwargs) def scatter_coords(self, coords, merge=False, colors=None, title=None, ",src/kpop/population/plot.py,"ArgSwap(idxs=0<->1 @(129,17)->(129,31))","class Plot(Attr): kwargs.pop('self', None) pop = self._population coords = pop.projection(which, 2, **coords_kwargs) return self.scatter_coords(coords, **scatter_kwargs) def scatter_coords(self, coords, merge=False, colors=None, title=None,","class Plot(Attr): kwargs.pop('self', None) pop = self._population coords = pop.projection(2, which, **coords_kwargs) return self.scatter_coords(coords, **scatter_kwargs) def scatter_coords(self, coords, merge=False, colors=None, title=None," 2112,https://:@github.com/fabiommendes/kpop.git,f7ed21864aab121b3cca7544545059b9c93008e5,"@@ -11,7 +11,7 @@ def file_or_path(func): def decorated(file, *args, **kwargs): if isinstance(file, str): with open(file) as F: - result = func(file, *args, **kwargs) + result = func(F, *args, **kwargs) return result else: return func(file, *args, **kwargs) ",src/kpop/io/utils.py,"ReplaceText(target='F' @(14,30)->(14,34))","def file_or_path(func): def decorated(file, *args, **kwargs): if isinstance(file, str): with open(file) as F: result = func(file, *args, **kwargs) return result else: return func(file, *args, **kwargs)","def file_or_path(func): def decorated(file, *args, **kwargs): if isinstance(file, str): with open(file) as F: result = func(F, *args, **kwargs) return result else: return func(file, *args, **kwargs)" 2113,https://:@github.com/ocean-perception/auv_nav.git,b9d53bbb3836981f47891730e765f9ccbb726345,"@@ -251,7 +251,7 @@ def interpolate_sensor_list(sensor_list, sensor_list[i].eastings, sensor_list[i].northings) - if _centre_list[i].covariance is not None: + if _centre_list[j].covariance is not None: sensor_list[i].covariance = interpolate_covariance( sensor_list[i].epoch_timestamp, _centre_list[j-1].epoch_timestamp, ",auv_nav/tools/interpolate.py,"ReplaceText(target='j' @(254,28)->(254,29))","def interpolate_sensor_list(sensor_list, sensor_list[i].eastings, sensor_list[i].northings) if _centre_list[i].covariance is not None: sensor_list[i].covariance = interpolate_covariance( sensor_list[i].epoch_timestamp, _centre_list[j-1].epoch_timestamp,","def interpolate_sensor_list(sensor_list, sensor_list[i].eastings, sensor_list[i].northings) if _centre_list[j].covariance is not None: sensor_list[i].covariance = interpolate_covariance( sensor_list[i].epoch_timestamp, _centre_list[j-1].epoch_timestamp," 2114,https://:@github.com/ocean-perception/auv_nav.git,338d30cbe4b97a33d0e85c880ac3dd44bd1212b5,"@@ -671,7 +671,7 @@ def plot_2d_deadreckoning(camera1_list, [float(i.eastings) for i in pf_fusion_dvl_list], [float(i.northings) for i in pf_fusion_dvl_list]], i) - if len(pf_timestamps_interval) > 1: + if len(pf_fusion_centre_list) > 1: make_frame(frame, ['pf_dvl_distribution', pf_timestamps_interval, ",auv_nav/plot/plot_process_data.py,"ReplaceText(target='pf_fusion_centre_list' @(674,15)->(674,37))","def plot_2d_deadreckoning(camera1_list, [float(i.eastings) for i in pf_fusion_dvl_list], [float(i.northings) for i in pf_fusion_dvl_list]], i) if len(pf_timestamps_interval) > 1: make_frame(frame, ['pf_dvl_distribution', pf_timestamps_interval,","def plot_2d_deadreckoning(camera1_list, [float(i.eastings) for i in pf_fusion_dvl_list], [float(i.northings) for i in pf_fusion_dvl_list]], i) if len(pf_fusion_centre_list) > 1: make_frame(frame, ['pf_dvl_distribution', pf_timestamps_interval," 2115,https://:@github.com/ocean-perception/auv_nav.git,189387b6c5a95518839624237c2f95073c301a8b,"@@ -49,7 +49,7 @@ def run_ransac(data, estimate, is_inlier, sample_size, goal_inliers, max_iterati if ic > goal_inliers and stop_at_goal: break # estimate final model using all inliers - m = fit_plane(inliers) + best_model = fit_plane(inliers) return best_model, inliers, i ",auv_cal/ransac.py,"ReplaceText(target='best_model' @(52,4)->(52,5))","def run_ransac(data, estimate, is_inlier, sample_size, goal_inliers, max_iterati if ic > goal_inliers and stop_at_goal: break # estimate final model using all inliers m = fit_plane(inliers) return best_model, inliers, i ","def run_ransac(data, estimate, is_inlier, sample_size, goal_inliers, max_iterati if ic > goal_inliers and stop_at_goal: break # estimate final model using all inliers best_model = fit_plane(inliers) return best_model, inliers, i " 2116,https://:@github.com/ocean-perception/auv_nav.git,8767eda5191ee84d65f3338f30382fbfd7815281,"@@ -428,7 +428,7 @@ class LaserCalibrator(): point_cloud_local = random.sample(inliers_cloud_list, cloud_sample_size) total_no_points = len(point_cloud_local) p = Plane([1, 0, 0, 1.5]) - m = p.fit_non_robust(cloud) + m = p.fit_non_robust(point_cloud_local) """""" m, _ = plane_fitting_ransac( point_cloud_local, ",auv_cal/laser_calibrator.py,"ReplaceText(target='point_cloud_local' @(431,33)->(431,38))","class LaserCalibrator(): point_cloud_local = random.sample(inliers_cloud_list, cloud_sample_size) total_no_points = len(point_cloud_local) p = Plane([1, 0, 0, 1.5]) m = p.fit_non_robust(cloud) """""" m, _ = plane_fitting_ransac( point_cloud_local,","class LaserCalibrator(): point_cloud_local = random.sample(inliers_cloud_list, cloud_sample_size) total_no_points = len(point_cloud_local) p = Plane([1, 0, 0, 1.5]) m = p.fit_non_robust(point_cloud_local) """""" m, _ = plane_fitting_ransac( point_cloud_local," 2117,https://:@github.com/DiffusionMapsAcademics/pyDiffMap.git,94705d0c523a9a87b7f6dd9b4074d895c805ce8d,"@@ -196,7 +196,7 @@ class Kernel(object): elif epsilon == 'bgh': # Berry, Giannakis Harlim method. if (self.metric != 'euclidean'): # TODO : replace with call to scipy metrics. warnings.warn('The BGH method for choosing epsilon assumes a euclidean metric. However, the metric being used is %s. Proceed at your own risk...' % self.metric) - if self.scaled_dists is not None: + if self.scaled_dists is None: self.scaled_dists = self._get_scaled_distance_mat(self.data, self.bandwidths) self.epsilon_fitted, self.d = choose_optimal_epsilon_BGH(self.scaled_dists.data**2) else: ",src/pydiffmap/kernel.py,"ReplaceText(target=' is ' @(199,32)->(199,40))","class Kernel(object): elif epsilon == 'bgh': # Berry, Giannakis Harlim method. if (self.metric != 'euclidean'): # TODO : replace with call to scipy metrics. warnings.warn('The BGH method for choosing epsilon assumes a euclidean metric. However, the metric being used is %s. Proceed at your own risk...' % self.metric) if self.scaled_dists is not None: self.scaled_dists = self._get_scaled_distance_mat(self.data, self.bandwidths) self.epsilon_fitted, self.d = choose_optimal_epsilon_BGH(self.scaled_dists.data**2) else:","class Kernel(object): elif epsilon == 'bgh': # Berry, Giannakis Harlim method. if (self.metric != 'euclidean'): # TODO : replace with call to scipy metrics. warnings.warn('The BGH method for choosing epsilon assumes a euclidean metric. However, the metric being used is %s. Proceed at your own risk...' % self.metric) if self.scaled_dists is None: self.scaled_dists = self._get_scaled_distance_mat(self.data, self.bandwidths) self.epsilon_fitted, self.d = choose_optimal_epsilon_BGH(self.scaled_dists.data**2) else:" 2118,https://:@github.com/grm/py-smart-gardena.git,1851380e4082d4440fdc12d0dc77e04eebfd3e2a,"@@ -162,7 +162,7 @@ class SmartSystem: devices_smart_system[real_id][device[""type""]] = [] devices_smart_system[real_id][device[""type""]].append(device) for parsed_device in devices_smart_system.values(): - location.add_device(DeviceFactory.build(self, device)) + location.add_device(DeviceFactory.build(self, parsed_device)) def start_ws(self): url = f""{self.SMART_HOST}/v1/locations"" ",src/gardena/smart_system.py,"ReplaceText(target='parsed_device' @(165,62)->(165,68))","class SmartSystem: devices_smart_system[real_id][device[""type""]] = [] devices_smart_system[real_id][device[""type""]].append(device) for parsed_device in devices_smart_system.values(): location.add_device(DeviceFactory.build(self, device)) def start_ws(self): url = f""{self.SMART_HOST}/v1/locations""","class SmartSystem: devices_smart_system[real_id][device[""type""]] = [] devices_smart_system[real_id][device[""type""]].append(device) for parsed_device in devices_smart_system.values(): location.add_device(DeviceFactory.build(self, parsed_device)) def start_ws(self): url = f""{self.SMART_HOST}/v1/locations""" 2119,https://:@github.com/Stupeflix/zfs_backup.git,95be33619441d81b9797e249625de88afcc764d5,"@@ -81,7 +81,7 @@ class Snapshot(object): def try_to_create(self): limit = datetime.now() - timedelta(seconds=self.settings['SNAPSHOT_INTERVAL']) - if 'date' in self.last_snapshot or self.last_snapshot['date'] <= limit: + if 'date' not in self.last_snapshot or self.last_snapshot['date'] <= limit: self.create() def remove_snapshot(self, snapshot): ",zfs_backup/snapshot.py,"ReplaceText(target=' not in ' @(84,17)->(84,21))","class Snapshot(object): def try_to_create(self): limit = datetime.now() - timedelta(seconds=self.settings['SNAPSHOT_INTERVAL']) if 'date' in self.last_snapshot or self.last_snapshot['date'] <= limit: self.create() def remove_snapshot(self, snapshot):","class Snapshot(object): def try_to_create(self): limit = datetime.now() - timedelta(seconds=self.settings['SNAPSHOT_INTERVAL']) if 'date' not in self.last_snapshot or self.last_snapshot['date'] <= limit: self.create() def remove_snapshot(self, snapshot):" 2120,https://:@github.com/ilblackdragon/studio.git,c6a526f0966c0bd609904d5edc3d530bee4b21b7,"@@ -14,7 +14,7 @@ class PubsubQueue(object): self.logger.setLevel(verbose) sub_name = sub_name if sub_name else queue_name + ""_sub"" self.logger.info(""Topic name = {}"".format(queue_name)) - self.logger.info(""Subscription name = {}"".format(queue_name)) + self.logger.info(""Subscription name = {}"".format(sub_name)) if queue_name not in [t.name for t in self.client.list_topics()]: self.topic.create() self.logger.info('topic {} created'.format(queue_name)) ",studio/pubsub_queue.py,"ReplaceText(target='sub_name' @(17,57)->(17,67))","class PubsubQueue(object): self.logger.setLevel(verbose) sub_name = sub_name if sub_name else queue_name + ""_sub"" self.logger.info(""Topic name = {}"".format(queue_name)) self.logger.info(""Subscription name = {}"".format(queue_name)) if queue_name not in [t.name for t in self.client.list_topics()]: self.topic.create() self.logger.info('topic {} created'.format(queue_name))","class PubsubQueue(object): self.logger.setLevel(verbose) sub_name = sub_name if sub_name else queue_name + ""_sub"" self.logger.info(""Topic name = {}"".format(queue_name)) self.logger.info(""Subscription name = {}"".format(sub_name)) if queue_name not in [t.name for t in self.client.list_topics()]: self.topic.create() self.logger.info('topic {} created'.format(queue_name))" 2121,https://:@github.com/ilblackdragon/studio.git,eb2c4eb5fc61d879b77062bec7c626815d20e30f,"@@ -195,7 +195,7 @@ class RMQueue(object): """""" self._logger.debug('declare queue ' + queue_name) with self._rmq_lock: - self._channel.queue_declare(self.on_queue_declareok, queue_name) + self._channel.queue_declare(queue_name, self.on_queue_declareok) def on_queue_declareok(self, method_frame): """""" ",studio/rabbit_queue.py,"ArgSwap(idxs=0<->1 @(198,12)->(198,39))","class RMQueue(object): """""" self._logger.debug('declare queue ' + queue_name) with self._rmq_lock: self._channel.queue_declare(self.on_queue_declareok, queue_name) def on_queue_declareok(self, method_frame): """"""","class RMQueue(object): """""" self._logger.debug('declare queue ' + queue_name) with self._rmq_lock: self._channel.queue_declare(queue_name, self.on_queue_declareok) def on_queue_declareok(self, method_frame): """"""" 2122,https://:@github.com/exopy/exopy_hqc_legacy.git,50201c6854aaac9abac67ba1a2c53bf41b871e34,"@@ -221,7 +221,7 @@ class SPADQ14(DllInstrument): # If we are not averaging we wait for all records to be acquired. if not n_records or (not average and - n_records < retrieved_records): + n_records < records_per_capture): time.sleep(1e-6) continue if not get_data(cu, id_, buffers_ptr, ",exopy_hqc_legacy/instruments/drivers/dll/sp_adq14.py,"ReplaceText(target='records_per_capture' @(224,45)->(224,62))","class SPADQ14(DllInstrument): # If we are not averaging we wait for all records to be acquired. if not n_records or (not average and n_records < retrieved_records): time.sleep(1e-6) continue if not get_data(cu, id_, buffers_ptr,","class SPADQ14(DllInstrument): # If we are not averaging we wait for all records to be acquired. if not n_records or (not average and n_records < records_per_capture): time.sleep(1e-6) continue if not get_data(cu, id_, buffers_ptr," 2123,https://:@github.com/uw-loci/multiscale.git,bf29e09937e4b119cac002762b170438fe00e13a,"@@ -164,7 +164,7 @@ def process_orientation_alignment(ret_image_path, orient_image_path, retardance, orientation = calculate_retardance_over_area( ret_roi, orient_roi) - alignment = calculate_alignment(orient_tile) + alignment = calculate_alignment(orient_roi) sample = blk.get_core_file_name(output_path) mouse, slide = sample.split('-') ",mp_img_manip/polarimetry.py,"ReplaceText(target='orient_roi' @(167,56)->(167,67))","def process_orientation_alignment(ret_image_path, orient_image_path, retardance, orientation = calculate_retardance_over_area( ret_roi, orient_roi) alignment = calculate_alignment(orient_tile) sample = blk.get_core_file_name(output_path) mouse, slide = sample.split('-')","def process_orientation_alignment(ret_image_path, orient_image_path, retardance, orientation = calculate_retardance_over_area( ret_roi, orient_roi) alignment = calculate_alignment(orient_roi) sample = blk.get_core_file_name(output_path) mouse, slide = sample.split('-')" 2124,https://:@github.com/uw-loci/multiscale.git,1b703cd8f176c289d52c195094a7f2035ebf0a15,"@@ -78,7 +78,7 @@ def plot_overlay(fixed_image: sitk.Image, moving_image: sitk.Image, transform: s if downsample: fixed_shrunk = trans.resize_image(fixed_image, fixed_image.GetSpacing()[0], downsample_target) - rotated_shrunk = trans.resize_image(rotated_image, moving_image.GetSpacing()[0], downsample_target) + rotated_shrunk = trans.resize_image(rotated_image, fixed_image.GetSpacing()[0], downsample_target) spacing = fixed_shrunk.GetSpacing() overlay_array = overlay_images(fixed_shrunk, rotated_shrunk) ",multiscale/itk/itk_plotting.py,"ReplaceText(target='fixed_image' @(81,67)->(81,79))","def plot_overlay(fixed_image: sitk.Image, moving_image: sitk.Image, transform: s if downsample: fixed_shrunk = trans.resize_image(fixed_image, fixed_image.GetSpacing()[0], downsample_target) rotated_shrunk = trans.resize_image(rotated_image, moving_image.GetSpacing()[0], downsample_target) spacing = fixed_shrunk.GetSpacing() overlay_array = overlay_images(fixed_shrunk, rotated_shrunk)","def plot_overlay(fixed_image: sitk.Image, moving_image: sitk.Image, transform: s if downsample: fixed_shrunk = trans.resize_image(fixed_image, fixed_image.GetSpacing()[0], downsample_target) rotated_shrunk = trans.resize_image(rotated_image, fixed_image.GetSpacing()[0], downsample_target) spacing = fixed_shrunk.GetSpacing() overlay_array = overlay_images(fixed_shrunk, rotated_shrunk)" 2125,https://:@github.com/uw-loci/multiscale.git,66a12265d2e2289686d445c9a9785581773bc31b,"@@ -106,7 +106,7 @@ def process_orientation_alignment(ret_image_path, orient_image_path, if roi_size is None: with open(output_path, 'w', newline='') as csvfile: print('\nWriting average retardance file for {} at tile size {}'.format( - output_path.name, tile_size[0])) + ret_image_path.name, tile_size[0])) writer = csv.writer(csvfile) writer.writerow(['Mouse', 'Slide', 'Modality', 'Tile', 'Retardance', 'Orientation', 'Alignment']) ",multiscale/polarimetry/polarimetry.py,"ReplaceText(target='ret_image_path' @(109,32)->(109,43))","def process_orientation_alignment(ret_image_path, orient_image_path, if roi_size is None: with open(output_path, 'w', newline='') as csvfile: print('\nWriting average retardance file for {} at tile size {}'.format( output_path.name, tile_size[0])) writer = csv.writer(csvfile) writer.writerow(['Mouse', 'Slide', 'Modality', 'Tile', 'Retardance', 'Orientation', 'Alignment'])","def process_orientation_alignment(ret_image_path, orient_image_path, if roi_size is None: with open(output_path, 'w', newline='') as csvfile: print('\nWriting average retardance file for {} at tile size {}'.format( ret_image_path.name, tile_size[0])) writer = csv.writer(csvfile) writer.writerow(['Mouse', 'Slide', 'Modality', 'Tile', 'Retardance', 'Orientation', 'Alignment'])" 2126,https://:@github.com/l616769490/fc-utils.git,9ce6c047b524094d5dce68b8b39bd880f25a51b8,"@@ -71,7 +71,7 @@ def fieldStrAndPer(d): if v != None: l1.append(k) noAppend = True # 标记lper和l2还未赋值 - if isinstance(l2, str): + if isinstance(v, str): if v.startswith('+') or v.startswith('-') or v.startswith('*') or v.startswith('/'): vv = dataToFloat(v[1:]) if vv: ",fcutils/sql_utils.py,"ReplaceText(target='v' @(74,26)->(74,28))","def fieldStrAndPer(d): if v != None: l1.append(k) noAppend = True # 标记lper和l2还未赋值 if isinstance(l2, str): if v.startswith('+') or v.startswith('-') or v.startswith('*') or v.startswith('/'): vv = dataToFloat(v[1:]) if vv:","def fieldStrAndPer(d): if v != None: l1.append(k) noAppend = True # 标记lper和l2还未赋值 if isinstance(v, str): if v.startswith('+') or v.startswith('-') or v.startswith('*') or v.startswith('/'): vv = dataToFloat(v[1:]) if vv:" 2127,https://:@github.com/shlomikushchi/zipline-live2.git,102cfcbe5b21dd95e73616e78b9d1b0dac7af55b,"@@ -139,7 +139,7 @@ def get_next_trading_dt(current, interval): next_dt = next_dt + interval next_dt = pd.Timestamp(next_dt, tz=trading.environment.exchange_tz) next_dt_utc = next_dt.tz_convert('UTC') - if trading.environment.is_market_hours(next_dt): + if trading.environment.is_market_hours(next_dt_utc): break next_dt = next_dt_utc.tz_convert(trading.environment.exchange_tz) ",zipline/utils/factory.py,"ReplaceText(target='next_dt_utc' @(142,47)->(142,54))","def get_next_trading_dt(current, interval): next_dt = next_dt + interval next_dt = pd.Timestamp(next_dt, tz=trading.environment.exchange_tz) next_dt_utc = next_dt.tz_convert('UTC') if trading.environment.is_market_hours(next_dt): break next_dt = next_dt_utc.tz_convert(trading.environment.exchange_tz) ","def get_next_trading_dt(current, interval): next_dt = next_dt + interval next_dt = pd.Timestamp(next_dt, tz=trading.environment.exchange_tz) next_dt_utc = next_dt.tz_convert('UTC') if trading.environment.is_market_hours(next_dt_utc): break next_dt = next_dt_utc.tz_convert(trading.environment.exchange_tz) " 2128,https://:@github.com/shlomikushchi/zipline-live2.git,0e4f3f957ad95d43e4890cc4b2ea3a10f9b3d4da,"@@ -272,7 +272,7 @@ def create_test_df_source(sim_params=None, bars='daily'): elif bars == 'minute': freq = pd.datetools.Minute() else: - raise ValueError('%s bars not understood.' % freq) + raise ValueError('%s bars not understood.' % bars) if sim_params: index = sim_params.trading_days ",zipline/utils/factory.py,"ReplaceText(target='bars' @(275,53)->(275,57))","def create_test_df_source(sim_params=None, bars='daily'): elif bars == 'minute': freq = pd.datetools.Minute() else: raise ValueError('%s bars not understood.' % freq) if sim_params: index = sim_params.trading_days","def create_test_df_source(sim_params=None, bars='daily'): elif bars == 'minute': freq = pd.datetools.Minute() else: raise ValueError('%s bars not understood.' % bars) if sim_params: index = sim_params.trading_days" 2129,https://:@github.com/shlomikushchi/zipline-live2.git,2104a35af8d43a398b4df4a947d79b642189c346,"@@ -2215,7 +2215,7 @@ class TradingAlgorithm(object): """""" control = RestrictedListOrder(on_error, restrictions) self.register_trading_control(control) - self.restrictions = restrictions + self.restrictions |= restrictions @api_method def set_long_only(self, on_error='fail'): ",zipline/algorithm.py,"ReplaceText(target='|=' @(2218,26)->(2218,27))","class TradingAlgorithm(object): """""" control = RestrictedListOrder(on_error, restrictions) self.register_trading_control(control) self.restrictions = restrictions @api_method def set_long_only(self, on_error='fail'):","class TradingAlgorithm(object): """""" control = RestrictedListOrder(on_error, restrictions) self.register_trading_control(control) self.restrictions |= restrictions @api_method def set_long_only(self, on_error='fail'):" 2130,https://:@github.com/shlomikushchi/zipline-live2.git,03782fdfd3e49af0407b15e796adb89268997dd1,"@@ -550,7 +550,7 @@ def assert_timestamp_and_datetime_equal(result, ) result = pd.Timestamp(result) - expected = pd.Timestamp(result) + expected = pd.Timestamp(expected) if compare_nat_equal and pd.isnull(result) and pd.isnull(expected): return ",zipline/testing/predicates.py,"ReplaceText(target='expected' @(553,28)->(553,34))","def assert_timestamp_and_datetime_equal(result, ) result = pd.Timestamp(result) expected = pd.Timestamp(result) if compare_nat_equal and pd.isnull(result) and pd.isnull(expected): return ","def assert_timestamp_and_datetime_equal(result, ) result = pd.Timestamp(result) expected = pd.Timestamp(expected) if compare_nat_equal and pd.isnull(result) and pd.isnull(expected): return " 2131,https://:@github.com/shlomikushchi/zipline-live2.git,6f5e353647162c074e0e88e16046cb1ec3be1563,"@@ -64,7 +64,7 @@ class RealtimeClock(object): current_time = pd.to_datetime('now', utc=True) server_time = (current_time + self.time_skew).floor('1 min') - if (server_time == self.before_trading_start_minutes[0] and + if (server_time >= self.before_trading_start_minutes[0] and not self._before_trading_start_bar_yielded): self._last_emit = server_time self._before_trading_start_bar_yielded = True ",zipline/gens/realtimeclock.py,"ReplaceText(target='>=' @(67,28)->(67,30))","class RealtimeClock(object): current_time = pd.to_datetime('now', utc=True) server_time = (current_time + self.time_skew).floor('1 min') if (server_time == self.before_trading_start_minutes[0] and not self._before_trading_start_bar_yielded): self._last_emit = server_time self._before_trading_start_bar_yielded = True","class RealtimeClock(object): current_time = pd.to_datetime('now', utc=True) server_time = (current_time + self.time_skew).floor('1 min') if (server_time >= self.before_trading_start_minutes[0] and not self._before_trading_start_bar_yielded): self._last_emit = server_time self._before_trading_start_bar_yielded = True" 2132,https://:@github.com/SiLab-Bonn/testbeam_analysis.git,e5351795584850b633befa2cf63f7a372b58c9e5,"@@ -313,7 +313,7 @@ def calculate_residuals(input_tracks_file, input_alignment_file, output_residual name='XResidualsY_DUT%d' % (actual_dut), title='Residual distribution in y direction as a function of the x position for DUT %d ' % (actual_dut), atom=tb.Atom.from_dtype(hist_x_residual_y_hist.dtype), - shape=hist_x_residual_x_hist.shape, + shape=hist_x_residual_y_hist.shape, filters=tb.Filters(complib='blosc', complevel=5, fletcher32=False)) out_x_res_y.attrs.xedges = hist_x_residual_y_xedges out_x_res_y.attrs.yedges = hist_x_residual_y_yedges ",testbeam_analysis/result_analysis.py,"ReplaceText(target='hist_x_residual_y_hist' @(316,61)->(316,83))","def calculate_residuals(input_tracks_file, input_alignment_file, output_residual name='XResidualsY_DUT%d' % (actual_dut), title='Residual distribution in y direction as a function of the x position for DUT %d ' % (actual_dut), atom=tb.Atom.from_dtype(hist_x_residual_y_hist.dtype), shape=hist_x_residual_x_hist.shape, filters=tb.Filters(complib='blosc', complevel=5, fletcher32=False)) out_x_res_y.attrs.xedges = hist_x_residual_y_xedges out_x_res_y.attrs.yedges = hist_x_residual_y_yedges","def calculate_residuals(input_tracks_file, input_alignment_file, output_residual name='XResidualsY_DUT%d' % (actual_dut), title='Residual distribution in y direction as a function of the x position for DUT %d ' % (actual_dut), atom=tb.Atom.from_dtype(hist_x_residual_y_hist.dtype), shape=hist_x_residual_y_hist.shape, filters=tb.Filters(complib='blosc', complevel=5, fletcher32=False)) out_x_res_y.attrs.xedges = hist_x_residual_y_xedges out_x_res_y.attrs.yedges = hist_x_residual_y_yedges" 2133,https://:@github.com/SiLab-Bonn/testbeam_analysis.git,c44b1a0a37f1897ef97caa7f510931d958b6291d,"@@ -398,7 +398,7 @@ def calculate_residuals(input_tracks_file, input_alignment_file, output_residual name='ColumnResidualsRow_DUT%d' % (actual_dut), title='Residual distribution in row direction as a function of the column position for DUT %d ' % (actual_dut), atom=tb.Atom.from_dtype(hist_col_residual_row_hist.dtype), - shape=hist_col_residual_col_hist.shape, + shape=hist_col_residual_row_hist.shape, filters=tb.Filters(complib='blosc', complevel=5, fletcher32=False)) out_col_res_row.attrs.xedges = hist_col_residual_row_xedges out_col_res_row.attrs.yedges = hist_col_residual_row_yedges ",testbeam_analysis/result_analysis.py,"ReplaceText(target='hist_col_residual_row_hist' @(401,65)->(401,91))","def calculate_residuals(input_tracks_file, input_alignment_file, output_residual name='ColumnResidualsRow_DUT%d' % (actual_dut), title='Residual distribution in row direction as a function of the column position for DUT %d ' % (actual_dut), atom=tb.Atom.from_dtype(hist_col_residual_row_hist.dtype), shape=hist_col_residual_col_hist.shape, filters=tb.Filters(complib='blosc', complevel=5, fletcher32=False)) out_col_res_row.attrs.xedges = hist_col_residual_row_xedges out_col_res_row.attrs.yedges = hist_col_residual_row_yedges","def calculate_residuals(input_tracks_file, input_alignment_file, output_residual name='ColumnResidualsRow_DUT%d' % (actual_dut), title='Residual distribution in row direction as a function of the column position for DUT %d ' % (actual_dut), atom=tb.Atom.from_dtype(hist_col_residual_row_hist.dtype), shape=hist_col_residual_row_hist.shape, filters=tb.Filters(complib='blosc', complevel=5, fletcher32=False)) out_col_res_row.attrs.xedges = hist_col_residual_row_xedges out_col_res_row.attrs.yedges = hist_col_residual_row_yedges" 2134,https://:@github.com/SiLab-Bonn/testbeam_analysis.git,7b1825cc07d59af6921e6b95c2e020e116d65c21,"@@ -418,7 +418,7 @@ def fit_tracks(input_track_candidates_file, input_alignment_file, output_tracks_ # Split data and fit on all available cores n_slices = cpu_count() - slices = np.array_split(n_tracks, n_slices) + slices = np.array_split(track_hits, n_slices) results = pool.map(_fit_tracks_loop, slices) del track_hits ",testbeam_analysis/track_analysis.py,"ReplaceText(target='track_hits' @(421,48)->(421,56))","def fit_tracks(input_track_candidates_file, input_alignment_file, output_tracks_ # Split data and fit on all available cores n_slices = cpu_count() slices = np.array_split(n_tracks, n_slices) results = pool.map(_fit_tracks_loop, slices) del track_hits ","def fit_tracks(input_track_candidates_file, input_alignment_file, output_tracks_ # Split data and fit on all available cores n_slices = cpu_count() slices = np.array_split(track_hits, n_slices) results = pool.map(_fit_tracks_loop, slices) del track_hits " 2135,https://:@github.com/SiLab-Bonn/testbeam_analysis.git,4f8bb30949aba54a1c83b0cc2e9dc03c633a6673,"@@ -593,7 +593,7 @@ def _find_tracks_loop(tracklets, tr_column, tr_row, tr_z, tr_charge, column_sigm # print '== ACTUAL DUT ==', dut_index actual_column_sigma, actual_row_sigma = column_sigma[dut_index], row_sigma[dut_index] - if not reference_hit_set and not np.isnan(tr_row[track_index][dut_index]): # Search for first DUT that registered a hit + if not reference_hit_set and not np.isnan(tr_column[track_index][dut_index]): # Search for first DUT that registered a hit actual_track_column, actual_track_row = tr_column[track_index][dut_index], tr_row[track_index][dut_index] reference_hit_set = True tracklets[track_index]['track_quality'] |= (65793 << dut_index) # First track hit has best quality by definition ",testbeam_analysis/track_analysis.py,"ReplaceText(target='tr_column' @(596,54)->(596,60))","def _find_tracks_loop(tracklets, tr_column, tr_row, tr_z, tr_charge, column_sigm # print '== ACTUAL DUT ==', dut_index actual_column_sigma, actual_row_sigma = column_sigma[dut_index], row_sigma[dut_index] if not reference_hit_set and not np.isnan(tr_row[track_index][dut_index]): # Search for first DUT that registered a hit actual_track_column, actual_track_row = tr_column[track_index][dut_index], tr_row[track_index][dut_index] reference_hit_set = True tracklets[track_index]['track_quality'] |= (65793 << dut_index) # First track hit has best quality by definition","def _find_tracks_loop(tracklets, tr_column, tr_row, tr_z, tr_charge, column_sigm # print '== ACTUAL DUT ==', dut_index actual_column_sigma, actual_row_sigma = column_sigma[dut_index], row_sigma[dut_index] if not reference_hit_set and not np.isnan(tr_column[track_index][dut_index]): # Search for first DUT that registered a hit actual_track_column, actual_track_row = tr_column[track_index][dut_index], tr_row[track_index][dut_index] reference_hit_set = True tracklets[track_index]['track_quality'] |= (65793 << dut_index) # First track hit has best quality by definition" 2136,https://:@github.com/pfalcon/ScratchABlock.git,3d0617383d0937d2e743d3eeb37fc5389129e831,"@@ -47,7 +47,7 @@ def loop_single_entry(cfg): if not b.items: landing_site = p if not landing_site: - farthest = max(back_jumps) + farthest = max(back_preds) print(""farthest"", farthest) newb = BBlock(farthest + ""_1"") cfg.add_node(newb.addr, newb) ",xform.py,"ReplaceText(target='back_preds' @(50,31)->(50,41))","def loop_single_entry(cfg): if not b.items: landing_site = p if not landing_site: farthest = max(back_jumps) print(""farthest"", farthest) newb = BBlock(farthest + ""_1"") cfg.add_node(newb.addr, newb)","def loop_single_entry(cfg): if not b.items: landing_site = p if not landing_site: farthest = max(back_preds) print(""farthest"", farthest) newb = BBlock(farthest + ""_1"") cfg.add_node(newb.addr, newb)" 2137,https://:@github.com/theislab/trVAE.git,839a30f966f4bd7654d56910dee543f129efea94,"@@ -493,7 +493,7 @@ class RCCVAE: if self.train_with_fake_labels: x_train = np.reshape(train_data.X, newshape=(-1, *self.x_dim)) x = [x_train, train_labels, pseudo_labels] - y = [x_train, pseudo_labels] + y = [x_train, train_labels] else: x_train = np.reshape(train_data.X, newshape=(-1, *self.x_dim)) x = [x_train, train_labels, train_labels] ",rcvae/models/_rccvae.py,"ReplaceText(target='train_labels' @(496,26)->(496,39))","class RCCVAE: if self.train_with_fake_labels: x_train = np.reshape(train_data.X, newshape=(-1, *self.x_dim)) x = [x_train, train_labels, pseudo_labels] y = [x_train, pseudo_labels] else: x_train = np.reshape(train_data.X, newshape=(-1, *self.x_dim)) x = [x_train, train_labels, train_labels]","class RCCVAE: if self.train_with_fake_labels: x_train = np.reshape(train_data.X, newshape=(-1, *self.x_dim)) x = [x_train, train_labels, pseudo_labels] y = [x_train, train_labels] else: x_train = np.reshape(train_data.X, newshape=(-1, *self.x_dim)) x = [x_train, train_labels, train_labels]" 2138,https://:@github.com/theislab/trVAE.git,7eac79cf26380e6f665884ef1b1a330aecdab93a,"@@ -139,7 +139,7 @@ def train_network(data_dict=None, model_path=f""../models/{data_name}-{img_resize}-{preprocess}/{arch_style}-{z_dim}/"", dropout_rate=dropout_rate) - print(train_data.shape, data_valid.shape) + print(train_data.shape, valid_data.shape) network.train(train_data, use_validation=True, ",tests/test_rccvae.py,"ReplaceText(target='valid_data' @(142,28)->(142,38))","def train_network(data_dict=None, model_path=f""../models/{data_name}-{img_resize}-{preprocess}/{arch_style}-{z_dim}/"", dropout_rate=dropout_rate) print(train_data.shape, data_valid.shape) network.train(train_data, use_validation=True,","def train_network(data_dict=None, model_path=f""../models/{data_name}-{img_resize}-{preprocess}/{arch_style}-{z_dim}/"", dropout_rate=dropout_rate) print(train_data.shape, valid_data.shape) network.train(train_data, use_validation=True," 2139,https://:@github.com/theislab/trVAE.git,106ef16445334677462106453aa6e43ce1ece084,"@@ -106,7 +106,7 @@ def reconstruct_whole_data(data_dict={}, z_dim=100): cell_type_data = train[train.obs[cell_type_key] == cell_type] cell_type_ctrl_data = train[((train.obs[cell_type_key] == cell_type) & (train.obs[""condition""] == ctrl_key))] - pred = network.predict(cell_type_data, + pred = network.predict(cell_type_ctrl_data, encoder_labels=np.zeros((cell_type_ctrl_data.shape[0], 1)), decoder_labels=np.ones((cell_type_ctrl_data.shape[0], 1))) ",tests/test_rcvae.py,"ReplaceText(target='cell_type_ctrl_data' @(109,31)->(109,45))","def reconstruct_whole_data(data_dict={}, z_dim=100): cell_type_data = train[train.obs[cell_type_key] == cell_type] cell_type_ctrl_data = train[((train.obs[cell_type_key] == cell_type) & (train.obs[""condition""] == ctrl_key))] pred = network.predict(cell_type_data, encoder_labels=np.zeros((cell_type_ctrl_data.shape[0], 1)), decoder_labels=np.ones((cell_type_ctrl_data.shape[0], 1))) ","def reconstruct_whole_data(data_dict={}, z_dim=100): cell_type_data = train[train.obs[cell_type_key] == cell_type] cell_type_ctrl_data = train[((train.obs[cell_type_key] == cell_type) & (train.obs[""condition""] == ctrl_key))] pred = network.predict(cell_type_ctrl_data, encoder_labels=np.zeros((cell_type_ctrl_data.shape[0], 1)), decoder_labels=np.ones((cell_type_ctrl_data.shape[0], 1))) " 2140,https://:@github.com/theislab/trVAE.git,6a19b6aa1c89f14ac093ebf0f20a8c6cb902a632,"@@ -222,7 +222,7 @@ def evaluate_network(data_dict=None, z_dim=100, n_files=5, k=5, arch_style=1, pr if sparse.issparse(valid_data.X): valid_data.X = valid_data.X.A - source_images_train = train_data[valid_data.obs[""condition""] == source_key].X + source_images_train = train_data[train_data.obs[""condition""] == source_key].X source_images_valid = valid_data[valid_data.obs[""condition""] == source_key].X source_images_train = np.reshape(source_images_train, (-1, img_width, img_height, n_channels)) ",tests/test_rccvae.py,"ReplaceText(target='train_data' @(225,41)->(225,51))","def evaluate_network(data_dict=None, z_dim=100, n_files=5, k=5, arch_style=1, pr if sparse.issparse(valid_data.X): valid_data.X = valid_data.X.A source_images_train = train_data[valid_data.obs[""condition""] == source_key].X source_images_valid = valid_data[valid_data.obs[""condition""] == source_key].X source_images_train = np.reshape(source_images_train, (-1, img_width, img_height, n_channels))","def evaluate_network(data_dict=None, z_dim=100, n_files=5, k=5, arch_style=1, pr if sparse.issparse(valid_data.X): valid_data.X = valid_data.X.A source_images_train = train_data[train_data.obs[""condition""] == source_key].X source_images_valid = valid_data[valid_data.obs[""condition""] == source_key].X source_images_train = np.reshape(source_images_train, (-1, img_width, img_height, n_channels))" 2141,https://:@github.com/theislab/trVAE.git,99e9fa47a8024f4ea73c83f462ea2a5f5c78b87e,"@@ -318,7 +318,7 @@ def visualize_trained_network_results(data_dict, z_dim=100, mmd_dimension=128, a frameon=False) for gene in top_100_genes[:3]: - sc.pl.violin(cell_type_adata, keys=gene, groupby=condition_key, + sc.pl.violin(pred_adatas, keys=gene, groupby=condition_key, save=f""_{data_name}_{cell_type}_{gene}.pdf"", show=False, wspace=0.2, ",tests/test_rcvae_multi.py,"ReplaceText(target='pred_adatas' @(321,25)->(321,40))","def visualize_trained_network_results(data_dict, z_dim=100, mmd_dimension=128, a frameon=False) for gene in top_100_genes[:3]: sc.pl.violin(cell_type_adata, keys=gene, groupby=condition_key, save=f""_{data_name}_{cell_type}_{gene}.pdf"", show=False, wspace=0.2,","def visualize_trained_network_results(data_dict, z_dim=100, mmd_dimension=128, a frameon=False) for gene in top_100_genes[:3]: sc.pl.violin(pred_adatas, keys=gene, groupby=condition_key, save=f""_{data_name}_{cell_type}_{gene}.pdf"", show=False, wspace=0.2," 2142,https://:@github.com/succhiello/hieratic.git,1a67208b4af1892081323d0f4ff4db36e5500ec8,"@@ -108,7 +108,7 @@ class ItemResource(Resource): persistence_converter = self.get_persistence_converter(self.engine_name) if persistence_converter is not None: updates = persistence_converter(updates) - self.engine.update(patch, primary_index, context, updates) + self.engine.update(primary_index, patch, context, updates) self.get_data() def delete(self, context=None): ",hieratic/item.py,"ArgSwap(idxs=0<->1 @(111,8)->(111,26))","class ItemResource(Resource): persistence_converter = self.get_persistence_converter(self.engine_name) if persistence_converter is not None: updates = persistence_converter(updates) self.engine.update(patch, primary_index, context, updates) self.get_data() def delete(self, context=None):","class ItemResource(Resource): persistence_converter = self.get_persistence_converter(self.engine_name) if persistence_converter is not None: updates = persistence_converter(updates) self.engine.update(primary_index, patch, context, updates) self.get_data() def delete(self, context=None):" 2143,https://:@github.com/jeff-99/hashdex.git,db7083cb6b71fdb7a28c04721b3551a146bfd6cb,"@@ -14,7 +14,7 @@ class DirectoryScanner(object): file_list.append(File(os.path.join(root, file), file)) for subdir in subdirs: - self._fetch_files(subdir, files) + self._fetch_files(subdir, file_list) return file_list ",hashdex/files.py,"ReplaceText(target='file_list' @(17,42)->(17,47))","class DirectoryScanner(object): file_list.append(File(os.path.join(root, file), file)) for subdir in subdirs: self._fetch_files(subdir, files) return file_list ","class DirectoryScanner(object): file_list.append(File(os.path.join(root, file), file)) for subdir in subdirs: self._fetch_files(subdir, file_list) return file_list " 2144,https://:@github.com/Gab0/linkageMapper.git,2e302c068dc6e0512eb5ec185273c7e34eca32cd,"@@ -186,7 +186,7 @@ def Execute(options): outputFastaName = ""LOCI_%s.fasta"" % locus_name outputFastaPath = os.path.join(options.outputPath, outputFastaName) - if os.path.isfile(outputFastaName): + if os.path.isfile(outputFastaPath): print(""Skipping locus %s. Already exists..."" % locus_name) continue ",linkageMapper/primerFinder.py,"ReplaceText(target='outputFastaPath' @(189,26)->(189,41))","def Execute(options): outputFastaName = ""LOCI_%s.fasta"" % locus_name outputFastaPath = os.path.join(options.outputPath, outputFastaName) if os.path.isfile(outputFastaName): print(""Skipping locus %s. Already exists..."" % locus_name) continue ","def Execute(options): outputFastaName = ""LOCI_%s.fasta"" % locus_name outputFastaPath = os.path.join(options.outputPath, outputFastaName) if os.path.isfile(outputFastaPath): print(""Skipping locus %s. Already exists..."" % locus_name) continue " 2145,https://:@github.com/enzoampil/psequant.git,a393849078b354a869643126d16e33273cfecf59,"@@ -155,7 +155,7 @@ def backtest( else: # Allow instance of BaseStrategy or from the predefined mapping - if issubclass(strategy, bt.Strategy): + if issubclass(bt.Strategy, strategy): strat_name = str(strategy) else: strat_name = strategy ",python/fastquant/backtest/backtest.py,"ArgSwap(idxs=0<->1 @(158,11)->(158,21))","def backtest( else: # Allow instance of BaseStrategy or from the predefined mapping if issubclass(strategy, bt.Strategy): strat_name = str(strategy) else: strat_name = strategy","def backtest( else: # Allow instance of BaseStrategy or from the predefined mapping if issubclass(bt.Strategy, strategy): strat_name = str(strategy) else: strat_name = strategy" 2146,https://:@github.com/infobyte/faraday_agent_dispatcher.git,c833c82e068e54645c983c5c50f4535661f6c2b1,"@@ -181,7 +181,7 @@ def process_repo_var_envs(executor_name, metadata: dict): env_vars = metadata[""environment_variables""] for env_var in env_vars: - def_value = config.instance[section].get(executor_name, None) + def_value = config.instance[section].get(env_var, None) value = click.prompt(f""Environment variable {env_var} value"", default=def_value) config.instance.set(section, env_var, value) ",faraday_agent_dispatcher/cli/utils/model_load.py,"ReplaceText(target='env_var' @(184,49)->(184,62))","def process_repo_var_envs(executor_name, metadata: dict): env_vars = metadata[""environment_variables""] for env_var in env_vars: def_value = config.instance[section].get(executor_name, None) value = click.prompt(f""Environment variable {env_var} value"", default=def_value) config.instance.set(section, env_var, value) ","def process_repo_var_envs(executor_name, metadata: dict): env_vars = metadata[""environment_variables""] for env_var in env_vars: def_value = config.instance[section].get(env_var, None) value = click.prompt(f""Environment variable {env_var} value"", default=def_value) config.instance.set(section, env_var, value) " 2147,https://:@github.com/leylabmpi/pyTecanFluent.git,a5ca3f143da09723ffc3fed37fe5e9f0dcb243d4,"@@ -680,7 +680,7 @@ def write_report(df_map, outFH, pcr_volume, mm_volume, ## total PCR total_pcr_volume = pcr_volume * n_rxn ## total mastermix - total_mm_volume = pcr_volume * n_rxn + total_mm_volume = mm_volume * n_rxn ## total primer if fp_tube > 0 and fp_volume > 0: total_fp_volume = fp_volume * n_rxn ",pyTecanFluent/Map2Robot.py,"ReplaceText(target='mm_volume' @(683,22)->(683,32))","def write_report(df_map, outFH, pcr_volume, mm_volume, ## total PCR total_pcr_volume = pcr_volume * n_rxn ## total mastermix total_mm_volume = pcr_volume * n_rxn ## total primer if fp_tube > 0 and fp_volume > 0: total_fp_volume = fp_volume * n_rxn","def write_report(df_map, outFH, pcr_volume, mm_volume, ## total PCR total_pcr_volume = pcr_volume * n_rxn ## total mastermix total_mm_volume = mm_volume * n_rxn ## total primer if fp_tube > 0 and fp_volume > 0: total_fp_volume = fp_volume * n_rxn" 2148,https://:@github.com/mindey/langsplit.git,11c289b80c6999eeeb17fc91212fb00a9d1b8354,"@@ -87,7 +87,7 @@ def split(text, sep='.:', ends=['\n', ':'], min_key_length=2, max_key_length=2, except Exception as e: # Alternatively, we could assign it to None key. - name[settings.UNKNOWN_LANGUAGE] += paragraph + result[settings.UNKNOWN_LANGUAGE] += paragraph logger.info('Language not detected: {}'.format(paragraph)) if i < number_of_paragraphs - 1: ",langsplit/splitter.py,"ReplaceText(target='result' @(90,24)->(90,28))","def split(text, sep='.:', ends=['\n', ':'], min_key_length=2, max_key_length=2, except Exception as e: # Alternatively, we could assign it to None key. name[settings.UNKNOWN_LANGUAGE] += paragraph logger.info('Language not detected: {}'.format(paragraph)) if i < number_of_paragraphs - 1:","def split(text, sep='.:', ends=['\n', ':'], min_key_length=2, max_key_length=2, except Exception as e: # Alternatively, we could assign it to None key. result[settings.UNKNOWN_LANGUAGE] += paragraph logger.info('Language not detected: {}'.format(paragraph)) if i < number_of_paragraphs - 1:" 2149,https://:@github.com/tkf/factlog.git,c032135fe5abcdedeb5a26c013e2f74c1c466a7d,"@@ -170,7 +170,7 @@ def list_run( from .filetitle import write_paths_and_titles write_paths_and_titles(output, paths, showpaths, separator) else: - output.writelines(interleave(paths, itertools.repeat(separator))) + output.writelines(interleave(showpaths, itertools.repeat(separator))) if output is not sys.stdout: output.close() ",factlog/record.py,"ReplaceText(target='showpaths' @(173,37)->(173,42))","def list_run( from .filetitle import write_paths_and_titles write_paths_and_titles(output, paths, showpaths, separator) else: output.writelines(interleave(paths, itertools.repeat(separator))) if output is not sys.stdout: output.close() ","def list_run( from .filetitle import write_paths_and_titles write_paths_and_titles(output, paths, showpaths, separator) else: output.writelines(interleave(showpaths, itertools.repeat(separator))) if output is not sys.stdout: output.close() " 2150,https://:@github.com/l0kix2/python-dehydrate.git,47212c6e5d2433bbe399dfbdb01ba65b48c5636b,"@@ -151,7 +151,7 @@ class ComplexField(Field): if self.is_iterable: return map(dehydrator.dehydrate, target) else: - return dehydrator.dehydrate(obj) + return dehydrator.dehydrate(target) @property def target(self): ",dehydrate/fields.py,"ReplaceText(target='target' @(154,40)->(154,43))","class ComplexField(Field): if self.is_iterable: return map(dehydrator.dehydrate, target) else: return dehydrator.dehydrate(obj) @property def target(self):","class ComplexField(Field): if self.is_iterable: return map(dehydrator.dehydrate, target) else: return dehydrator.dehydrate(target) @property def target(self):" 2151,https://:@github.com/wf4ever/ro-manager.git,cc9a10e9cd88e634ee8ff745e099696d173021de,"@@ -74,7 +74,7 @@ class Minim_graph(object): self._minimgr.add( (rule, MINIM.query, querynode) ) self._minimgr.add( (querynode, MINIM.sparql_query, rdflib.Literal(ForEach)) ) if ResultMod: - self._minimgr.add( (querynode, MINIM.result_mod, rdflib.Literal(Exists)) ) + self._minimgr.add( (querynode, MINIM.result_mod, rdflib.Literal(ResultMod)) ) if Exists: existsnode = rdflib.BNode() self._minimgr.add( (rule, MINIM.exists, existsnode) ) ",src/checklist/minim_graph.py,"ReplaceText(target='ResultMod' @(77,80)->(77,86))","class Minim_graph(object): self._minimgr.add( (rule, MINIM.query, querynode) ) self._minimgr.add( (querynode, MINIM.sparql_query, rdflib.Literal(ForEach)) ) if ResultMod: self._minimgr.add( (querynode, MINIM.result_mod, rdflib.Literal(Exists)) ) if Exists: existsnode = rdflib.BNode() self._minimgr.add( (rule, MINIM.exists, existsnode) )","class Minim_graph(object): self._minimgr.add( (rule, MINIM.query, querynode) ) self._minimgr.add( (querynode, MINIM.sparql_query, rdflib.Literal(ForEach)) ) if ResultMod: self._minimgr.add( (querynode, MINIM.result_mod, rdflib.Literal(ResultMod)) ) if Exists: existsnode = rdflib.BNode() self._minimgr.add( (rule, MINIM.exists, existsnode) )" 2152,https://:@github.com/frlender/qn.git,5b94be8b02089eb0d50c102c249c9ddd4a185091,"@@ -253,7 +253,7 @@ def loadPkl(path): def dumpPkl(obj,path): with open(path,'wb') as pf: - pickle.dump(obj,path) + pickle.dump(obj,pf) def getBaseDir(): currentPath = os.getcwd() ",py/qn.py,"ReplaceText(target='pf' @(256,18)->(256,22))","def loadPkl(path): def dumpPkl(obj,path): with open(path,'wb') as pf: pickle.dump(obj,path) def getBaseDir(): currentPath = os.getcwd()","def loadPkl(path): def dumpPkl(obj,path): with open(path,'wb') as pf: pickle.dump(obj,pf) def getBaseDir(): currentPath = os.getcwd()" 2153,https://:@bitbucket.org/pyKLIP/pyklip.git,e2bf632237365bd23a1b8287ba1bfd85d8cb7702,"@@ -311,7 +311,7 @@ class Data(object): self.filenums = filenums_collapsed self.filenames = filenames_collapsed - if additional_collapsed is not None: + if additional_params is not None: for param_field, param_collapsed in zip(additional_params, additional_collapsed): param_collapsed.shape = (Ncubes * collapse_channels, ) + param_collapsed.shape[2:] setattr(self, param_field, param_collapsed) ",pyklip/instruments/Instrument.py,"ReplaceText(target='additional_params' @(314,11)->(314,31))","class Data(object): self.filenums = filenums_collapsed self.filenames = filenames_collapsed if additional_collapsed is not None: for param_field, param_collapsed in zip(additional_params, additional_collapsed): param_collapsed.shape = (Ncubes * collapse_channels, ) + param_collapsed.shape[2:] setattr(self, param_field, param_collapsed)","class Data(object): self.filenums = filenums_collapsed self.filenames = filenames_collapsed if additional_params is not None: for param_field, param_collapsed in zip(additional_params, additional_collapsed): param_collapsed.shape = (Ncubes * collapse_channels, ) + param_collapsed.shape[2:] setattr(self, param_field, param_collapsed)" 2154,https://:@bitbucket.org/pyKLIP/pyklip.git,dc2b513633ddd04ac1746a971723a38dafb9365d,"@@ -200,7 +200,7 @@ class CHARISData(Data): with fits.open(filepath, lazy_load_hdus=False) as hdulist: cube = hdulist[1].data prihdr = hdulist[0].header - exthdr = hdulist[0].header + exthdr = hdulist[1].header w = wcs.WCS(header=prihdr, naxis=[1,2]) astr_hdrs = [w.deepcopy() for _ in range(cube.shape[0])] #repeat astrom header for each wavelength slice ",pyklip/instruments/CHARIS.py,"ReplaceText(target='1' @(203,33)->(203,34))","class CHARISData(Data): with fits.open(filepath, lazy_load_hdus=False) as hdulist: cube = hdulist[1].data prihdr = hdulist[0].header exthdr = hdulist[0].header w = wcs.WCS(header=prihdr, naxis=[1,2]) astr_hdrs = [w.deepcopy() for _ in range(cube.shape[0])] #repeat astrom header for each wavelength slice ","class CHARISData(Data): with fits.open(filepath, lazy_load_hdus=False) as hdulist: cube = hdulist[1].data prihdr = hdulist[0].header exthdr = hdulist[1].header w = wcs.WCS(header=prihdr, naxis=[1,2]) astr_hdrs = [w.deepcopy() for _ in range(cube.shape[0])] #repeat astrom header for each wavelength slice " 2155,https://:@bitbucket.org/pyKLIP/pyklip.git,34a9207f22f175f184748b87f9cef6416647890e,"@@ -1173,7 +1173,7 @@ def klip_dataset(dataset, mode='ADI+SDI', outputdir=""."", fileprefix="""", annuli=5 if psf_library.dataset is dataset: raise ValueError(""The PSF Library is not prepared for this dataset. Run psf_library.prepare_library()"") if aligned_center is not None: - if np.array_equal(aligned_center, psf_library.aligned_center): + if not np.array_equal(aligned_center, psf_library.aligned_center): raise ValueError(""The images need to be aligned to the same center as the RDI Library"") else: ",pyklip/parallelized.py,"ReplaceText(target='not ' @(1176,15)->(1176,15))","def klip_dataset(dataset, mode='ADI+SDI', outputdir=""."", fileprefix="""", annuli=5 if psf_library.dataset is dataset: raise ValueError(""The PSF Library is not prepared for this dataset. Run psf_library.prepare_library()"") if aligned_center is not None: if np.array_equal(aligned_center, psf_library.aligned_center): raise ValueError(""The images need to be aligned to the same center as the RDI Library"") else:","def klip_dataset(dataset, mode='ADI+SDI', outputdir=""."", fileprefix="""", annuli=5 if psf_library.dataset is dataset: raise ValueError(""The PSF Library is not prepared for this dataset. Run psf_library.prepare_library()"") if aligned_center is not None: if not np.array_equal(aligned_center, psf_library.aligned_center): raise ValueError(""The images need to be aligned to the same center as the RDI Library"") else:" 2156,https://:@bitbucket.org/pyKLIP/pyklip.git,4748ec86588a4b3b60dcb17d36e14485cdcd19ff,"@@ -63,7 +63,7 @@ def point_source_detection(image, center,threshold,pix2as=None,mask_radius = 4,m # Mask out a band of 10 pixels around the edges of the finite pixels of the image. if maskout_edge is not None: - IWA,OWA,inner_mask,outer_mask = get_occ(image, centroid = (center[0][0]+stamp_size//2,center[0][1]+stamp_size//2)) + IWA,OWA,inner_mask,outer_mask = get_occ(image_cpy, centroid = (center[0][0]+stamp_size//2,center[0][1]+stamp_size//2)) conv_kernel = np.ones((maskout_edge,maskout_edge)) flat_cube_wider_mask = convolve2d(outer_mask,conv_kernel,mode=""same"") image_cpy[np.where(np.isnan(flat_cube_wider_mask))] = np.nan ",pyklip/kpp/detection/detection.py,"ReplaceText(target='image_cpy' @(66,52)->(66,57))","def point_source_detection(image, center,threshold,pix2as=None,mask_radius = 4,m # Mask out a band of 10 pixels around the edges of the finite pixels of the image. if maskout_edge is not None: IWA,OWA,inner_mask,outer_mask = get_occ(image, centroid = (center[0][0]+stamp_size//2,center[0][1]+stamp_size//2)) conv_kernel = np.ones((maskout_edge,maskout_edge)) flat_cube_wider_mask = convolve2d(outer_mask,conv_kernel,mode=""same"") image_cpy[np.where(np.isnan(flat_cube_wider_mask))] = np.nan","def point_source_detection(image, center,threshold,pix2as=None,mask_radius = 4,m # Mask out a band of 10 pixels around the edges of the finite pixels of the image. if maskout_edge is not None: IWA,OWA,inner_mask,outer_mask = get_occ(image_cpy, centroid = (center[0][0]+stamp_size//2,center[0][1]+stamp_size//2)) conv_kernel = np.ones((maskout_edge,maskout_edge)) flat_cube_wider_mask = convolve2d(outer_mask,conv_kernel,mode=""same"") image_cpy[np.where(np.isnan(flat_cube_wider_mask))] = np.nan" 2157,https://:@github.com/kalaspuff/stockholm.git,08ee0890e1b7b22c8fc757ee2584e5cdc9ec459c,"@@ -564,7 +564,7 @@ class MoneyModel(Generic[MoneyType]): if self._currency and isinstance(self._currency, BaseCurrency): min_decimals = self._currency.decimal_digits min_decimals = DEFAULT_MIN_DECIMALS if min_decimals is None else min_decimals - min_decimals = min(cast(min_decimals, int), max_decimals) + min_decimals = min(cast(int, min_decimals), max_decimals) elif max_decimals is None: max_decimals = max(min_decimals, DEFAULT_MAX_DECIMALS) ",stockholm/money.py,"ArgSwap(idxs=0<->1 @(567,31)->(567,35))","class MoneyModel(Generic[MoneyType]): if self._currency and isinstance(self._currency, BaseCurrency): min_decimals = self._currency.decimal_digits min_decimals = DEFAULT_MIN_DECIMALS if min_decimals is None else min_decimals min_decimals = min(cast(min_decimals, int), max_decimals) elif max_decimals is None: max_decimals = max(min_decimals, DEFAULT_MAX_DECIMALS) ","class MoneyModel(Generic[MoneyType]): if self._currency and isinstance(self._currency, BaseCurrency): min_decimals = self._currency.decimal_digits min_decimals = DEFAULT_MIN_DECIMALS if min_decimals is None else min_decimals min_decimals = min(cast(int, min_decimals), max_decimals) elif max_decimals is None: max_decimals = max(min_decimals, DEFAULT_MAX_DECIMALS) " 2158,https://:@github.com/rbw/snowstorm.git,dcbeaa22bd05821a088861feb4f8f3ad76ff3db1,"@@ -33,7 +33,7 @@ class Response: body = await self.text() content = ujson.loads(body).get(""result"") - if ""error"" in body: + if ""error"" in content: err = ErrorSchema().load(content[""error""]) text = f""{err['message']} ({self.status}): {err['detail']}"" if err[""detail""] else err[""message""] raise ErrorResponse(text) ",snow/request/core/base.py,"ReplaceText(target='content' @(36,22)->(36,26))","class Response: body = await self.text() content = ujson.loads(body).get(""result"") if ""error"" in body: err = ErrorSchema().load(content[""error""]) text = f""{err['message']} ({self.status}): {err['detail']}"" if err[""detail""] else err[""message""] raise ErrorResponse(text)","class Response: body = await self.text() content = ujson.loads(body).get(""result"") if ""error"" in content: err = ErrorSchema().load(content[""error""]) text = f""{err['message']} ({self.status}): {err['detail']}"" if err[""detail""] else err[""message""] raise ErrorResponse(text)" 2159,https://:@github.com/mayjolux/udata.git,2a578ad9630779fced19b836b5252f62c7ed2caa,"@@ -207,7 +207,7 @@ class DatasetBlueprintTest(FrontTestCase): for i in range(1, len(feed.entries)): published_date = feed.entries[i].published_parsed prev_published_date = feed.entries[i - 1].published_parsed - self.assertGreaterEqual(published_date, prev_published_date) + self.assertGreaterEqual(prev_published_date, published_date) def test_recent_feed_owner(self): owner = UserFactory() ",udata/tests/frontend/test_dataset_frontend.py,"ArgSwap(idxs=0<->1 @(210,12)->(210,35))","class DatasetBlueprintTest(FrontTestCase): for i in range(1, len(feed.entries)): published_date = feed.entries[i].published_parsed prev_published_date = feed.entries[i - 1].published_parsed self.assertGreaterEqual(published_date, prev_published_date) def test_recent_feed_owner(self): owner = UserFactory()","class DatasetBlueprintTest(FrontTestCase): for i in range(1, len(feed.entries)): published_date = feed.entries[i].published_parsed prev_published_date = feed.entries[i - 1].published_parsed self.assertGreaterEqual(prev_published_date, published_date) def test_recent_feed_owner(self): owner = UserFactory()" 2160,https://:@github.com/mayjolux/udata.git,e70455456fabb68859a47a6ef916bc4adb2ccddb,"@@ -148,7 +148,7 @@ class DatasetBadgesAPI(API): form.populate_obj(badge) for existing_badge in dataset.badges: if existing_badge.kind == badge.kind: - return badge + return existing_badge dataset.add_badge(badge) return badge, 201 ",udata/core/dataset/api.py,"ReplaceText(target='existing_badge' @(151,23)->(151,28))","class DatasetBadgesAPI(API): form.populate_obj(badge) for existing_badge in dataset.badges: if existing_badge.kind == badge.kind: return badge dataset.add_badge(badge) return badge, 201 ","class DatasetBadgesAPI(API): form.populate_obj(badge) for existing_badge in dataset.badges: if existing_badge.kind == badge.kind: return existing_badge dataset.add_badge(badge) return badge, 201 " 2161,https://:@github.com/mayjolux/udata.git,6b1aaaff35c2f373873324561fea22752adf37e9,"@@ -104,7 +104,7 @@ class ReuseDatasetsAPI(API): except Dataset.DoesNotExist: api.abort(404, 'Dataset {0} does not exists'.format(request.json['id'])) if dataset in reuse.datasets: - return dataset + return reuse reuse.datasets.append(dataset) reuse.save() return reuse, 201 ",udata/core/reuse/api.py,"ReplaceText(target='reuse' @(107,19)->(107,26))","class ReuseDatasetsAPI(API): except Dataset.DoesNotExist: api.abort(404, 'Dataset {0} does not exists'.format(request.json['id'])) if dataset in reuse.datasets: return dataset reuse.datasets.append(dataset) reuse.save() return reuse, 201","class ReuseDatasetsAPI(API): except Dataset.DoesNotExist: api.abort(404, 'Dataset {0} does not exists'.format(request.json['id'])) if dataset in reuse.datasets: return reuse reuse.datasets.append(dataset) reuse.save() return reuse, 201" 2162,https://:@github.com/liushilive/LsBook.git,ef6afa367b34525354dee724607c2490bed605b6,"@@ -83,6 +83,6 @@ def is_summary_exist(book: Book): """""" book_summary = os.path.join(book.book_path, ""summary.md"") if not os.path.isfile(book_summary): - file_not_found_error(book) + file_not_found_error(book_summary) else: book.summary_path = book_summary ",LsBook/parse/parse_summary.py,"ReplaceText(target='book_summary' @(86,29)->(86,33))","def is_summary_exist(book: Book): """""" book_summary = os.path.join(book.book_path, ""summary.md"") if not os.path.isfile(book_summary): file_not_found_error(book) else: book.summary_path = book_summary","def is_summary_exist(book: Book): """""" book_summary = os.path.join(book.book_path, ""summary.md"") if not os.path.isfile(book_summary): file_not_found_error(book_summary) else: book.summary_path = book_summary" 2163,https://:@github.com/liushilive/LsBook.git,592651c6c34d89532a35cfffb597e42512146525,"@@ -58,7 +58,7 @@ def _render_html(book_title, title, author, basePath, book_summary, language, i18n, github_url, base_assets): """"""生产HTML,返回索引"""""" # 解析页面 - base_assets_path = os.path.join(base_assets, basePath) if base_assets else basePath # 资源路径 + base_assets_path = os.path.join(basePath, base_assets) if base_assets else basePath # 资源路径 book_page, toc_tree, tag_katex, tag_mermaid, tag_prism, tag_lightbox, assets_img = parse_file( os.path.join(book_path, href), ",LsBook/renderer/renderer_html.py,"ArgSwap(idxs=0<->1 @(61,23)->(61,35))","def _render_html(book_title, title, author, basePath, book_summary, language, i18n, github_url, base_assets): """"""生产HTML,返回索引"""""" # 解析页面 base_assets_path = os.path.join(base_assets, basePath) if base_assets else basePath # 资源路径 book_page, toc_tree, tag_katex, tag_mermaid, tag_prism, tag_lightbox, assets_img = parse_file( os.path.join(book_path, href),","def _render_html(book_title, title, author, basePath, book_summary, language, i18n, github_url, base_assets): """"""生产HTML,返回索引"""""" # 解析页面 base_assets_path = os.path.join(basePath, base_assets) if base_assets else basePath # 资源路径 book_page, toc_tree, tag_katex, tag_mermaid, tag_prism, tag_lightbox, assets_img = parse_file( os.path.join(book_path, href)," 2164,https://:@github.com/eieste/MethodCache.git,672a3590ede2a2e6f7a347fd69c0583b2ec4bd9b,"@@ -66,7 +66,7 @@ def add_to_cache(options={}, func=None, params=None): if ""ttl"" not in options: assert type(cleaned_options[""store""].ttl) is int - cleaned_options[""ttl""] = options[""store""].ttl + cleaned_options[""ttl""] = cleaned_options[""store""].ttl else: assert type(options[""ttl""]) is int ",methodcache/cache.py,"ReplaceText(target='cleaned_options' @(69,33)->(69,40))","def add_to_cache(options={}, func=None, params=None): if ""ttl"" not in options: assert type(cleaned_options[""store""].ttl) is int cleaned_options[""ttl""] = options[""store""].ttl else: assert type(options[""ttl""]) is int","def add_to_cache(options={}, func=None, params=None): if ""ttl"" not in options: assert type(cleaned_options[""store""].ttl) is int cleaned_options[""ttl""] = cleaned_options[""store""].ttl else: assert type(options[""ttl""]) is int" 2165,https://:@github.com/alphardex/crawltools.git,89c92158c4c366af1e22a16d060fdb390683c4b5,"@@ -17,7 +17,7 @@ def crawl(url): data['url'] = item['url'] data['downloads'] = item['downloads_count'] data['votes'] = item['votes_count'] - data['comments'] = items['comments_count'] + data['comments'] = item['comments_count'] pprint(data) total.append(data) ",looter/examples/sharecuts.py,"ReplaceText(target='item' @(20,27)->(20,32))","def crawl(url): data['url'] = item['url'] data['downloads'] = item['downloads_count'] data['votes'] = item['votes_count'] data['comments'] = items['comments_count'] pprint(data) total.append(data) ","def crawl(url): data['url'] = item['url'] data['downloads'] = item['downloads_count'] data['votes'] = item['votes_count'] data['comments'] = item['comments_count'] pprint(data) total.append(data) " 2166,https://:@github.com/andrewsanchez/genbankqc.git,2aa87a49e09fefbbe7fe2cba2e6074bba157322b,"@@ -38,7 +38,7 @@ def cli(filter_level, max_unknowns, c_deviations, s_deviations, m_deviations, print(""Completed "", s.species) print(s) except Exception: - print('Failed ', species.species) + print('Failed ', s.species) traceback.print_exc() else: from genbankqc import Genbank ",genbankqc/__main__.py,"ReplaceText(target='s' @(41,29)->(41,36))","def cli(filter_level, max_unknowns, c_deviations, s_deviations, m_deviations, print(""Completed "", s.species) print(s) except Exception: print('Failed ', species.species) traceback.print_exc() else: from genbankqc import Genbank","def cli(filter_level, max_unknowns, c_deviations, s_deviations, m_deviations, print(""Completed "", s.species) print(s) except Exception: print('Failed ', s.species) traceback.print_exc() else: from genbankqc import Genbank" 2167,https://:@github.com/mattlong/fabric.git,7d2c14330a3382a86e51fe16a0151299cc4d23ba,"@@ -207,4 +207,4 @@ Got: def eq_contents(path, text): with open(path) as fd: - eq_(fd.read(), text) + eq_(text, fd.read()) ",tests/utils.py,"ArgSwap(idxs=0<->1 @(210,8)->(210,11))","Got: def eq_contents(path, text): with open(path) as fd: eq_(fd.read(), text)","Got: def eq_contents(path, text): with open(path) as fd: eq_(text, fd.read())" 2168,https://:@github.com/rsanchezgarc/carbonCleaner.git,df470ae67588e8a1c7ba04ce14b517552e0ad788,"@@ -41,7 +41,7 @@ def cleanOneMic(micFname, boxSize, deepLearningModel=DEFAULT_MODEL_PATH, inputCo global MASK_PREDICTOR_HANDLER with LOCK: if MASK_PREDICTOR_HANDLER is None: - MASK_PREDICTOR_HANDLER= MaskPredictor(deepLearningModel, boxSize, gpus) + MASK_PREDICTOR_HANDLER= MaskPredictor(boxSize, deepLearningModel, gpus) maskPredictor= MASK_PREDICTOR_HANDLER ",micrograph_cleaner_em/cleanOneMic.py,"ArgSwap(idxs=0<->1 @(44,30)->(44,43))","def cleanOneMic(micFname, boxSize, deepLearningModel=DEFAULT_MODEL_PATH, inputCo global MASK_PREDICTOR_HANDLER with LOCK: if MASK_PREDICTOR_HANDLER is None: MASK_PREDICTOR_HANDLER= MaskPredictor(deepLearningModel, boxSize, gpus) maskPredictor= MASK_PREDICTOR_HANDLER","def cleanOneMic(micFname, boxSize, deepLearningModel=DEFAULT_MODEL_PATH, inputCo global MASK_PREDICTOR_HANDLER with LOCK: if MASK_PREDICTOR_HANDLER is None: MASK_PREDICTOR_HANDLER= MaskPredictor(boxSize, deepLearningModel, gpus) maskPredictor= MASK_PREDICTOR_HANDLER" 2169,https://:@github.com/Storj/storjkademlia.git,61631b21db3a4204bef38431799244fda90e7e4d,"@@ -9,7 +9,7 @@ from kademlia.log import Logger class KademliaProtocol(RPCProtocol): def __init__(self, sourceNode, storage, ksize): RPCProtocol.__init__(self) - self.router = RoutingTable(self, sourceNode, ksize) + self.router = RoutingTable(self, ksize, sourceNode) self.storage = storage self.sourceID = sourceNode.id self.log = Logger(system=self) ",kademlia/protocol.py,"ArgSwap(idxs=1<->2 @(12,22)->(12,34))","from kademlia.log import Logger class KademliaProtocol(RPCProtocol): def __init__(self, sourceNode, storage, ksize): RPCProtocol.__init__(self) self.router = RoutingTable(self, sourceNode, ksize) self.storage = storage self.sourceID = sourceNode.id self.log = Logger(system=self)","from kademlia.log import Logger class KademliaProtocol(RPCProtocol): def __init__(self, sourceNode, storage, ksize): RPCProtocol.__init__(self) self.router = RoutingTable(self, ksize, sourceNode) self.storage = storage self.sourceID = sourceNode.id self.log = Logger(system=self)" 2170,https://:@github.com/biwin/django-allauth-underground.git,e34cc91401970a2c2c265ca7e3f76c44b26dc1c9,"@@ -27,7 +27,7 @@ def verified_email_required(function=None, def _wrapped_view(request, *args, **kwargs): if not EmailAddress.objects.filter(user=request.user, verified=True).exists(): - send_email_confirmation(request.user, request) + send_email_confirmation(request, request.user) return render(request, 'account/verified_email_required.html') return view_func(request, *args, **kwargs) ",allauth/account/decorators.py,"ArgSwap(idxs=0<->1 @(30,16)->(30,39))","def verified_email_required(function=None, def _wrapped_view(request, *args, **kwargs): if not EmailAddress.objects.filter(user=request.user, verified=True).exists(): send_email_confirmation(request.user, request) return render(request, 'account/verified_email_required.html') return view_func(request, *args, **kwargs)","def verified_email_required(function=None, def _wrapped_view(request, *args, **kwargs): if not EmailAddress.objects.filter(user=request.user, verified=True).exists(): send_email_confirmation(request, request.user) return render(request, 'account/verified_email_required.html') return view_func(request, *args, **kwargs)" 2171,https://:@github.com/tuxdna/django-mako.git,066efc87e5324ae40f188150c9c59a4edf477513,"@@ -27,7 +27,7 @@ def render_to_string(template_name, dictionary, context_instance=None): context_dictionary.update(d) # fetch and render template template = middleware.lookup.get_template(template_name) - return template.render(**dictionary) + return template.render(**context_dictionary) def render_to_response(template_name, dictionary, context_instance=None, **kwargs): """""" ",djangomako/shortcuts.py,"ReplaceText(target='context_dictionary' @(30,29)->(30,39))","def render_to_string(template_name, dictionary, context_instance=None): context_dictionary.update(d) # fetch and render template template = middleware.lookup.get_template(template_name) return template.render(**dictionary) def render_to_response(template_name, dictionary, context_instance=None, **kwargs): """"""","def render_to_string(template_name, dictionary, context_instance=None): context_dictionary.update(d) # fetch and render template template = middleware.lookup.get_template(template_name) return template.render(**context_dictionary) def render_to_response(template_name, dictionary, context_instance=None, **kwargs): """"""" 2172,https://:@github.com/brainiak/brainiak-cloud.git,43c7525c9a9be12d33426b24fac353dc4d92c35a,"@@ -130,5 +130,5 @@ class FCMAExperiment(Experiment): if result > -1: tmp = result result = -1 - return str(result) + return str(tmp) return ""Data received!"" ",rtcloud/experiments/FCMAExperiment.py,"ReplaceText(target='tmp' @(133,23)->(133,29))","class FCMAExperiment(Experiment): if result > -1: tmp = result result = -1 return str(result) return ""Data received!""","class FCMAExperiment(Experiment): if result > -1: tmp = result result = -1 return str(tmp) return ""Data received!""" 2173,https://:@github.com/NCATS-Tangerine/ros.git,3d8810f69f4c417b8fe46464667d082882b99f81,"@@ -29,6 +29,6 @@ def exec_operator(self, model, job_name): op_node = wf.spec.get(""workflow"",{}).get(job_name,{}) if op_node: router = Router (wf) - result = router.route (wf, op_node, job_name, op_node['code'], op_node['args']) + result = router.route (wf, job_name, op_node, op_node['code'], op_node['args']) wf.set_result (job_name, result) return result ",ros/dag/tasks.py,"ArgSwap(idxs=1<->2 @(32,17)->(32,29))","def exec_operator(self, model, job_name): op_node = wf.spec.get(""workflow"",{}).get(job_name,{}) if op_node: router = Router (wf) result = router.route (wf, op_node, job_name, op_node['code'], op_node['args']) wf.set_result (job_name, result) return result","def exec_operator(self, model, job_name): op_node = wf.spec.get(""workflow"",{}).get(job_name,{}) if op_node: router = Router (wf) result = router.route (wf, job_name, op_node, op_node['code'], op_node['args']) wf.set_result (job_name, result) return result" 2174,https://:@github.com/ICIJ/solr2es.git,e4d9cad0605a2a3048b237167f8523b02a47fc22,"@@ -158,7 +158,7 @@ def translate_doc(row, translation_names, default_values) -> dict: translated_value = value[0] if type(value) is list else value if '.' in translated_key: - translated_value = reduce(lambda i, acc: (acc, i), reversed(translated_key.split('.')[1:] + [value])) + translated_value = reduce(lambda i, acc: (acc, i), reversed(translated_key.split('.')[1:] + [translated_value])) translated_key = translated_key.split('.')[0] elif translated_key == '_id': return key, value ",solr2es/__main__.py,"ReplaceText(target='translated_value' @(161,105)->(161,110))","def translate_doc(row, translation_names, default_values) -> dict: translated_value = value[0] if type(value) is list else value if '.' in translated_key: translated_value = reduce(lambda i, acc: (acc, i), reversed(translated_key.split('.')[1:] + [value])) translated_key = translated_key.split('.')[0] elif translated_key == '_id': return key, value","def translate_doc(row, translation_names, default_values) -> dict: translated_value = value[0] if type(value) is list else value if '.' in translated_key: translated_value = reduce(lambda i, acc: (acc, i), reversed(translated_key.split('.')[1:] + [translated_value])) translated_key = translated_key.split('.')[0] elif translated_key == '_id': return key, value" 2175,https://:@github.com/guyfawcus/ArchMap.git,3dc6ce049e92b3997c00c443d3da1a42da586105,"@@ -123,7 +123,7 @@ def make_gis(parsed_users, output_file_geojson, output_file_kml, send_to_geojson message(""Writing geojson to "" + output_file_geojson) output = open(output_file_geojson, 'w') - output.write(geojson_str) + output.write(geojson_str_pretty) output.close() # Write 'kml' to 'output_file_kml' if wanted. ",archmap.py,"ReplaceText(target='geojson_str_pretty' @(126,21)->(126,32))","def make_gis(parsed_users, output_file_geojson, output_file_kml, send_to_geojson message(""Writing geojson to "" + output_file_geojson) output = open(output_file_geojson, 'w') output.write(geojson_str) output.close() # Write 'kml' to 'output_file_kml' if wanted.","def make_gis(parsed_users, output_file_geojson, output_file_kml, send_to_geojson message(""Writing geojson to "" + output_file_geojson) output = open(output_file_geojson, 'w') output.write(geojson_str_pretty) output.close() # Write 'kml' to 'output_file_kml' if wanted." 2176,https://:@github.com/machinekoder/speed-friending-matcher.git,ea954a502879b22a25d54fd8f40bf35315aede13,"@@ -45,7 +45,7 @@ class Application(object): for output in raw_ouputs: name, arguments = output.split(':') outputs.append((name, arguments)) - if len(output) == 0: + if len(outputs) == 0: raise ValueError() except ValueError: raise RuntimeError('Incorrect output plugin string') ",application.py,"ReplaceText(target='outputs' @(48,19)->(48,25))","class Application(object): for output in raw_ouputs: name, arguments = output.split(':') outputs.append((name, arguments)) if len(output) == 0: raise ValueError() except ValueError: raise RuntimeError('Incorrect output plugin string')","class Application(object): for output in raw_ouputs: name, arguments = output.split(':') outputs.append((name, arguments)) if len(outputs) == 0: raise ValueError() except ValueError: raise RuntimeError('Incorrect output plugin string')" 2177,https://:@github.com/ruipgil/TrackToTrip.git,a67fab1c7801d2eaf8086db367f04282dcadf822,"@@ -70,7 +70,7 @@ def update_location_centroid(point, cluster, max_distance, min_samples): biggest_centroid = centroid if biggest_centroid is None: - biggest_centroid = compute_centroid(cluster) + biggest_centroid = compute_centroid(points) return biggest_centroid, cluster ",tracktotrip/location.py,"ReplaceText(target='points' @(73,44)->(73,51))","def update_location_centroid(point, cluster, max_distance, min_samples): biggest_centroid = centroid if biggest_centroid is None: biggest_centroid = compute_centroid(cluster) return biggest_centroid, cluster ","def update_location_centroid(point, cluster, max_distance, min_samples): biggest_centroid = centroid if biggest_centroid is None: biggest_centroid = compute_centroid(points) return biggest_centroid, cluster " 2178,https://:@github.com/neurodata/primitives-interfaces.git,8df5f9ba565690a95034f2d41b00f38d5c70a592,"@@ -106,7 +106,7 @@ class DatasetToGraphList(transformer.TransformerPrimitiveBase[Inputs, Outputs, H graphs.append(temp_graph) # get the task type from the task docs - temp_path = location_base_uri.split('/') + temp_path = datasetDoc_uri.split('/') problemDoc_uri = '/'.join(temp_path[:-2]) + '/' + '/'.join(temp_path[-2:]).replace('dataset', 'problem') with open(problemDoc_uri) as json_file: ",jhu_primitives/dataset_to_graph_list/dataset_to_graph_list.py,"ReplaceText(target='datasetDoc_uri' @(109,20)->(109,37))","class DatasetToGraphList(transformer.TransformerPrimitiveBase[Inputs, Outputs, H graphs.append(temp_graph) # get the task type from the task docs temp_path = location_base_uri.split('/') problemDoc_uri = '/'.join(temp_path[:-2]) + '/' + '/'.join(temp_path[-2:]).replace('dataset', 'problem') with open(problemDoc_uri) as json_file:","class DatasetToGraphList(transformer.TransformerPrimitiveBase[Inputs, Outputs, H graphs.append(temp_graph) # get the task type from the task docs temp_path = datasetDoc_uri.split('/') problemDoc_uri = '/'.join(temp_path[:-2]) + '/' + '/'.join(temp_path[-2:]).replace('dataset', 'problem') with open(problemDoc_uri) as json_file:" 2179,https://:@github.com/neurodata/primitives-interfaces.git,67d23cf31c662487d6aac6bae63e2c54ad00066c,"@@ -100,7 +100,7 @@ class LargestConnectedComponent(TransformerPrimitiveBase[Inputs, Outputs, Hyperp # check if the component is largest if len(connected_component) > len(G_largest): # if it is largest - flag as such - G_largest = i + G_largest = connected_component # obtain indices associated with the node_ids in this component temp_indices = [i for i, x in enumerate(nodeIDs) if x in list(connected_component)] ",jhu_primitives/lcc/lcc.py,"ReplaceText(target='connected_component' @(103,28)->(103,29))","class LargestConnectedComponent(TransformerPrimitiveBase[Inputs, Outputs, Hyperp # check if the component is largest if len(connected_component) > len(G_largest): # if it is largest - flag as such G_largest = i # obtain indices associated with the node_ids in this component temp_indices = [i for i, x in enumerate(nodeIDs) if x in list(connected_component)]","class LargestConnectedComponent(TransformerPrimitiveBase[Inputs, Outputs, Hyperp # check if the component is largest if len(connected_component) > len(G_largest): # if it is largest - flag as such G_largest = connected_component # obtain indices associated with the node_ids in this component temp_indices = [i for i, x in enumerate(nodeIDs) if x in list(connected_component)]" 2180,https://:@github.com/agorinenko/power_dict.git,25aaa83e38e440e9f2d49c49f1620d071805410d,"@@ -96,7 +96,7 @@ class SchemaValidator: return DictUtils.get_required_value(context, name, **kwargs) else: - if required_error is not None: + if default_value is not None: kwargs['default_value'] = default_value return DictUtils.get_value(context, name, **kwargs) ",power_dict/schema_validator.py,"ReplaceText(target='default_value' @(99,19)->(99,33))","class SchemaValidator: return DictUtils.get_required_value(context, name, **kwargs) else: if required_error is not None: kwargs['default_value'] = default_value return DictUtils.get_value(context, name, **kwargs)","class SchemaValidator: return DictUtils.get_required_value(context, name, **kwargs) else: if default_value is not None: kwargs['default_value'] = default_value return DictUtils.get_value(context, name, **kwargs)" 2181,https://:@github.com/mwilliamson/nope.git,cd87dfe247ad7fb3a9f324a8369a3a741c56104f,"@@ -164,7 +164,7 @@ def _create_type_rules(): primary_type.define(sub_signature | applied_type | type_ref) explicit_type = (signature | type_) + finished >> (lambda result: result[0]) - type_definition = (type_ref + skip(equals) + type_ + skip(finished)) >> _make_type_definition + type_definition = (type_name + skip(equals) + type_ + skip(finished)) >> _make_type_definition return explicit_type, type_definition ",nope/parser/typing.py,"ReplaceText(target='type_name' @(167,23)->(167,31))","def _create_type_rules(): primary_type.define(sub_signature | applied_type | type_ref) explicit_type = (signature | type_) + finished >> (lambda result: result[0]) type_definition = (type_ref + skip(equals) + type_ + skip(finished)) >> _make_type_definition return explicit_type, type_definition ","def _create_type_rules(): primary_type.define(sub_signature | applied_type | type_ref) explicit_type = (signature | type_) + finished >> (lambda result: result[0]) type_definition = (type_name + skip(equals) + type_ + skip(finished)) >> _make_type_definition return explicit_type, type_definition " 2182,https://:@github.com/mwilliamson/nope.git,17ff327b5165e537fa683d94ad430564a974a9b3,"@@ -168,7 +168,7 @@ def _create_type_rules(): type_definition = (type_name + skip(equals) + type_ + skip(finished)) >> _make_type_definition - structural_type_attr = (attr_name + skip(colon) + type_) >> tuple + structural_type_attr = (attr_name + skip(colon) + explicit_type) >> tuple structural_type_attrs = many(structural_type_attr) structural_type_definition = (type_name + skip(colon) + structural_type_attrs + skip(finished)) >> _make_structural_type_definition ",nope/parser/typing.py,"ReplaceText(target='explicit_type' @(171,54)->(171,59))","def _create_type_rules(): type_definition = (type_name + skip(equals) + type_ + skip(finished)) >> _make_type_definition structural_type_attr = (attr_name + skip(colon) + type_) >> tuple structural_type_attrs = many(structural_type_attr) structural_type_definition = (type_name + skip(colon) + structural_type_attrs + skip(finished)) >> _make_structural_type_definition","def _create_type_rules(): type_definition = (type_name + skip(equals) + type_ + skip(finished)) >> _make_type_definition structural_type_attr = (attr_name + skip(colon) + explicit_type) >> tuple structural_type_attrs = many(structural_type_attr) structural_type_definition = (type_name + skip(colon) + structural_type_attrs + skip(finished)) >> _make_structural_type_definition" 2183,https://:@github.com/regexpressyourself/passman.git,0ed931e680654f9ca017a093115f1f7f0e833ca4,"@@ -96,7 +96,7 @@ def generatePasswordPrompt(): siz = getUserInput(""Password length"") - if not siz=='' and not siz.isdecimal(): + if not siz=='' or not siz.isdecimal(): print(""not a number"") return """" ",menu.py,"ReplaceText(target='or' @(99,19)->(99,22))","def generatePasswordPrompt(): siz = getUserInput(""Password length"") if not siz=='' and not siz.isdecimal(): print(""not a number"") return """" ","def generatePasswordPrompt(): siz = getUserInput(""Password length"") if not siz=='' or not siz.isdecimal(): print(""not a number"") return """" " 2184,https://:@github.com/BFriedrichs/motorturbine.git,f42dc59b1228d645dce3e9c711385d094990727f,"@@ -29,7 +29,7 @@ class ListField(base_field.BaseField): raise errors.TypeMismatch(list, value) for item in value: - self.validate(value) + self.validate(item) old_val = copy.deepcopy(self.value) sync_val = {} self.value.clear() ",motorturbine/fields/list_field.py,"ReplaceText(target='item' @(32,26)->(32,31))","class ListField(base_field.BaseField): raise errors.TypeMismatch(list, value) for item in value: self.validate(value) old_val = copy.deepcopy(self.value) sync_val = {} self.value.clear()","class ListField(base_field.BaseField): raise errors.TypeMismatch(list, value) for item in value: self.validate(item) old_val = copy.deepcopy(self.value) sync_val = {} self.value.clear()" 2185,https://:@github.com/commerceblock/pymainstay.git,8cd31dc74cc63ab966ab5f6585d29972b089de1a,"@@ -127,7 +127,7 @@ def parse_msc_args(raw_args): dest='txid', help=""Verify that the proof sequence is committed to the staychain containing TxID"") - parser_verify.add_argument(""-l"",""--list"", type=str, + verify_group.add_argument(""-l"",""--list"", type=str, dest='list', help=""Verify the list of comma separated commitments against the sequence proof"") ",mst/args.py,"ReplaceText(target='verify_group' @(130,4)->(130,17))","def parse_msc_args(raw_args): dest='txid', help=""Verify that the proof sequence is committed to the staychain containing TxID"") parser_verify.add_argument(""-l"",""--list"", type=str, dest='list', help=""Verify the list of comma separated commitments against the sequence proof"") ","def parse_msc_args(raw_args): dest='txid', help=""Verify that the proof sequence is committed to the staychain containing TxID"") verify_group.add_argument(""-l"",""--list"", type=str, dest='list', help=""Verify the list of comma separated commitments against the sequence proof"") " 2186,https://:@github.com/lxml-cffi/lxml-cffi.git,7baf99b8232de27923d0a607ac10a2f77f6a66e2,"@@ -275,7 +275,7 @@ class Cleaner(object): for el in _find_styled_elements(doc): old = el.get('style') new = _css_javascript_re.sub('', old) - new = _css_import_re.sub('', old) + new = _css_import_re.sub('', new) if self._has_sneaky_javascript(new): # Something tricky is going on... del el.attrib['style'] ",src/lxml/html/clean.py,"ReplaceText(target='new' @(278,49)->(278,52))","class Cleaner(object): for el in _find_styled_elements(doc): old = el.get('style') new = _css_javascript_re.sub('', old) new = _css_import_re.sub('', old) if self._has_sneaky_javascript(new): # Something tricky is going on... del el.attrib['style']","class Cleaner(object): for el in _find_styled_elements(doc): old = el.get('style') new = _css_javascript_re.sub('', old) new = _css_import_re.sub('', new) if self._has_sneaky_javascript(new): # Something tricky is going on... del el.attrib['style']" 2187,https://:@github.com/lxml-cffi/lxml-cffi.git,ce0d5931b9e5293b8375457de2e40c9c197f4dda,"@@ -334,7 +334,7 @@ class LXMLOutputChecker(OutputChecker): attrs.append('-%s=""%s""' % (name, self.format_text(value, False))) else: if name in want.attrib: - text = self.collect_diff_text(value, want.attrib[name], False) + text = self.collect_diff_text(want.attrib[name], value, False) else: text = self.format_text(value, False) attrs.append('%s=""%s""' % (name, text)) ",src/lxml/doctestcompare.py,"ArgSwap(idxs=0<->1 @(337,27)->(337,49))","class LXMLOutputChecker(OutputChecker): attrs.append('-%s=""%s""' % (name, self.format_text(value, False))) else: if name in want.attrib: text = self.collect_diff_text(value, want.attrib[name], False) else: text = self.format_text(value, False) attrs.append('%s=""%s""' % (name, text))","class LXMLOutputChecker(OutputChecker): attrs.append('-%s=""%s""' % (name, self.format_text(value, False))) else: if name in want.attrib: text = self.collect_diff_text(want.attrib[name], value, False) else: text = self.format_text(value, False) attrs.append('%s=""%s""' % (name, text))" 2188,https://:@github.com/abinit/abiflows.git,03b1d8ebd465d1153f35d7956d1937418b7be7ae,"@@ -296,7 +296,7 @@ class RelaxFWWorkflowSRC(AbstractFWWorkflow): initialization_info=initialization_info, wf_task_index_prefix='ioncell', deps={SRC_ion_fws['run_fw'].tasks[0].task_type: '@structure'}) - fws.extend(SRC_ion_fws['fws']) + fws.extend(SRC_ioncell_fws['fws']) links_dict.update(SRC_ioncell_fws['links_dict']) links_dict.update({SRC_ion_fws['check_fw']: SRC_ioncell_fws['setup_fw']}) ",abiflows/fireworks/workflows/abinit_workflows.py,"ReplaceText(target='SRC_ioncell_fws' @(299,19)->(299,30))","class RelaxFWWorkflowSRC(AbstractFWWorkflow): initialization_info=initialization_info, wf_task_index_prefix='ioncell', deps={SRC_ion_fws['run_fw'].tasks[0].task_type: '@structure'}) fws.extend(SRC_ion_fws['fws']) links_dict.update(SRC_ioncell_fws['links_dict']) links_dict.update({SRC_ion_fws['check_fw']: SRC_ioncell_fws['setup_fw']})","class RelaxFWWorkflowSRC(AbstractFWWorkflow): initialization_info=initialization_info, wf_task_index_prefix='ioncell', deps={SRC_ion_fws['run_fw'].tasks[0].task_type: '@structure'}) fws.extend(SRC_ioncell_fws['fws']) links_dict.update(SRC_ioncell_fws['links_dict']) links_dict.update({SRC_ion_fws['check_fw']: SRC_ioncell_fws['setup_fw']})" 2189,https://:@github.com/abinit/abiflows.git,5e2edecbad2a8bef67436888703c9ba54eb80a18,"@@ -807,7 +807,7 @@ class AbiFireTask(BasicTaskMixin, FireTaskBase): optconf, qadapter_spec, qtk_qadapter = self.run_autoparal(self.abiinput, os.path.abspath('.'), self.ftm) if self.use_SRC_scheme: return FWAction(mod_spec={'_set': {'_queueadapter': qadapter_spec, 'mpi_ncpus': optconf['mpi_ncpus'], - 'optconf': optconf, 'qtk_queueadapter': qadapter_spec.as_dict()}}) + 'optconf': optconf, 'qtk_queueadapter': qtk_qadapter.as_dict()}}) self.history.log_autoparal(optconf) self.abiinput.set_vars(optconf.vars) ",abiflows/fireworks/tasks/abinit_tasks.py,"ReplaceText(target='qtk_qadapter' @(810,87)->(810,100))","class AbiFireTask(BasicTaskMixin, FireTaskBase): optconf, qadapter_spec, qtk_qadapter = self.run_autoparal(self.abiinput, os.path.abspath('.'), self.ftm) if self.use_SRC_scheme: return FWAction(mod_spec={'_set': {'_queueadapter': qadapter_spec, 'mpi_ncpus': optconf['mpi_ncpus'], 'optconf': optconf, 'qtk_queueadapter': qadapter_spec.as_dict()}}) self.history.log_autoparal(optconf) self.abiinput.set_vars(optconf.vars) ","class AbiFireTask(BasicTaskMixin, FireTaskBase): optconf, qadapter_spec, qtk_qadapter = self.run_autoparal(self.abiinput, os.path.abspath('.'), self.ftm) if self.use_SRC_scheme: return FWAction(mod_spec={'_set': {'_queueadapter': qadapter_spec, 'mpi_ncpus': optconf['mpi_ncpus'], 'optconf': optconf, 'qtk_queueadapter': qtk_qadapter.as_dict()}}) self.history.log_autoparal(optconf) self.abiinput.set_vars(optconf.vars) " 2190,https://:@github.com/abinit/abiflows.git,701df642b1ef138bbbae47cf771f1671d8a15537,"@@ -695,7 +695,7 @@ class PiezoElasticFWWorkflowSRC(AbstractFWWorkflow): ec_nostress_clamped = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='clamped_ion') ec_nostress_relaxed = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='relaxed_ion') - ec_stress_relaxed = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='relaxed_ion_stress_corrected') + ec_stress_relaxed = myfw_stress.tasks[-1].get_elastic_tensor(tensor_type='relaxed_ion_stress_corrected') ec_dicts = {'clamped_ion': ec_nostress_clamped.extended_dict(), 'relaxed_ion': ec_nostress_relaxed.extended_dict(), ",abiflows/fireworks/workflows/abinit_workflows.py,"ReplaceText(target='myfw_stress' @(698,28)->(698,41))","class PiezoElasticFWWorkflowSRC(AbstractFWWorkflow): ec_nostress_clamped = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='clamped_ion') ec_nostress_relaxed = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='relaxed_ion') ec_stress_relaxed = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='relaxed_ion_stress_corrected') ec_dicts = {'clamped_ion': ec_nostress_clamped.extended_dict(), 'relaxed_ion': ec_nostress_relaxed.extended_dict(),","class PiezoElasticFWWorkflowSRC(AbstractFWWorkflow): ec_nostress_clamped = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='clamped_ion') ec_nostress_relaxed = myfw_nostress.tasks[-1].get_elastic_tensor(tensor_type='relaxed_ion') ec_stress_relaxed = myfw_stress.tasks[-1].get_elastic_tensor(tensor_type='relaxed_ion_stress_corrected') ec_dicts = {'clamped_ion': ec_nostress_clamped.extended_dict(), 'relaxed_ion': ec_nostress_relaxed.extended_dict()," 2191,https://:@github.com/abinit/abiflows.git,0d2231a3586ae709e7be68977369c685e9818e7b,"@@ -409,7 +409,7 @@ def createSRCFireworks(setup_task, run_task, handlers=None, validators=None, spe else: src_task_index = SRCTaskIndex.from_task(run_task) setup_spec = copy.deepcopy(spec) - setup_spec['SRC_task_index'] = task_index + setup_spec['SRC_task_index'] = src_task_index pass ",abiflows/fireworks/tasks/src_tasks_abc.py,"ReplaceText(target='src_task_index' @(412,35)->(412,45))","def createSRCFireworks(setup_task, run_task, handlers=None, validators=None, spe else: src_task_index = SRCTaskIndex.from_task(run_task) setup_spec = copy.deepcopy(spec) setup_spec['SRC_task_index'] = task_index pass ","def createSRCFireworks(setup_task, run_task, handlers=None, validators=None, spe else: src_task_index = SRCTaskIndex.from_task(run_task) setup_spec = copy.deepcopy(spec) setup_spec['SRC_task_index'] = src_task_index pass " 2192,https://:@github.com/abinit/abiflows.git,597da3f247e9fc96c786b140f2bba3e734eed034,"@@ -353,7 +353,7 @@ def createSRCFireworks(setup_task, run_task, control_task, spec=None, initializa control_fw = Firework(control_task, spec=run_spec, name=src_task_index.run_str) links_dict = {setup_fw.fw_id: [run_fw.fw_id], - run_fw.fw_id: [control_task.fw_id]} + run_fw.fw_id: [control_fw.fw_id]} return {'setup_fw': setup_fw, 'run_fw': run_fw, 'control_fw': control_fw, 'links_dict': links_dict, 'fws': [setup_fw, run_fw, control_fw]} ",abiflows/fireworks/tasks/src_tasks_abc.py,"ReplaceText(target='control_fw' @(356,33)->(356,45))","def createSRCFireworks(setup_task, run_task, control_task, spec=None, initializa control_fw = Firework(control_task, spec=run_spec, name=src_task_index.run_str) links_dict = {setup_fw.fw_id: [run_fw.fw_id], run_fw.fw_id: [control_task.fw_id]} return {'setup_fw': setup_fw, 'run_fw': run_fw, 'control_fw': control_fw, 'links_dict': links_dict, 'fws': [setup_fw, run_fw, control_fw]} ","def createSRCFireworks(setup_task, run_task, control_task, spec=None, initializa control_fw = Firework(control_task, spec=run_spec, name=src_task_index.run_str) links_dict = {setup_fw.fw_id: [run_fw.fw_id], run_fw.fw_id: [control_fw.fw_id]} return {'setup_fw': setup_fw, 'run_fw': run_fw, 'control_fw': control_fw, 'links_dict': links_dict, 'fws': [setup_fw, run_fw, control_fw]} " 2193,https://:@github.com/abinit/abiflows.git,5379371a8a68ecf3226958a55cbcee8e6d2664d8,"@@ -425,7 +425,7 @@ def createSRCFireworks(setup_task, run_task, control_task, spec=None, initializa control_spec = copy.deepcopy(spec) control_spec = set_short_single_core_to_spec(control_spec) control_spec['SRC_task_index'] = src_task_index - control_fw = Firework(control_task, spec=run_spec, name=src_task_index.control_str) + control_fw = Firework(control_task, spec=control_spec, name=src_task_index.control_str) links_dict = {setup_fw.fw_id: [run_fw.fw_id], run_fw.fw_id: [control_fw.fw_id]} ",abiflows/fireworks/tasks/src_tasks_abc.py,"ReplaceText(target='control_spec' @(428,45)->(428,53))","def createSRCFireworks(setup_task, run_task, control_task, spec=None, initializa control_spec = copy.deepcopy(spec) control_spec = set_short_single_core_to_spec(control_spec) control_spec['SRC_task_index'] = src_task_index control_fw = Firework(control_task, spec=run_spec, name=src_task_index.control_str) links_dict = {setup_fw.fw_id: [run_fw.fw_id], run_fw.fw_id: [control_fw.fw_id]}","def createSRCFireworks(setup_task, run_task, control_task, spec=None, initializa control_spec = copy.deepcopy(spec) control_spec = set_short_single_core_to_spec(control_spec) control_spec['SRC_task_index'] = src_task_index control_fw = Firework(control_task, spec=control_spec, name=src_task_index.control_str) links_dict = {setup_fw.fw_id: [run_fw.fw_id], run_fw.fw_id: [control_fw.fw_id]}" 2194,https://:@github.com/abinit/abiflows.git,54110d5a1108a2b41d4b038d78b3362ecb89fae9,"@@ -397,7 +397,7 @@ class ControlTask(SRCTaskMixin, FireTaskBase): modified_objects[update['key']] = mod else: new_spec[update['key']] = target_object - modified_objects[update['key']] = mod + modified_objects[update['key']] = target_object elif update['target'] == 'setup_fw_spec': if 'mod' in update: mod = getattr(target_object, update['mod'])() ",abiflows/fireworks/tasks/src_tasks_abc.py,"ReplaceText(target='target_object' @(400,58)->(400,61))","class ControlTask(SRCTaskMixin, FireTaskBase): modified_objects[update['key']] = mod else: new_spec[update['key']] = target_object modified_objects[update['key']] = mod elif update['target'] == 'setup_fw_spec': if 'mod' in update: mod = getattr(target_object, update['mod'])()","class ControlTask(SRCTaskMixin, FireTaskBase): modified_objects[update['key']] = mod else: new_spec[update['key']] = target_object modified_objects[update['key']] = target_object elif update['target'] == 'setup_fw_spec': if 'mod' in update: mod = getattr(target_object, update['mod'])()" 2195,https://:@github.com/ecotrust/madrona.git,9d39eb4684bcb2a3b37879c4d7641e1d608f9b78,"@@ -18,7 +18,7 @@ def simpleLoad(request): user = loadform.cleaned_data['user'] name = loadform.cleaned_data['name'] mpas = Mpa.objects.filter(user=user, name=name) - return mpaLoad(request, loadform, mpas) + return mpaLoad(request, mpas, loadform) def simpleCommit(request): ''' ",example_projects/simple/views.py,"ArgSwap(idxs=1<->2 @(21,11)->(21,18))","def simpleLoad(request): user = loadform.cleaned_data['user'] name = loadform.cleaned_data['name'] mpas = Mpa.objects.filter(user=user, name=name) return mpaLoad(request, loadform, mpas) def simpleCommit(request): '''","def simpleLoad(request): user = loadform.cleaned_data['user'] name = loadform.cleaned_data['name'] mpas = Mpa.objects.filter(user=user, name=name) return mpaLoad(request, mpas, loadform) def simpleCommit(request): '''" 2196,https://:@github.com/ecotrust/madrona.git,25d8645a5a7a7db8bed2cbc25e21ac164b4a0f50,"@@ -58,7 +58,7 @@ def show(request, map_name='default'): # if any one fails, 403 or 404 will be raised user = request.user from lingcod.sharing.utils import get_viewable_object_or_respond - for pk in mpaids: + for pk in mpas: # Does it even exist? try: obj = mpa_class.objects.get(pk=pk) ",lingcod/staticmap/views.py,"ReplaceText(target='mpas' @(61,14)->(61,20))","def show(request, map_name='default'): # if any one fails, 403 or 404 will be raised user = request.user from lingcod.sharing.utils import get_viewable_object_or_respond for pk in mpaids: # Does it even exist? try: obj = mpa_class.objects.get(pk=pk)","def show(request, map_name='default'): # if any one fails, 403 or 404 will be raised user = request.user from lingcod.sharing.utils import get_viewable_object_or_respond for pk in mpas: # Does it even exist? try: obj = mpa_class.objects.get(pk=pk)" 2197,https://:@github.com/YugaByte/cassandra-python-driver.git,6d34a00cee5b033bf285994af739a09419e447a2,"@@ -89,8 +89,8 @@ class Metadata(object): if keyspace in cf_def_rows: for table_row in cf_def_rows[keyspace]: table_meta = self._build_table_metadata( - keyspace_meta, table_row, col_def_rows[keyspace]) - keyspace.tables[table_meta.name] = table_meta + keyspace_meta, table_row, col_def_rows[keyspace]) + keyspace_meta.tables[table_meta.name] = table_meta def _build_keyspace_metadata(self, row): name = row[""keyspace_name""] ",cassandra/metadata.py,"ReplaceText(target='keyspace_meta' @(93,20)->(93,28))","class Metadata(object): if keyspace in cf_def_rows: for table_row in cf_def_rows[keyspace]: table_meta = self._build_table_metadata( keyspace_meta, table_row, col_def_rows[keyspace]) keyspace.tables[table_meta.name] = table_meta def _build_keyspace_metadata(self, row): name = row[""keyspace_name""]","class Metadata(object): if keyspace in cf_def_rows: for table_row in cf_def_rows[keyspace]: table_meta = self._build_table_metadata( keyspace_meta, table_row, col_def_rows[keyspace]) keyspace_meta.tables[table_meta.name] = table_meta def _build_keyspace_metadata(self, row): name = row[""keyspace_name""]" 2198,https://:@github.com/YugaByte/cassandra-python-driver.git,c7a77b8862551e73fd09b749316c422eee7a2308,"@@ -26,7 +26,7 @@ class RoundRobinPolicy(LoadBalancingPolicy): def populate(self, cluster, hosts): self._live_hosts = set(hosts) - if len(hosts) == 1: + if len(hosts) <= 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1) ",cassandra/policies.py,"ReplaceText(target='<=' @(29,22)->(29,24))","class RoundRobinPolicy(LoadBalancingPolicy): def populate(self, cluster, hosts): self._live_hosts = set(hosts) if len(hosts) == 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1)","class RoundRobinPolicy(LoadBalancingPolicy): def populate(self, cluster, hosts): self._live_hosts = set(hosts) if len(hosts) <= 1: self._position = 0 else: self._position = randint(0, len(hosts) - 1)" 2199,https://:@github.com/YugaByte/cassandra-python-driver.git,2984ba71634e5c3d4b23bb42a977401ca60ffc01,"@@ -230,7 +230,7 @@ class BaseModel(object): 'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__) ) - if not issubclass(klass, poly_base): + if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) ) ",cqlengine/models.py,"ReplaceText(target='cls' @(233,37)->(233,46))","class BaseModel(object): 'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__) ) if not issubclass(klass, poly_base): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) )","class BaseModel(object): 'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__) ) if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) )" 2200,https://:@github.com/YugaByte/cassandra-python-driver.git,5dc9e971267c2072c60ae9271c6e230813f72e15,"@@ -232,7 +232,7 @@ class BaseModel(object): if not issubclass(klass, cls): raise PolyMorphicModelException( - '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) + '{} is not a subclass of {}'.format(klass.__name__, cls.__name__) ) field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()} ",cqlengine/models.py,"ReplaceText(target='cls' @(235,72)->(235,81))","class BaseModel(object): if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__) ) field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()}","class BaseModel(object): if not issubclass(klass, cls): raise PolyMorphicModelException( '{} is not a subclass of {}'.format(klass.__name__, cls.__name__) ) field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()}" 2201,https://:@github.com/YugaByte/cassandra-python-driver.git,21081fb30673a52506de2ef2b3c38ae519afef99,"@@ -895,7 +895,7 @@ class ModelMetaClass(type): if MultipleObjectsReturnedBase is not None: break - MultipleObjectsReturnedBase = DoesNotExistBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) + MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) # create the class and add a QuerySet to it ",cassandra/cqlengine/models.py,"ReplaceText(target='MultipleObjectsReturnedBase' @(898,38)->(898,54))","class ModelMetaClass(type): if MultipleObjectsReturnedBase is not None: break MultipleObjectsReturnedBase = DoesNotExistBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) # create the class and add a QuerySet to it","class ModelMetaClass(type): if MultipleObjectsReturnedBase is not None: break MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned) attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {}) # create the class and add a QuerySet to it" 2202,https://:@github.com/redvox/piranha.git,94ece99f61f2c12e57b36d3bf00e9260304cee67,"@@ -14,7 +14,7 @@ def assume_role(account, role): sts = boto3.client('sts') response = sts.assume_role(RoleArn=f'arn:aws:iam::{account}:role/{role}', RoleSessionName=f'{role}-session-{account}') - if not response and not response['ResponseMetadata']['HTTPStatusCode'] == 200: + if not response or not response['ResponseMetadata']['HTTPStatusCode'] == 200: raise Exception(f'could not assume {role} in {account}') return boto3.Session( aws_access_key_id=response['Credentials']['AccessKeyId'], ",piranha/client.py,"ReplaceText(target='or' @(17,20)->(17,23))","def assume_role(account, role): sts = boto3.client('sts') response = sts.assume_role(RoleArn=f'arn:aws:iam::{account}:role/{role}', RoleSessionName=f'{role}-session-{account}') if not response and not response['ResponseMetadata']['HTTPStatusCode'] == 200: raise Exception(f'could not assume {role} in {account}') return boto3.Session( aws_access_key_id=response['Credentials']['AccessKeyId'],","def assume_role(account, role): sts = boto3.client('sts') response = sts.assume_role(RoleArn=f'arn:aws:iam::{account}:role/{role}', RoleSessionName=f'{role}-session-{account}') if not response or not response['ResponseMetadata']['HTTPStatusCode'] == 200: raise Exception(f'could not assume {role} in {account}') return boto3.Session( aws_access_key_id=response['Credentials']['AccessKeyId']," 2203,https://:@github.com/NeuralSandwich/stone.git,f51cc62e6b9fed63302e585294a3790e4eef5b1d,"@@ -51,7 +51,7 @@ def create_add_page(site: Site, source: str, target: str, data=None, content=None): """"""Create a Page() and file on disk"""""" init_content = '# Hello, World!' - if content is None and not isinstance(str, content): + if content is None and not isinstance(content, str): content = init_content try: ",stone/stone.py,"ArgSwap(idxs=0<->1 @(54,31)->(54,41))","def create_add_page(site: Site, source: str, target: str, data=None, content=None): """"""Create a Page() and file on disk"""""" init_content = '# Hello, World!' if content is None and not isinstance(str, content): content = init_content try:","def create_add_page(site: Site, source: str, target: str, data=None, content=None): """"""Create a Page() and file on disk"""""" init_content = '# Hello, World!' if content is None and not isinstance(content, str): content = init_content try:" 2204,https://:@github.com/legoktm/wdapi.git,b7b1335a06b92c9b5182d54db8f8d1ba46c2cbe5,"@@ -94,7 +94,7 @@ def canClaimBeAdded(item, claim, checkDupe=True): if not claim.getTarget().getID() in prop.constraints()['oneof']: return False, 'oneof' if 'single' in prop.constraints(): - if item.getID() in item.claims: + if claim.getID() in item.claims: return False, 'single' #TODO: target, unique, item, reciprocal ",wdapi/main.py,"ReplaceText(target='claim' @(97,11)->(97,15))","def canClaimBeAdded(item, claim, checkDupe=True): if not claim.getTarget().getID() in prop.constraints()['oneof']: return False, 'oneof' if 'single' in prop.constraints(): if item.getID() in item.claims: return False, 'single' #TODO: target, unique, item, reciprocal","def canClaimBeAdded(item, claim, checkDupe=True): if not claim.getTarget().getID() in prop.constraints()['oneof']: return False, 'oneof' if 'single' in prop.constraints(): if claim.getID() in item.claims: return False, 'single' #TODO: target, unique, item, reciprocal" 2205,https://:@github.com/rileyjmurray/sageopt.git,61205194a6127bf10cc751efa5dfdf8f180967e6,"@@ -355,7 +355,7 @@ class Polynomial(Signomial): vec = self.alpha[j, :].copy() c = self.c[j] * vec[i] vec[i] -= 1 - d[tuple(vec.tolist())] = c + d[tuple(vec.tolist())] += c d[self.n * (0,)] += 0 p = Polynomial(d) return p ",sageopt/symbolic/polynomials.py,"ReplaceText(target='+=' @(358,39)->(358,40))","class Polynomial(Signomial): vec = self.alpha[j, :].copy() c = self.c[j] * vec[i] vec[i] -= 1 d[tuple(vec.tolist())] = c d[self.n * (0,)] += 0 p = Polynomial(d) return p","class Polynomial(Signomial): vec = self.alpha[j, :].copy() c = self.c[j] * vec[i] vec[i] -= 1 d[tuple(vec.tolist())] += c d[self.n * (0,)] += 0 p = Polynomial(d) return p" 2206,https://:@github.com/adammhaile/dotconfig.git,2fec17b2aa23c329b0570f73cf86c082a914d2cd,"@@ -76,7 +76,7 @@ class Config(object): # finally, override with given cli args for k, v in cli_args.iteritems(): - if k not in self._data or k is not None: + if k not in self._data or v is not None: self._data[k] = v def __getitem__(self, item): ",dotconfig/__init__.py,"ReplaceText(target='v' @(79,42)->(79,43))","class Config(object): # finally, override with given cli args for k, v in cli_args.iteritems(): if k not in self._data or k is not None: self._data[k] = v def __getitem__(self, item):","class Config(object): # finally, override with given cli args for k, v in cli_args.iteritems(): if k not in self._data or v is not None: self._data[k] = v def __getitem__(self, item):" 2207,https://:@github.com/ralphje/pesigcheck.git,a043237a56b6e55a6e8250dde8811883d4ce9d03,"@@ -125,7 +125,7 @@ class VerificationContext(object): intermediates, trust_roots = [], [] for store in self.stores: for cert in store: - asn1cert = certificate.to_asn1crypto + asn1cert = cert.to_asn1crypto (trust_roots if store.trusted else intermediates).append(asn1cert) all_certs[asn1cert] = cert ",signify/context.py,"ReplaceText(target='cert' @(128,27)->(128,38))","class VerificationContext(object): intermediates, trust_roots = [], [] for store in self.stores: for cert in store: asn1cert = certificate.to_asn1crypto (trust_roots if store.trusted else intermediates).append(asn1cert) all_certs[asn1cert] = cert ","class VerificationContext(object): intermediates, trust_roots = [], [] for store in self.stores: for cert in store: asn1cert = cert.to_asn1crypto (trust_roots if store.trusted else intermediates).append(asn1cert) all_certs[asn1cert] = cert " 2208,https://:@github.com/fritzprix/jconfigpy.git,535f34af57ff0e5c9673de43f00ded78c17d2347,"@@ -762,7 +762,7 @@ def prompt_int(item): def prompt_hex(item): if not isinstance(item, JConfigHex): return - if item.is_visible(): + if not item.is_visible(): return print('\nCONFIG_{0}'.format(item.get_name())) val = 'h' ",jconfigpy.py,"ReplaceText(target='not ' @(765,7)->(765,7))","def prompt_int(item): def prompt_hex(item): if not isinstance(item, JConfigHex): return if item.is_visible(): return print('\nCONFIG_{0}'.format(item.get_name())) val = 'h'","def prompt_int(item): def prompt_hex(item): if not isinstance(item, JConfigHex): return if not item.is_visible(): return print('\nCONFIG_{0}'.format(item.get_name())) val = 'h'" 2209,https://:@github.com/radimsuckr/onesignal-client.git,55031d8ffb8b2c9ebd96a5b19f8ecb5daf4035f8,"@@ -75,7 +75,7 @@ class OneSignal: notification.id = response[""id""] - return response + return notification def cancel(self, notification): """"""Cancel a notification ",onesignal/core.py,"ReplaceText(target='notification' @(78,15)->(78,23))","class OneSignal: notification.id = response[""id""] return response def cancel(self, notification): """"""Cancel a notification","class OneSignal: notification.id = response[""id""] return notification def cancel(self, notification): """"""Cancel a notification" 2210,https://:@github.com/dmonroy/schema-migrations.git,c70624818776029230bfe6438c121fcbcfde2f26,"@@ -82,7 +82,7 @@ class MigrationController(object): if not os.path.isdir(migration_folder): continue - if migration_folder == '__pycache__': + if migration == '__pycache__': continue migration_info = self.migration_info( ",schema_migrations/__init__.py,"ReplaceText(target='migration' @(85,19)->(85,35))","class MigrationController(object): if not os.path.isdir(migration_folder): continue if migration_folder == '__pycache__': continue migration_info = self.migration_info(","class MigrationController(object): if not os.path.isdir(migration_folder): continue if migration == '__pycache__': continue migration_info = self.migration_info(" 2211,https://:@github.com/EnigmaCurry/nose-test-select.git,815e528ec9a2772bddf672b888456154fafbb817,"@@ -79,7 +79,7 @@ class NoseTestSelect(Plugin): for pattern in self.patterns['exclude']: file_pattern, method_pattern = pattern.split(':', 1) if fnmatch.fnmatch(method_file, file_pattern) and \ - fnmatch.fnmatch(method_name, method_pattern): + fnmatch.fnmatch(class_method_name, method_pattern): return False return None ",nose_test_select/nose_test_select.py,"ReplaceText(target='class_method_name' @(82,31)->(82,42))","class NoseTestSelect(Plugin): for pattern in self.patterns['exclude']: file_pattern, method_pattern = pattern.split(':', 1) if fnmatch.fnmatch(method_file, file_pattern) and \ fnmatch.fnmatch(method_name, method_pattern): return False return None","class NoseTestSelect(Plugin): for pattern in self.patterns['exclude']: file_pattern, method_pattern = pattern.split(':', 1) if fnmatch.fnmatch(method_file, file_pattern) and \ fnmatch.fnmatch(class_method_name, method_pattern): return False return None" 2212,https://:@github.com/jiwoncpark/baobab.git,a6a56166079636e36467522f1854976980648167,"@@ -49,7 +49,7 @@ class TestDistributions(unittest.TestCase): exp_kurtosis = gamma(5/p) * gamma(1/p) / gamma(3/p)**2.0 - 3.0 #exp_entropy = 1/p - np.log(p / (2 * alpha * gamma(1/p))) precision = 2 - np.testing.assert_almost_equal(sample_mean, mu, precision) + np.testing.assert_almost_equal(sample_mean, exp_mean, precision) np.testing.assert_almost_equal(sample_var, exp_var, precision) np.testing.assert_almost_equal(sample_skew, exp_skew, precision) np.testing.assert_almost_equal(sample_kurtosis, exp_kurtosis, precision) ",baobab/tests/test_distributions/test_distributions.py,"ReplaceText(target='exp_mean' @(52,52)->(52,54))","class TestDistributions(unittest.TestCase): exp_kurtosis = gamma(5/p) * gamma(1/p) / gamma(3/p)**2.0 - 3.0 #exp_entropy = 1/p - np.log(p / (2 * alpha * gamma(1/p))) precision = 2 np.testing.assert_almost_equal(sample_mean, mu, precision) np.testing.assert_almost_equal(sample_var, exp_var, precision) np.testing.assert_almost_equal(sample_skew, exp_skew, precision) np.testing.assert_almost_equal(sample_kurtosis, exp_kurtosis, precision)","class TestDistributions(unittest.TestCase): exp_kurtosis = gamma(5/p) * gamma(1/p) / gamma(3/p)**2.0 - 3.0 #exp_entropy = 1/p - np.log(p / (2 * alpha * gamma(1/p))) precision = 2 np.testing.assert_almost_equal(sample_mean, exp_mean, precision) np.testing.assert_almost_equal(sample_var, exp_var, precision) np.testing.assert_almost_equal(sample_skew, exp_skew, precision) np.testing.assert_almost_equal(sample_kurtosis, exp_kurtosis, precision)" 2213,https://:@github.com/andrewlorente/catsnap.git,eec5e151ce2751dbd8ceeded16137e7db353c63b,"@@ -48,8 +48,8 @@ def view_album(request_format, album_id): if request_format == 'html': return render_template('view_album.html.jinja', - images = image_structs, + images=image_structs, album=album) else: - return images + return image_structs ",catsnap/web/controllers/album.py,"ReplaceText(target='image_structs' @(54,15)->(54,21))","def view_album(request_format, album_id): if request_format == 'html': return render_template('view_album.html.jinja', images = image_structs, album=album) else: return images ","def view_album(request_format, album_id): if request_format == 'html': return render_template('view_album.html.jinja', images=image_structs, album=album) else: return image_structs " 2214,https://:@github.com/d9pouces/DebTools.git,fa678ba16208c0725036f0e5c407b3e39a2cf60e,"@@ -140,7 +140,7 @@ def main(): package_names = [x for x in packages_to_create] package_names.sort() for package_name in package_names: - package_version = package_names[package_name] + package_version = packages_to_create[package_name] if normalize_package_name(package_name) in excluded_packages: print('%s is excluded' % package_name) continue ",debtools/multideb.py,"ReplaceText(target='packages_to_create' @(143,26)->(143,39))","def main(): package_names = [x for x in packages_to_create] package_names.sort() for package_name in package_names: package_version = package_names[package_name] if normalize_package_name(package_name) in excluded_packages: print('%s is excluded' % package_name) continue","def main(): package_names = [x for x in packages_to_create] package_names.sort() for package_name in package_names: package_version = packages_to_create[package_name] if normalize_package_name(package_name) in excluded_packages: print('%s is excluded' % package_name) continue" 2215,https://:@github.com/shiroyuki/passerine.git,c9ac93750b7b09b440c8cd53654264d52135c005,"@@ -79,7 +79,7 @@ class Collection(object): update_instruction = {'$set': changeset} - self.api.update({'_id': document.id}, changeset, upsert=upsert) + self.api.update({'_id': document.id}, update_instruction, upsert=upsert) document.reset_bits() ",tori/db/odm/collection.py,"ReplaceText(target='update_instruction' @(82,46)->(82,55))","class Collection(object): update_instruction = {'$set': changeset} self.api.update({'_id': document.id}, changeset, upsert=upsert) document.reset_bits() ","class Collection(object): update_instruction = {'$set': changeset} self.api.update({'_id': document.id}, update_instruction, upsert=upsert) document.reset_bits() " 2216,https://:@github.com/mattian7741/ergo.git,13ce6ef335f20303dfa0fac363deebeff08641b6,"@@ -20,7 +20,7 @@ class VerifyVersionCommand(install): def run(self): tag = os.getenv('CIRCLE_TAG') - if tag != VERSION: + if tag == VERSION: info = ""Git tag: {0} does not match the version of this app: {1}"".format( tag, VERSION ) ",setup.py,"ReplaceText(target='==' @(23,15)->(23,17))","class VerifyVersionCommand(install): def run(self): tag = os.getenv('CIRCLE_TAG') if tag != VERSION: info = ""Git tag: {0} does not match the version of this app: {1}"".format( tag, VERSION )","class VerifyVersionCommand(install): def run(self): tag = os.getenv('CIRCLE_TAG') if tag == VERSION: info = ""Git tag: {0} does not match the version of this app: {1}"".format( tag, VERSION )" 2217,https://:@github.com/wallento/riscv-python-model.git,e62d687b72d75f6d5e6037963c1e533b00cbc1d8,"@@ -30,7 +30,7 @@ class InstructionAUIPC(InstructionUType): class InstructionJAL(InstructionJType): def execute(self, model: Model): model.state.intreg[self.rd] = model.state.pc + 4 - model.state.pc = self.imm + model.state.pc += self.imm @isa(""jalr"", RV32I, opcode=0b1100111, funct3=0b000) ",riscvmodel/insn.py,"ReplaceText(target='+=' @(33,23)->(33,24))","class InstructionAUIPC(InstructionUType): class InstructionJAL(InstructionJType): def execute(self, model: Model): model.state.intreg[self.rd] = model.state.pc + 4 model.state.pc = self.imm @isa(""jalr"", RV32I, opcode=0b1100111, funct3=0b000)","class InstructionAUIPC(InstructionUType): class InstructionJAL(InstructionJType): def execute(self, model: Model): model.state.intreg[self.rd] = model.state.pc + 4 model.state.pc += self.imm @isa(""jalr"", RV32I, opcode=0b1100111, funct3=0b000)" 2218,https://:@github.com/wojtekwanczyk/easy_manage.git,4b06119cd0c88ad6bdac965479e49b9170163956,"@@ -125,7 +125,7 @@ class RedfishTools: to_find = name_list[0] found = None for key, value in data.items(): - if in_or_eq(to_find, key): + if in_or_eq(key, to_find): found = self.find(name_list[1:], strict, value, misses) else: found = self.find(name_list, strict, value, misses-1) ",easy_manage/tools/redfish_tools.py,"ArgSwap(idxs=0<->1 @(128,15)->(128,23))","class RedfishTools: to_find = name_list[0] found = None for key, value in data.items(): if in_or_eq(to_find, key): found = self.find(name_list[1:], strict, value, misses) else: found = self.find(name_list, strict, value, misses-1)","class RedfishTools: to_find = name_list[0] found = None for key, value in data.items(): if in_or_eq(key, to_find): found = self.find(name_list[1:], strict, value, misses) else: found = self.find(name_list, strict, value, misses-1)" 2219,https://:@github.com/CTSNE/NodeDefender.git,62a1dbb0099406b2e1d6e254d69c4d2b764b8ae7,"@@ -43,7 +43,7 @@ def Current(node): ret_data.append(sensor_data) ret_data.append(node_data) - return ret_data + return node_data def Average(node): node = db.session.query(NodeModel).filter(NodeModel.name == ",NodeDefender/models/manage/data/node/heat.py,"ReplaceText(target='node_data' @(46,11)->(46,19))","def Current(node): ret_data.append(sensor_data) ret_data.append(node_data) return ret_data def Average(node): node = db.session.query(NodeModel).filter(NodeModel.name ==","def Current(node): ret_data.append(sensor_data) ret_data.append(node_data) return node_data def Average(node): node = db.session.query(NodeModel).filter(NodeModel.name ==" 2220,https://:@github.com/CTSNE/NodeDefender.git,cd60da0847ef6b05456608f19d7235ecb6a53e52,"@@ -9,7 +9,7 @@ from geopy.geocoders import Nominatim def create(name, group, location): NodeDefender.db.node.create(name) NodeDefender.db.group.add_node(group, name) - NodeDefender.db.node.set_location(group, **location) + NodeDefender.db.node.set_location(name, **location) NodeDefender.mail.node.new_node(name) url = url_for('NodeView.NodesNode', name = serializer.dumps(name)) emit('redirect', (url), namespace='/general') ",NodeDefender/frontend/sockets/node.py,"ReplaceText(target='name' @(12,38)->(12,43))","from geopy.geocoders import Nominatim def create(name, group, location): NodeDefender.db.node.create(name) NodeDefender.db.group.add_node(group, name) NodeDefender.db.node.set_location(group, **location) NodeDefender.mail.node.new_node(name) url = url_for('NodeView.NodesNode', name = serializer.dumps(name)) emit('redirect', (url), namespace='/general')","from geopy.geocoders import Nominatim def create(name, group, location): NodeDefender.db.node.create(name) NodeDefender.db.group.add_node(group, name) NodeDefender.db.node.set_location(name, **location) NodeDefender.mail.node.new_node(name) url = url_for('NodeView.NodesNode', name = serializer.dumps(name)) emit('redirect', (url), namespace='/general')" 2221,https://:@github.com/ShixiangWang/loon.git,73ed4c8148e5f4ae188eb76453fee0a2f84133d5,"@@ -15,7 +15,7 @@ def batch(input, cmds, sep=',', header=False, dry_run=False, _logger=None): sys.exit(1) data = read_csv(input, sep=sep, rm_comment=True) - if not header: + if header: # Remove header _ = data.pop(0) ",src/loon/tool.py,"ReplaceText(target='' @(18,7)->(18,11))","def batch(input, cmds, sep=',', header=False, dry_run=False, _logger=None): sys.exit(1) data = read_csv(input, sep=sep, rm_comment=True) if not header: # Remove header _ = data.pop(0) ","def batch(input, cmds, sep=',', header=False, dry_run=False, _logger=None): sys.exit(1) data = read_csv(input, sep=sep, rm_comment=True) if header: # Remove header _ = data.pop(0) " 2222,https://:@github.com/colemanja91/pyeloqua.git,30aaf05072a734ac40836ae4542844b05c6abb25,"@@ -384,7 +384,7 @@ class Eloqua(object): try: test1 = datetime.strptime(start, '%Y-%m-%d %H:%M:%S') - test2 = datetime.strptime(start, '%Y-%m-%d %H:%M:%S') + test2 = datetime.strptime(end, '%Y-%m-%d %H:%M:%S') except: raise ValueError(""Invalid datetime format; use 'YYYY-MM-DD hh:mm:ss'"") ",pyeloqua/pyeloqua.py,"ReplaceText(target='end' @(387,38)->(387,43))","class Eloqua(object): try: test1 = datetime.strptime(start, '%Y-%m-%d %H:%M:%S') test2 = datetime.strptime(start, '%Y-%m-%d %H:%M:%S') except: raise ValueError(""Invalid datetime format; use 'YYYY-MM-DD hh:mm:ss'"") ","class Eloqua(object): try: test1 = datetime.strptime(start, '%Y-%m-%d %H:%M:%S') test2 = datetime.strptime(end, '%Y-%m-%d %H:%M:%S') except: raise ValueError(""Invalid datetime format; use 'YYYY-MM-DD hh:mm:ss'"") " 2223,https://:@github.com/colemanja91/pyeloqua.git,aa8d74f801c77ed45e1dda75a4a5008584f5a7ee,"@@ -388,7 +388,7 @@ class Eloqua(object): except: raise ValueError(""Invalid datetime format; use 'YYYY-MM-DD hh:mm:ss'"") - if (entity!='activities' or (entity in ['contacts', 'accounts'] and field in ['createdAt', 'updatedAt'])): + if (entity!='activities' or (entity in ['contacts', 'accounts'] and field not in ['createdAt', 'updatedAt'])): fieldDef = self.GetFields(entity=entity, fields=[field], cdoID=cdoID) if (fieldDef[0]['dataType'] != 'date'): ",pyeloqua/pyeloqua.py,"ReplaceText(target=' not in ' @(391,81)->(391,85))","class Eloqua(object): except: raise ValueError(""Invalid datetime format; use 'YYYY-MM-DD hh:mm:ss'"") if (entity!='activities' or (entity in ['contacts', 'accounts'] and field in ['createdAt', 'updatedAt'])): fieldDef = self.GetFields(entity=entity, fields=[field], cdoID=cdoID) if (fieldDef[0]['dataType'] != 'date'):","class Eloqua(object): except: raise ValueError(""Invalid datetime format; use 'YYYY-MM-DD hh:mm:ss'"") if (entity!='activities' or (entity in ['contacts', 'accounts'] and field not in ['createdAt', 'updatedAt'])): fieldDef = self.GetFields(entity=entity, fields=[field], cdoID=cdoID) if (fieldDef[0]['dataType'] != 'date'):" 2224,https://:@github.com/catalogicsoftware/kubedrctl.git,c63739163b5305947daf5bb0fc8c36e6f69f9e30,"@@ -25,7 +25,7 @@ def cli(ctx, accesskey, secretkey, repopwd, endpoint, bucket, targetdir, snapid) """""" - if not accesskey or not secretkey or not repopwd or not endpoint or not bucket and not targetdir: + if not accesskey or not secretkey or not repopwd or not endpoint or not bucket or not targetdir: raise Exception('One of the required parameters (accesskey, secretkey, repopwd, endpoint, bucket, targetdir) is missing. ') params = { ",kubedrctl/cli/commands/cmd_restore.py,"ReplaceText(target='or' @(28,83)->(28,86))","def cli(ctx, accesskey, secretkey, repopwd, endpoint, bucket, targetdir, snapid) """""" if not accesskey or not secretkey or not repopwd or not endpoint or not bucket and not targetdir: raise Exception('One of the required parameters (accesskey, secretkey, repopwd, endpoint, bucket, targetdir) is missing. ') params = {","def cli(ctx, accesskey, secretkey, repopwd, endpoint, bucket, targetdir, snapid) """""" if not accesskey or not secretkey or not repopwd or not endpoint or not bucket or not targetdir: raise Exception('One of the required parameters (accesskey, secretkey, repopwd, endpoint, bucket, targetdir) is missing. ') params = {" 2225,https://:@github.com/celliern/energy_plus_wrapper.git,4dcb0b83b81bcaed91696567caea30c80a01ca5c,"@@ -85,7 +85,7 @@ def _build_command_line(tmp, idd_file, idf_file, weather_file, ""-w"", tmp / weather_file.basename(), ""-p"", prefix, ""-d"", tmp.abspath()] + - ([""-i"", tmp / idf_file.basename()] + ([""-i"", tmp / idd_file.basename()] if idd_file is not None else []) + [""-s"", ""d"", ""-r"", ",src/energyplus_wrapper/main.py,"ReplaceText(target='idd_file' @(88,33)->(88,41))","def _build_command_line(tmp, idd_file, idf_file, weather_file, ""-w"", tmp / weather_file.basename(), ""-p"", prefix, ""-d"", tmp.abspath()] + ([""-i"", tmp / idf_file.basename()] if idd_file is not None else []) + [""-s"", ""d"", ""-r"",","def _build_command_line(tmp, idd_file, idf_file, weather_file, ""-w"", tmp / weather_file.basename(), ""-p"", prefix, ""-d"", tmp.abspath()] + ([""-i"", tmp / idd_file.basename()] if idd_file is not None else []) + [""-s"", ""d"", ""-r""," 2226,https://:@github.com/shuoli84/gevent_socketio2.git,7eed4169f86cd7522cab0ef7552da0f2187d7b6c,"@@ -228,7 +228,7 @@ class Socket(EventEmitter): def ping_timeout(): pass - self.ping_timeout_job = gevent.spawn_later(ping_timeout, self.ping_timeout) + self.ping_timeout_job = gevent.spawn_later(self.ping_timeout, ping_timeout) if 'open' == self.ready_state or 'opening' == self.ready_state: self.ping_job = gevent.spawn_later(self.ping_interval/1000, ping) ",socketio_client/engine/socket.py,"ArgSwap(idxs=0<->1 @(231,36)->(231,54))","class Socket(EventEmitter): def ping_timeout(): pass self.ping_timeout_job = gevent.spawn_later(ping_timeout, self.ping_timeout) if 'open' == self.ready_state or 'opening' == self.ready_state: self.ping_job = gevent.spawn_later(self.ping_interval/1000, ping)","class Socket(EventEmitter): def ping_timeout(): pass self.ping_timeout_job = gevent.spawn_later(self.ping_timeout, ping_timeout) if 'open' == self.ready_state or 'opening' == self.ready_state: self.ping_job = gevent.spawn_later(self.ping_interval/1000, ping)" 2227,https://:@bitbucket.org/berkeleylab/pypixie16.git,f7202b4fe9fa06ce4a176f5c694ab0210ab43630,"@@ -70,7 +70,7 @@ def read_list_mode_data(filename, progress=False, keep_trace=False): # about 300x faster than multiple f.read(2) trace = np.fromfile(f, '({},2)(73,23))","def read_list_mode_data(filename, progress=False, keep_trace=False): # about 300x faster than multiple f.read(2) trace = np.fromfile(f, '({},2)(93,23))","def calculate_CFD(traces, t=None, CFD_threshold=None, w=1, B=5, D=5, L=1, Nbkgd= CFD = CFD[0] errors = errors[0] return CFD, cfdtime, errors def calculate_CFD_using_FF(traces, t=None, CFD_threshold=None, w=1, B=5, D=5, L=1, Nbkgd=100):","def calculate_CFD(traces, t=None, CFD_threshold=None, w=1, B=5, D=5, L=1, Nbkgd= CFD = CFD[0] errors = errors[0] return CFD, cfdtrigger, errors def calculate_CFD_using_FF(traces, t=None, CFD_threshold=None, w=1, B=5, D=5, L=1, Nbkgd=100):" 2229,https://:@github.com/toros-astro/corral.git,51ffc50bbb290899fb9e64f5719903c1ba987e3d,"@@ -15,7 +15,7 @@ import importlib def to_namedtuple(name, d): keys = list(d.keys()) - namedtuple = collections.namedtuple(name, d) + namedtuple = collections.namedtuple(name, keys) return namedtuple(**d) ",corral/util.py,"ReplaceText(target='keys' @(18,46)->(18,47))","import importlib def to_namedtuple(name, d): keys = list(d.keys()) namedtuple = collections.namedtuple(name, d) return namedtuple(**d) ","import importlib def to_namedtuple(name, d): keys = list(d.keys()) namedtuple = collections.namedtuple(name, keys) return namedtuple(**d) " 2230,https://:@github.com/karimbahgat/PyAgg.git,23867f72529c5843bd585a0124a9b67099bd8ed9,"@@ -11,7 +11,7 @@ def test_smoothline(): smooth=True, fillcolor=(222,0,0), fillsize=2) - canvas.draw_text((50,50), ""Hello"", textfont=""segoe print bold"", textsize=55) + canvas.draw_text(""Hello"", (50,50), textfont=""segoe print bold"", textsize=55) return canvas def test_histogram(): ",graph_tester.py,"ArgSwap(idxs=0<->1 @(14,4)->(14,20))","def test_smoothline(): smooth=True, fillcolor=(222,0,0), fillsize=2) canvas.draw_text((50,50), ""Hello"", textfont=""segoe print bold"", textsize=55) return canvas def test_histogram():","def test_smoothline(): smooth=True, fillcolor=(222,0,0), fillsize=2) canvas.draw_text(""Hello"", (50,50), textfont=""segoe print bold"", textsize=55) return canvas def test_histogram():" 2231,https://:@github.com/nikist97/Python-DataStructures.git,c6621b3e0914f635762da1e16298441534b5758c,"@@ -1345,7 +1345,7 @@ class DuplicatePriorityQueue(PriorityQueue): if self.type() is not None and type(element) != self.type(): raise TypeError(""Type of the parameter is not "" + str(self.type())) - if self.has_duplicates(): + if not self.has_duplicates(): return super().contains_element(element) for test_element in self.__elements.values(): ",ADTs/AbstractDataStructures.py,"ReplaceText(target='not ' @(1348,11)->(1348,11))","class DuplicatePriorityQueue(PriorityQueue): if self.type() is not None and type(element) != self.type(): raise TypeError(""Type of the parameter is not "" + str(self.type())) if self.has_duplicates(): return super().contains_element(element) for test_element in self.__elements.values():","class DuplicatePriorityQueue(PriorityQueue): if self.type() is not None and type(element) != self.type(): raise TypeError(""Type of the parameter is not "" + str(self.type())) if not self.has_duplicates(): return super().contains_element(element) for test_element in self.__elements.values():" 2232,https://:@github.com/heewinkim/hian.git,2c199eaf141fc1fa049c3c7b9eaf56731b8d4694,"@@ -62,7 +62,7 @@ class PyAlgorithm(object): intersection = intersection.intersection(box_) if intersection.area == box_list[0].area: - if intersection.area == PyAlgorithm.unionRects(rect_list).area: + if intersection.area <= PyAlgorithm.unionRects(rect_list).area: return intersection else: return box(0,0,0,0) ",utilpack/core/algorithm.py,"ReplaceText(target='<=' @(65,33)->(65,35))","class PyAlgorithm(object): intersection = intersection.intersection(box_) if intersection.area == box_list[0].area: if intersection.area == PyAlgorithm.unionRects(rect_list).area: return intersection else: return box(0,0,0,0)","class PyAlgorithm(object): intersection = intersection.intersection(box_) if intersection.area == box_list[0].area: if intersection.area <= PyAlgorithm.unionRects(rect_list).area: return intersection else: return box(0,0,0,0)" 2233,https://:@bitbucket.org/whatshap/whatshap.git,e6a843308297d2a4b170ea9feffc33159a40ea91,"@@ -365,7 +365,7 @@ def run_whatshap(phase_input_files, variant_file, reference=None, # for each family. for representative_sample, family in families.items(): if len(family) == 1: - logger.info('---- Processing individual %s', sample) + logger.info('---- Processing individual %s', representative_sample) else: logger.info('---- Processing family with individuals: %s', ','.join(family)) max_coverage_per_sample = max(1, max_coverage // len(family)) ",whatshap/phase.py,"ReplaceText(target='representative_sample' @(368,50)->(368,56))","def run_whatshap(phase_input_files, variant_file, reference=None, # for each family. for representative_sample, family in families.items(): if len(family) == 1: logger.info('---- Processing individual %s', sample) else: logger.info('---- Processing family with individuals: %s', ','.join(family)) max_coverage_per_sample = max(1, max_coverage // len(family))","def run_whatshap(phase_input_files, variant_file, reference=None, # for each family. for representative_sample, family in families.items(): if len(family) == 1: logger.info('---- Processing individual %s', representative_sample) else: logger.info('---- Processing family with individuals: %s', ','.join(family)) max_coverage_per_sample = max(1, max_coverage // len(family))" 2234,https://:@bitbucket.org/whatshap/whatshap.git,cd3f978e88fe07fb886ad4026b35979962bf0d14,"@@ -163,7 +163,7 @@ def eval_overlap(n1, n2): overlap = zip(n1['sites'][hang1:], n2['sites']) match, mismatch = (0, 0) for (c1, c2) in overlap: - if c1 in ['A', 'C', 'G', 'T'] and c1 in ['A', 'C', 'G', 'T']: + if c1 in ['A', 'C', 'G', 'T'] and c2 in ['A', 'C', 'G', 'T']: if c1 == c2: match += 1 else: ",whatshap/cli/phase.py,"ReplaceText(target='c2' @(166,36)->(166,38))","def eval_overlap(n1, n2): overlap = zip(n1['sites'][hang1:], n2['sites']) match, mismatch = (0, 0) for (c1, c2) in overlap: if c1 in ['A', 'C', 'G', 'T'] and c1 in ['A', 'C', 'G', 'T']: if c1 == c2: match += 1 else:","def eval_overlap(n1, n2): overlap = zip(n1['sites'][hang1:], n2['sites']) match, mismatch = (0, 0) for (c1, c2) in overlap: if c1 in ['A', 'C', 'G', 'T'] and c2 in ['A', 'C', 'G', 'T']: if c1 == c2: match += 1 else:" 2235,https://:@github.com/zach-king/oink.git,4580509c05ac17322f1ac19cffbee9dde781e902,"@@ -114,7 +114,7 @@ def route(command): arg_index = command_args_length - given_args_length if arg_index >= len(comm['required_args']): arg_index = 0 - error = colorize(comm['required_args'][arg_index], 'blue') + ' is required' + error = colorize(comm['required_args'][given_args_length], 'blue') + ' is required' elif given_args_length > max_args_length: error = '{} argument(s) were expected, but {} were given.'.format( command_args_length, given_args_length) ",oink/router.py,"ReplaceText(target='given_args_length' @(117,55)->(117,64))","def route(command): arg_index = command_args_length - given_args_length if arg_index >= len(comm['required_args']): arg_index = 0 error = colorize(comm['required_args'][arg_index], 'blue') + ' is required' elif given_args_length > max_args_length: error = '{} argument(s) were expected, but {} were given.'.format( command_args_length, given_args_length)","def route(command): arg_index = command_args_length - given_args_length if arg_index >= len(comm['required_args']): arg_index = 0 error = colorize(comm['required_args'][given_args_length], 'blue') + ' is required' elif given_args_length > max_args_length: error = '{} argument(s) were expected, but {} were given.'.format( command_args_length, given_args_length)" 2236,https://:@github.com/Mordred/certbot-plugin-websupport.git,b170de9b1db0678ac502540948f1cd062d2f84b9,"@@ -95,7 +95,7 @@ class _WebsupportClient(object): } logger.debug('Attempting to add record to zone %s: %s', zone_id, data) - response = self._send_request('POST', '/v1/user/self/zone/{0}/record'.format(domain), data) + response = self._send_request('POST', '/v1/user/self/zone/{0}/record'.format(zone_id), data) if response.status_code != 200 and response.status_code != 201: raise errors.PluginError('Error communicating with Websupport API: {0}'.format(response.status_code)) ",certbot_plugin_websupport/dns.py,"ReplaceText(target='zone_id' @(98,85)->(98,91))","class _WebsupportClient(object): } logger.debug('Attempting to add record to zone %s: %s', zone_id, data) response = self._send_request('POST', '/v1/user/self/zone/{0}/record'.format(domain), data) if response.status_code != 200 and response.status_code != 201: raise errors.PluginError('Error communicating with Websupport API: {0}'.format(response.status_code))","class _WebsupportClient(object): } logger.debug('Attempting to add record to zone %s: %s', zone_id, data) response = self._send_request('POST', '/v1/user/self/zone/{0}/record'.format(zone_id), data) if response.status_code != 200 and response.status_code != 201: raise errors.PluginError('Error communicating with Websupport API: {0}'.format(response.status_code))" 2237,https://:@github.com/riot-appstore/memory_map_manager.git,4a4ea7729853b223ad080495226a2dbae5082e29,"@@ -12,7 +12,7 @@ from gen_helpers import to_underscore_case def _parse_filename(f_arg, d_arg, name_contains): - if f_arg is None: + if f_arg is not None: for file in os.listdir(os.path.join(os.path.dirname(__file__), d_arg)): if file.endswith("".json""): if name_contains in file: ",memory_map_manager/code_gen.py,"ReplaceText(target=' is not ' @(15,12)->(15,16))","from gen_helpers import to_underscore_case def _parse_filename(f_arg, d_arg, name_contains): if f_arg is None: for file in os.listdir(os.path.join(os.path.dirname(__file__), d_arg)): if file.endswith("".json""): if name_contains in file:","from gen_helpers import to_underscore_case def _parse_filename(f_arg, d_arg, name_contains): if f_arg is not None: for file in os.listdir(os.path.join(os.path.dirname(__file__), d_arg)): if file.endswith("".json""): if name_contains in file:" 2238,https://:@github.com/PlaceDevs/place-scraper.git,c13614931c14e05a2cf8efcc0ef70706f9f56315,"@@ -142,7 +142,7 @@ class PlaceScraper(object): def handle_batch_place(self, frame): for x in frame['payload']: - self.handle_place(frame) + self.handle_place(x) def main(): ",placescraper/base.py,"ReplaceText(target='x' @(145,30)->(145,35))","class PlaceScraper(object): def handle_batch_place(self, frame): for x in frame['payload']: self.handle_place(frame) def main():","class PlaceScraper(object): def handle_batch_place(self, frame): for x in frame['payload']: self.handle_place(x) def main():" 2239,https://:@github.com/niklasf/python-agentspeak.git,e102065b7df1fd92c539be5c3bd2a012edcec740,"@@ -165,7 +165,7 @@ def _member(env, agent, term, intention): choicepoint = object() for member in pyson.evaluate(term.args[1], intention.scope): - agent.stack.append(choicepoint) + intention.stack.append(choicepoint) if pyson.unify(term.args[0], member, intention.scope, intention.stack): yield ",pyson/stdlib.py,"ReplaceText(target='intention' @(168,8)->(168,13))","def _member(env, agent, term, intention): choicepoint = object() for member in pyson.evaluate(term.args[1], intention.scope): agent.stack.append(choicepoint) if pyson.unify(term.args[0], member, intention.scope, intention.stack): yield","def _member(env, agent, term, intention): choicepoint = object() for member in pyson.evaluate(term.args[1], intention.scope): intention.stack.append(choicepoint) if pyson.unify(term.args[0], member, intention.scope, intention.stack): yield" 2240,https://:@github.com/thepinkowl/tuyaha-float.git,8c48c10d8d8bda1f996551e16820d6c9cc1ea82f,"@@ -165,7 +165,7 @@ class TuyaApi: json = data ) if not response.ok: - _LOGGER.warning(""request error, status code is %d, device %s"", devId, response.status_code) + _LOGGER.warning(""request error, status code is %d, device %s"", response.status_code, devId) return response_json = response.json() if response_json['header']['code'] != 'SUCCESS': ",tuyaha/tuyaapi.py,"ArgSwap(idxs=1<->2 @(168,12)->(168,27))","class TuyaApi: json = data ) if not response.ok: _LOGGER.warning(""request error, status code is %d, device %s"", devId, response.status_code) return response_json = response.json() if response_json['header']['code'] != 'SUCCESS':","class TuyaApi: json = data ) if not response.ok: _LOGGER.warning(""request error, status code is %d, device %s"", response.status_code, devId) return response_json = response.json() if response_json['header']['code'] != 'SUCCESS':" 2241,https://:@github.com/shane-breeze/atuproot.git,206e736a62c914f577717679adc3f16b9fa1d6b7,"@@ -36,7 +36,7 @@ class EventSumsProducer(object): event.METnoX_diMuonParaProjPt_Minus_DiMuon_pt = dimu_para - dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt = dimu_perp + dimu_pt event.METnoX_diMuonParaProjPt_Div_DiMuon_pt = dimu_para / dimu_pt - event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_para + dimu_pt) / dimu_pt + event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_perp + dimu_pt) / dimu_pt # MHT ht, mht, mhphi = create_mht( ",sequence/Readers/EventSumsProducer.py,"ReplaceText(target='dimu_perp' @(39,70)->(39,79))","class EventSumsProducer(object): event.METnoX_diMuonParaProjPt_Minus_DiMuon_pt = dimu_para - dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt = dimu_perp + dimu_pt event.METnoX_diMuonParaProjPt_Div_DiMuon_pt = dimu_para / dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_para + dimu_pt) / dimu_pt # MHT ht, mht, mhphi = create_mht(","class EventSumsProducer(object): event.METnoX_diMuonParaProjPt_Minus_DiMuon_pt = dimu_para - dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt = dimu_perp + dimu_pt event.METnoX_diMuonParaProjPt_Div_DiMuon_pt = dimu_para / dimu_pt event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_perp + dimu_pt) / dimu_pt # MHT ht, mht, mhphi = create_mht(" 2242,https://:@github.com/lpryszcz/redundans.git,4a62bd283b434b2faebbab9b82fd6a333bfad8ea,"@@ -65,7 +65,7 @@ def get_libraries(fastq, fasta, mapq, threads, verbose, limit=0): # add libraries strating from lowest insert size for fq1, fq2, ismedian, ismean, isstd, pairs in sorted(libdata, key=lambda x: x[3]): # add new library set if - if not libraries or ismedian > 1.5*libraries[-1][4][0]: + if not libraries or ismean > 1.5*libraries[-1][4][0]: # libnames, libFs, libRs, orientations, libIS, libISStDev libraries.append([[], [], [], [], [], []]) i = 1 ",redundans.py,"ReplaceText(target='ismean' @(68,28)->(68,36))","def get_libraries(fastq, fasta, mapq, threads, verbose, limit=0): # add libraries strating from lowest insert size for fq1, fq2, ismedian, ismean, isstd, pairs in sorted(libdata, key=lambda x: x[3]): # add new library set if if not libraries or ismedian > 1.5*libraries[-1][4][0]: # libnames, libFs, libRs, orientations, libIS, libISStDev libraries.append([[], [], [], [], [], []]) i = 1","def get_libraries(fastq, fasta, mapq, threads, verbose, limit=0): # add libraries strating from lowest insert size for fq1, fq2, ismedian, ismean, isstd, pairs in sorted(libdata, key=lambda x: x[3]): # add new library set if if not libraries or ismean > 1.5*libraries[-1][4][0]: # libnames, libFs, libRs, orientations, libIS, libISStDev libraries.append([[], [], [], [], [], []]) i = 1" 2243,https://:@github.com/hammerlab/epitopes.git,0d8477a0e957f316d6005ba87853d1699307e0f5,"@@ -223,7 +223,7 @@ def mutate_protein_from_transcript( seq = str(seq_region), start = start_pos, stop = end_pos, - mutation_start = aa_position, + mutation_start = mutation_start_pos_in_region, n_removed = n_aa_deleted, n_inserted = n_aa_inserted, annot = annot) ",epitopes/mutate.py,"ReplaceText(target='mutation_start_pos_in_region' @(226,25)->(226,36))","def mutate_protein_from_transcript( seq = str(seq_region), start = start_pos, stop = end_pos, mutation_start = aa_position, n_removed = n_aa_deleted, n_inserted = n_aa_inserted, annot = annot)","def mutate_protein_from_transcript( seq = str(seq_region), start = start_pos, stop = end_pos, mutation_start = mutation_start_pos_in_region, n_removed = n_aa_deleted, n_inserted = n_aa_inserted, annot = annot)" 2244,https://:@gitlab.com/pjbecotte/settingscascade.git,390778a0958c04c13ef365b4c0c159f7d353ba3e,"@@ -45,7 +45,7 @@ class Item: self.items.add(val) count[key] += 1 if key == ""el"": - self.el = key + self.el = val self.score = Score(count[""id""], count[""class""], count[""el""]) ",src/settingscascade/selector.py,"ReplaceText(target='val' @(48,26)->(48,29))","class Item: self.items.add(val) count[key] += 1 if key == ""el"": self.el = key self.score = Score(count[""id""], count[""class""], count[""el""]) ","class Item: self.items.add(val) count[key] += 1 if key == ""el"": self.el = val self.score = Score(count[""id""], count[""class""], count[""el""]) " 2245,https://:@github.com/Javinator9889/ServiceCreator.git,f874aa280e7860ed7603d182fca0c62997debbb4,"@@ -81,7 +81,7 @@ def makeBashScript(filename: str, new_sh_file: str): pprint(script_content) pprint(script_content[0].rstrip()) pprint(script_content[0].strip()) - if (script_content[0].rstrip() != OP_BASH_HEADER) or (script_content[0].rstrip() != OP_SH_HEADER): + if (script_content[0].rstrip() != OP_BASH_HEADER) and (script_content[0].rstrip() != OP_SH_HEADER): script_content.insert(0, OP_SH_HEADER + ""\n\n"") usr_exec_file = os.path.basename(new_sh_file) pprint(script_content) ",service_creator/utils/__init__.py,"ReplaceText(target='and' @(84,54)->(84,56))","def makeBashScript(filename: str, new_sh_file: str): pprint(script_content) pprint(script_content[0].rstrip()) pprint(script_content[0].strip()) if (script_content[0].rstrip() != OP_BASH_HEADER) or (script_content[0].rstrip() != OP_SH_HEADER): script_content.insert(0, OP_SH_HEADER + ""\n\n"") usr_exec_file = os.path.basename(new_sh_file) pprint(script_content)","def makeBashScript(filename: str, new_sh_file: str): pprint(script_content) pprint(script_content[0].rstrip()) pprint(script_content[0].strip()) if (script_content[0].rstrip() != OP_BASH_HEADER) and (script_content[0].rstrip() != OP_SH_HEADER): script_content.insert(0, OP_SH_HEADER + ""\n\n"") usr_exec_file = os.path.basename(new_sh_file) pprint(script_content)" 2246,https://:@github.com/AlexeyTrekin/pansharpen.git,ab65f7248e7b2fbac5f5ac43ff0af7c8902766e3,"@@ -54,7 +54,7 @@ def scale(img, dtype, if np.issubdtype(dtype, np.integer): if out_min is None: out_min = np.iinfo(dtype).min - if in_max is None: + if out_max is None: out_max = np.iinfo(dtype).max # default range for float is 0:1 else: ",pysharpen/preprocessing/type_conversion.py,"ReplaceText(target='out_max' @(57,11)->(57,17))","def scale(img, dtype, if np.issubdtype(dtype, np.integer): if out_min is None: out_min = np.iinfo(dtype).min if in_max is None: out_max = np.iinfo(dtype).max # default range for float is 0:1 else:","def scale(img, dtype, if np.issubdtype(dtype, np.integer): if out_min is None: out_min = np.iinfo(dtype).min if out_max is None: out_max = np.iinfo(dtype).max # default range for float is 0:1 else:" 2247,https://:@github.com/hendrikx-itc/python-minerva.git,6044f69ae630756a5e2ba468cc1da4f1ea904725,"@@ -64,7 +64,7 @@ def names_to_entity_ids(cursor, entity_type: str, names: List[str]) -> List[int] for name, entity_id in rows: if entity_id is None: - entity_id = create_entity_from_name(cursor, entity_type, name) + entity_id = create_entity_from_name(cursor, entity_type_name, name) entity_ids.append(entity_id) ",src/minerva/directory/helpers.py,"ReplaceText(target='entity_type_name' @(67,56)->(67,67))","def names_to_entity_ids(cursor, entity_type: str, names: List[str]) -> List[int] for name, entity_id in rows: if entity_id is None: entity_id = create_entity_from_name(cursor, entity_type, name) entity_ids.append(entity_id) ","def names_to_entity_ids(cursor, entity_type: str, names: List[str]) -> List[int] for name, entity_id in rows: if entity_id is None: entity_id = create_entity_from_name(cursor, entity_type_name, name) entity_ids.append(entity_id) " 2248,https://:@github.com/maykinmedia/django-better-admin-arrayfield.git,4ff331cf5b11f24e87e5573d36960802603a5773,"@@ -30,7 +30,7 @@ class DynamicArrayField(forms.Field): ) if errors: raise forms.ValidationError(list(chain.from_iterable(errors))) - if cleaned_data and self.required: + if not cleaned_data and self.required: raise forms.ValidationError(self.error_messages[""required""]) return cleaned_data ",django_better_admin_arrayfield/forms/fields.py,"ReplaceText(target='not ' @(33,11)->(33,11))","class DynamicArrayField(forms.Field): ) if errors: raise forms.ValidationError(list(chain.from_iterable(errors))) if cleaned_data and self.required: raise forms.ValidationError(self.error_messages[""required""]) return cleaned_data ","class DynamicArrayField(forms.Field): ) if errors: raise forms.ValidationError(list(chain.from_iterable(errors))) if not cleaned_data and self.required: raise forms.ValidationError(self.error_messages[""required""]) return cleaned_data " 2249,https://:@github.com/gsanhueza/BlastSight.git,e569ea39b5e97a60abf3e0d8a75eb4f7299b00b9,"@@ -22,7 +22,7 @@ class NormalMode(Mode): self.set_z_rotation(widget, widget.zWorldRot + dx) elif event.buttons() == Qt.RightButton: self.set_x_rotation(widget, widget.xWorldRot + dy) - self.set_y_rotation(widget, widget.yWorldRot - dx) + self.set_y_rotation(widget, widget.yWorldRot + dx) elif event.buttons() == Qt.MiddleButton: # FIXME Dependent on aspect ratio distance_x = 200 * abs(widget.zCameraPos + widget.centroid[2]) / widget.width() ",libraries/Controller/normalmode.py,"ReplaceText(target='+' @(25,57)->(25,58))","class NormalMode(Mode): self.set_z_rotation(widget, widget.zWorldRot + dx) elif event.buttons() == Qt.RightButton: self.set_x_rotation(widget, widget.xWorldRot + dy) self.set_y_rotation(widget, widget.yWorldRot - dx) elif event.buttons() == Qt.MiddleButton: # FIXME Dependent on aspect ratio distance_x = 200 * abs(widget.zCameraPos + widget.centroid[2]) / widget.width()","class NormalMode(Mode): self.set_z_rotation(widget, widget.zWorldRot + dx) elif event.buttons() == Qt.RightButton: self.set_x_rotation(widget, widget.xWorldRot + dy) self.set_y_rotation(widget, widget.yWorldRot + dx) elif event.buttons() == Qt.MiddleButton: # FIXME Dependent on aspect ratio distance_x = 200 * abs(widget.zCameraPos + widget.centroid[2]) / widget.width()" 2250,https://:@github.com/gsanhueza/BlastSight.git,ba4c91b6850cb04fec7d049d0f20e7ea86b79454,"@@ -34,7 +34,7 @@ class LineGL(GLDrawable): # Fill buffers (see GLDrawable) self.fill_buffer(_POSITION, 3, vertices, GLfloat, GL_FLOAT, self.vbos[_POSITION]) - self.fill_buffer(_COLOR, 4, colors, GLfloat, GL_FLOAT, self.vbos[_POSITION]) + self.fill_buffer(_COLOR, 4, colors, GLfloat, GL_FLOAT, self.vbos[_COLOR]) glVertexAttribDivisor(_COLOR, 1) ",blastsight/view/drawables/linegl.py,"ReplaceText(target='_COLOR' @(37,73)->(37,82))","class LineGL(GLDrawable): # Fill buffers (see GLDrawable) self.fill_buffer(_POSITION, 3, vertices, GLfloat, GL_FLOAT, self.vbos[_POSITION]) self.fill_buffer(_COLOR, 4, colors, GLfloat, GL_FLOAT, self.vbos[_POSITION]) glVertexAttribDivisor(_COLOR, 1) ","class LineGL(GLDrawable): # Fill buffers (see GLDrawable) self.fill_buffer(_POSITION, 3, vertices, GLfloat, GL_FLOAT, self.vbos[_POSITION]) self.fill_buffer(_COLOR, 4, colors, GLfloat, GL_FLOAT, self.vbos[_COLOR]) glVertexAttribDivisor(_COLOR, 1) " 2251,https://:@github.com/clemsciences/comparison_sigurdr_siegfried.git,1d6a62eda93744950d2959abd1c2389b12d70d97,"@@ -57,7 +57,7 @@ def read_txt(main_link: str) -> List: """""" retrieved_texts = [] directory = ""extracted_"" + main_link.split(""/"")[-1].split(""."")[0][:-3] - if os.path.exists(directory): + if not os.path.exists(directory): nib_scripts.extract_tei_from_html() for i in range(1, len(os.listdir(directory))): filename = os.path.join(directory, str(i) + "".txt"") ",sigurd/nib_augsburg/nib_reader.py,"ReplaceText(target='not ' @(60,7)->(60,7))","def read_txt(main_link: str) -> List: """""" retrieved_texts = [] directory = ""extracted_"" + main_link.split(""/"")[-1].split(""."")[0][:-3] if os.path.exists(directory): nib_scripts.extract_tei_from_html() for i in range(1, len(os.listdir(directory))): filename = os.path.join(directory, str(i) + "".txt"")","def read_txt(main_link: str) -> List: """""" retrieved_texts = [] directory = ""extracted_"" + main_link.split(""/"")[-1].split(""."")[0][:-3] if not os.path.exists(directory): nib_scripts.extract_tei_from_html() for i in range(1, len(os.listdir(directory))): filename = os.path.join(directory, str(i) + "".txt"")" 2252,https://:@github.com/cfhamlet/os-3m-engine.git,b6a8890df08b38e6201e3b8cc18e870a7f61fda4,"@@ -89,7 +89,7 @@ def create(frontend_cls='os_m3_engine.ootb.StdinFrontend', default_engine_transport_config = ENGINE_TRANSPORT_BRIDGE_CONFIG \ if backend_cls is not None else ENGINE_TRANSPORT_CONFIG - e_transport_config = engine_backend_config + e_transport_config = engine_transport_config if engine_transport_config in (ENGINE_TRANSPORT_CONFIG, ENGINE_TRANSPORT_BRIDGE_CONFIG): e_transport_config = None ",src/os_m3_engine/launcher.py,"ReplaceText(target='engine_transport_config' @(92,25)->(92,46))","def create(frontend_cls='os_m3_engine.ootb.StdinFrontend', default_engine_transport_config = ENGINE_TRANSPORT_BRIDGE_CONFIG \ if backend_cls is not None else ENGINE_TRANSPORT_CONFIG e_transport_config = engine_backend_config if engine_transport_config in (ENGINE_TRANSPORT_CONFIG, ENGINE_TRANSPORT_BRIDGE_CONFIG): e_transport_config = None ","def create(frontend_cls='os_m3_engine.ootb.StdinFrontend', default_engine_transport_config = ENGINE_TRANSPORT_BRIDGE_CONFIG \ if backend_cls is not None else ENGINE_TRANSPORT_CONFIG e_transport_config = engine_transport_config if engine_transport_config in (ENGINE_TRANSPORT_CONFIG, ENGINE_TRANSPORT_BRIDGE_CONFIG): e_transport_config = None " 2253,https://:@github.com/dstegelman/python-usps.git,88e04fab6f7c4b8024558de10796513b6b355333,"@@ -57,7 +57,7 @@ class USPSAddressService(object): if root.tag == 'Error': raise USPSXMLError(root) error = root.find('.//Error') - if error is None: + if error is not None: raise USPSXMLError(error) return root ",usps/addressinformation/base.py,"ReplaceText(target=' is not ' @(60,16)->(60,20))","class USPSAddressService(object): if root.tag == 'Error': raise USPSXMLError(root) error = root.find('.//Error') if error is None: raise USPSXMLError(error) return root ","class USPSAddressService(object): if root.tag == 'Error': raise USPSXMLError(root) error = root.find('.//Error') if error is not None: raise USPSXMLError(error) return root " 2254,https://:@github.com/NiklasRosenstein/upython.git,9ccceff81d433a6220665e53a1938522df4fdf0c,"@@ -120,7 +120,7 @@ def _check_include_file(filename, include_patterns, exclude_patterns): def is_virtualenv(): - return hasattr(sys, 'real_prefix') or (sys.prefix == sys.base_prefix) + return hasattr(sys, 'real_prefix') or (sys.prefix != sys.base_prefix) class PackageNotFound(Exception): ",lib/install.py,"ReplaceText(target='!=' @(123,52)->(123,54))","def _check_include_file(filename, include_patterns, exclude_patterns): def is_virtualenv(): return hasattr(sys, 'real_prefix') or (sys.prefix == sys.base_prefix) class PackageNotFound(Exception):","def _check_include_file(filename, include_patterns, exclude_patterns): def is_virtualenv(): return hasattr(sys, 'real_prefix') or (sys.prefix != sys.base_prefix) class PackageNotFound(Exception):" 2255,https://:@github.com/NYTimes/kaichu.git,357040e9a665e2eb1cf99654a220741c625b347e,"@@ -53,7 +53,7 @@ class KaichuManager(object): else: return True else: - return True + return False def __init__(self, tissue, options, noseconfig): ",kaichu/kaichu/interface.py,"ReplaceText(target='False' @(56,19)->(56,23))","class KaichuManager(object): else: return True else: return True def __init__(self, tissue, options, noseconfig): ","class KaichuManager(object): else: return True else: return False def __init__(self, tissue, options, noseconfig): " 2256,https://:@github.com/jflaherty/phishnet_api_v3.git,738aa8a756f8f816459af12dc10d8763dfb1136c,"@@ -24,7 +24,7 @@ def check_apikey(f): def check_authkey(f): def wrapper(*args, **kwargs): - if not args[0].authkey and not args[0].uid == args[1]: + if not args[0].authkey or not args[0].uid == args[1]: args[0].authorize(args[1]) return f(*args, **kwargs) return wrapper ",phishnet_api_v3/decorators.py,"ReplaceText(target='or' @(27,31)->(27,34))","def check_apikey(f): def check_authkey(f): def wrapper(*args, **kwargs): if not args[0].authkey and not args[0].uid == args[1]: args[0].authorize(args[1]) return f(*args, **kwargs) return wrapper","def check_apikey(f): def check_authkey(f): def wrapper(*args, **kwargs): if not args[0].authkey or not args[0].uid == args[1]: args[0].authorize(args[1]) return f(*args, **kwargs) return wrapper" 2257,https://:@github.com/gxx/pathresolver.git,9ff96ef6ac8c6fe324fb2007cc769016b9a0f085,"@@ -10,7 +10,7 @@ MATCH_ALL = '*' # ---- Basic Resolvers ---- # # Resolve by Attribute -attribute_resolver = KeyResolver(lambda k, v: getattr(k, v), (AttributeError, TypeError)) +attribute_resolver = KeyResolver(lambda k, v: getattr(v, k), (AttributeError, TypeError)) # Resolve by Key (i.e. dictionary) key_lookup_resolver = KeyResolver(lambda k, v: v[k], (KeyError, TypeError)) ",pathresolver/resolver/resolvers.py,"ArgSwap(idxs=0<->1 @(13,46)->(13,53))","MATCH_ALL = '*' # ---- Basic Resolvers ---- # # Resolve by Attribute attribute_resolver = KeyResolver(lambda k, v: getattr(k, v), (AttributeError, TypeError)) # Resolve by Key (i.e. dictionary) key_lookup_resolver = KeyResolver(lambda k, v: v[k], (KeyError, TypeError))","MATCH_ALL = '*' # ---- Basic Resolvers ---- # # Resolve by Attribute attribute_resolver = KeyResolver(lambda k, v: getattr(v, k), (AttributeError, TypeError)) # Resolve by Key (i.e. dictionary) key_lookup_resolver = KeyResolver(lambda k, v: v[k], (KeyError, TypeError))" 2258,https://:@github.com/frank2/schizophrenia.git,443bfd84c89aa270ba30bdeb303a616354959d34,"@@ -305,7 +305,7 @@ class Manager(object): def launch_task(self, task_obj, *args, **kwargs): tid_obj = self.register_task(task_obj) task_obj.run(*args, **kwargs) - return tid_obj + return task_obj def spawn_task(self, task_name, *args, **kwargs): return self.launch_task(self.create_task(task_name), *args, **kwargs) ",schizophrenia/manager.py,"ReplaceText(target='task_obj' @(308,15)->(308,22))","class Manager(object): def launch_task(self, task_obj, *args, **kwargs): tid_obj = self.register_task(task_obj) task_obj.run(*args, **kwargs) return tid_obj def spawn_task(self, task_name, *args, **kwargs): return self.launch_task(self.create_task(task_name), *args, **kwargs)","class Manager(object): def launch_task(self, task_obj, *args, **kwargs): tid_obj = self.register_task(task_obj) task_obj.run(*args, **kwargs) return task_obj def spawn_task(self, task_name, *args, **kwargs): return self.launch_task(self.create_task(task_name), *args, **kwargs)" 2259,https://:@github.com/hibtc/madqt.git,f832813972a0b40d95237d0c645157c550772e0d,"@@ -410,7 +410,7 @@ class Model: # shortcut for thin elements: if float(self.elements[ix].length) == 0: - return y[x] + return y[ix] lo = x.start-1 if x.start > 0 else x.start hi = x.stop+1 ",src/madgui/model/madx.py,"ReplaceText(target='ix' @(413,21)->(413,22))","class Model: # shortcut for thin elements: if float(self.elements[ix].length) == 0: return y[x] lo = x.start-1 if x.start > 0 else x.start hi = x.stop+1","class Model: # shortcut for thin elements: if float(self.elements[ix].length) == 0: return y[ix] lo = x.start-1 if x.start > 0 else x.start hi = x.stop+1" 2260,https://:@github.com/soulhave/woven-gutter-gae.git,33b93fde1ae059d1ad2911ef221eb0131ffebcff,"@@ -100,7 +100,7 @@ class SwitchManager(ModelDict): conditions = self.get(key) if not conditions: # XXX: option to have default return value? - return False + return True conditions = conditions.value if conditions.get('global'): ",gargoyle/models.py,"ReplaceText(target='True' @(103,19)->(103,24))","class SwitchManager(ModelDict): conditions = self.get(key) if not conditions: # XXX: option to have default return value? return False conditions = conditions.value if conditions.get('global'):","class SwitchManager(ModelDict): conditions = self.get(key) if not conditions: # XXX: option to have default return value? return True conditions = conditions.value if conditions.get('global'):" 2261,https://:@github.com/soulhave/woven-gutter-gae.git,a2b6a601ae849f4c610967c28fe469b02fd8f730,"@@ -6,4 +6,4 @@ class SwitchAdmin(admin.ModelAdmin): list_filter = ('status',) search_fields = ('label', 'key', 'value') -admin.site.register(SwitchAdmin, Switch) \ No newline at end of file +admin.site.register(Switch, SwitchAdmin) \ No newline at end of file ",gargoyle/admin.py,"ArgSwap(idxs=0<->1 @(9,0)->(9,19))","class SwitchAdmin(admin.ModelAdmin): list_filter = ('status',) search_fields = ('label', 'key', 'value') admin.site.register(SwitchAdmin, Switch) \ No newline at end of file \ No newline at end of file","class SwitchAdmin(admin.ModelAdmin): list_filter = ('status',) search_fields = ('label', 'key', 'value') \ No newline at end of file admin.site.register(Switch, SwitchAdmin) \ No newline at end of file" 2262,https://:@github.com/combatopera/aridity.git,46f2e7adf7dace0001676c27a9811a55183e53f1,"@@ -72,7 +72,7 @@ class AbstractContext(Resolvable): # TODO LATER: Some methods should probably be c = self for name in path[:-1]: that = self.resolvables.get(name) - that = Context(c) if that is None else that.resolve(c) + c = Context(c) if that is None else that.resolve(c) del c ",aridimpl/context.py,"ReplaceText(target='c' @(75,12)->(75,16))","class AbstractContext(Resolvable): # TODO LATER: Some methods should probably be c = self for name in path[:-1]: that = self.resolvables.get(name) that = Context(c) if that is None else that.resolve(c) del c ","class AbstractContext(Resolvable): # TODO LATER: Some methods should probably be c = self for name in path[:-1]: that = self.resolvables.get(name) c = Context(c) if that is None else that.resolve(c) del c " 2263,https://:@github.com/hudora/huDjango.git,874df198c5508223ff55fd96539fda603f660a81,"@@ -50,7 +50,7 @@ class ClientTrackMiddleware(object): request.clienttrack_last_visit = request.clienttrack_first_visit = None def process_response(self, request, response): - if (not getattr('clienttrack_prohibit', request, False)) or not request.clienttrack_first_visit: + if (not getattr(request, 'clienttrack_prohibit', False)) or not request.clienttrack_first_visit: # even if clienttrack_prohibit is True, we we set the cookie for first time visitors. if not request.clienttrack_first_visit: request.clienttrack_first_visit = time.time() ",hudjango/middleware/clienttrack.py,"ArgSwap(idxs=0<->1 @(53,16)->(53,23))","class ClientTrackMiddleware(object): request.clienttrack_last_visit = request.clienttrack_first_visit = None def process_response(self, request, response): if (not getattr('clienttrack_prohibit', request, False)) or not request.clienttrack_first_visit: # even if clienttrack_prohibit is True, we we set the cookie for first time visitors. if not request.clienttrack_first_visit: request.clienttrack_first_visit = time.time()","class ClientTrackMiddleware(object): request.clienttrack_last_visit = request.clienttrack_first_visit = None def process_response(self, request, response): if (not getattr(request, 'clienttrack_prohibit', False)) or not request.clienttrack_first_visit: # even if clienttrack_prohibit is True, we we set the cookie for first time visitors. if not request.clienttrack_first_visit: request.clienttrack_first_visit = time.time()" 2264,https://:@gitlab.com/cossartlab/cicada.git,f25250e95ffb716ac3e8bc60be839b9b1e10497d,"@@ -453,7 +453,7 @@ class CicadaTransientAmplitudeAnalysis(CicadaAnalysis): ax1.set_facecolor(background_color) fig.patch.set_facecolor(background_color) - svm = sns.catplot(x=x_axis_name, y=""MeanProminence"", hue=hue, data=gobal_amplitude_data_table, + svm = sns.catplot(x=x_axis_name, y=""MeanProminence"", hue=hue, data=data_table, hue_order=None, kind=kind, orient=None, color=fig_facecolor, palette=palette, ax=ax1) ",src/cicada/analysis/cicada_transient_amplitude_analysis.py,"ReplaceText(target='data_table' @(456,75)->(456,101))","class CicadaTransientAmplitudeAnalysis(CicadaAnalysis): ax1.set_facecolor(background_color) fig.patch.set_facecolor(background_color) svm = sns.catplot(x=x_axis_name, y=""MeanProminence"", hue=hue, data=gobal_amplitude_data_table, hue_order=None, kind=kind, orient=None, color=fig_facecolor, palette=palette, ax=ax1) ","class CicadaTransientAmplitudeAnalysis(CicadaAnalysis): ax1.set_facecolor(background_color) fig.patch.set_facecolor(background_color) svm = sns.catplot(x=x_axis_name, y=""MeanProminence"", hue=hue, data=data_table, hue_order=None, kind=kind, orient=None, color=fig_facecolor, palette=palette, ax=ax1) " 2265,https://:@github.com/gtoonstra/sqlineage.git,cb395147b4f4c81248642228da9739995db2bb71,"@@ -15,7 +15,7 @@ class TestSimpleInsert(unittest.TestCase): self.result = [] def verify_result(self, expected): - self.assertEqual(self.result, expected) + self.assertEqual(expected, self.result) def run_test(self, filename, expected): self.clear_result() ",tests/test_simple_insert.py,"ArgSwap(idxs=0<->1 @(18,8)->(18,24))","class TestSimpleInsert(unittest.TestCase): self.result = [] def verify_result(self, expected): self.assertEqual(self.result, expected) def run_test(self, filename, expected): self.clear_result()","class TestSimpleInsert(unittest.TestCase): self.result = [] def verify_result(self, expected): self.assertEqual(expected, self.result) def run_test(self, filename, expected): self.clear_result()" 2266,https://:@github.com/iamjli/keggx.git,c311827d187f2f04dbe6389ed3f274c8b978d703,"@@ -386,6 +386,6 @@ def output_DiGraph_as_graphml(graph, path): for source,target in list(graph_out.edges): if graph_out.has_edge(target, source): graph_out.remove_edge(source, target) - nx.write_graphml(graph, path) + nx.write_graphml(graph_out, path) return path ",src/KEGGX.py,"ReplaceText(target='graph_out' @(389,18)->(389,23))","def output_DiGraph_as_graphml(graph, path): for source,target in list(graph_out.edges): if graph_out.has_edge(target, source): graph_out.remove_edge(source, target) nx.write_graphml(graph, path) return path","def output_DiGraph_as_graphml(graph, path): for source,target in list(graph_out.edges): if graph_out.has_edge(target, source): graph_out.remove_edge(source, target) nx.write_graphml(graph_out, path) return path" 2267,https://:@github.com/sgammon/canteen.git,a08718c0c160e698968f8cbebb367ba22df0370a,"@@ -569,7 +569,7 @@ class RedisAdapter(DirectedGraphAdapter): elif cls.EngineConfig.mode == RedisMode.hashkey_blob: # build key and extract group - desired_key = model.Key.from_raw(flattened) + desired_key = model.Key.from_raw(joined) root = (ancestor for ancestor in desired_key.ancestry).next() tail = ( desired_key.flatten(True)[0].replace(root.flatten(True)[0], '') or ( ",canteen/model/adapter/redis.py,"ReplaceText(target='joined' @(572,41)->(572,50))","class RedisAdapter(DirectedGraphAdapter): elif cls.EngineConfig.mode == RedisMode.hashkey_blob: # build key and extract group desired_key = model.Key.from_raw(flattened) root = (ancestor for ancestor in desired_key.ancestry).next() tail = ( desired_key.flatten(True)[0].replace(root.flatten(True)[0], '') or (","class RedisAdapter(DirectedGraphAdapter): elif cls.EngineConfig.mode == RedisMode.hashkey_blob: # build key and extract group desired_key = model.Key.from_raw(joined) root = (ancestor for ancestor in desired_key.ancestry).next() tail = ( desired_key.flatten(True)[0].replace(root.flatten(True)[0], '') or (" 2268,https://:@github.com/prateek3211/statsmodels.git,5b5665a3859f663e8709e16e5e8207344716ecfd,"@@ -50,7 +50,7 @@ def plot_corr(dcorr, xnames=None, ynames=None, title=None, normcolor=False, if ax is None: create_colorbar = True else: - create_colorbar = True + create_colorbar = False fig, ax = utils.create_mpl_ax(ax) from matplotlib import cm ",scikits/statsmodels/graphics/correlation.py,"ReplaceText(target='False' @(53,26)->(53,30))","def plot_corr(dcorr, xnames=None, ynames=None, title=None, normcolor=False, if ax is None: create_colorbar = True else: create_colorbar = True fig, ax = utils.create_mpl_ax(ax) from matplotlib import cm","def plot_corr(dcorr, xnames=None, ynames=None, title=None, normcolor=False, if ax is None: create_colorbar = True else: create_colorbar = False fig, ax = utils.create_mpl_ax(ax) from matplotlib import cm" 2269,https://:@github.com/prateek3211/statsmodels.git,e2e40c4c53e8e87c98423da5c648c25d1ed24799,"@@ -69,5 +69,5 @@ def bkfilter(X, low=6, high=32, K=12): bweights -= bweights.mean() # make sure weights sum to zero if X.ndim == 2: bweights = bweights[:,None] - return fftconvolve(bweights, X, mode='valid') # get a centered moving avg/ + return fftconvolve(X, bweights, mode='valid') # get a centered moving avg/ # convolution ",statsmodels/tsa/filters/bk_filter.py,"ArgSwap(idxs=0<->1 @(72,11)->(72,22))","def bkfilter(X, low=6, high=32, K=12): bweights -= bweights.mean() # make sure weights sum to zero if X.ndim == 2: bweights = bweights[:,None] return fftconvolve(bweights, X, mode='valid') # get a centered moving avg/ # convolution","def bkfilter(X, low=6, high=32, K=12): bweights -= bweights.mean() # make sure weights sum to zero if X.ndim == 2: bweights = bweights[:,None] return fftconvolve(X, bweights, mode='valid') # get a centered moving avg/ # convolution" 2270,https://:@github.com/prateek3211/statsmodels.git,38a7e8ec399169b49185265450c1a6dbdf423c2f,"@@ -99,7 +99,7 @@ class QuantReg(RegressionModel): beta = np.ones(rank) # TODO: better start diff = 10 - while itrat < 1000 or diff > 1e-6: + while itrat < 1000 and diff > 1e-6: itrat += 1 beta0 = beta beta = dot(pinv(dot(xstar.T, exog)), xstar.T, endog) ",statsmodels/regression/quantreg.py,"ReplaceText(target='and' @(102,27)->(102,29))","class QuantReg(RegressionModel): beta = np.ones(rank) # TODO: better start diff = 10 while itrat < 1000 or diff > 1e-6: itrat += 1 beta0 = beta beta = dot(pinv(dot(xstar.T, exog)), xstar.T, endog)","class QuantReg(RegressionModel): beta = np.ones(rank) # TODO: better start diff = 10 while itrat < 1000 and diff > 1e-6: itrat += 1 beta0 = beta beta = dot(pinv(dot(xstar.T, exog)), xstar.T, endog)" 2271,https://:@github.com/prateek3211/statsmodels.git,d9b699a35e1c148891fe77831cb840c3a8410c35,"@@ -158,7 +158,7 @@ def lowess(endog, exog, frac=2.0/3.0, it=3, delta=0.0, is_sorted=False, if not is_sorted: # Sort both inputs according to the ascending order of x values - sort_index = np.argsort(exog) + sort_index = np.argsort(x) x = np.array(x[sort_index]) y = np.array(y[sort_index]) ",statsmodels/nonparametric/smoothers_lowess.py,"ReplaceText(target='x' @(161,32)->(161,36))","def lowess(endog, exog, frac=2.0/3.0, it=3, delta=0.0, is_sorted=False, if not is_sorted: # Sort both inputs according to the ascending order of x values sort_index = np.argsort(exog) x = np.array(x[sort_index]) y = np.array(y[sort_index]) ","def lowess(endog, exog, frac=2.0/3.0, it=3, delta=0.0, is_sorted=False, if not is_sorted: # Sort both inputs according to the ascending order of x values sort_index = np.argsort(x) x = np.array(x[sort_index]) y = np.array(y[sort_index]) " 2272,https://:@github.com/prateek3211/statsmodels.git,7b29fa27d738c9c60f2a79df77b3b523a2d78028,"@@ -171,7 +171,7 @@ def lowess(endog, exog, frac=2.0/3.0, it=3, delta=0.0, is_sorted=False, # rebuild yfitted with original indices # a bit messy: y might have been selected twice if not is_sorted: - yfitted_ = np.empty_like(endog) + yfitted_ = np.empty_like(y) yfitted_.fill(np.nan) yfitted_[sort_index] = yfitted yfitted = yfitted_ ",statsmodels/nonparametric/smoothers_lowess.py,"ReplaceText(target='y' @(174,37)->(174,42))","def lowess(endog, exog, frac=2.0/3.0, it=3, delta=0.0, is_sorted=False, # rebuild yfitted with original indices # a bit messy: y might have been selected twice if not is_sorted: yfitted_ = np.empty_like(endog) yfitted_.fill(np.nan) yfitted_[sort_index] = yfitted yfitted = yfitted_","def lowess(endog, exog, frac=2.0/3.0, it=3, delta=0.0, is_sorted=False, # rebuild yfitted with original indices # a bit messy: y might have been selected twice if not is_sorted: yfitted_ = np.empty_like(y) yfitted_.fill(np.nan) yfitted_[sort_index] = yfitted yfitted = yfitted_" 2273,https://:@github.com/prateek3211/statsmodels.git,d1ed308fa17c86b94a41ee568e896751a4ca6f26,"@@ -433,7 +433,7 @@ class VARMAX(MLEModel): if self.measurement_error: # Force these to be positive constrained[self._params_obs_cov] = ( - constrained[self._params_obs_cov]**2) + unconstrained[self._params_obs_cov]**2) return constrained ",statsmodels/tsa/statespace/varmax.py,"ReplaceText(target='unconstrained' @(436,16)->(436,27))","class VARMAX(MLEModel): if self.measurement_error: # Force these to be positive constrained[self._params_obs_cov] = ( constrained[self._params_obs_cov]**2) return constrained ","class VARMAX(MLEModel): if self.measurement_error: # Force these to be positive constrained[self._params_obs_cov] = ( unconstrained[self._params_obs_cov]**2) return constrained " 2274,https://:@github.com/prateek3211/statsmodels.git,8a0a1a18dcbb5701937c4466a7724813cc870b60,"@@ -815,7 +815,7 @@ class GLM(base.LikelihoodModel): """""" if (max_start_irls > 0) and (start_params is None): - irls_rslt = self._fit_irls(start_params=start_params, maxiter=maxiter, + irls_rslt = self._fit_irls(start_params=start_params, maxiter=max_start_irls, tol=tol, scale=scale, cov_type=cov_type, cov_kwds=cov_kwds, use_t=use_t, **kwargs) start_params = irls_rslt.params ",statsmodels/genmod/generalized_linear_model.py,"ReplaceText(target='max_start_irls' @(818,74)->(818,81))","class GLM(base.LikelihoodModel): """""" if (max_start_irls > 0) and (start_params is None): irls_rslt = self._fit_irls(start_params=start_params, maxiter=maxiter, tol=tol, scale=scale, cov_type=cov_type, cov_kwds=cov_kwds, use_t=use_t, **kwargs) start_params = irls_rslt.params","class GLM(base.LikelihoodModel): """""" if (max_start_irls > 0) and (start_params is None): irls_rslt = self._fit_irls(start_params=start_params, maxiter=max_start_irls, tol=tol, scale=scale, cov_type=cov_type, cov_kwds=cov_kwds, use_t=use_t, **kwargs) start_params = irls_rslt.params" 2275,https://:@github.com/prateek3211/statsmodels.git,6882e53d5cfd5d2b3dc2d08f480f6529ac0883d7,"@@ -158,7 +158,7 @@ class Model(object): if len(cols) < len(exog.columns): exog = exog[cols] cols = list(design_info.term_names) - for col in cols: + for col in drop_cols: try: cols.remove(col) except ValueError: ",statsmodels/base/model.py,"ReplaceText(target='drop_cols' @(161,27)->(161,31))","class Model(object): if len(cols) < len(exog.columns): exog = exog[cols] cols = list(design_info.term_names) for col in cols: try: cols.remove(col) except ValueError:","class Model(object): if len(cols) < len(exog.columns): exog = exog[cols] cols = list(design_info.term_names) for col in drop_cols: try: cols.remove(col) except ValueError:" 2276,https://:@github.com/prateek3211/statsmodels.git,2f20e7e54fc4afcc367a8b858f107eacd5ff607f,"@@ -1998,7 +1998,7 @@ class MixedLM(base.LikelihoodModel): for meth in method: if meth.lower() in [""newton"", ""ncg""]: raise ValueError( - ""method %s not available for MixedLM"" % method) + ""method %s not available for MixedLM"" % meth) self.reml = reml self.cov_pen = cov_pen ",statsmodels/regression/mixed_linear_model.py,"ReplaceText(target='meth' @(2001,60)->(2001,66))","class MixedLM(base.LikelihoodModel): for meth in method: if meth.lower() in [""newton"", ""ncg""]: raise ValueError( ""method %s not available for MixedLM"" % method) self.reml = reml self.cov_pen = cov_pen","class MixedLM(base.LikelihoodModel): for meth in method: if meth.lower() in [""newton"", ""ncg""]: raise ValueError( ""method %s not available for MixedLM"" % meth) self.reml = reml self.cov_pen = cov_pen" 2277,https://:@github.com/prateek3211/statsmodels.git,b35f775ec7358aae763f23c6dc7a9f158680b234,"@@ -1869,7 +1869,7 @@ class GLMResults(base.LikelihoodModelResults): ] if hasattr(self, 'cov_type'): - top_right.append(('Covariance Type:', [self.cov_type])) + top_left.append(('Covariance Type:', [self.cov_type])) if title is None: title = ""Generalized Linear Model Regression Results"" ",statsmodels/genmod/generalized_linear_model.py,"ReplaceText(target='top_left' @(1872,12)->(1872,21))","class GLMResults(base.LikelihoodModelResults): ] if hasattr(self, 'cov_type'): top_right.append(('Covariance Type:', [self.cov_type])) if title is None: title = ""Generalized Linear Model Regression Results""","class GLMResults(base.LikelihoodModelResults): ] if hasattr(self, 'cov_type'): top_left.append(('Covariance Type:', [self.cov_type])) if title is None: title = ""Generalized Linear Model Regression Results""" 2278,https://:@github.com/prateek3211/statsmodels.git,fa6a59297eda1a12e834a621ba34df48ccfca314,"@@ -32,7 +32,7 @@ def _check_wts(weights, wts): warnings.warn('`wts` method is deprecated. Use `weights` instead', DeprecationWarning) weights = weights if weights is not None else wts - return wts + return weights class Penalty(object): ",statsmodels/base/_penalties.py,"ReplaceText(target='weights' @(35,11)->(35,14))","def _check_wts(weights, wts): warnings.warn('`wts` method is deprecated. Use `weights` instead', DeprecationWarning) weights = weights if weights is not None else wts return wts class Penalty(object):","def _check_wts(weights, wts): warnings.warn('`wts` method is deprecated. Use `weights` instead', DeprecationWarning) weights = weights if weights is not None else wts return weights class Penalty(object):" 2279,https://:@github.com/chiffa/BioFlow.git,b5cb03eaa3f4c00494581e4b1583b5189a40b387,"@@ -63,5 +63,5 @@ def wipe_dir(path): else: logger.debug('performing a rmtree') - rmtree(path) + rmtree(directory_name) return True ",BioFlow/utils/general_utils/high_level_os_io.py,"ReplaceText(target='directory_name' @(66,15)->(66,19))","def wipe_dir(path): else: logger.debug('performing a rmtree') rmtree(path) return True","def wipe_dir(path): else: logger.debug('performing a rmtree') rmtree(directory_name) return True" 2280,https://:@github.com/scottstanie/apertools.git,e3c2d04bf6e3d5469c1d4e799bcec8ca85bccf1d,"@@ -117,6 +117,6 @@ def combine_complex(img_list): img_out += next_img # Now only on overlap, take the previous's pixels overlap_idxs = (img_out != 0) & (next_img != 0) - img_out[overlap_idxs] = img_out[overlap_idxs] + img_out[overlap_idxs] = next_img[overlap_idxs] return img_out ",apertools/stitching.py,"ReplaceText(target='next_img' @(120,32)->(120,39))","def combine_complex(img_list): img_out += next_img # Now only on overlap, take the previous's pixels overlap_idxs = (img_out != 0) & (next_img != 0) img_out[overlap_idxs] = img_out[overlap_idxs] return img_out","def combine_complex(img_list): img_out += next_img # Now only on overlap, take the previous's pixels overlap_idxs = (img_out != 0) & (next_img != 0) img_out[overlap_idxs] = next_img[overlap_idxs] return img_out" 2281,https://:@github.com/ihfazhillah/qaamus-python.git,fb2343f4524f9b5817e794936444edfbad66da67,"@@ -37,7 +37,7 @@ class IndAraParser(object): dengan arti utama dengan **kata-kunci** *ind* adalah indonesia *ara* adalah arti arabnya."""""" - if soup is not None: + if soup is None: soup = self.soup ind = [x.text for x in soup.select(""td > a"")] ",qaamus/ind_ara_parser.py,"ReplaceText(target=' is ' @(40,15)->(40,23))","class IndAraParser(object): dengan arti utama dengan **kata-kunci** *ind* adalah indonesia *ara* adalah arti arabnya."""""" if soup is not None: soup = self.soup ind = [x.text for x in soup.select(""td > a"")]","class IndAraParser(object): dengan arti utama dengan **kata-kunci** *ind* adalah indonesia *ara* adalah arti arabnya."""""" if soup is None: soup = self.soup ind = [x.text for x in soup.select(""td > a"")]" 2282,https://:@github.com/thautwarm/Linq.py.git,c58d2c116f1addfb74225139011eda70b5313883,"@@ -23,7 +23,7 @@ def Extend(self: Flow, *others): @extension_class(list) def Sort(self: Flow, by): - if not is_to_destruct(by): + if is_to_destruct(by): by = destruct_func(by) self.stream.sort(key=by) return self ",linq/standard/list.py,"ReplaceText(target='' @(26,7)->(26,11))","def Extend(self: Flow, *others): @extension_class(list) def Sort(self: Flow, by): if not is_to_destruct(by): by = destruct_func(by) self.stream.sort(key=by) return self","def Extend(self: Flow, *others): @extension_class(list) def Sort(self: Flow, by): if is_to_destruct(by): by = destruct_func(by) self.stream.sort(key=by) return self" 2283,https://:@github.com/jlevy44/PathFlowAI.git,7ff099037b829dd952bc9148248639ffeaf25300,"@@ -277,7 +277,7 @@ def save_dataset(arr, masks, out_zarr, out_pkl, no_zarr): out_pkl:str Pickle output file. """""" - if no_zarr: + if not no_zarr: arr.astype('uint8').to_zarr(out_zarr, overwrite=True) pickle.dump(masks,open(out_pkl,'wb')) ",pathflowai/utils.py,"ReplaceText(target='not ' @(280,4)->(280,4))","def save_dataset(arr, masks, out_zarr, out_pkl, no_zarr): out_pkl:str Pickle output file. """""" if no_zarr: arr.astype('uint8').to_zarr(out_zarr, overwrite=True) pickle.dump(masks,open(out_pkl,'wb')) ","def save_dataset(arr, masks, out_zarr, out_pkl, no_zarr): out_pkl:str Pickle output file. """""" if not no_zarr: arr.astype('uint8').to_zarr(out_zarr, overwrite=True) pickle.dump(masks,open(out_pkl,'wb')) " 2284,https://:@github.com/jlevy44/PathFlowAI.git,2076c33a19501c7b2fd778d86da7f66558e5b1de,"@@ -694,7 +694,7 @@ def modify_patch_info(input_info_db='patch_info.db', slide_labels=pd.DataFrame() included_annotations = copy.deepcopy(pos_annotation_class) included_annotations.extend(other_annotations) print(df.shape,included_annotations) - if not modify_patches: + if modify_patches: df=df[np.isin(df['annotation'],included_annotations)] for target in targets: df[target]=0. ",pathflowai/utils.py,"ReplaceText(target='' @(697,6)->(697,10))","def modify_patch_info(input_info_db='patch_info.db', slide_labels=pd.DataFrame() included_annotations = copy.deepcopy(pos_annotation_class) included_annotations.extend(other_annotations) print(df.shape,included_annotations) if not modify_patches: df=df[np.isin(df['annotation'],included_annotations)] for target in targets: df[target]=0.","def modify_patch_info(input_info_db='patch_info.db', slide_labels=pd.DataFrame() included_annotations = copy.deepcopy(pos_annotation_class) included_annotations.extend(other_annotations) print(df.shape,included_annotations) if modify_patches: df=df[np.isin(df['annotation'],included_annotations)] for target in targets: df[target]=0." 2285,https://:@github.com/roma-guru/ricksay.git,d2c761b3274df3d042f0f94a559f4c7dc4f3f5be,"@@ -782,7 +782,7 @@ class Setup(): targets = target.split('/') dests = dest.split('/') - while (len(targets) > 1) and (len(target) > 1) and (targets[0] == dests[0]): + while (len(targets) > 1) and (len(dests) > 1) and (targets[0] == dests[0]): targets = targets[1:] dests = dests[1:] ",setup.py,"ReplaceText(target='dests' @(785,46)->(785,52))","class Setup(): targets = target.split('/') dests = dest.split('/') while (len(targets) > 1) and (len(target) > 1) and (targets[0] == dests[0]): targets = targets[1:] dests = dests[1:] ","class Setup(): targets = target.split('/') dests = dest.split('/') while (len(targets) > 1) and (len(dests) > 1) and (targets[0] == dests[0]): targets = targets[1:] dests = dests[1:] " 2286,https://:@github.com/roma-guru/ricksay.git,c38b34a000395d8e5082d2b0b3dfc5e0e594f227,"@@ -375,7 +375,7 @@ class Backend(): self.output = self.output.replace(AUTO_PUSH, '').replace(AUTO_POP, '') - if self.balloon is not None: + if self.balloon is None: if (self.balloontop > 0) or (self.balloonbottom > 0): self.output = self.output.split('\n') self.output = self.output[self.balloontop : ~(self.balloonbottom)] ",src/backend.py,"ReplaceText(target=' is ' @(378,23)->(378,31))","class Backend(): self.output = self.output.replace(AUTO_PUSH, '').replace(AUTO_POP, '') if self.balloon is not None: if (self.balloontop > 0) or (self.balloonbottom > 0): self.output = self.output.split('\n') self.output = self.output[self.balloontop : ~(self.balloonbottom)]","class Backend(): self.output = self.output.replace(AUTO_PUSH, '').replace(AUTO_POP, '') if self.balloon is None: if (self.balloontop > 0) or (self.balloonbottom > 0): self.output = self.output.split('\n') self.output = self.output[self.balloontop : ~(self.balloonbottom)]" 2287,https://:@github.com/roma-guru/ricksay.git,de5f9c9d5a30aa94131d0af7d659cb4aeb330521,"@@ -509,7 +509,7 @@ class Ponysay(): ponies = {} for ponydir in ponydirs: for pony in Metadata.restrictedPonies(ponydir, logic): - if (pony in ponies) and not (pony in ponies): # XXX and (pony not in passed) + if (pony in oldponies) and not (pony in ponies): # XXX and (pony not in passed) ponies[pony] = ponydir + pony + '.pony' if len(ponies) > 0: oldponies = ponies ",src/ponysay.py,"ReplaceText(target='oldponies' @(512,36)->(512,42))","class Ponysay(): ponies = {} for ponydir in ponydirs: for pony in Metadata.restrictedPonies(ponydir, logic): if (pony in ponies) and not (pony in ponies): # XXX and (pony not in passed) ponies[pony] = ponydir + pony + '.pony' if len(ponies) > 0: oldponies = ponies","class Ponysay(): ponies = {} for ponydir in ponydirs: for pony in Metadata.restrictedPonies(ponydir, logic): if (pony in oldponies) and not (pony in ponies): # XXX and (pony not in passed) ponies[pony] = ponydir + pony + '.pony' if len(ponies) > 0: oldponies = ponies" 2288,https://:@github.com/roma-guru/ricksay.git,d234ee6c6cbefbd31ef763692c9f8bc39aeff832,"@@ -826,7 +826,7 @@ class Ponysay(): for (opt, ponies, quotes) in [('-f', standard, False), ('+f', extra, False), ('-F', both, False), ('-q', standard, True)]: if args.opts[opt] is not None: for pony in args.opts[opt]: - selection.append((opt, ponies, quotes)) + selection.append((pony, ponies, quotes)) ## TODO +q -Q (pony, quote) = self.__getPony(selection, args) ",src/ponysay.py,"ReplaceText(target='pony' @(829,38)->(829,41))","class Ponysay(): for (opt, ponies, quotes) in [('-f', standard, False), ('+f', extra, False), ('-F', both, False), ('-q', standard, True)]: if args.opts[opt] is not None: for pony in args.opts[opt]: selection.append((opt, ponies, quotes)) ## TODO +q -Q (pony, quote) = self.__getPony(selection, args) ","class Ponysay(): for (opt, ponies, quotes) in [('-f', standard, False), ('+f', extra, False), ('-F', both, False), ('-q', standard, True)]: if args.opts[opt] is not None: for pony in args.opts[opt]: selection.append((pony, ponies, quotes)) ## TODO +q -Q (pony, quote) = self.__getPony(selection, args) " 2289,https://:@github.com/roma-guru/ricksay.git,5125dd6400ca89a64f536be824a1de905f8a0920,"@@ -140,7 +140,7 @@ def linklist(ponydirs = None, quoters = [], ucsiser = None): for ponydir in ponydirs: # Loop ponydirs ## Get all pony files in the directory - ponies = _get_file_list(ponydirs, '.pony') + ponies = _get_file_list(ponydir, '.pony') ## If there are no ponies in the directory skip to next directory, otherwise, print the directories name if len(ponies) == 0: ",src/lists.py,"ReplaceText(target='ponydir' @(143,32)->(143,40))","def linklist(ponydirs = None, quoters = [], ucsiser = None): for ponydir in ponydirs: # Loop ponydirs ## Get all pony files in the directory ponies = _get_file_list(ponydirs, '.pony') ## If there are no ponies in the directory skip to next directory, otherwise, print the directories name if len(ponies) == 0:","def linklist(ponydirs = None, quoters = [], ucsiser = None): for ponydir in ponydirs: # Loop ponydirs ## Get all pony files in the directory ponies = _get_file_list(ponydir, '.pony') ## If there are no ponies in the directory skip to next directory, otherwise, print the directories name if len(ponies) == 0:" 2290,https://:@github.com/CMakerA/WiSync.git,2a61dc7bcac9acd62f122e90ec78a41297b045b3,"@@ -19,7 +19,7 @@ class Button(InteractableUIElement): else: self.size = size - super().__init__(self.size, self.__idle, self.__hover, self.__click, position, on_click, on_hover, on_leave) + super().__init__(position, self.__idle, self.__hover, self.__click, self.size, on_click, on_hover, on_leave) self.id = Iders.btnIdler.add(self) ",elements/Button.py,"ArgSwap(idxs=0<->4 @(22,8)->(22,24))","class Button(InteractableUIElement): else: self.size = size super().__init__(self.size, self.__idle, self.__hover, self.__click, position, on_click, on_hover, on_leave) self.id = Iders.btnIdler.add(self) ","class Button(InteractableUIElement): else: self.size = size super().__init__(position, self.__idle, self.__hover, self.__click, self.size, on_click, on_hover, on_leave) self.id = Iders.btnIdler.add(self) " 2291,https://:@github.com/cmayes/md_utils.git,ea173c3c2052fc62697ae5af0cc4cbc2e7f25eb7,"@@ -93,7 +93,7 @@ def calc_pka(file_data, kbt, coord_ts): logger.info(""Found local max '%f' at coordinate '%f'"", cur_corr, cur_coord) return -math.log10(inv_C_0 / sum_for_pka), cur_corr, cur_coord else: - if cur_corr >= coord_ts: + if cur_coord >= coord_ts: logger.info(""Integrating to input TS coordinate '%f' with value , '%f'"", cur_coord, cur_corr) return -math.log10(inv_C_0 / sum_for_pka), cur_corr, cur_coord ",md_utils/calc_pka.py,"ReplaceText(target='cur_coord' @(96,15)->(96,23))","def calc_pka(file_data, kbt, coord_ts): logger.info(""Found local max '%f' at coordinate '%f'"", cur_corr, cur_coord) return -math.log10(inv_C_0 / sum_for_pka), cur_corr, cur_coord else: if cur_corr >= coord_ts: logger.info(""Integrating to input TS coordinate '%f' with value , '%f'"", cur_coord, cur_corr) return -math.log10(inv_C_0 / sum_for_pka), cur_corr, cur_coord ","def calc_pka(file_data, kbt, coord_ts): logger.info(""Found local max '%f' at coordinate '%f'"", cur_corr, cur_coord) return -math.log10(inv_C_0 / sum_for_pka), cur_corr, cur_coord else: if cur_coord >= coord_ts: logger.info(""Integrating to input TS coordinate '%f' with value , '%f'"", cur_coord, cur_corr) return -math.log10(inv_C_0 / sum_for_pka), cur_corr, cur_coord " 2292,https://:@github.com/pozytywnie/django-facebook-auth.git,54f877d7cd262204abc1bf41a95e043a58431f44,"@@ -34,7 +34,7 @@ class UserFactory(object): copy_field('email', True) copy_field('first_name') copy_field('last_name') - if access_token is None: + if access_token is not None: user.access_token = access_token user.save() ",facebook_auth/backends.py,"ReplaceText(target=' is not ' @(37,23)->(37,27))","class UserFactory(object): copy_field('email', True) copy_field('first_name') copy_field('last_name') if access_token is None: user.access_token = access_token user.save()","class UserFactory(object): copy_field('email', True) copy_field('first_name') copy_field('last_name') if access_token is not None: user.access_token = access_token user.save()" 2293,https://:@github.com/pozytywnie/django-facebook-auth.git,5301679f7ff26baab5b635204d309e89e907a47f,"@@ -254,5 +254,5 @@ def debug_all_tokens_for_user(user_id): logger.info('Deleting user tokens except best one.') tokens_to_delete = sorted(processed_user_tokens) tokens_to_delete.remove(best_token.id) - for token_id in processed_user_tokens: + for token_id in tokens_to_delete: UserToken.objects.filter(id=token_id).update(deleted=True) ",facebook_auth/models.py,"ReplaceText(target='tokens_to_delete' @(257,28)->(257,49))","def debug_all_tokens_for_user(user_id): logger.info('Deleting user tokens except best one.') tokens_to_delete = sorted(processed_user_tokens) tokens_to_delete.remove(best_token.id) for token_id in processed_user_tokens: UserToken.objects.filter(id=token_id).update(deleted=True)","def debug_all_tokens_for_user(user_id): logger.info('Deleting user tokens except best one.') tokens_to_delete = sorted(processed_user_tokens) tokens_to_delete.remove(best_token.id) for token_id in tokens_to_delete: UserToken.objects.filter(id=token_id).update(deleted=True)" 2294,https://:@github.com/mc3/DSKM.git,dfe280d538e627d15b6058a7806290a8d09dbd4b,"@@ -620,7 +620,7 @@ def nsAliveTest(theZone): # query all authoritative NS for SOA of zone nameservers = misc.authNS(theZone) for nameserver in nameservers[:]: try: - l.logDebug('Querying {} for SOA of {} via TCP'.format(theZone, nameserver)) + l.logDebug('Querying {} for SOA of {} via TCP'.format(nameserver, theZone)) response = dns.query.tcp(request, nameserver, 10) rcode = response.rcode() if rcode == 0: continue ",DSKM/zone.py,"ArgSwap(idxs=0<->1 @(623,23)->(623,65))","def nsAliveTest(theZone): # query all authoritative NS for SOA of zone nameservers = misc.authNS(theZone) for nameserver in nameservers[:]: try: l.logDebug('Querying {} for SOA of {} via TCP'.format(theZone, nameserver)) response = dns.query.tcp(request, nameserver, 10) rcode = response.rcode() if rcode == 0: continue","def nsAliveTest(theZone): # query all authoritative NS for SOA of zone nameservers = misc.authNS(theZone) for nameserver in nameservers[:]: try: l.logDebug('Querying {} for SOA of {} via TCP'.format(nameserver, theZone)) response = dns.query.tcp(request, nameserver, 10) rcode = response.rcode() if rcode == 0: continue" 2295,https://:@github.com/AppImageCrafters/AppImageBuilder.git,dc91ba9d15ad0a470ae3a5c0e677d1616ced3fd0,"@@ -61,7 +61,7 @@ class IconBundler: return os.path.join(root, svg_icon_name) if png_icon_name in files: - new_path = os.path.join(root, svg_icon_name) + new_path = os.path.join(root, png_icon_name) new_size = self._extract_icon_size_from_path(new_path) if new_size > size: ",AppImageBuilder/app_dir/metadata/icon_bundler.py,"ReplaceText(target='png_icon_name' @(64,46)->(64,59))","class IconBundler: return os.path.join(root, svg_icon_name) if png_icon_name in files: new_path = os.path.join(root, svg_icon_name) new_size = self._extract_icon_size_from_path(new_path) if new_size > size:","class IconBundler: return os.path.join(root, svg_icon_name) if png_icon_name in files: new_path = os.path.join(root, png_icon_name) new_size = self._extract_icon_size_from_path(new_path) if new_size > size:" 2296,https://:@github.com/jeticg/datatool.git,5fa4adc2522957fb89ef2d22974602ce4ed5047b,"@@ -58,7 +58,7 @@ class DataLoader(): for filePattern in file: files += matchPattern(filePattern) elif isinstance(file, str): - files = matchPattern(filePattern) + files = matchPattern(file) else: raise RuntimeError(""natlang.dataLoader.load [ERROR]: parameter "" + ""type"") ",natlang/loader.py,"ReplaceText(target='file' @(61,33)->(61,44))","class DataLoader(): for filePattern in file: files += matchPattern(filePattern) elif isinstance(file, str): files = matchPattern(filePattern) else: raise RuntimeError(""natlang.dataLoader.load [ERROR]: parameter "" + ""type"")","class DataLoader(): for filePattern in file: files += matchPattern(filePattern) elif isinstance(file, str): files = matchPattern(file) else: raise RuntimeError(""natlang.dataLoader.load [ERROR]: parameter "" + ""type"")" 2297,https://:@github.com/robinandeer/cosmid.git,77c83d4f1a1835ca7d52d6b20272d126b5d3fb47,"@@ -123,7 +123,7 @@ class Registry(object): options = resource.versions() version = self.matchOne(target, options) - if resource is None: + if version is None: message = (""Couldn't match version '{v}' to '{id}'; options: {vers}"" .format(v=target, id=resource.id, vers="", "".join(options))) ",cosmid/core.py,"ReplaceText(target='version' @(126,7)->(126,15))","class Registry(object): options = resource.versions() version = self.matchOne(target, options) if resource is None: message = (""Couldn't match version '{v}' to '{id}'; options: {vers}"" .format(v=target, id=resource.id, vers="", "".join(options))) ","class Registry(object): options = resource.versions() version = self.matchOne(target, options) if version is None: message = (""Couldn't match version '{v}' to '{id}'; options: {vers}"" .format(v=target, id=resource.id, vers="", "".join(options))) " 2298,https://:@github.com/haata/pycapnp-async.git,11543b7abfb898e84c9412a7b5563e4481ffcf9b,"@@ -22,7 +22,7 @@ def example_simple_rpc(): write_stream = capnp.FdAsyncIoStream(write.fileno()) restorer = capnp.Restorer(capability.TestSturdyRefObjectId, _restore) - server = capnp.RpcServer(loop, restorer, write_stream) + server = capnp.RpcServer(loop, write_stream, restorer) client = capnp.RpcClient(loop, read_stream) ref = capability.TestSturdyRefObjectId.new_message() ",examples/example_capability.py,"ArgSwap(idxs=1<->2 @(25,13)->(25,28))","def example_simple_rpc(): write_stream = capnp.FdAsyncIoStream(write.fileno()) restorer = capnp.Restorer(capability.TestSturdyRefObjectId, _restore) server = capnp.RpcServer(loop, restorer, write_stream) client = capnp.RpcClient(loop, read_stream) ref = capability.TestSturdyRefObjectId.new_message()","def example_simple_rpc(): write_stream = capnp.FdAsyncIoStream(write.fileno()) restorer = capnp.Restorer(capability.TestSturdyRefObjectId, _restore) server = capnp.RpcServer(loop, write_stream, restorer) client = capnp.RpcClient(loop, read_stream) ref = capability.TestSturdyRefObjectId.new_message()" 2299,https://:@github.com/bwhmather/flask-libsass.git,c6f0e9cfdad73cc77a364c95d2070d723d2c89e8,"@@ -55,7 +55,7 @@ class Sass(object): rebuild = current_app.config.get('SASS_REBUILD', False) - if rebuild: + if not rebuild: if not hasattr(stack.top, 'sass_cache'): stack.top.sass_cache = {} cache = stack.top.sass_cache ",flask_libsass.py,"ReplaceText(target='not ' @(58,11)->(58,11))","class Sass(object): rebuild = current_app.config.get('SASS_REBUILD', False) if rebuild: if not hasattr(stack.top, 'sass_cache'): stack.top.sass_cache = {} cache = stack.top.sass_cache","class Sass(object): rebuild = current_app.config.get('SASS_REBUILD', False) if not rebuild: if not hasattr(stack.top, 'sass_cache'): stack.top.sass_cache = {} cache = stack.top.sass_cache" 2300,https://:@github.com/yunojuno/django-s3-upload.git,65e49f3277f987c47d189105c6d979d666bb3004,"@@ -45,7 +45,7 @@ def create_upload_data(content_type, source_filename, upload_to): bucket_url = ""https://%s/%s"" % (endpoint, bucket) return { - ""policy"": policy, + ""policy"": encoded, ""signature"": signature_b64, ""key"": key, ""AWSAccessKeyId"": access_key, ",s3direct/utils.py,"ReplaceText(target='encoded' @(48,18)->(48,24))","def create_upload_data(content_type, source_filename, upload_to): bucket_url = ""https://%s/%s"" % (endpoint, bucket) return { ""policy"": policy, ""signature"": signature_b64, ""key"": key, ""AWSAccessKeyId"": access_key,","def create_upload_data(content_type, source_filename, upload_to): bucket_url = ""https://%s/%s"" % (endpoint, bucket) return { ""policy"": encoded, ""signature"": signature_b64, ""key"": key, ""AWSAccessKeyId"": access_key," 2301,https://:@github.com/Manticore-attic/pyfft.git,01cdc24797472eec5114b68f02ce8c68fa348853,"@@ -53,7 +53,7 @@ def clFFT_ExecuteInterleaved(plan, batchSize, dir, data_in, data_out): currWrite = 1 if numKernelsOdd else 2 for kInfo in kernelInfo: - if isInPlace and numKernelsOdd and not inPlaceDone and kernelInfo.in_place_possible: + if isInPlace and numKernelsOdd and not inPlaceDone and kInfo.in_place_possible: currWrite = currRead inPlaceDone = True ",pycudafft/fft_execute.py,"ReplaceText(target='kInfo' @(56,58)->(56,68))","def clFFT_ExecuteInterleaved(plan, batchSize, dir, data_in, data_out): currWrite = 1 if numKernelsOdd else 2 for kInfo in kernelInfo: if isInPlace and numKernelsOdd and not inPlaceDone and kernelInfo.in_place_possible: currWrite = currRead inPlaceDone = True ","def clFFT_ExecuteInterleaved(plan, batchSize, dir, data_in, data_out): currWrite = 1 if numKernelsOdd else 2 for kInfo in kernelInfo: if isInPlace and numKernelsOdd and not inPlaceDone and kInfo.in_place_possible: currWrite = currRead inPlaceDone = True " 2302,https://:@github.com/sepandhaghighi/pyshutdown.git,8b1b84e10d5acc1b1ec07ae271fdd3f61a414c87,"@@ -12,7 +12,7 @@ def get_method(): get_method=input(""Please Enter Method , Shutdown[1] , Hibernate[2] , Restart[3]"") if get_method==""2"": flag=""-h"" - elif flag==""3"": + elif get_method==""3"": flag=""-r"" else: flag=""-s"" ",main.py,"ReplaceText(target='get_method' @(15,9)->(15,13))","def get_method(): get_method=input(""Please Enter Method , Shutdown[1] , Hibernate[2] , Restart[3]"") if get_method==""2"": flag=""-h"" elif flag==""3"": flag=""-r"" else: flag=""-s""","def get_method(): get_method=input(""Please Enter Method , Shutdown[1] , Hibernate[2] , Restart[3]"") if get_method==""2"": flag=""-h"" elif get_method==""3"": flag=""-r"" else: flag=""-s""" 2303,https://:@github.com/cfhamlet/os-m3-engine.git,b6a8890df08b38e6201e3b8cc18e870a7f61fda4,"@@ -89,7 +89,7 @@ def create(frontend_cls='os_m3_engine.ootb.StdinFrontend', default_engine_transport_config = ENGINE_TRANSPORT_BRIDGE_CONFIG \ if backend_cls is not None else ENGINE_TRANSPORT_CONFIG - e_transport_config = engine_backend_config + e_transport_config = engine_transport_config if engine_transport_config in (ENGINE_TRANSPORT_CONFIG, ENGINE_TRANSPORT_BRIDGE_CONFIG): e_transport_config = None ",src/os_m3_engine/launcher.py,"ReplaceText(target='engine_transport_config' @(92,25)->(92,46))","def create(frontend_cls='os_m3_engine.ootb.StdinFrontend', default_engine_transport_config = ENGINE_TRANSPORT_BRIDGE_CONFIG \ if backend_cls is not None else ENGINE_TRANSPORT_CONFIG e_transport_config = engine_backend_config if engine_transport_config in (ENGINE_TRANSPORT_CONFIG, ENGINE_TRANSPORT_BRIDGE_CONFIG): e_transport_config = None ","def create(frontend_cls='os_m3_engine.ootb.StdinFrontend', default_engine_transport_config = ENGINE_TRANSPORT_BRIDGE_CONFIG \ if backend_cls is not None else ENGINE_TRANSPORT_CONFIG e_transport_config = engine_transport_config if engine_transport_config in (ENGINE_TRANSPORT_CONFIG, ENGINE_TRANSPORT_BRIDGE_CONFIG): e_transport_config = None " 2304,https://:@github.com/ssi-dk/bifrost.git,d05050feff39d057a8db6b64d31645efbf741200,"@@ -143,7 +143,7 @@ def query_ncbi_species(species_entry): if result is not None: return result[""ncbi_species""] elif group_result is not None: - return result[""ncbi_species""] + return group_result[""ncbi_species""] else: return None except Exception as e: ",lib/bifrostlib/bifrostlib/mongo_interface.py,"ReplaceText(target='group_result' @(146,23)->(146,29))","def query_ncbi_species(species_entry): if result is not None: return result[""ncbi_species""] elif group_result is not None: return result[""ncbi_species""] else: return None except Exception as e:","def query_ncbi_species(species_entry): if result is not None: return result[""ncbi_species""] elif group_result is not None: return group_result[""ncbi_species""] else: return None except Exception as e:" 2305,https://:@github.com/ssi-dk/bifrost.git,6f801b0adf5cf2209dec1052337b3eff413d65b0,"@@ -268,7 +268,7 @@ def update_run_report(run, n_intervals): ) def update_rerun_form(run_name): run_name = run_name.split(""/"")[0] - if run_name == """" or hasattr(keys, ""rerun""): + if run_name == """" or not hasattr(keys, ""rerun""): return None run_data = import_data.get_run(run_name) ",reporter/run_checker.py,"ReplaceText(target='not ' @(271,25)->(271,25))","def update_run_report(run, n_intervals): ) def update_rerun_form(run_name): run_name = run_name.split(""/"")[0] if run_name == """" or hasattr(keys, ""rerun""): return None run_data = import_data.get_run(run_name)","def update_run_report(run, n_intervals): ) def update_rerun_form(run_name): run_name = run_name.split(""/"")[0] if run_name == """" or not hasattr(keys, ""rerun""): return None run_data = import_data.get_run(run_name)" 2306,https://:@github.com/ayharano/pppipam.git,13ee95b04c1ccf5febedcd9568e15543b8c66365,"@@ -190,7 +190,7 @@ class AddressSpace_description_TestCase(unittest.TestCase): description_str = ""address 0 for ipv4"" self.address_space.describe( description=description_str, - ip_parameter=network, + ip_parameter=zero_ipv4, ) self.assertEqual( self.address_space.description( ",tests/test_description.py,"ReplaceText(target='zero_ipv4' @(193,25)->(193,32))","class AddressSpace_description_TestCase(unittest.TestCase): description_str = ""address 0 for ipv4"" self.address_space.describe( description=description_str, ip_parameter=network, ) self.assertEqual( self.address_space.description(","class AddressSpace_description_TestCase(unittest.TestCase): description_str = ""address 0 for ipv4"" self.address_space.describe( description=description_str, ip_parameter=zero_ipv4, ) self.assertEqual( self.address_space.description(" 2307,https://:@github.com/ayharano/pppipam.git,6d57637be02e5d8597a63ba7fc3fd8525a5c2952,"@@ -263,7 +263,7 @@ class AddressSpace: self.__parent_supernet[child] = as_network children_of_as_network.add(child) children_of_supernet.remove(child) - children_of_supernet.add(as_address) + children_of_supernet.add(as_network) else: raise TypeError(""ip_parameter must be a valid IP parameter"") ",pppipam/pppipam.py,"ReplaceText(target='as_network' @(266,37)->(266,47))","class AddressSpace: self.__parent_supernet[child] = as_network children_of_as_network.add(child) children_of_supernet.remove(child) children_of_supernet.add(as_address) else: raise TypeError(""ip_parameter must be a valid IP parameter"") ","class AddressSpace: self.__parent_supernet[child] = as_network children_of_as_network.add(child) children_of_supernet.remove(child) children_of_supernet.add(as_network) else: raise TypeError(""ip_parameter must be a valid IP parameter"") " 2308,https://:@github.com/ayharano/pppipam.git,12fedde026bcd8de6562f0d3c6e3224e529c557e,"@@ -289,7 +289,7 @@ class AddressSpace: self.__description[as_network] = description described = True - self.__parent_supernet[as_address] = supernet + self.__parent_supernet[as_network] = supernet children_of_as_network = ( self.__children_ip_object.setdefault(as_network, set()) ) ",pppipam/pppipam.py,"ReplaceText(target='as_network' @(292,35)->(292,45))","class AddressSpace: self.__description[as_network] = description described = True self.__parent_supernet[as_address] = supernet children_of_as_network = ( self.__children_ip_object.setdefault(as_network, set()) )","class AddressSpace: self.__description[as_network] = description described = True self.__parent_supernet[as_network] = supernet children_of_as_network = ( self.__children_ip_object.setdefault(as_network, set()) )" 2309,https://:@github.com/alx-k/flask-jerify.git,cf3942ac578dbcb0deb358bf7bfb7c230a5d1f34,"@@ -23,7 +23,7 @@ def jerror_handler(e): """"""http://jsonapi.org/format/#errors """""" - if not hasattr('name', e): + if not hasattr(e, 'name'): raise InternalServerError(e.description) app.logger.error(e.description) ",flask_jerify/flask_jerify.py,"ArgSwap(idxs=0<->1 @(26,11)->(26,18))","def jerror_handler(e): """"""http://jsonapi.org/format/#errors """""" if not hasattr('name', e): raise InternalServerError(e.description) app.logger.error(e.description)","def jerror_handler(e): """"""http://jsonapi.org/format/#errors """""" if not hasattr(e, 'name'): raise InternalServerError(e.description) app.logger.error(e.description)" 2310,https://:@github.com/chenliangomc/RTFMaker.git,f82b42a9366a5ed2cbc83ebbe25dc6f0668f75c6,"@@ -139,7 +139,7 @@ class RTable(object): self._table_elements['body'].append(new_row) html_foot = getattr(obj, 'tfoot') if html_foot: - for a_foot in html_body.find_all('td'): + for a_foot in html_foot.find_all('td'): foot_cell = { 'value': a_foot.get_text(strip=True), } ",RTFMaker/utils.py,"ReplaceText(target='html_foot' @(142,30)->(142,39))","class RTable(object): self._table_elements['body'].append(new_row) html_foot = getattr(obj, 'tfoot') if html_foot: for a_foot in html_body.find_all('td'): foot_cell = { 'value': a_foot.get_text(strip=True), }","class RTable(object): self._table_elements['body'].append(new_row) html_foot = getattr(obj, 'tfoot') if html_foot: for a_foot in html_foot.find_all('td'): foot_cell = { 'value': a_foot.get_text(strip=True), }" 2311,https://:@github.com/jianlins/PyFastNER.git,442227d122a7feee9766e2676cee1702c7ba645b,"@@ -324,7 +324,7 @@ class FastCNER: self.logger.debug( 'try add matched rule ({}-{})\t{}'.format(match_begin, match_end, str(self.rule_store[rule_id]))) current_span.rule_id = rule_id - if key in matches: + if key in overlap_checkers: current_spans_list = matches[key] overlap_checker = overlap_checkers[key] overlapped_pos = overlap_checker.search(current_span.begin, current_span.end) ",PyFastNER/FastCNER.py,"ReplaceText(target='overlap_checkers' @(327,22)->(327,29))","class FastCNER: self.logger.debug( 'try add matched rule ({}-{})\t{}'.format(match_begin, match_end, str(self.rule_store[rule_id]))) current_span.rule_id = rule_id if key in matches: current_spans_list = matches[key] overlap_checker = overlap_checkers[key] overlapped_pos = overlap_checker.search(current_span.begin, current_span.end)","class FastCNER: self.logger.debug( 'try add matched rule ({}-{})\t{}'.format(match_begin, match_end, str(self.rule_store[rule_id]))) current_span.rule_id = rule_id if key in overlap_checkers: current_spans_list = matches[key] overlap_checker = overlap_checkers[key] overlapped_pos = overlap_checker.search(current_span.begin, current_span.end)" 2312,https://:@github.com/groupe-conseil-nutshimit-nippour/django-geoprisma.git,a3a4dc9a0142e237dfac5961107b7338e9ef6298,"@@ -142,7 +142,7 @@ class FeatureServerProxyFactory(object): def isCreate(self): data_id = self.featureServerProxy.getID() - return data_id is not None and self.request.body != """" and self.request.method == ""POST"" + return data_id is None and self.request.body != """" and self.request.method == ""POST"" def isUpdate(self): data_id = self.featureServerProxy.getID() ",geoprisma/core/proxies/featureserverproxy.py,"ReplaceText(target=' is ' @(145,22)->(145,30))","class FeatureServerProxyFactory(object): def isCreate(self): data_id = self.featureServerProxy.getID() return data_id is not None and self.request.body != """" and self.request.method == ""POST"" def isUpdate(self): data_id = self.featureServerProxy.getID()","class FeatureServerProxyFactory(object): def isCreate(self): data_id = self.featureServerProxy.getID() return data_id is None and self.request.body != """" and self.request.method == ""POST"" def isUpdate(self): data_id = self.featureServerProxy.getID()" 2313,https://:@github.com/collective/mr.poe.git,dedca8e5c98124f6a43a18986e142e8cb7ecc3cf,"@@ -59,7 +59,7 @@ def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() - if handler.__class__ not in map(type, logger.handlers): + if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler) ",raven/conf/__init__.py,"ReplaceText(target=' in ' @(62,24)->(62,32))","def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() if handler.__class__ not in map(type, logger.handlers): return False logger.addHandler(handler)","def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler)" 2314,https://:@github.com/espenmn/medialog.mobilethemeTwo.git,21b37308d028659d0a540289ba2e1f30340a9481,"@@ -39,7 +39,7 @@ class Scrape(BrowserView): parts = url.split('//', 1) this_base_url = parts[0]+'//'+parts[1].split('/', 1)[0] - if url not in scrape_whitelist: + if this_base_url not in scrape_whitelist: return ""URL domain is not in whitelist"" #get html from the requested url ",medialog/mobilethemeTwo/views.py,"ReplaceText(target='this_base_url' @(42,11)->(42,14))","class Scrape(BrowserView): parts = url.split('//', 1) this_base_url = parts[0]+'//'+parts[1].split('/', 1)[0] if url not in scrape_whitelist: return ""URL domain is not in whitelist"" #get html from the requested url","class Scrape(BrowserView): parts = url.split('//', 1) this_base_url = parts[0]+'//'+parts[1].split('/', 1)[0] if this_base_url not in scrape_whitelist: return ""URL domain is not in whitelist"" #get html from the requested url" 2315,https://:@github.com/pyrated/vinyl.git,dec097819ed4e5635c3d8f64754fa6f3531278cc,"@@ -18,7 +18,7 @@ import os import sphinx_rtd_theme # We cannot install llvmlite on READTHEDOCS -if os.environ.get('READTHEDOCS') != 'True': +if os.environ.get('READTHEDOCS') == 'True': from unittest.mock import MagicMock class MockModule(MagicMock): @classmethod ",docs/source/conf.py,"ReplaceText(target='==' @(21,33)->(21,35))","import os import sphinx_rtd_theme # We cannot install llvmlite on READTHEDOCS if os.environ.get('READTHEDOCS') != 'True': from unittest.mock import MagicMock class MockModule(MagicMock): @classmethod","import os import sphinx_rtd_theme # We cannot install llvmlite on READTHEDOCS if os.environ.get('READTHEDOCS') == 'True': from unittest.mock import MagicMock class MockModule(MagicMock): @classmethod" 2316,https://:@github.com/marcofinalist/weathervane.git,4ddc4538762f2bb439b55019f2fea94480654988,"@@ -169,6 +169,6 @@ class WeatherVaneInterface(object): bits = self.spi.read_pin(self.station_bits) result = 0 for index, value in enumerate(bits): - result = value * 2**index + result += value * 2**index return self.STATIONS[result] \ No newline at end of file ",weathervane/weathervaneinterface.py,"ReplaceText(target='+=' @(172,19)->(172,20))","class WeatherVaneInterface(object): bits = self.spi.read_pin(self.station_bits) result = 0 for index, value in enumerate(bits): result = value * 2**index return self.STATIONS[result] \ No newline at end of file","class WeatherVaneInterface(object): bits = self.spi.read_pin(self.station_bits) result = 0 for index, value in enumerate(bits): result += value * 2**index return self.STATIONS[result] \ No newline at end of file" 2317,https://:@github.com/ofgulban/compoda.git,610dfad6de73410b4b99e8e9260b06dbe4ab91b7,"@@ -49,7 +49,7 @@ def closure(data, k=1.0): out = np.copy(data) for i in range(data.shape[1]): out[:, i] = np.divide(out[:, i], data_sum) - out = data * k + out = out * k return out ",compoda/core.py,"ReplaceText(target='out' @(52,10)->(52,14))","def closure(data, k=1.0): out = np.copy(data) for i in range(data.shape[1]): out[:, i] = np.divide(out[:, i], data_sum) out = data * k return out ","def closure(data, k=1.0): out = np.copy(data) for i in range(data.shape[1]): out[:, i] = np.divide(out[:, i], data_sum) out = out * k return out " 2318,https://:@github.com/monashbiomedicalimaging/arcana.git,bf8c927f1d0f7c4af2175ddec836c6ffea5a3858,"@@ -88,7 +88,7 @@ class XNATSource(ArchiveSource, XNATMixin): proj_summ_sess_name) = XNATArchive.project_summary_name( project.id) try: - proc_session = xnat_login.experiments[ + proc_session = subject.experiments[ self.session_id + XNATArchive.PROCESSED_SUFFIX] proc_datasets = dict( (s.type, s) for s in proc_session.scans.itervalues()) ",nianalysis/archive/xnat.py,"ReplaceText(target='subject' @(91,31)->(91,41))","class XNATSource(ArchiveSource, XNATMixin): proj_summ_sess_name) = XNATArchive.project_summary_name( project.id) try: proc_session = xnat_login.experiments[ self.session_id + XNATArchive.PROCESSED_SUFFIX] proc_datasets = dict( (s.type, s) for s in proc_session.scans.itervalues())","class XNATSource(ArchiveSource, XNATMixin): proj_summ_sess_name) = XNATArchive.project_summary_name( project.id) try: proc_session = subject.experiments[ self.session_id + XNATArchive.PROCESSED_SUFFIX] proc_datasets = dict( (s.type, s) for s in proc_session.scans.itervalues())" 2319,https://:@github.com/monashbiomedicalimaging/arcana.git,31946410e68317edea4ee76c6c24441065fc93ae,"@@ -417,7 +417,7 @@ class TestProjectInfo(BaseMultiSubjectTestCase): proj_dir, subject.id, SUMMARY_NAME, dataset.filename) for session in subject.sessions: - for dataset in subject.datasets: + for dataset in session.datasets: dataset.path = os.path.join( proj_dir, session.subject_id, session.visit_id, dataset.filename) ",test/unittests/archive/test_local.py,"ReplaceText(target='session' @(420,35)->(420,42))","class TestProjectInfo(BaseMultiSubjectTestCase): proj_dir, subject.id, SUMMARY_NAME, dataset.filename) for session in subject.sessions: for dataset in subject.datasets: dataset.path = os.path.join( proj_dir, session.subject_id, session.visit_id, dataset.filename)","class TestProjectInfo(BaseMultiSubjectTestCase): proj_dir, subject.id, SUMMARY_NAME, dataset.filename) for session in subject.sessions: for dataset in session.datasets: dataset.path = os.path.join( proj_dir, session.subject_id, session.visit_id, dataset.filename)" 2320,https://:@github.com/monashbiomedicalimaging/arcana.git,6bf29a9a339f7985d310d567a66cfca085cc4708,"@@ -268,7 +268,7 @@ class BaseArchiveSink(BaseArchiveNode): PATH_TRAIT) # Add input fields for field in fields: - assert isinstance(dataset, FieldSpec) + assert isinstance(field, FieldSpec) self._add_trait(self.inputs, field.name + FIELD_SUFFIX, field.dtype) ",nianalysis/archive/base.py,"ReplaceText(target='field' @(271,30)->(271,37))","class BaseArchiveSink(BaseArchiveNode): PATH_TRAIT) # Add input fields for field in fields: assert isinstance(dataset, FieldSpec) self._add_trait(self.inputs, field.name + FIELD_SUFFIX, field.dtype) ","class BaseArchiveSink(BaseArchiveNode): PATH_TRAIT) # Add input fields for field in fields: assert isinstance(field, FieldSpec) self._add_trait(self.inputs, field.name + FIELD_SUFFIX, field.dtype) " 2321,https://:@github.com/monashbiomedicalimaging/arcana.git,8bf472a77f50efc4d28d38d4aca46200c35e87e2,"@@ -353,7 +353,7 @@ class LocalArchive(Archive): Dataset.from_path( os.path.join(session_path, dname), multiplicity=multiplicity)) - if FIELDS_FNAME in dname: + if FIELDS_FNAME in dnames: fields = self.fields_from_json(os.path.join( session_path, FIELDS_FNAME), multiplicity=multiplicity) ",nianalysis/archive/local.py,"ReplaceText(target='dnames' @(356,31)->(356,36))","class LocalArchive(Archive): Dataset.from_path( os.path.join(session_path, dname), multiplicity=multiplicity)) if FIELDS_FNAME in dname: fields = self.fields_from_json(os.path.join( session_path, FIELDS_FNAME), multiplicity=multiplicity)","class LocalArchive(Archive): Dataset.from_path( os.path.join(session_path, dname), multiplicity=multiplicity)) if FIELDS_FNAME in dnames: fields = self.fields_from_json(os.path.join( session_path, FIELDS_FNAME), multiplicity=multiplicity)" 2322,https://:@github.com/monashbiomedicalimaging/arcana.git,b3a6e4ec34cbfc92ef62dde78f995c4075feaa46,"@@ -424,7 +424,7 @@ class Study(object): ""is not a valid option ('{}')"".format( ""', '"".join(unrecognised_values), name, self._param_error_location, - ""', '"".join(switch.choices))) + ""', '"".join(spec.choices))) if self._referenced_switches is not None: self._referenced_switches.add(name) return switch.value in values ",arcana/study/base.py,"ReplaceText(target='spec' @(427,32)->(427,38))","class Study(object): ""is not a valid option ('{}')"".format( ""', '"".join(unrecognised_values), name, self._param_error_location, ""', '"".join(switch.choices))) if self._referenced_switches is not None: self._referenced_switches.add(name) return switch.value in values","class Study(object): ""is not a valid option ('{}')"".format( ""', '"".join(unrecognised_values), name, self._param_error_location, ""', '"".join(spec.choices))) if self._referenced_switches is not None: self._referenced_switches.add(name) return switch.value in values" 2323,https://:@github.com/monashbiomedicalimaging/arcana.git,be154e732593c6c8dd36391db9048315ad74fabc,"@@ -214,7 +214,7 @@ class Study(object): ""to\n{}."".format(e, bound_inpt, spec)) raise e else: - if inpt.format not in spec.valid_formats: + if bound_inpt.format not in spec.valid_formats: raise ArcanaUsageError( ""Cannot pass {} as an input to {} as it is"" "" not in one of the valid formats ('{}')"" ",arcana/study/base.py,"ReplaceText(target='bound_inpt' @(217,31)->(217,35))","class Study(object): ""to\n{}."".format(e, bound_inpt, spec)) raise e else: if inpt.format not in spec.valid_formats: raise ArcanaUsageError( ""Cannot pass {} as an input to {} as it is"" "" not in one of the valid formats ('{}')""","class Study(object): ""to\n{}."".format(e, bound_inpt, spec)) raise e else: if bound_inpt.format not in spec.valid_formats: raise ArcanaUsageError( ""Cannot pass {} as an input to {} as it is"" "" not in one of the valid formats ('{}')""" 2324,https://:@github.com/monashbiomedicalimaging/arcana.git,21199db4a62a164140eef9c7a45966056c069541,"@@ -116,7 +116,7 @@ class ModulesEnvironment(BaseEnvironment): .format(req.name, local_name)) avail_versions = [] for local_ver_name in version_names: - ver_name = self.map_version(req_range, local_ver_name) + ver_name = self.map_version(req, local_ver_name) try: avail_versions.append( req.v(ver_name, local_name=local_name, ",arcana/environment/modules.py,"ReplaceText(target='req' @(119,44)->(119,53))","class ModulesEnvironment(BaseEnvironment): .format(req.name, local_name)) avail_versions = [] for local_ver_name in version_names: ver_name = self.map_version(req_range, local_ver_name) try: avail_versions.append( req.v(ver_name, local_name=local_name,","class ModulesEnvironment(BaseEnvironment): .format(req.name, local_name)) avail_versions = [] for local_ver_name in version_names: ver_name = self.map_version(req, local_ver_name) try: avail_versions.append( req.v(ver_name, local_name=local_name," 2325,https://:@github.com/monashbiomedicalimaging/arcana.git,35edaede784a97ddf4c0f961a4d6aac1cf3fb878,"@@ -683,7 +683,7 @@ class Study(object): in_branch = switch.value in values if not in_branch: try: - in_branch = switch.fallbacks[switch.value] in values + in_branch = spec.fallbacks[switch.value] in values except KeyError: pass return in_branch ",arcana/study/base.py,"ReplaceText(target='spec' @(686,32)->(686,38))","class Study(object): in_branch = switch.value in values if not in_branch: try: in_branch = switch.fallbacks[switch.value] in values except KeyError: pass return in_branch","class Study(object): in_branch = switch.value in values if not in_branch: try: in_branch = spec.fallbacks[switch.value] in values except KeyError: pass return in_branch" 2326,https://:@github.com/agartland/metadataVis.git,469bf0c8e514d09c966c73d21b9ff0c335d12255,"@@ -39,7 +39,7 @@ def _generateWideform(longform_df, rx=None): for entry in rowmeta_columns: rowmeta_dict[entry] = longform_df[entry] - if (rx is None): + if (rx is not None): ptid_md = pd.DataFrame(data=rowmeta_dict, columns=rowmeta_dict.keys()) ptid_md = ptid_md.drop_duplicates() ",LongformReader.py,"ReplaceText(target=' is not ' @(42,10)->(42,14))","def _generateWideform(longform_df, rx=None): for entry in rowmeta_columns: rowmeta_dict[entry] = longform_df[entry] if (rx is None): ptid_md = pd.DataFrame(data=rowmeta_dict, columns=rowmeta_dict.keys()) ptid_md = ptid_md.drop_duplicates()","def _generateWideform(longform_df, rx=None): for entry in rowmeta_columns: rowmeta_dict[entry] = longform_df[entry] if (rx is not None): ptid_md = pd.DataFrame(data=rowmeta_dict, columns=rowmeta_dict.keys()) ptid_md = ptid_md.drop_duplicates()" 2327,https://:@github.com/combatopera/pyven.git,2deb919498af4943aa18a7281037468809bda2d0,"@@ -22,7 +22,7 @@ class BinMix(Node): self.blockbuf.copybuf(self.tone(self.block)) if not noiseflag: self.blockbuf.orbuf(self.noise(self.block)) - elif noiseflag: + elif not noiseflag: self.blockbuf.copybuf(self.noise(self.block)) else: self.blockbuf.fill(0) ",pym2149/mix.py,"ReplaceText(target='not ' @(25,9)->(25,9))","class BinMix(Node): self.blockbuf.copybuf(self.tone(self.block)) if not noiseflag: self.blockbuf.orbuf(self.noise(self.block)) elif noiseflag: self.blockbuf.copybuf(self.noise(self.block)) else: self.blockbuf.fill(0)","class BinMix(Node): self.blockbuf.copybuf(self.tone(self.block)) if not noiseflag: self.blockbuf.orbuf(self.noise(self.block)) elif not noiseflag: self.blockbuf.copybuf(self.noise(self.block)) else: self.blockbuf.fill(0)" 2328,https://:@github.com/rolurq/flask-gulp.git,615013477dcfcf53b64e5cba0858f3b01e66b8fb,"@@ -61,7 +61,7 @@ def cjsx(filename, data): command = ""%s -c -s"" % (executable or 'cjsx') if bare: - command = ' '.join((executable, '-b')) + command = ' '.join((command, '-b')) return runner(command, filename, data, '.js') ",flask_static/extensions.py,"ReplaceText(target='command' @(64,28)->(64,38))","def cjsx(filename, data): command = ""%s -c -s"" % (executable or 'cjsx') if bare: command = ' '.join((executable, '-b')) return runner(command, filename, data, '.js') ","def cjsx(filename, data): command = ""%s -c -s"" % (executable or 'cjsx') if bare: command = ' '.join((command, '-b')) return runner(command, filename, data, '.js') " 2329,https://:@github.com/jiep/unicode.git,fe2f6fe46f14778cfcb74852d817d1876d171352,"@@ -92,7 +92,7 @@ def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: - print_diff(d, args.domain) + print_diff(args.domain, d) if write: f.write(d + ""\n"") if (args.check): ",v2d/main.py,"ArgSwap(idxs=0<->1 @(95,16)->(95,26))","def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: print_diff(d, args.domain) if write: f.write(d + ""\n"") if (args.check):","def main(): print('Similar domains to {}'.format(dom)) domains.difference_update(set(dom)) for d in domains: print_diff(args.domain, d) if write: f.write(d + ""\n"") if (args.check):" 2330,https://:@gitlab.com/admintotal/django-cfdi.git,9f131df38460abaafb00566867ce47b522fce7fd,"@@ -882,7 +882,7 @@ def get_xml_object(xml_text): nominas.append(nomina_object) - if nomina_object: + if nominas: xml.complemento.nominas = nominas xml.complemento.nomina = nominas[0] else: ",cfdi/utils.py,"ReplaceText(target='nominas' @(885,15)->(885,28))","def get_xml_object(xml_text): nominas.append(nomina_object) if nomina_object: xml.complemento.nominas = nominas xml.complemento.nomina = nominas[0] else:","def get_xml_object(xml_text): nominas.append(nomina_object) if nominas: xml.complemento.nominas = nominas xml.complemento.nomina = nominas[0] else:" 2331,https://:@github.com/ludeeus/addonupdater.git,fe325d28af7bcade5a806009c943fc0afbca63b1,"@@ -378,7 +378,7 @@ class AddonUpdater(): remote_buildfile = self.get_file_obj(buildfile) buildfile_content = self.get_file_content(remote_buildfile) - used_file = remote_dockerfile.split('BUILD_FROM=hassioaddons/')[1] + used_file = dockerfile_content.split('BUILD_FROM=hassioaddons/')[1] used_file = used_file.split('\n')[0] base = used_file.split(':')[1] ",addonupdater/updater.py,"ReplaceText(target='dockerfile_content' @(381,20)->(381,37))","class AddonUpdater(): remote_buildfile = self.get_file_obj(buildfile) buildfile_content = self.get_file_content(remote_buildfile) used_file = remote_dockerfile.split('BUILD_FROM=hassioaddons/')[1] used_file = used_file.split('\n')[0] base = used_file.split(':')[1]","class AddonUpdater(): remote_buildfile = self.get_file_obj(buildfile) buildfile_content = self.get_file_content(remote_buildfile) used_file = dockerfile_content.split('BUILD_FROM=hassioaddons/')[1] used_file = used_file.split('\n')[0] base = used_file.split(':')[1]" 2332,https://:@github.com/VictorPavlushin/netbox-netdev-inventory.git,00111f3155731e4bf1b380744519a89576a96a49,"@@ -161,7 +161,7 @@ class DeviceImporter(ContextDecorator): self._search_key_case_insensitive(interfaces, lag) ) except KeyError: - logger.error(""%s not exist in polled interfaces"", ifname) + logger.error(""%s not exist in polled interfaces"", lag) continue interfaces[ifname][""lag""] = real_lag_name ",netbox_netprod_importer/importer.py,"ReplaceText(target='lag' @(164,66)->(164,72))","class DeviceImporter(ContextDecorator): self._search_key_case_insensitive(interfaces, lag) ) except KeyError: logger.error(""%s not exist in polled interfaces"", ifname) continue interfaces[ifname][""lag""] = real_lag_name","class DeviceImporter(ContextDecorator): self._search_key_case_insensitive(interfaces, lag) ) except KeyError: logger.error(""%s not exist in polled interfaces"", lag) continue interfaces[ifname][""lag""] = real_lag_name" 2333,https://:@github.com/tswicegood/cbv_utils.git,25d2e1ce328e485ec26f4debd8f7aebc1ee6a623,"@@ -96,7 +96,7 @@ class ProcessInlineFormsetView(ProcessFormView): obj = form.save(commit=False) inline_formset = self.get_inline_formset() if inline_formset.is_valid(): - form.save() + obj.save() inline_formset.save() return self.form_valid(form, inline_formset) return self.form_invalid(form=form, inline_formset=inline_formset) ",cbv_utils/views.py,"ReplaceText(target='obj' @(99,16)->(99,20))","class ProcessInlineFormsetView(ProcessFormView): obj = form.save(commit=False) inline_formset = self.get_inline_formset() if inline_formset.is_valid(): form.save() inline_formset.save() return self.form_valid(form, inline_formset) return self.form_invalid(form=form, inline_formset=inline_formset)","class ProcessInlineFormsetView(ProcessFormView): obj = form.save(commit=False) inline_formset = self.get_inline_formset() if inline_formset.is_valid(): obj.save() inline_formset.save() return self.form_valid(form, inline_formset) return self.form_invalid(form=form, inline_formset=inline_formset)" 2334,https://:@github.com/romeric/florence.git,aa75d1bb83ec9de5e8ee60d9a87d2a86d7293aeb,"@@ -6010,7 +6010,7 @@ class Mesh(object): else: quality_func = lambda mesh: mesh.Lengths() elif quality_assessor == ""aspect_ratio"": - quality_assessor = lambda mesh: mesh.AspectRatios() + quality_func = lambda mesh: mesh.AspectRatios() elif quality_assessor == ""angle"": quality_func = lambda mesh: mesh.Angles() else: ",Florence/MeshGeneration/Mesh.py,"ReplaceText(target='quality_func' @(6013,16)->(6013,32))","class Mesh(object): else: quality_func = lambda mesh: mesh.Lengths() elif quality_assessor == ""aspect_ratio"": quality_assessor = lambda mesh: mesh.AspectRatios() elif quality_assessor == ""angle"": quality_func = lambda mesh: mesh.Angles() else:","class Mesh(object): else: quality_func = lambda mesh: mesh.Lengths() elif quality_assessor == ""aspect_ratio"": quality_func = lambda mesh: mesh.AspectRatios() elif quality_assessor == ""angle"": quality_func = lambda mesh: mesh.Angles() else:" 2335,https://:@github.com/DomainGroupOSS/ml-recsys-tools.git,467f8e1d859af1109bb830b3c35a752baeddbb67,"@@ -81,7 +81,7 @@ class FactorizationRecommender(BaseDFSparseRecommender): all_metrics.plot() self.early_stop_metrics_df = all_metrics - self._set_epochs(epochs=epochs_max) + self._set_epochs(epochs=max_epoch) if not refit_on_all: simple_logger.info('Loading best model from checkpoint at %d epochs' % max_epoch) self.model, self.model_checkpoint = self.model_checkpoint, None ",ml_recsys_tools/recommenders/factorization_base.py,"ReplaceText(target='max_epoch' @(84,32)->(84,42))","class FactorizationRecommender(BaseDFSparseRecommender): all_metrics.plot() self.early_stop_metrics_df = all_metrics self._set_epochs(epochs=epochs_max) if not refit_on_all: simple_logger.info('Loading best model from checkpoint at %d epochs' % max_epoch) self.model, self.model_checkpoint = self.model_checkpoint, None","class FactorizationRecommender(BaseDFSparseRecommender): all_metrics.plot() self.early_stop_metrics_df = all_metrics self._set_epochs(epochs=max_epoch) if not refit_on_all: simple_logger.info('Loading best model from checkpoint at %d epochs' % max_epoch) self.model, self.model_checkpoint = self.model_checkpoint, None" 2336,https://:@github.com/south-coast-science/scs_core.git,6ca2ac668b486924816ed461e8f40a87d82136da,"@@ -25,7 +25,7 @@ class Filesystem(object): if head and not os.path.exists(head): cls.mkdir(head) - if os.path.exists(path): # handles case of trailing / + if not os.path.exists(path): # handles case of trailing / os.mkdir(path) ",src/scs_core/sys/filesystem.py,"ReplaceText(target='not ' @(28,11)->(28,11))","class Filesystem(object): if head and not os.path.exists(head): cls.mkdir(head) if os.path.exists(path): # handles case of trailing / os.mkdir(path) ","class Filesystem(object): if head and not os.path.exists(head): cls.mkdir(head) if not os.path.exists(path): # handles case of trailing / os.mkdir(path) " 2337,https://:@github.com/south-coast-science/scs_core.git,653bf53c4d76b1b422d8aa11174c9a5351bbd1f6,"@@ -81,7 +81,7 @@ class ExegeteRenderingTRhRow(JSONable): @classmethod def construct(cls, gas, rh, t_min, t_max, t_delta, exegete: Exegete): - cells = [ExegeteRenderingTRhCell(t, exegete.error(gas, t, rh)) + cells = [ExegeteRenderingTRhCell(t, exegete.error(gas, rh, t)) for t in range(t_min, t_max + 1, t_delta)] return ExegeteRenderingTRhRow(rh, cells) ",src/scs_core/gas/exegesis/exegete_rendering_t_rh.py,"ArgSwap(idxs=1<->2 @(84,44)->(84,57))","class ExegeteRenderingTRhRow(JSONable): @classmethod def construct(cls, gas, rh, t_min, t_max, t_delta, exegete: Exegete): cells = [ExegeteRenderingTRhCell(t, exegete.error(gas, t, rh)) for t in range(t_min, t_max + 1, t_delta)] return ExegeteRenderingTRhRow(rh, cells)","class ExegeteRenderingTRhRow(JSONable): @classmethod def construct(cls, gas, rh, t_min, t_max, t_delta, exegete: Exegete): cells = [ExegeteRenderingTRhCell(t, exegete.error(gas, rh, t)) for t in range(t_min, t_max + 1, t_delta)] return ExegeteRenderingTRhRow(rh, cells)" 2338,https://:@github.com/south-coast-science/scs_core.git,653bf53c4d76b1b422d8aa11174c9a5351bbd1f6,"@@ -43,7 +43,7 @@ print(""-"") for rh in range(10, 91, 5): for t in range(0, 46, 5): - interpretation = exegete.interpretation('NO2', text, t, rh) + interpretation = exegete.interpretation('NO2', text, rh, t) print(""rh: %2d t: %2d text: %3.1f interpretation: %3.1f"" % (rh, t, text, interpretation)) print(""-"") ",tests/gas/exegesis/sbl1/sbl1_no2_v1_test.py,"ArgSwap(idxs=2<->3 @(46,25)->(46,47))","print(""-"") for rh in range(10, 91, 5): for t in range(0, 46, 5): interpretation = exegete.interpretation('NO2', text, t, rh) print(""rh: %2d t: %2d text: %3.1f interpretation: %3.1f"" % (rh, t, text, interpretation)) print(""-"")","print(""-"") for rh in range(10, 91, 5): for t in range(0, 46, 5): interpretation = exegete.interpretation('NO2', text, rh, t) print(""rh: %2d t: %2d text: %3.1f interpretation: %3.1f"" % (rh, t, text, interpretation)) print(""-"")" 2339,https://:@github.com/south-coast-science/scs_core.git,73c3c80fcc88fce844e0e387499753667dac811e,"@@ -68,7 +68,7 @@ class S3Manager(object): bucket_list.append(str(inters), bucket[""Name""]) inters += 1 - return bucket_list + return response def retrieve_from_bucket(self, bucket_name, resource_name): ",src/scs_core/aws/manager/s3_manager.py,"ReplaceText(target='response' @(71,15)->(71,26))","class S3Manager(object): bucket_list.append(str(inters), bucket[""Name""]) inters += 1 return bucket_list def retrieve_from_bucket(self, bucket_name, resource_name):","class S3Manager(object): bucket_list.append(str(inters), bucket[""Name""]) inters += 1 return response def retrieve_from_bucket(self, bucket_name, resource_name):" 2340,https://:@github.com/south-coast-science/scs_core.git,ac11b0e941914f83f984d183811a83bb0a5df544,"@@ -59,7 +59,7 @@ class AccessKey(PersistentJSONable): @classmethod def persistence_location(cls, host): - return host.aws_dir(), cls.__FILENAME + return cls.aws_dir(), cls.__FILENAME @classmethod ",src/scs_core/aws/client/access_key.py,"ReplaceText(target='cls' @(62,15)->(62,19))","class AccessKey(PersistentJSONable): @classmethod def persistence_location(cls, host): return host.aws_dir(), cls.__FILENAME @classmethod","class AccessKey(PersistentJSONable): @classmethod def persistence_location(cls, host): return cls.aws_dir(), cls.__FILENAME @classmethod" 2341,https://:@github.com/south-coast-science/scs_core.git,e6293b84e0b7594738b85db5a7365fdbb5770461,"@@ -53,7 +53,7 @@ class DeviceTester(object): delta = now - latest_pub elapsed_minutes = delta.total_seconds() / 60 - return elapsed_minutes > self.__config.unresponsive_minutes_allowed + return elapsed_minutes < self.__config.unresponsive_minutes_allowed def has_status_changed(self, s3_device_status_list): ",src/scs_core/aws/monitor/device_tester.py,"ReplaceText(target='<' @(56,35)->(56,36))","class DeviceTester(object): delta = now - latest_pub elapsed_minutes = delta.total_seconds() / 60 return elapsed_minutes > self.__config.unresponsive_minutes_allowed def has_status_changed(self, s3_device_status_list):","class DeviceTester(object): delta = now - latest_pub elapsed_minutes = delta.total_seconds() / 60 return elapsed_minutes < self.__config.unresponsive_minutes_allowed def has_status_changed(self, s3_device_status_list):" 2342,https://:@github.com/davidfstr/notifymail.git,585ae19eba35db57e969941ea2c340bd3be499d8,"@@ -8,7 +8,7 @@ def is_older_than(file1, file2): return os.path.getmtime(file1) < os.path.getmtime(file2) # Generate README.rst if missing or out of date -if not os.path.exists('README.rst') and is_older_than('README.rst', 'README.md'): +if not os.path.exists('README.rst') or is_older_than('README.rst', 'README.md'): os.system('pandoc --from=markdown --to=rst --output=README.rst README.md') with open('README.rst') as file: long_description = file.read() ",setup.py,"ReplaceText(target='or' @(11,36)->(11,39))","def is_older_than(file1, file2): return os.path.getmtime(file1) < os.path.getmtime(file2) # Generate README.rst if missing or out of date if not os.path.exists('README.rst') and is_older_than('README.rst', 'README.md'): os.system('pandoc --from=markdown --to=rst --output=README.rst README.md') with open('README.rst') as file: long_description = file.read()","def is_older_than(file1, file2): return os.path.getmtime(file1) < os.path.getmtime(file2) # Generate README.rst if missing or out of date if not os.path.exists('README.rst') or is_older_than('README.rst', 'README.md'): os.system('pandoc --from=markdown --to=rst --output=README.rst README.md') with open('README.rst') as file: long_description = file.read()" 2343,https://:@github.com/hile/oodi.git,169b7db094c64a5c2ca695bf93782fce0b50945f,"@@ -26,7 +26,7 @@ class Command(ScriptCommand): iterators = [] for path in paths: try: - iterators.append(IterableTrackPaths(self.script.configuration, path)) + iterators.append(IterableTrackPaths(path, self.script.configuration)) except LibraryError as e: self.error(e) return iterators ",oodi/bin/commands/base.py,"ArgSwap(idxs=0<->1 @(29,33)->(29,51))","class Command(ScriptCommand): iterators = [] for path in paths: try: iterators.append(IterableTrackPaths(self.script.configuration, path)) except LibraryError as e: self.error(e) return iterators","class Command(ScriptCommand): iterators = [] for path in paths: try: iterators.append(IterableTrackPaths(path, self.script.configuration)) except LibraryError as e: self.error(e) return iterators" 2344,https://:@github.com/tpm2-software/tpm2-pytss.git,675d845e04810a4129e9e5b21889a0258fcad7b2,"@@ -141,7 +141,7 @@ class BaseContextMetaClass(type): and ""uint8_t"" in docstring.split() ): return_value.append( - to_bytearray(value.value, args[i + 1].value) + to_bytearray(args[i + 1].value, value.value) ) skip = True continue ",tpm2_pytss/context.py,"ArgSwap(idxs=0<->1 @(144,36)->(144,48))","class BaseContextMetaClass(type): and ""uint8_t"" in docstring.split() ): return_value.append( to_bytearray(value.value, args[i + 1].value) ) skip = True continue","class BaseContextMetaClass(type): and ""uint8_t"" in docstring.split() ): return_value.append( to_bytearray(args[i + 1].value, value.value) ) skip = True continue" 2345,https://:@github.com/josesho/bootstrap_contrast.git,1d55129dee9130374774bb1234b577e061974d93,"@@ -1089,7 +1089,7 @@ def pairedcontrast(data, x, y, idcol, hue = None, linestyle = 'dotted') # Set xlimit to appropriate limits.. - newxlim = (ax_left.get_xlim()[0], xpos + 0.25) + newxlim = (ax_left.get_xlim()[0], xposPlusViolin + 0.25) ax_left.set_xlim(newxlim) # Remove left axes x-axis title. ",bootstrapContrast/bootstrapContrast.py,"ReplaceText(target='xposPlusViolin' @(1092,38)->(1092,42))","def pairedcontrast(data, x, y, idcol, hue = None, linestyle = 'dotted') # Set xlimit to appropriate limits.. newxlim = (ax_left.get_xlim()[0], xpos + 0.25) ax_left.set_xlim(newxlim) # Remove left axes x-axis title.","def pairedcontrast(data, x, y, idcol, hue = None, linestyle = 'dotted') # Set xlimit to appropriate limits.. newxlim = (ax_left.get_xlim()[0], xposPlusViolin + 0.25) ax_left.set_xlim(newxlim) # Remove left axes x-axis title." 2346,https://:@github.com/josesho/bootstrap_contrast.git,5875648efb0994fdac3eae216fe36d51cc0f629c,"@@ -88,7 +88,7 @@ def plotbootstrap_hubspoke(bslist, ax, violinWidth, violinOffset, for i in range(0, len(bslist)): bsi=bslist[i] # array=list(bsi.items())[7][1] # Pull out the bootstrapped array. - array=bslist['diffarray'] + array=bsi['diffarray'] ylims.append(array) # Then plot as violinplot. ",bootstrapContrast/plot_bootstrap_tools.py,"ReplaceText(target='bsi' @(91,14)->(91,20))","def plotbootstrap_hubspoke(bslist, ax, violinWidth, violinOffset, for i in range(0, len(bslist)): bsi=bslist[i] # array=list(bsi.items())[7][1] # Pull out the bootstrapped array. array=bslist['diffarray'] ylims.append(array) # Then plot as violinplot.","def plotbootstrap_hubspoke(bslist, ax, violinWidth, violinOffset, for i in range(0, len(bslist)): bsi=bslist[i] # array=list(bsi.items())[7][1] # Pull out the bootstrapped array. array=bsi['diffarray'] ylims.append(array) # Then plot as violinplot." 2347,https://:@gitlab.com/harry.sky.vortex/melodiam.git,bbc45aeb762242382c68cfe6fa9a32e600eb3630,"@@ -106,7 +106,7 @@ class SpotifyAPI(object): # Update ETag if song's playback was manipulated if song[""progress_ms""] < self.current_song[""progress""] or song[""progress_ms""] - 10000 > self.current_song[""progress""]: self.current_song_json_updated = str(time()) - LISTEN_ALONG_API.set_current_playing_song(song_uri=song[""uri""], position_ms=song[""progress_ms""]) + LISTEN_ALONG_API.set_current_playing_song(song_uri=item[""uri""], position_ms=song[""progress_ms""]) self.current_song[""progress""] = song[""progress_ms""] self.current_song_json = json.dumps(self.current_song) ",backend/spotify.py,"ReplaceText(target='item' @(109,71)->(109,75))","class SpotifyAPI(object): # Update ETag if song's playback was manipulated if song[""progress_ms""] < self.current_song[""progress""] or song[""progress_ms""] - 10000 > self.current_song[""progress""]: self.current_song_json_updated = str(time()) LISTEN_ALONG_API.set_current_playing_song(song_uri=song[""uri""], position_ms=song[""progress_ms""]) self.current_song[""progress""] = song[""progress_ms""] self.current_song_json = json.dumps(self.current_song)","class SpotifyAPI(object): # Update ETag if song's playback was manipulated if song[""progress_ms""] < self.current_song[""progress""] or song[""progress_ms""] - 10000 > self.current_song[""progress""]: self.current_song_json_updated = str(time()) LISTEN_ALONG_API.set_current_playing_song(song_uri=item[""uri""], position_ms=song[""progress_ms""]) self.current_song[""progress""] = song[""progress_ms""] self.current_song_json = json.dumps(self.current_song)" 2348,https://:@gitlab.com/harry.sky.vortex/melodiam.git,db126e963e784dee9d11f2331622ef9eca5baf9d,"@@ -32,7 +32,7 @@ async def get_listen_along_users_endpoint(request: StarletteRequest) -> PlainTex for user in ListenAlong.users: users_json += user.public_json + "","" - users_json = ']' + users_json += ']' return PlainTextResponse(content=users_json, media_type=""application/json"") @SERVER.route('/get_current_song', methods=['GET']) ",backend/music/main.py,"ReplaceText(target='+=' @(35,15)->(35,16))","async def get_listen_along_users_endpoint(request: StarletteRequest) -> PlainTex for user in ListenAlong.users: users_json += user.public_json + "","" users_json = ']' return PlainTextResponse(content=users_json, media_type=""application/json"") @SERVER.route('/get_current_song', methods=['GET'])","async def get_listen_along_users_endpoint(request: StarletteRequest) -> PlainTex for user in ListenAlong.users: users_json += user.public_json + "","" users_json += ']' return PlainTextResponse(content=users_json, media_type=""application/json"") @SERVER.route('/get_current_song', methods=['GET'])" 2349,https://:@gitlab.com/harry.sky.vortex/melodiam.git,9850cc42634b01312cc8754a03df8abccd2054ce,"@@ -21,7 +21,7 @@ class ListenAlong(): @staticmethod def _set_song(user: ListenAlongUser, song_json: str) -> None: if user.tokens: - status = SpotifyWebAPI.set_current_playing_song(song_json, user.tokens.access) + status = SpotifyWebAPI.set_current_playing_song(user.tokens.access, song_json) if user.public.status != status: user.public.status = status user.public_json = json.dumps(asdict(user.public)) ",backend/music/features/listen_along.py,"ArgSwap(idxs=0<->1 @(24,21)->(24,59))","class ListenAlong(): @staticmethod def _set_song(user: ListenAlongUser, song_json: str) -> None: if user.tokens: status = SpotifyWebAPI.set_current_playing_song(song_json, user.tokens.access) if user.public.status != status: user.public.status = status user.public_json = json.dumps(asdict(user.public))","class ListenAlong(): @staticmethod def _set_song(user: ListenAlongUser, song_json: str) -> None: if user.tokens: status = SpotifyWebAPI.set_current_playing_song(user.tokens.access, song_json) if user.public.status != status: user.public.status = status user.public_json = json.dumps(asdict(user.public))" 2350,https://:@github.com/ladybug-tools/honeybee-radiance-command.git,fe62562a0b228b8e46309aa88c116882247c89b9,"@@ -18,7 +18,7 @@ def run_command(input_command, env=None, cwd=None): if platform.system() == 'Windows': command = input_command.replace('\'', '""') else: - command = command.replace('""', '\'') + command = input_command.replace('""', '\'') # change cwd - Popen cwd input simply doesn't work. cur_dir = os.getcwd() ",honeybee_radiance_command/_command_util.py,"ReplaceText(target='input_command' @(21,18)->(21,25))","def run_command(input_command, env=None, cwd=None): if platform.system() == 'Windows': command = input_command.replace('\'', '""') else: command = command.replace('""', '\'') # change cwd - Popen cwd input simply doesn't work. cur_dir = os.getcwd()","def run_command(input_command, env=None, cwd=None): if platform.system() == 'Windows': command = input_command.replace('\'', '""') else: command = input_command.replace('""', '\'') # change cwd - Popen cwd input simply doesn't work. cur_dir = os.getcwd()" 2351,https://:@bitbucket.org/bertrandboichon/pi.hifi.git,bf0316f181d6e6597722b0f3023f70a592c49d04,"@@ -11,7 +11,7 @@ class post_install(install): install.run(self) print(""*** Executing post install actions:"") # update mpd configuration if necessary - if '/tmp/mpd.fifo' in open('/etc/mpd.conf').read(): + if '/tmp/mpd.fifo' not in open('/etc/mpd.conf').read(): os.system(""sudo cat /etc/fifo-mpd.conf >> /etc/mpd.conf"") os.system(""sudo service mpd restart"") # update music display init script ",setup.py,"ReplaceText(target=' not in ' @(14,26)->(14,30))","class post_install(install): install.run(self) print(""*** Executing post install actions:"") # update mpd configuration if necessary if '/tmp/mpd.fifo' in open('/etc/mpd.conf').read(): os.system(""sudo cat /etc/fifo-mpd.conf >> /etc/mpd.conf"") os.system(""sudo service mpd restart"") # update music display init script","class post_install(install): install.run(self) print(""*** Executing post install actions:"") # update mpd configuration if necessary if '/tmp/mpd.fifo' not in open('/etc/mpd.conf').read(): os.system(""sudo cat /etc/fifo-mpd.conf >> /etc/mpd.conf"") os.system(""sudo service mpd restart"") # update music display init script" 2352,https://:@github.com/hotoffthehamster/dob.git,9615cad9da920842a23b9a124b1d39356ebe7d2e,"@@ -43,7 +43,7 @@ def echo_copyright(): cur_year = str(datetime.now().year) year_range = '2018' if cur_year != year_range: - year_range = '2018-{}'.format(year_range) + year_range = '2018-{}'.format(cur_year) gpl3_notice_2018 = [ '{app_name} {version}'.format( app_name=__BigName__, ",dob/copyright.py,"ReplaceText(target='cur_year' @(46,38)->(46,48))","def echo_copyright(): cur_year = str(datetime.now().year) year_range = '2018' if cur_year != year_range: year_range = '2018-{}'.format(year_range) gpl3_notice_2018 = [ '{app_name} {version}'.format( app_name=__BigName__,","def echo_copyright(): cur_year = str(datetime.now().year) year_range = '2018' if cur_year != year_range: year_range = '2018-{}'.format(cur_year) gpl3_notice_2018 = [ '{app_name} {version}'.format( app_name=__BigName__," 2353,https://:@github.com/superadm1n/CiscoAutomationFramework.git,2ffcf5da63e3479f7bcae3d552f04695b36d9466,"@@ -594,7 +594,7 @@ class IOS(TerminalCommands, CommandGetMethods): ) #mac_table_list.append(line.split()) - if len(line.split()) >= 1: + if len(line.split()) > 1: if '--' in line.split()[0]: flag = 1 ",CiscoAutomationFramework/CiscoIOS.py,"ReplaceText(target='>' @(597,33)->(597,35))","class IOS(TerminalCommands, CommandGetMethods): ) #mac_table_list.append(line.split()) if len(line.split()) >= 1: if '--' in line.split()[0]: flag = 1 ","class IOS(TerminalCommands, CommandGetMethods): ) #mac_table_list.append(line.split()) if len(line.split()) > 1: if '--' in line.split()[0]: flag = 1 " 2354,https://:@github.com/bruth/ipipe.git,dc24d06d645ab03e988a066267787aff98baee32,"@@ -20,7 +20,7 @@ class Parser(object): output.extend(parsed) else: output.append(parsed) - return parsed + return output class FileParser(Parser): ",pipes/parser.py,"ReplaceText(target='output' @(23,15)->(23,21))","class Parser(object): output.extend(parsed) else: output.append(parsed) return parsed class FileParser(Parser):","class Parser(object): output.extend(parsed) else: output.append(parsed) return output class FileParser(Parser):" 2355,https://:@github.com/la-mar/permian-frac-exchange.git,3d0d86bfbb6871abdded1c5357dac5ca1c3ed756,"@@ -249,7 +249,7 @@ class Parser(object): ) -> pd.Series: try: apply_to = apply_to or apply_on - self.df[apply_on] = self.df[apply_on].apply(func) + self.df[apply_to] = self.df[apply_on].apply(func) except KeyError as ke: logger.debug( MSG_PARSER_CHECK.format(op_name=self.operator.name, col_name=apply_on) ",src/fsec/parser.py,"ReplaceText(target='apply_to' @(252,20)->(252,28))","class Parser(object): ) -> pd.Series: try: apply_to = apply_to or apply_on self.df[apply_on] = self.df[apply_on].apply(func) except KeyError as ke: logger.debug( MSG_PARSER_CHECK.format(op_name=self.operator.name, col_name=apply_on)","class Parser(object): ) -> pd.Series: try: apply_to = apply_to or apply_on self.df[apply_to] = self.df[apply_on].apply(func) except KeyError as ke: logger.debug( MSG_PARSER_CHECK.format(op_name=self.operator.name, col_name=apply_on)" 2356,https://:@bitbucket.org/sambowers/biota.git,b9c2b1b28e5a5fb57b30e7c474ecf2e6f729edeb,"@@ -304,9 +304,9 @@ def calculateTWC(tile, patch_size = 'auto', output = False, show = False): # Extract the data WC = woody_cover[ymin:ymax, xmin:xmax] - + # If at least 50 % of data is present... - if TWC.mask.sum() <= ((patch_size ** 2) * 0.5): + if WC.mask.sum() <= ((patch_size ** 2) * 0.5): # Calculate proportion of woody cover in patch TWC.data[n, m] = int(round((float(WC.sum()) / ((patch_size ** 2) - WC.mask.sum())) * 100)) ",biota/indices.py,"ReplaceText(target='WC' @(309,11)->(309,14))","def calculateTWC(tile, patch_size = 'auto', output = False, show = False): # Extract the data WC = woody_cover[ymin:ymax, xmin:xmax] # If at least 50 % of data is present... if TWC.mask.sum() <= ((patch_size ** 2) * 0.5): # Calculate proportion of woody cover in patch TWC.data[n, m] = int(round((float(WC.sum()) / ((patch_size ** 2) - WC.mask.sum())) * 100))","def calculateTWC(tile, patch_size = 'auto', output = False, show = False): # Extract the data WC = woody_cover[ymin:ymax, xmin:xmax] # If at least 50 % of data is present... if WC.mask.sum() <= ((patch_size ** 2) * 0.5): # Calculate proportion of woody cover in patch TWC.data[n, m] = int(round((float(WC.sum()) / ((patch_size ** 2) - WC.mask.sum())) * 100))" 2357,https://:@github.com/yedhrab/YInstabot.git,c9d3f3b18656d7b19eb7b179fc7adb171bb6efe8,"@@ -106,7 +106,7 @@ def main(): DEBUG, WAIT, NO_REFRESH, PATHS = not args.quite, args.wait, args.noRefresh, args.paths for PATH in PATHS: - if not os.path.isfile(PATHS): + if not os.path.isfile(PATH): print(f""`{PATH}` dosyaya ait değil."") continue ",yinstabot/workspace.py,"ReplaceText(target='PATH' @(109,30)->(109,35))","def main(): DEBUG, WAIT, NO_REFRESH, PATHS = not args.quite, args.wait, args.noRefresh, args.paths for PATH in PATHS: if not os.path.isfile(PATHS): print(f""`{PATH}` dosyaya ait değil."") continue ","def main(): DEBUG, WAIT, NO_REFRESH, PATHS = not args.quite, args.wait, args.noRefresh, args.paths for PATH in PATHS: if not os.path.isfile(PATH): print(f""`{PATH}` dosyaya ait değil."") continue " 2358,https://:@github.com/fladi/pyrc522.git,83bd4bd1c169259a8e4c3e7736e2aa610f3a8691,"@@ -48,7 +48,7 @@ class RFID(object): self.spi.max_speed_hz = speed GPIO.setmode(pin_mode) - if pin_rst is None: + if pin_rst is not None: GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) GPIO.setup(pin_irq, GPIO.IN, pull_up_down=GPIO.PUD_UP) ",pirc522/rfid.py,"ReplaceText(target=' is not ' @(51,18)->(51,22))","class RFID(object): self.spi.max_speed_hz = speed GPIO.setmode(pin_mode) if pin_rst is None: GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) GPIO.setup(pin_irq, GPIO.IN, pull_up_down=GPIO.PUD_UP)","class RFID(object): self.spi.max_speed_hz = speed GPIO.setmode(pin_mode) if pin_rst is not None: GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) GPIO.setup(pin_irq, GPIO.IN, pull_up_down=GPIO.PUD_UP)" 2359,https://:@github.com/ac-tuwien/pymhlib.git,07e69d451d8e2f665c23f31c780cfa58f583cf4f,"@@ -63,7 +63,7 @@ def run_optimization(problem_name: str, instance_class, solution_class, default_ :param iter_cb: optional callback function that is called each iteration by some of the algorithms :param seed: optional seed value for the random number generators; 0: random initialization """""" - if embedded: + if not embedded: add_general_arguments_and_parse_settings(default_inst_file, seed) init_logger() ",pymhlib/demos/common.py,"ReplaceText(target='not ' @(66,7)->(66,7))","def run_optimization(problem_name: str, instance_class, solution_class, default_ :param iter_cb: optional callback function that is called each iteration by some of the algorithms :param seed: optional seed value for the random number generators; 0: random initialization """""" if embedded: add_general_arguments_and_parse_settings(default_inst_file, seed) init_logger()","def run_optimization(problem_name: str, instance_class, solution_class, default_ :param iter_cb: optional callback function that is called each iteration by some of the algorithms :param seed: optional seed value for the random number generators; 0: random initialization """""" if not embedded: add_general_arguments_and_parse_settings(default_inst_file, seed) init_logger()" 2360,https://:@github.com/trevorparker/vane.git,8b9eb3a87c10bce414017216fbd7ef333e124597,"@@ -140,7 +140,7 @@ def _fetch_weather_json( if (with_forecast): forecast_url = forecast_urls[provider] r = requests.get( - forecast_url.format(location, units, api_key)) + forecast_url.format(loc_parsed, units, api_key)) f = json.loads(r.text) if (c['response']['features']['forecast'] != 1): return {'e': 'Unable to load forecast'} ",vane/utils.py,"ReplaceText(target='loc_parsed' @(143,44)->(143,52))","def _fetch_weather_json( if (with_forecast): forecast_url = forecast_urls[provider] r = requests.get( forecast_url.format(location, units, api_key)) f = json.loads(r.text) if (c['response']['features']['forecast'] != 1): return {'e': 'Unable to load forecast'}","def _fetch_weather_json( if (with_forecast): forecast_url = forecast_urls[provider] r = requests.get( forecast_url.format(loc_parsed, units, api_key)) f = json.loads(r.text) if (c['response']['features']['forecast'] != 1): return {'e': 'Unable to load forecast'}" 2361,https://:@github.com/juancgvazquez/MODApy.git,7c64bc5452715160f8767c891f04d7a0a4848ebc,"@@ -227,7 +227,7 @@ class Pipeline(object): logger2.info(step.name) args = step.args.replace( - 'patientname', tmpdir + patientname).replace('reference', ref).replace('samplename', samplename) + 'patientname', tmpdir + patientname).replace('reference', ref).replace('samplename', patientname) cmdver = step.version.replace('.', '_') javacmds = ['GATK', 'picard', 'SnpSift', 'snpEff'] if any(javacmd in step.command for javacmd in javacmds): ",MODApy/pipeline.py,"ReplaceText(target='patientname' @(230,101)->(230,111))","class Pipeline(object): logger2.info(step.name) args = step.args.replace( 'patientname', tmpdir + patientname).replace('reference', ref).replace('samplename', samplename) cmdver = step.version.replace('.', '_') javacmds = ['GATK', 'picard', 'SnpSift', 'snpEff'] if any(javacmd in step.command for javacmd in javacmds):","class Pipeline(object): logger2.info(step.name) args = step.args.replace( 'patientname', tmpdir + patientname).replace('reference', ref).replace('samplename', patientname) cmdver = step.version.replace('.', '_') javacmds = ['GATK', 'picard', 'SnpSift', 'snpEff'] if any(javacmd in step.command for javacmd in javacmds):" 2362,https://:@github.com/linhd-postdata/averell.git,538e7f13b3b57170d94241111b416c31deb75d5c,"@@ -99,7 +99,7 @@ def download_corpora(corpus_indices=None, else: url = CORPORA_SOURCES[index][""properties""][""url""] filename = download_corpus(url, f""{folder_name}.zip"") - folder_list.append(uncompress_corpus(filename, output_folder)) + folder_list.append(uncompress_corpus(filename, folder_path)) else: logging.error(""No corpus selected. Nothing will be downloaded"") return folder_list ",src/averell/utils.py,"ReplaceText(target='folder_path' @(102,63)->(102,76))","def download_corpora(corpus_indices=None, else: url = CORPORA_SOURCES[index][""properties""][""url""] filename = download_corpus(url, f""{folder_name}.zip"") folder_list.append(uncompress_corpus(filename, output_folder)) else: logging.error(""No corpus selected. Nothing will be downloaded"") return folder_list","def download_corpora(corpus_indices=None, else: url = CORPORA_SOURCES[index][""properties""][""url""] filename = download_corpus(url, f""{folder_name}.zip"") folder_list.append(uncompress_corpus(filename, folder_path)) else: logging.error(""No corpus selected. Nothing will be downloaded"") return folder_list" 2363,https://:@github.com/poqweur/ctec-utils.git,28470709205c35754325af5e817fded28921a389,"@@ -122,7 +122,7 @@ class OraclePool(object): result_db = cursor.execute(sql, param) if commit: conn.commit() - result = result_db.rowcount + result = cursor.rowcount else: result = result_db.fetchall() except Exception as e: ",ctec_utils/Database.py,"ReplaceText(target='cursor' @(125,25)->(125,34))","class OraclePool(object): result_db = cursor.execute(sql, param) if commit: conn.commit() result = result_db.rowcount else: result = result_db.fetchall() except Exception as e:","class OraclePool(object): result_db = cursor.execute(sql, param) if commit: conn.commit() result = cursor.rowcount else: result = result_db.fetchall() except Exception as e:" 2364,https://:@github.com/fsepy/sfeprapy.git,ffdf8d512d6ca26a685f58fceac853d9ac9241b6,"@@ -137,7 +137,7 @@ def dict_flatten(dict_in: dict): else: dict_out[k] = dict_in[k] - return dict_in + return dict_out def main(x: dict, num_samples: int): ",sfeprapy/func/mcs_gen.py,"ReplaceText(target='dict_out' @(140,11)->(140,18))","def dict_flatten(dict_in: dict): else: dict_out[k] = dict_in[k] return dict_in def main(x: dict, num_samples: int):","def dict_flatten(dict_in: dict): else: dict_out[k] = dict_in[k] return dict_out def main(x: dict, num_samples: int):" 2365,https://:@github.com/galias11/nlp_model_gen.git,7854eb5aac80b1f6d24bbdd7d319bb9ebb4e429a,"@@ -173,7 +173,7 @@ class ModelManagerController: try: Logger.log('L-0021') custom_model = self.__initialize_custom_model() - new_model = Model(model_id, model_name, description, author, model_name, analyzer_rule_set) + new_model = Model(model_id, model_name, description, author, model_id, analyzer_rule_set) new_model.set_reference(custom_model) Logger.log('L-0022') self.__apply_tokenizer_exceptions(new_model, tokenizer_exceptions_path) ",nlp_model_gen/packages/modelManager/ModelManagerController.py,"ReplaceText(target='model_id' @(176,73)->(176,83))","class ModelManagerController: try: Logger.log('L-0021') custom_model = self.__initialize_custom_model() new_model = Model(model_id, model_name, description, author, model_name, analyzer_rule_set) new_model.set_reference(custom_model) Logger.log('L-0022') self.__apply_tokenizer_exceptions(new_model, tokenizer_exceptions_path)","class ModelManagerController: try: Logger.log('L-0021') custom_model = self.__initialize_custom_model() new_model = Model(model_id, model_name, description, author, model_id, analyzer_rule_set) new_model.set_reference(custom_model) Logger.log('L-0022') self.__apply_tokenizer_exceptions(new_model, tokenizer_exceptions_path)" 2366,https://:@github.com/galias11/nlp_model_gen.git,f03a84b2eaa77db12a4d7698bb982a2be062566b,"@@ -104,7 +104,7 @@ class Model: token_analyzer = Analyzer(self.__analyzer_rules_set) for sent in doc.sents: for token in sent: - generated_token = Token(token.lemma_, token.is_oov, token.pos_, token.sent, token.sentiment, token.tag_, sent.text) + generated_token = Token(token.lemma_, token.is_oov, token.pos_, token.sent, token.sentiment, token.tag_, token.text) token_analyzer.analyze_token(generated_token) if not only_positives or generated_token.is_positive(): results.append(generated_token) ",nlp_model_gen/packages/modelManager/model/Model.py,"ReplaceText(target='token' @(107,121)->(107,125))","class Model: token_analyzer = Analyzer(self.__analyzer_rules_set) for sent in doc.sents: for token in sent: generated_token = Token(token.lemma_, token.is_oov, token.pos_, token.sent, token.sentiment, token.tag_, sent.text) token_analyzer.analyze_token(generated_token) if not only_positives or generated_token.is_positive(): results.append(generated_token)","class Model: token_analyzer = Analyzer(self.__analyzer_rules_set) for sent in doc.sents: for token in sent: generated_token = Token(token.lemma_, token.is_oov, token.pos_, token.sent, token.sentiment, token.tag_, token.text) token_analyzer.analyze_token(generated_token) if not only_positives or generated_token.is_positive(): results.append(generated_token)" 2367,https://:@github.com/axelfahy/bff.git,0023bab225d0c2571fb47e12a1edf19d61396a5d,"@@ -602,7 +602,7 @@ def plot_series(df: pd.DataFrame, column: str, groupby: str = '1S', .mean() .resample(groupby) .apply(sem) - if groupby == 'S' and groupby != '1S' else + if groupby != 'S' and groupby != '1S' else df[column].groupby('datetime').apply(sem)) ax.fill_between(x, df_plot - df_sem, df_plot + df_sem, ",bff/fancy.py,"ReplaceText(target='!=' @(605,33)->(605,35))","def plot_series(df: pd.DataFrame, column: str, groupby: str = '1S', .mean() .resample(groupby) .apply(sem) if groupby == 'S' and groupby != '1S' else df[column].groupby('datetime').apply(sem)) ax.fill_between(x, df_plot - df_sem, df_plot + df_sem,","def plot_series(df: pd.DataFrame, column: str, groupby: str = '1S', .mean() .resample(groupby) .apply(sem) if groupby != 'S' and groupby != '1S' else df[column].groupby('datetime').apply(sem)) ax.fill_between(x, df_plot - df_sem, df_plot + df_sem," 2368,https://:@github.com/GearPlug/mercadolibre-python.git,3b0fa8eb47a81093e884a5699c2d25a1c700b1d0,"@@ -401,7 +401,7 @@ class Client(object): _params = {'access_token': self.access_token} if params: _params.update(params) - response = requests.request(method, self.BASE_URL + endpoint, params=params, **kwargs) + response = requests.request(method, self.BASE_URL + endpoint, params=_params, **kwargs) return self._parse(response) def _parse(self, response): ",mercadolibre/client.py,"ReplaceText(target='_params' @(404,77)->(404,83))","class Client(object): _params = {'access_token': self.access_token} if params: _params.update(params) response = requests.request(method, self.BASE_URL + endpoint, params=params, **kwargs) return self._parse(response) def _parse(self, response):","class Client(object): _params = {'access_token': self.access_token} if params: _params.update(params) response = requests.request(method, self.BASE_URL + endpoint, params=_params, **kwargs) return self._parse(response) def _parse(self, response):" 2369,https://:@bitbucket.org/jairhul/pytransport.git,1b8a3ebc993ea9e74429198fa3607e1bfe537601,"@@ -270,7 +270,7 @@ def RemoveIllegals(line): """""" illegal = ['""', '', '(', ')'] - linelist = [element for element in line if element in illegal] + linelist = [element for element in line if element not in illegal] line = _np.array(linelist) return line ",pytransport/_General.py,"ReplaceText(target=' not in ' @(273,54)->(273,58))","def RemoveIllegals(line): """""" illegal = ['""', '', '(', ')'] linelist = [element for element in line if element in illegal] line = _np.array(linelist) return line ","def RemoveIllegals(line): """""" illegal = ['""', '', '(', ')'] linelist = [element for element in line if element not in illegal] line = _np.array(linelist) return line " 2370,https://:@github.com/lsst-sqre/jupyterlabdemo.git,f6240ef0aeebdfe6e62c3f1bcf79a0fb085febd6,"@@ -480,7 +480,7 @@ class LSSTSpawner(namespacedkubespawner.NamespacedKubeSpawner): for vol in vollist: volname = self._get_volume_name_for_mountpoint(vol[""mountpoint""]) shortname = vol[""mountpoint""][1:].replace(""/"", ""-"") - if volname in already_vols: + if shortname in already_vols: self.log.info( ""Volume '{}' already exists for pod."".format(volname)) continue ",jupyterhub/sample_configs/20-spawner.py,"ReplaceText(target='shortname' @(483,15)->(483,22))","class LSSTSpawner(namespacedkubespawner.NamespacedKubeSpawner): for vol in vollist: volname = self._get_volume_name_for_mountpoint(vol[""mountpoint""]) shortname = vol[""mountpoint""][1:].replace(""/"", ""-"") if volname in already_vols: self.log.info( ""Volume '{}' already exists for pod."".format(volname)) continue","class LSSTSpawner(namespacedkubespawner.NamespacedKubeSpawner): for vol in vollist: volname = self._get_volume_name_for_mountpoint(vol[""mountpoint""]) shortname = vol[""mountpoint""][1:].replace(""/"", ""-"") if shortname in already_vols: self.log.info( ""Volume '{}' already exists for pod."".format(volname)) continue" 2371,https://:@github.com/pyfarm/pyfarm-core.git,66dacd9725338a5f49d12ccee0e0ec8f9e5f8068,"@@ -68,7 +68,7 @@ class Task(TaskModel): def __init__(self, job, frame, parent_task=None, state=None, priority=None, attempts=None, agent=None): # build parent job id - if not modelfor(job, TABLE_JOB): + if modelfor(job, TABLE_JOB): jobid = job.jobid if jobid is None: raise ValueError(""`job` with null id provided"") ",models/task.py,"ReplaceText(target='' @(71,11)->(71,15))","class Task(TaskModel): def __init__(self, job, frame, parent_task=None, state=None, priority=None, attempts=None, agent=None): # build parent job id if not modelfor(job, TABLE_JOB): jobid = job.jobid if jobid is None: raise ValueError(""`job` with null id provided"")","class Task(TaskModel): def __init__(self, job, frame, parent_task=None, state=None, priority=None, attempts=None, agent=None): # build parent job id if modelfor(job, TABLE_JOB): jobid = job.jobid if jobid is None: raise ValueError(""`job` with null id provided"")" 2372,https://:@github.com/pyfarm/pyfarm-core.git,47a4cc9232a09974dea7f246b96d0338a4a4339b,"@@ -116,5 +116,5 @@ class Task(TaskModel): if priority is not None: self.priority = priority - if attempts is None: + if attempts is not None: self.attempts = attempts ",models/task.py,"ReplaceText(target=' is not ' @(119,19)->(119,23))","class Task(TaskModel): if priority is not None: self.priority = priority if attempts is None: self.attempts = attempts","class Task(TaskModel): if priority is not None: self.priority = priority if attempts is not None: self.attempts = attempts" 2373,https://:@github.com/amarouane-ABDLHAK/cumulus-process-py.git,3955f6f5628f0b5233ad19cf54303bd164f981f1,"@@ -85,7 +85,7 @@ class Granule(object): m = re.match(self.inputs[f], os.path.basename(filename)) if m is not None: # does the file exist locally - if os.path.exists(f): + if os.path.exists(filename): self.local_in[f] = filename else: self.remote_in[f] = filename ",cumulus/granule.py,"ReplaceText(target='filename' @(88,34)->(88,35))","class Granule(object): m = re.match(self.inputs[f], os.path.basename(filename)) if m is not None: # does the file exist locally if os.path.exists(f): self.local_in[f] = filename else: self.remote_in[f] = filename","class Granule(object): m = re.match(self.inputs[f], os.path.basename(filename)) if m is not None: # does the file exist locally if os.path.exists(filename): self.local_in[f] = filename else: self.remote_in[f] = filename" 2374,https://:@github.com/CodeClubLux/TopCompiler.git,ec1cbd020e522f8e478000d7d898003972e11490,"@@ -14,7 +14,7 @@ class Enum(Node): args = self.const[name] names = [codegen.getName() for _ in args] codegen.inFunction() - if len(args) > 0: + if len(names) > 0: codegen.append(""function ""+self.package+""_""+name+""("") codegen.append("","".join(names)) codegen.append(""){return [""+str(count)+"",""+"","".join(names)+""]}"") ",AST/Enum.py,"ReplaceText(target='names' @(17,19)->(17,23))","class Enum(Node): args = self.const[name] names = [codegen.getName() for _ in args] codegen.inFunction() if len(args) > 0: codegen.append(""function ""+self.package+""_""+name+""("") codegen.append("","".join(names)) codegen.append(""){return [""+str(count)+"",""+"","".join(names)+""]}"")","class Enum(Node): args = self.const[name] names = [codegen.getName() for _ in args] codegen.inFunction() if len(names) > 0: codegen.append(""function ""+self.package+""_""+name+""("") codegen.append("","".join(names)) codegen.append(""){return [""+str(count)+"",""+"","".join(names)+""]}"")" 2375,https://:@github.com/GIScience/openpoiservice.git,5a686db7a201b52f836e824910d9218bd2ff790b,"@@ -171,7 +171,7 @@ class QueryBuilder(object): if tag in filters: - filters.append(query.c.key == tag.lower()) + filters_list.append(query.c.key == tag.lower()) if settings['filterable'] == 'like': filters_list.append(query.c.value.like('%' + filters[tag].lower() + '%')) ",openpoiservice/server/api/query_builder.py,"ReplaceText(target='filters_list' @(174,16)->(174,23))","class QueryBuilder(object): if tag in filters: filters.append(query.c.key == tag.lower()) if settings['filterable'] == 'like': filters_list.append(query.c.value.like('%' + filters[tag].lower() + '%'))","class QueryBuilder(object): if tag in filters: filters_list.append(query.c.key == tag.lower()) if settings['filterable'] == 'like': filters_list.append(query.c.value.like('%' + filters[tag].lower() + '%'))" 2376,https://:@github.com/theblackcat102/jieba-tw.git,5270ed66ff64b2001c1bf5c4ba927fec09189e33,"@@ -366,7 +366,7 @@ class Tokenizer(object): f = open(f, 'rb') for lineno, ln in enumerate(f, 1): line = ln.strip() - if not isinstance(f, text_type): + if not isinstance(line, text_type): try: line = line.decode('utf-8').lstrip('\ufeff') except UnicodeDecodeError: ",jieba/__init__.py,"ReplaceText(target='line' @(369,30)->(369,31))","class Tokenizer(object): f = open(f, 'rb') for lineno, ln in enumerate(f, 1): line = ln.strip() if not isinstance(f, text_type): try: line = line.decode('utf-8').lstrip('\ufeff') except UnicodeDecodeError:","class Tokenizer(object): f = open(f, 'rb') for lineno, ln in enumerate(f, 1): line = ln.strip() if not isinstance(line, text_type): try: line = line.decode('utf-8').lstrip('\ufeff') except UnicodeDecodeError:" 2377,https://:@github.com/mozilla/measure-noise.git,b100399b2d650a794f50c897dfb2ec3462ad814f,"@@ -103,7 +103,7 @@ def process( # EG https://treeherder.mozilla.org/perf.html#/graphs?highlightAlerts=1&series=mozilla-central,fee739b45f7960e4a520d8e0bd781dd9d0a3bec4,1,10&timerange=31536000 url = ""https://treeherder.mozilla.org/perf.html#/graphs?"" + value2url_param({ ""highlightAlerts"": 1, - ""series"": [sig.repository, sig.id, 1, coalesce(sig.framework, sig.framework_id)], + ""series"": [sig.repository, sig.id, 1, coalesce(sig.framework_id, sig.framework)], ""timerange"": 31536000, }) ",measure_noise/analysis.py,"ArgSwap(idxs=0<->1 @(106,46)->(106,54))","def process( # EG https://treeherder.mozilla.org/perf.html#/graphs?highlightAlerts=1&series=mozilla-central,fee739b45f7960e4a520d8e0bd781dd9d0a3bec4,1,10&timerange=31536000 url = ""https://treeherder.mozilla.org/perf.html#/graphs?"" + value2url_param({ ""highlightAlerts"": 1, ""series"": [sig.repository, sig.id, 1, coalesce(sig.framework, sig.framework_id)], ""timerange"": 31536000, }) ","def process( # EG https://treeherder.mozilla.org/perf.html#/graphs?highlightAlerts=1&series=mozilla-central,fee739b45f7960e4a520d8e0bd781dd9d0a3bec4,1,10&timerange=31536000 url = ""https://treeherder.mozilla.org/perf.html#/graphs?"" + value2url_param({ ""highlightAlerts"": 1, ""series"": [sig.repository, sig.id, 1, coalesce(sig.framework_id, sig.framework)], ""timerange"": 31536000, }) " 2378,https://:@github.com/USGS-WiM/WIMLib.git,f9f74b29ed1dfc901b31e3df81f9f2459918dc4e,"@@ -93,7 +93,7 @@ class MapLayer(object): raise Exception(datasetPath +"" doesn't exist"") #test for schema lock, before continue trys=0 - while arcpy.TestSchemaLock(datasetPath) or trys>6: + while arcpy.TestSchemaLock(datasetPath) or trys<6: time.sleep(10) trys+=1 #next ",WIMLib/MapLayer.py,"ReplaceText(target='<' @(96,59)->(96,60))","class MapLayer(object): raise Exception(datasetPath +"" doesn't exist"") #test for schema lock, before continue trys=0 while arcpy.TestSchemaLock(datasetPath) or trys>6: time.sleep(10) trys+=1 #next","class MapLayer(object): raise Exception(datasetPath +"" doesn't exist"") #test for schema lock, before continue trys=0 while arcpy.TestSchemaLock(datasetPath) or trys<6: time.sleep(10) trys+=1 #next" 2379,https://:@github.com/xiawu/newchain-web3.py.git,b253f8a8d55a087800e8e5b0947e7972a1f8258d,"@@ -31,7 +31,7 @@ def pad_right(string, chars, filler=""0""): def is_prefixed(value, prefix): return value.startswith( - force_bytes(prefix) if is_bytes(prefix) else force_text(prefix) + force_bytes(prefix) if is_bytes(value) else force_text(prefix) ) ",web3/utils/formatting.py,"ReplaceText(target='value' @(34,40)->(34,46))","def pad_right(string, chars, filler=""0""): def is_prefixed(value, prefix): return value.startswith( force_bytes(prefix) if is_bytes(prefix) else force_text(prefix) ) ","def pad_right(string, chars, filler=""0""): def is_prefixed(value, prefix): return value.startswith( force_bytes(prefix) if is_bytes(value) else force_text(prefix) ) " 2380,https://:@github.com/xiawu/newchain-web3.py.git,6c2e459fbb1c3e9cf665b8138744510f2f797149,"@@ -143,7 +143,7 @@ def outputBlockFormatter(block): if is_array(block.get(""transactions"")): for item in block[""transactions""]: - if is_string(item): + if not is_string(item): item = outputTransactionFormatter(item) return block ",web3/formatters.py,"ReplaceText(target='not ' @(146,15)->(146,15))","def outputBlockFormatter(block): if is_array(block.get(""transactions"")): for item in block[""transactions""]: if is_string(item): item = outputTransactionFormatter(item) return block","def outputBlockFormatter(block): if is_array(block.get(""transactions"")): for item in block[""transactions""]: if not is_string(item): item = outputTransactionFormatter(item) return block" 2381,https://:@github.com/xiawu/newchain-web3.py.git,9f8282b202f17f1e98a305b49657b7ff2387b85a,"@@ -611,7 +611,7 @@ def call_contract_function(contract=None, if transaction is None: call_transaction = {} else: - call_transaction = dict(**call_transaction) + call_transaction = dict(**transaction) if not arguments: arguments = [] ",web3/contract.py,"ReplaceText(target='transaction' @(614,34)->(614,50))","def call_contract_function(contract=None, if transaction is None: call_transaction = {} else: call_transaction = dict(**call_transaction) if not arguments: arguments = []","def call_contract_function(contract=None, if transaction is None: call_transaction = {} else: call_transaction = dict(**transaction) if not arguments: arguments = []" 2382,https://:@github.com/Elizafox/taillight.git,731c28874dd7aa29f59a862e6b01f4ea8010978e,"@@ -131,7 +131,7 @@ class Signal: with self._slots_lock: for slot in self.slots: if slot.function is function: - ret.append(function) + ret.append(slot) if ret: return ret ",taillight/signal.py,"ReplaceText(target='slot' @(134,31)->(134,39))","class Signal: with self._slots_lock: for slot in self.slots: if slot.function is function: ret.append(function) if ret: return ret","class Signal: with self._slots_lock: for slot in self.slots: if slot.function is function: ret.append(slot) if ret: return ret" 2383,https://:@github.com/Fak3/minidjango.git,659ab9846e81d95bb75dbb3c00147324bf0d6541,"@@ -22,7 +22,7 @@ def login(request): else: errors = {} response = HttpResponse() - response.session.set_test_cookie() + request.session.set_test_cookie() t = template_loader.get_template('registration/login') c = Context(request, { 'form': formfields.FormWrapper(manipulator, request.POST, errors), ",django/views/auth/login.py,"ReplaceText(target='request' @(25,4)->(25,12))","def login(request): else: errors = {} response = HttpResponse() response.session.set_test_cookie() t = template_loader.get_template('registration/login') c = Context(request, { 'form': formfields.FormWrapper(manipulator, request.POST, errors),","def login(request): else: errors = {} response = HttpResponse() request.session.set_test_cookie() t = template_loader.get_template('registration/login') c = Context(request, { 'form': formfields.FormWrapper(manipulator, request.POST, errors)," 2384,https://:@github.com/Fak3/minidjango.git,34655a3e7816d6a8e5da6b3fd613b49b454a4691,"@@ -227,7 +227,7 @@ class DateFormat(TimeFormat): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) - week_number = j / 7 + week_number = j // 7 if jan1_weekday > 4: week_number -= 1 return week_number ",django/utils/dateformat.py,"ReplaceText(target='//' @(230,32)->(230,33))","class DateFormat(TimeFormat): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j / 7 if jan1_weekday > 4: week_number -= 1 return week_number","class DateFormat(TimeFormat): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j // 7 if jan1_weekday > 4: week_number -= 1 return week_number" 2385,https://:@github.com/Fak3/minidjango.git,a97648a7e03fb95b09e888e5d59d82d57fb289b7,"@@ -105,7 +105,7 @@ class DecoratorsTest(TestCase): """""" def my_view(request): return ""response"" - my_view_cached = cache_page(123, my_view) + my_view_cached = cache_page(my_view, 123) self.assertEqual(my_view_cached(HttpRequest()), ""response"") class MethodDecoratorAdapterTests(TestCase): ",tests/regressiontests/decorators/tests.py,"ArgSwap(idxs=0<->1 @(108,25)->(108,35))","class DecoratorsTest(TestCase): """""" def my_view(request): return ""response"" my_view_cached = cache_page(123, my_view) self.assertEqual(my_view_cached(HttpRequest()), ""response"") class MethodDecoratorAdapterTests(TestCase):","class DecoratorsTest(TestCase): """""" def my_view(request): return ""response"" my_view_cached = cache_page(my_view, 123) self.assertEqual(my_view_cached(HttpRequest()), ""response"") class MethodDecoratorAdapterTests(TestCase):" 2386,https://:@github.com/Fak3/minidjango.git,b2050ff546da4164f90a795e55d7d8c55981783d,"@@ -169,7 +169,7 @@ class SQLCompiler(object): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] - if table in only_load and col not in only_load[table]: + if table in only_load and column not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases: ",django/db/models/sql/compiler.py,"ReplaceText(target='column' @(172,46)->(172,49))","class SQLCompiler(object): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and col not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases:","class SQLCompiler(object): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and column not in only_load[table]: continue r = '%s.%s' % (qn(alias), qn(column)) if with_aliases:" 2387,https://:@github.com/Fak3/minidjango.git,cfba2460370a6d1808b78e2ba0709ea5c8b7e773,"@@ -42,7 +42,7 @@ def check_settings(base_url=None): Checks if the staticfiles settings have sane values. """""" - if base_url is not None: + if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured( ",django/contrib/staticfiles/utils.py,"ReplaceText(target=' is ' @(45,15)->(45,23))","def check_settings(base_url=None): Checks if the staticfiles settings have sane values. """""" if base_url is not None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured(","def check_settings(base_url=None): Checks if the staticfiles settings have sane values. """""" if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured(" 2388,https://:@github.com/Fak3/minidjango.git,d72d5ce8274992ce01e39f866a7a250bc459eefe,"@@ -37,7 +37,7 @@ class GeoSQLCompiler(compiler.SQLCompiler): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] - if table in only_load and col not in only_load[table]: + if table in only_load and column not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases: ",django/contrib/gis/db/models/sql/compiler.py,"ReplaceText(target='column' @(40,46)->(40,49))","class GeoSQLCompiler(compiler.SQLCompiler): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and col not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases:","class GeoSQLCompiler(compiler.SQLCompiler): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and column not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases:" 2389,https://:@github.com/Fak3/minidjango.git,6ecbac21a9017a53fe18ac81c9c1d2f28185a292,"@@ -111,5 +111,5 @@ class OSMWidget(BaseGeometryWidget): return 900913 def render(self, name, value, attrs=None): - return super(self, OSMWidget).render(name, value, + return super(OSMWidget, self).render(name, value, {'default_lon': self.default_lon, 'default_lat': self.default_lat}) ",django/contrib/gis/forms/widgets.py,"ArgSwap(idxs=0<->1 @(114,15)->(114,20))","class OSMWidget(BaseGeometryWidget): return 900913 def render(self, name, value, attrs=None): return super(self, OSMWidget).render(name, value, {'default_lon': self.default_lon, 'default_lat': self.default_lat})","class OSMWidget(BaseGeometryWidget): return 900913 def render(self, name, value, attrs=None): return super(OSMWidget, self).render(name, value, {'default_lon': self.default_lon, 'default_lat': self.default_lat})" 2390,https://:@github.com/Fak3/minidjango.git,86c248aa646183ef4a1cb407bb3e4cb597272f63,"@@ -575,7 +575,7 @@ class SQLCompiler(object): for order, order_params in ordering_group_by: # Even if we have seen the same SQL string, it might have # different params, so, we add same SQL in ""has params"" case. - if order not in seen or params: + if order not in seen or order_params: result.append(order) params.extend(order_params) seen.add(order) ",django/db/models/sql/compiler.py,"ReplaceText(target='order_params' @(578,44)->(578,50))","class SQLCompiler(object): for order, order_params in ordering_group_by: # Even if we have seen the same SQL string, it might have # different params, so, we add same SQL in ""has params"" case. if order not in seen or params: result.append(order) params.extend(order_params) seen.add(order)","class SQLCompiler(object): for order, order_params in ordering_group_by: # Even if we have seen the same SQL string, it might have # different params, so, we add same SQL in ""has params"" case. if order not in seen or order_params: result.append(order) params.extend(order_params) seen.add(order)" 2391,https://:@github.com/Fak3/minidjango.git,fddb0131d37109c809ec391e1a134ef1d9e442a7,"@@ -57,7 +57,7 @@ def check_password(password, encoded, setter=None, preferred='default'): must_update = hasher.algorithm != preferred.algorithm if not must_update: - must_update = hasher.must_update(encoded) + must_update = preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) if setter and is_correct and must_update: setter(password) ",django/contrib/auth/hashers.py,"ReplaceText(target='preferred' @(60,22)->(60,28))","def check_password(password, encoded, setter=None, preferred='default'): must_update = hasher.algorithm != preferred.algorithm if not must_update: must_update = hasher.must_update(encoded) is_correct = hasher.verify(password, encoded) if setter and is_correct and must_update: setter(password)","def check_password(password, encoded, setter=None, preferred='default'): must_update = hasher.algorithm != preferred.algorithm if not must_update: must_update = preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) if setter and is_correct and must_update: setter(password)" 2392,https://:@github.com/Fak3/minidjango.git,e8223b889aab3b5ac0c2312eb9ee2307ea635c97,"@@ -228,7 +228,7 @@ class GenericRelationTests(TestCase): # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) - self.assertEqual(qs[0].links__sum, l.id) + self.assertEqual(qs[0].links__sum, hs1.id) l.delete() # Now if we don't have proper left join, we will not produce any # results at all here. ",tests/generic_relations_regress/tests.py,"ReplaceText(target='hs1' @(231,43)->(231,44))","class GenericRelationTests(TestCase): # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].links__sum, l.id) l.delete() # Now if we don't have proper left join, we will not produce any # results at all here.","class GenericRelationTests(TestCase): # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].links__sum, hs1.id) l.delete() # Now if we don't have proper left join, we will not produce any # results at all here." 2393,https://:@github.com/Fak3/minidjango.git,3074c5b19e2da5f7a5359c3cf3c5308eb194cdf9,"@@ -112,7 +112,7 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): - super(cls, ClassDecoratedTestCase).setUpClass() + super(ClassDecoratedTestCase, cls).setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self): ",tests/settings_tests/tests.py,"ArgSwap(idxs=0<->1 @(115,8)->(115,13))","class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): super(cls, ClassDecoratedTestCase).setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self):","class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): super(ClassDecoratedTestCase, cls).setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self):" 2394,https://:@github.com/Fak3/minidjango.git,c2b4967e76fd671e6199e4dd54d2a2c1f096b8eb,"@@ -23,7 +23,7 @@ def import_string(dotted_path): return getattr(module, class_name) except AttributeError: msg = 'Module ""%s"" does not define a ""%s"" attribute/class' % ( - dotted_path, class_name) + module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) ",django/utils/module_loading.py,"ReplaceText(target='module_path' @(26,12)->(26,23))","def import_string(dotted_path): return getattr(module, class_name) except AttributeError: msg = 'Module ""%s"" does not define a ""%s"" attribute/class' % ( dotted_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) ","def import_string(dotted_path): return getattr(module, class_name) except AttributeError: msg = 'Module ""%s"" does not define a ""%s"" attribute/class' % ( module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) " 2395,https://:@github.com/Fak3/minidjango.git,abcdb237bb313d116ce2ac8e90f79f61429afc70,"@@ -31,7 +31,7 @@ class DatabaseCreation(BaseDatabaseCreation): try: if verbosity >= 1: print(""Destroying old test database for alias %s..."" % ( - self._get_database_display_str(target_database_name, verbosity), + self._get_database_display_str(verbosity, target_database_name), )) cursor.execute(""DROP DATABASE %s"" % qn(target_database_name)) cursor.execute(""CREATE DATABASE %s"" % qn(target_database_name)) ",django/db/backends/mysql/creation.py,"ArgSwap(idxs=0<->1 @(34,28)->(34,58))","class DatabaseCreation(BaseDatabaseCreation): try: if verbosity >= 1: print(""Destroying old test database for alias %s..."" % ( self._get_database_display_str(target_database_name, verbosity), )) cursor.execute(""DROP DATABASE %s"" % qn(target_database_name)) cursor.execute(""CREATE DATABASE %s"" % qn(target_database_name))","class DatabaseCreation(BaseDatabaseCreation): try: if verbosity >= 1: print(""Destroying old test database for alias %s..."" % ( self._get_database_display_str(verbosity, target_database_name), )) cursor.execute(""DROP DATABASE %s"" % qn(target_database_name)) cursor.execute(""CREATE DATABASE %s"" % qn(target_database_name))" 2396,https://:@github.com/Fak3/minidjango.git,542b7f6c50df18f2aa201cf1de81577c1bee643c,"@@ -50,7 +50,7 @@ class SeparateDatabaseAndState(Operation): to_state = base_state.clone() for dbop in self.database_operations[:-(pos + 1)]: dbop.state_forwards(app_label, to_state) - from_state = base_state.clone() + from_state = to_state.clone() database_operation.state_forwards(app_label, from_state) database_operation.database_backwards(app_label, schema_editor, from_state, to_state) ",django/db/migrations/operations/special.py,"ReplaceText(target='to_state' @(53,25)->(53,35))","class SeparateDatabaseAndState(Operation): to_state = base_state.clone() for dbop in self.database_operations[:-(pos + 1)]: dbop.state_forwards(app_label, to_state) from_state = base_state.clone() database_operation.state_forwards(app_label, from_state) database_operation.database_backwards(app_label, schema_editor, from_state, to_state) ","class SeparateDatabaseAndState(Operation): to_state = base_state.clone() for dbop in self.database_operations[:-(pos + 1)]: dbop.state_forwards(app_label, to_state) from_state = to_state.clone() database_operation.state_forwards(app_label, from_state) database_operation.database_backwards(app_label, schema_editor, from_state, to_state) " 2397,https://:@github.com/Fak3/minidjango.git,d5088f838d837fc9e3109c828f18511055f20bea,"@@ -383,7 +383,7 @@ class CombinedExpression(Expression): return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection) if (lhs_output and rhs_output and self.connector == self.SUB and lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and - lhs_output.get_internal_type() == lhs_output.get_internal_type()): + lhs_output.get_internal_type() == rhs_output.get_internal_type()): return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection) expressions = [] expression_params = [] ",django/db/models/expressions.py,"ReplaceText(target='rhs_output' @(386,50)->(386,60))","class CombinedExpression(Expression): return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection) if (lhs_output and rhs_output and self.connector == self.SUB and lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and lhs_output.get_internal_type() == lhs_output.get_internal_type()): return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection) expressions = [] expression_params = []","class CombinedExpression(Expression): return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection) if (lhs_output and rhs_output and self.connector == self.SUB and lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and lhs_output.get_internal_type() == rhs_output.get_internal_type()): return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection) expressions = [] expression_params = []" 2398,https://:@github.com/Fak3/minidjango.git,67a6ba391bbcf1a4c6bb0c42cb17e4fc0530f6d2,"@@ -42,7 +42,7 @@ class PasswordResetTokenGenerator: return False # Check the timestamp is within limit - if (self._num_days(self._today()) - ts) >= settings.PASSWORD_RESET_TIMEOUT_DAYS: + if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True ",django/contrib/auth/tokens.py,"ReplaceText(target='>' @(45,48)->(45,50))","class PasswordResetTokenGenerator: return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) >= settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True","class PasswordResetTokenGenerator: return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS: return False return True" 2399,https://:@github.com/Fak3/minidjango.git,acc8dd4142ec81def9a73507120c0262ba6b1264,"@@ -60,7 +60,7 @@ class RWLock: def writer_enters(self): with self.mutex: if self.active_writers == 0 and self.waiting_writers == 0 and self.active_readers == 0: - self.active_writers += 1 + self.active_writers = 1 self.can_write.release() else: self.waiting_writers += 1 ",django/utils/synch.py,"ReplaceText(target='=' @(63,36)->(63,38))","class RWLock: def writer_enters(self): with self.mutex: if self.active_writers == 0 and self.waiting_writers == 0 and self.active_readers == 0: self.active_writers += 1 self.can_write.release() else: self.waiting_writers += 1","class RWLock: def writer_enters(self): with self.mutex: if self.active_writers == 0 and self.waiting_writers == 0 and self.active_readers == 0: self.active_writers = 1 self.can_write.release() else: self.waiting_writers += 1" 2400,https://:@github.com/benemery/filewatch.git,3fbf9780eb51d3efe869bfbeb85e7e6bb25f152e,"@@ -58,4 +58,4 @@ class Watcher(object): def _get_key(self, full_path): """"""Build a checksum used to identify this filepath"""""" full_path_checksum = hashlib.sha1(full_path).digest() - return full_path + return full_path_checksum ",filewatch/watcher.py,"ReplaceText(target='full_path_checksum' @(61,15)->(61,24))","class Watcher(object): def _get_key(self, full_path): """"""Build a checksum used to identify this filepath"""""" full_path_checksum = hashlib.sha1(full_path).digest() return full_path","class Watcher(object): def _get_key(self, full_path): """"""Build a checksum used to identify this filepath"""""" full_path_checksum = hashlib.sha1(full_path).digest() return full_path_checksum" 2401,https://:@github.com/akrzos/collectd-swift-stat.git,59c358b8b3b5c90fe62fa2157ece5fc2be480535,"@@ -47,7 +47,7 @@ def read(data=None): metric.plugin = 'swift_stat' metric.interval = INTERVAL metric.type = 'gauge' - metric.type_instance = m_instance + metric.type_instance = name metric.values = [stats[m_instance]] metric.dispatch() else: ",collectd_swift_stat/__init__.py,"ReplaceText(target='name' @(50,35)->(50,45))","def read(data=None): metric.plugin = 'swift_stat' metric.interval = INTERVAL metric.type = 'gauge' metric.type_instance = m_instance metric.values = [stats[m_instance]] metric.dispatch() else:","def read(data=None): metric.plugin = 'swift_stat' metric.interval = INTERVAL metric.type = 'gauge' metric.type_instance = name metric.values = [stats[m_instance]] metric.dispatch() else:" 2402,https://:@github.com/luidale/starpa.git,5abc255ec0b0e4a08b2df4ce43687bd8725c840f,"@@ -260,7 +260,7 @@ class identify(): #index bam samtools_index_command = ( settings[""samtools_call""], ""index"", - length_split_bam + strand_split_bam ) os.system("" "".join(samtools_index_command)) ",src/starpa/identify.py,"ReplaceText(target='strand_split_bam' @(263,16)->(263,32))","class identify(): #index bam samtools_index_command = ( settings[""samtools_call""], ""index"", length_split_bam ) os.system("" "".join(samtools_index_command))","class identify(): #index bam samtools_index_command = ( settings[""samtools_call""], ""index"", strand_split_bam ) os.system("" "".join(samtools_index_command))" 2403,https://:@github.com/luidale/starpa.git,1b6ffa79af68393e10d9bfb610f5a8e4427d4247,"@@ -693,7 +693,7 @@ class identify(): input_bam # input_bam, ""2>"", featurecounts_info ) - with open(output_SAF) as f_out: + with open(input_SAF) as f_out: for line in f_out: print(line) ",src/starpa/identify.py,"ReplaceText(target='input_SAF' @(696,18)->(696,28))","class identify(): input_bam # input_bam, ""2>"", featurecounts_info ) with open(output_SAF) as f_out: for line in f_out: print(line) ","class identify(): input_bam # input_bam, ""2>"", featurecounts_info ) with open(input_SAF) as f_out: for line in f_out: print(line) " 2404,https://:@github.com/luidale/starpa.git,9d0b06a03151b6790c58e244b1dc9b420b1e5480,"@@ -850,7 +850,7 @@ class quantify(): for j,pos in enumerate(genomic_seq): if pos == ""*"": genomic_seq_conv.append(""*"") - elif pos == consensus_seq[i]: + elif pos == consensus_seq[j]: genomic_seq_conv.append(""."") else: genomic_seq_conv.append(pos) ",src/starpa/quantify.py,"ReplaceText(target='j' @(853,42)->(853,43))","class quantify(): for j,pos in enumerate(genomic_seq): if pos == ""*"": genomic_seq_conv.append(""*"") elif pos == consensus_seq[i]: genomic_seq_conv.append(""."") else: genomic_seq_conv.append(pos)","class quantify(): for j,pos in enumerate(genomic_seq): if pos == ""*"": genomic_seq_conv.append(""*"") elif pos == consensus_seq[j]: genomic_seq_conv.append(""."") else: genomic_seq_conv.append(pos)" 2405,https://:@github.com/chris17453/python-vipaccess.git,91818b4487f75b3de8758e5634b9f1661cab720e,"@@ -120,7 +120,7 @@ def main(): help=""Specify the token secret on the command line (base32 encoded)"") m.add_argument('-f', '--dotfile', type=PathType(exists=True), default=os.path.expanduser('~/.vipaccess'), help=""File in which the credential is stored (default ~/.vipaccess"") - m.add_argument('-v', '--verbose', action='store_true') + pshow.add_argument('-v', '--verbose', action='store_true') pshow.set_defaults(func=show) p.set_default_subparser('show') ",vipaccess/cli.py,"ReplaceText(target='pshow' @(123,4)->(123,5))","def main(): help=""Specify the token secret on the command line (base32 encoded)"") m.add_argument('-f', '--dotfile', type=PathType(exists=True), default=os.path.expanduser('~/.vipaccess'), help=""File in which the credential is stored (default ~/.vipaccess"") m.add_argument('-v', '--verbose', action='store_true') pshow.set_defaults(func=show) p.set_default_subparser('show')","def main(): help=""Specify the token secret on the command line (base32 encoded)"") m.add_argument('-f', '--dotfile', type=PathType(exists=True), default=os.path.expanduser('~/.vipaccess'), help=""File in which the credential is stored (default ~/.vipaccess"") pshow.add_argument('-v', '--verbose', action='store_true') pshow.set_defaults(func=show) p.set_default_subparser('show')" 2406,https://:@github.com/thrau/pymq.git,3b7c4e61b1e5a9387085ac91448070df0a8b6f73,"@@ -233,7 +233,7 @@ class AbstractEventBus(EventBus, abc.ABC): callbacks = self._subscribers.get((channel, pattern)) - if callback: + if callbacks: callbacks.remove(callback) if len(callbacks) == 0: del self._subscribers[(channel, pattern)] ",pymq/provider/base.py,"ReplaceText(target='callbacks' @(236,11)->(236,19))","class AbstractEventBus(EventBus, abc.ABC): callbacks = self._subscribers.get((channel, pattern)) if callback: callbacks.remove(callback) if len(callbacks) == 0: del self._subscribers[(channel, pattern)]","class AbstractEventBus(EventBus, abc.ABC): callbacks = self._subscribers.get((channel, pattern)) if callbacks: callbacks.remove(callback) if len(callbacks) == 0: del self._subscribers[(channel, pattern)]" 2407,https://:@github.com/DFE/MONK.git,3b791f19cdc3176fa917ec66fec8d31d1fc05141,"@@ -89,7 +89,7 @@ class Device(object): ""awk '{print $1}'"",])) ips = out.split(""\n"") if out and not out.startswith(""127.0.0.1""): - self._logger.debug(""found IP addresses:"" + str(out)) + self._logger.debug(""found IP addresses:"" + str(ips)) return out.split('\n') else: raise NoIPException(""couldn't receive any IP address:'{}'"".format( ",monk_tf/dev.py,"ReplaceText(target='ips' @(92,59)->(92,62))","class Device(object): ""awk '{print $1}'"",])) ips = out.split(""\n"") if out and not out.startswith(""127.0.0.1""): self._logger.debug(""found IP addresses:"" + str(out)) return out.split('\n') else: raise NoIPException(""couldn't receive any IP address:'{}'"".format(","class Device(object): ""awk '{print $1}'"",])) ips = out.split(""\n"") if out and not out.startswith(""127.0.0.1""): self._logger.debug(""found IP addresses:"" + str(ips)) return out.split('\n') else: raise NoIPException(""couldn't receive any IP address:'{}'"".format(" 2408,https://:@github.com/mush42/oy-cms.git,9ca054ae384ec1ab1efee4aead448b647662176f,"@@ -79,7 +79,7 @@ class Page(StarlitModule): return rv def set_page_and_response_if_appropriate(self): - if isinstance(request.routing_exception, NotFound) and current_page: + if not isinstance(request.routing_exception, NotFound) and current_page: return self.page_view() def _add_contenttype_handler( ",starlit/contrib/page/__init__.py,"ReplaceText(target='not ' @(82,11)->(82,11))","class Page(StarlitModule): return rv def set_page_and_response_if_appropriate(self): if isinstance(request.routing_exception, NotFound) and current_page: return self.page_view() def _add_contenttype_handler(","class Page(StarlitModule): return rv def set_page_and_response_if_appropriate(self): if not isinstance(request.routing_exception, NotFound) and current_page: return self.page_view() def _add_contenttype_handler(" 2409,https://:@github.com/Brian-Williams/robotframework-testlink.git,1a86edf13d65fc36c268b4f600f937303ccd778b,"@@ -29,7 +29,7 @@ class RobotTestLinkHelper(TestLinkHelper): def _get_missing_params_from_robot_variables(self, param_dict): for testlink_param, robot_variable in robot_report_params.items(): - setdefault_if_not_none(param_dict, testlink_param, self._get_param_from_robot(testlink_param)) + setdefault_if_not_none(param_dict, testlink_param, self._get_param_from_robot(robot_variable)) def _setParamsFromRobot(self): """""" ",robottestlink/robottestlinkhelper.py,"ReplaceText(target='robot_variable' @(32,90)->(32,104))","class RobotTestLinkHelper(TestLinkHelper): def _get_missing_params_from_robot_variables(self, param_dict): for testlink_param, robot_variable in robot_report_params.items(): setdefault_if_not_none(param_dict, testlink_param, self._get_param_from_robot(testlink_param)) def _setParamsFromRobot(self): """"""","class RobotTestLinkHelper(TestLinkHelper): def _get_missing_params_from_robot_variables(self, param_dict): for testlink_param, robot_variable in robot_report_params.items(): setdefault_if_not_none(param_dict, testlink_param, self._get_param_from_robot(robot_variable)) def _setParamsFromRobot(self): """"""" 2410,https://:@github.com/FRESNA/atlite.git,923bbb453e31e43220f786e48a89266f976d787b,"@@ -160,7 +160,7 @@ def compute_indicatormatrix(orig, dest, orig_proj='latlong', dest_proj='latlong' def maybe_swap_spatial_dims(ds, namex='x', namey='y'): swaps = {} lx, rx = ds.indexes[namex][[0, -1]] - uy, ly = ds.indexes[namex][[0, -1]] + uy, ly = ds.indexes[namey][[0, -1]] if lx > rx: swaps[namex] = slice(None, None, -1) ",atlite/gis.py,"ReplaceText(target='namey' @(163,24)->(163,29))","def compute_indicatormatrix(orig, dest, orig_proj='latlong', dest_proj='latlong' def maybe_swap_spatial_dims(ds, namex='x', namey='y'): swaps = {} lx, rx = ds.indexes[namex][[0, -1]] uy, ly = ds.indexes[namex][[0, -1]] if lx > rx: swaps[namex] = slice(None, None, -1)","def compute_indicatormatrix(orig, dest, orig_proj='latlong', dest_proj='latlong' def maybe_swap_spatial_dims(ds, namex='x', namey='y'): swaps = {} lx, rx = ds.indexes[namex][[0, -1]] uy, ly = ds.indexes[namey][[0, -1]] if lx > rx: swaps[namex] = slice(None, None, -1)" 2411,https://:@github.com/bpeschier/django-compressor-requirejs.git,cdd6170db7941d8cdc584a832098a2964a4ba2ff,"@@ -96,7 +96,7 @@ class RequireJSCompiler(FilterBase): output = compressor.filter_output(filtered) path = compressor.get_filepath(output, basename=basename) # Write it - compressor.storage.save(path, ContentFile(content.encode(compressor.charset))) + compressor.storage.save(path, ContentFile(output.encode(compressor.charset))) return mark_safe(compressor.storage.url(path)) # ",requirejs/filter.py,"ReplaceText(target='output' @(99,50)->(99,57))","class RequireJSCompiler(FilterBase): output = compressor.filter_output(filtered) path = compressor.get_filepath(output, basename=basename) # Write it compressor.storage.save(path, ContentFile(content.encode(compressor.charset))) return mark_safe(compressor.storage.url(path)) #","class RequireJSCompiler(FilterBase): output = compressor.filter_output(filtered) path = compressor.get_filepath(output, basename=basename) # Write it compressor.storage.save(path, ContentFile(output.encode(compressor.charset))) return mark_safe(compressor.storage.url(path)) #" 2412,https://:@github.com/kemerelab/jagular.git,a192f4fe9b90d49acd6d67d51ae6e08e71fae165,"@@ -385,7 +385,7 @@ class JagularFileMap(object): timestamps = timestamps + timestamps_ # list concatenation channel_data = np.hstack((channel_data, channel_data_)) if timestamps: - yield timestamps, channel_data_ + yield timestamps, channel_data else: ii+=1 except IndexError: ",jagular/io.py,"ReplaceText(target='channel_data' @(388,42)->(388,55))","class JagularFileMap(object): timestamps = timestamps + timestamps_ # list concatenation channel_data = np.hstack((channel_data, channel_data_)) if timestamps: yield timestamps, channel_data_ else: ii+=1 except IndexError:","class JagularFileMap(object): timestamps = timestamps + timestamps_ # list concatenation channel_data = np.hstack((channel_data, channel_data_)) if timestamps: yield timestamps, channel_data else: ii+=1 except IndexError:" 2413,https://:@github.com/lucis-fluxum/matisse-controller.git,3f8ad49e02ea4d6cab798a5828e228242093d3e2,"@@ -54,7 +54,7 @@ class StatusUpdateThread(QThread): slow_pz_pos_text = f""Slow Pz:{slow_pz_pos:.3f}"" refcell_pos_text = f""RefCell:{refcell_pos:.3f}"" stabilizing_text = f""Stabilize:{green_text('ON') if is_stabilizing else red_text('OFF')}"" - scanning_text = f""Scanning:{green_text('ON') if is_stabilizing else red_text('OFF')}"" + scanning_text = f""Scanning:{green_text('ON') if is_scanning else red_text('OFF')}"" locked_text = f""{green_text('LOCKED') if is_locked else red_text('NO LOCK')}"" wavemeter_text = f""Wavemeter:{wavemeter_value}"" ",matisse_controller/gui/threads/status_update_thread.py,"ReplaceText(target='is_scanning' @(57,68)->(57,82))","class StatusUpdateThread(QThread): slow_pz_pos_text = f""Slow Pz:{slow_pz_pos:.3f}"" refcell_pos_text = f""RefCell:{refcell_pos:.3f}"" stabilizing_text = f""Stabilize:{green_text('ON') if is_stabilizing else red_text('OFF')}"" scanning_text = f""Scanning:{green_text('ON') if is_stabilizing else red_text('OFF')}"" locked_text = f""{green_text('LOCKED') if is_locked else red_text('NO LOCK')}"" wavemeter_text = f""Wavemeter:{wavemeter_value}"" ","class StatusUpdateThread(QThread): slow_pz_pos_text = f""Slow Pz:{slow_pz_pos:.3f}"" refcell_pos_text = f""RefCell:{refcell_pos:.3f}"" stabilizing_text = f""Stabilize:{green_text('ON') if is_stabilizing else red_text('OFF')}"" scanning_text = f""Scanning:{green_text('ON') if is_scanning else red_text('OFF')}"" locked_text = f""{green_text('LOCKED') if is_locked else red_text('NO LOCK')}"" wavemeter_text = f""Wavemeter:{wavemeter_value}"" " 2414,https://:@github.com/pozytywnie/raven-python.git,dedca8e5c98124f6a43a18986e142e8cb7ecc3cf,"@@ -59,7 +59,7 @@ def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() - if handler.__class__ not in map(type, logger.handlers): + if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler) ",raven/conf/__init__.py,"ReplaceText(target=' in ' @(62,24)->(62,32))","def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() if handler.__class__ not in map(type, logger.handlers): return False logger.addHandler(handler)","def setup_logging(handler, exclude=['raven', 'sentry.errors']): Returns a boolean based on if logging was configured or not. """""" logger = logging.getLogger() if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler)" 2415,https://:@github.com/pozytywnie/raven-python.git,f0ad0ca6a9de44128982de50c30157b779b69d71,"@@ -16,7 +16,7 @@ class TransportRegistry(object): self.register_transport(transport) def register_transport(self, transport): - if not hasattr(transport, 'scheme') and not hasattr(transport.scheme, '__iter__'): + if not hasattr(transport, 'scheme') or not hasattr(transport.scheme, '__iter__'): raise AttributeError('Transport %s must have a scheme list', transport.__class__.__name__) for scheme in transport.scheme: ",raven/transport/registry.py,"ReplaceText(target='or' @(19,44)->(19,47))","class TransportRegistry(object): self.register_transport(transport) def register_transport(self, transport): if not hasattr(transport, 'scheme') and not hasattr(transport.scheme, '__iter__'): raise AttributeError('Transport %s must have a scheme list', transport.__class__.__name__) for scheme in transport.scheme:","class TransportRegistry(object): self.register_transport(transport) def register_transport(self, transport): if not hasattr(transport, 'scheme') or not hasattr(transport.scheme, '__iter__'): raise AttributeError('Transport %s must have a scheme list', transport.__class__.__name__) for scheme in transport.scheme:" 2416,https://:@github.com/drakantas/Ryoken.git,fb88049c62556d929525509f5e9c192ae2fc6f3b,"@@ -29,4 +29,4 @@ class StrLengthDict(dict): if key in self: raise KeyError('Key already exists') - super().__setitem__(key, (len(key), value)) + super().__setitem__(key, (len(value), value)) ",ryoken/collections.py,"ReplaceText(target='value' @(32,38)->(32,41))","class StrLengthDict(dict): if key in self: raise KeyError('Key already exists') super().__setitem__(key, (len(key), value))","class StrLengthDict(dict): if key in self: raise KeyError('Key already exists') super().__setitem__(key, (len(value), value))" 2417,https://:@gitlab.com/aaron235/gemini-python.git,78c0df38e2193875c19167cd4dd42028e973352a,"@@ -30,7 +30,7 @@ class Gemini( object ): argStringb64 = b64encode( bytes( argString, ""utf-8"" ) ).decode( ""utf-8"" ) signature = hmac.new( bytes( self.__private, 'utf-8' ), - bytes( argString, 'utf-8' ), + bytes( argStringb64, 'utf-8' ), sha384 ) headerPayload = { 'X-GEMINI-APIKEY': self.__public, ",gemini/gemini.py,"ReplaceText(target='argStringb64' @(33,11)->(33,20))","class Gemini( object ): argStringb64 = b64encode( bytes( argString, ""utf-8"" ) ).decode( ""utf-8"" ) signature = hmac.new( bytes( self.__private, 'utf-8' ), bytes( argString, 'utf-8' ), sha384 ) headerPayload = { 'X-GEMINI-APIKEY': self.__public,","class Gemini( object ): argStringb64 = b64encode( bytes( argString, ""utf-8"" ) ).decode( ""utf-8"" ) signature = hmac.new( bytes( self.__private, 'utf-8' ), bytes( argStringb64, 'utf-8' ), sha384 ) headerPayload = { 'X-GEMINI-APIKEY': self.__public," 2418,https://:@github.com/Haufe-Lexware/hl.plone.boardnotifications.git,fe26e02ea6c31a95c8ab89e41a136d1ac4519ad5,"@@ -316,7 +316,7 @@ class Notifier(Persistent): di['commenttext'] = safe_unicode(comment.getText()) subscriptions = getUtility(ISubscriptions) subscribers = set(subscriptions.subscribers_for(thread)) | set(subscriptions.subscribers_for(forum)) - mdtool = getToolByName(comment, 'portal_memberdata') + mdtool = getToolByName(thread, 'portal_memberdata') keys = mdtool.propertyIds() for mdata in subscribers: if (comment is not None) and (mdata.getId() == comment.Creator()): ",hl/plone/boardnotifications/notify.py,"ReplaceText(target='thread' @(319,31)->(319,38))","class Notifier(Persistent): di['commenttext'] = safe_unicode(comment.getText()) subscriptions = getUtility(ISubscriptions) subscribers = set(subscriptions.subscribers_for(thread)) | set(subscriptions.subscribers_for(forum)) mdtool = getToolByName(comment, 'portal_memberdata') keys = mdtool.propertyIds() for mdata in subscribers: if (comment is not None) and (mdata.getId() == comment.Creator()):","class Notifier(Persistent): di['commenttext'] = safe_unicode(comment.getText()) subscriptions = getUtility(ISubscriptions) subscribers = set(subscriptions.subscribers_for(thread)) | set(subscriptions.subscribers_for(forum)) mdtool = getToolByName(thread, 'portal_memberdata') keys = mdtool.propertyIds() for mdata in subscribers: if (comment is not None) and (mdata.getId() == comment.Creator()):" 2419,https://:@github.com/agorinenko/drf-toolkit.git,537a2f9d0a9c740e706c377dd7aa07121b77ca74,"@@ -10,7 +10,7 @@ def validate_request(schema): context = DrfUtils.get_request_parameters(request) context = SchemaValidator.validate(context, schema) kwargs['context'] = context - return view_func(request, *args, **kwargs) + return view_func(view, *args, **kwargs) return _wrapped_view ",drf_toolkit/decorators.py,"ReplaceText(target='view' @(13,29)->(13,36))","def validate_request(schema): context = DrfUtils.get_request_parameters(request) context = SchemaValidator.validate(context, schema) kwargs['context'] = context return view_func(request, *args, **kwargs) return _wrapped_view ","def validate_request(schema): context = DrfUtils.get_request_parameters(request) context = SchemaValidator.validate(context, schema) kwargs['context'] = context return view_func(view, *args, **kwargs) return _wrapped_view " 2420,https://:@gitlab.com/sehnem/pynmet.git,256a7fdab2287ba0f65440766ea6ecf825b058b4,"@@ -51,7 +51,7 @@ class inmet: self.lat = inmet.sites.loc[code].lat self.lon = inmet.sites.loc[code].lon self.alt = inmet.sites.loc[code].alt - self.dados = get_from_ldb(code, db, local) + self.dados = get_from_ldb(code, local, db) def resample(self, periodo): metodos = {'Temperatura': np.mean, 'Temperatura_max': np.max, ",pynmet/inmet.py,"ArgSwap(idxs=1<->2 @(54,21)->(54,33))","class inmet: self.lat = inmet.sites.loc[code].lat self.lon = inmet.sites.loc[code].lon self.alt = inmet.sites.loc[code].alt self.dados = get_from_ldb(code, db, local) def resample(self, periodo): metodos = {'Temperatura': np.mean, 'Temperatura_max': np.max,","class inmet: self.lat = inmet.sites.loc[code].lat self.lon = inmet.sites.loc[code].lon self.alt = inmet.sites.loc[code].alt self.dados = get_from_ldb(code, local, db) def resample(self, periodo): metodos = {'Temperatura': np.mean, 'Temperatura_max': np.max," 2421,https://:@github.com/noobermin/lspplot.git,b384a18d8f70361e1a92ce11e76213b00f396be5,"@@ -86,7 +86,7 @@ trajdefaults = dict( ); def trajectories(ret,trajs,**kw): - getkw=mk_getkw(trajdefaults, kw); + getkw=mk_getkw(kw, trajdefaults); x,y = getkw(""coords""); if not test(kw, ""no_resize""): xlim, ylim = ret['axes'].get_xlim(), ret['axes'].get_ylim(); ",lspplot/pc.py,"ArgSwap(idxs=0<->1 @(89,10)->(89,18))","trajdefaults = dict( ); def trajectories(ret,trajs,**kw): getkw=mk_getkw(trajdefaults, kw); x,y = getkw(""coords""); if not test(kw, ""no_resize""): xlim, ylim = ret['axes'].get_xlim(), ret['axes'].get_ylim();","trajdefaults = dict( ); def trajectories(ret,trajs,**kw): getkw=mk_getkw(kw, trajdefaults); x,y = getkw(""coords""); if not test(kw, ""no_resize""): xlim, ylim = ret['axes'].get_xlim(), ret['axes'].get_ylim();" 2422,https://:@github.com/plures/xnd.git,5af6cf49bfa52ba6381de63c836ca0dcbcd20fe1,"@@ -25,7 +25,7 @@ class xnd(_xnd): ""the 'type' and 'levels' arguments are mutually exclusive"") elif isinstance(type, str): type = ndt(type) - return _xnd(value, type) + return _xnd(type, value) @classmethod def empty(cls, t): ",python/xnd/__init__.py,"ArgSwap(idxs=0<->1 @(28,15)->(28,19))","class xnd(_xnd): ""the 'type' and 'levels' arguments are mutually exclusive"") elif isinstance(type, str): type = ndt(type) return _xnd(value, type) @classmethod def empty(cls, t):","class xnd(_xnd): ""the 'type' and 'levels' arguments are mutually exclusive"") elif isinstance(type, str): type = ndt(type) return _xnd(type, value) @classmethod def empty(cls, t):" 2423,https://:@github.com/OCA/wms.git,c1c96372dd2ecbe990cc33eb630d243bd748804b,"@@ -243,7 +243,7 @@ class SinglePackPutaway(Component): if not pack_transfer.is_dest_location_valid(move, scanned_location): return self._response_for_forbidden_location() - if not pack_transfer.is_dest_location_to_confirm(move, scanned_location): + if pack_transfer.is_dest_location_to_confirm(move, scanned_location): if confirmation: # keep the move in sync otherwise we would have a move line outside # the dest location of the move ",shopfloor/services/single_pack_putaway.py,"ReplaceText(target='' @(246,11)->(246,15))","class SinglePackPutaway(Component): if not pack_transfer.is_dest_location_valid(move, scanned_location): return self._response_for_forbidden_location() if not pack_transfer.is_dest_location_to_confirm(move, scanned_location): if confirmation: # keep the move in sync otherwise we would have a move line outside # the dest location of the move","class SinglePackPutaway(Component): if not pack_transfer.is_dest_location_valid(move, scanned_location): return self._response_for_forbidden_location() if pack_transfer.is_dest_location_to_confirm(move, scanned_location): if confirmation: # keep the move in sync otherwise we would have a move line outside # the dest location of the move" 2424,https://:@github.com/OCA/wms.git,47a835c99aa0b8c1c4db3fd8b73fa04b8eca6d95,"@@ -40,7 +40,7 @@ class PackTransferValidateAction(Component): zone_locations = self.env[""stock.location""].search( [(""id"", ""child_of"", move_dest_location.id)] ) - return scanned_location in zone_locations + return scanned_location not in zone_locations def set_destination_and_done(self, move, scanned_location): ",shopfloor/actions/pack_transfer_validate.py,"ReplaceText(target=' not in ' @(43,31)->(43,35))","class PackTransferValidateAction(Component): zone_locations = self.env[""stock.location""].search( [(""id"", ""child_of"", move_dest_location.id)] ) return scanned_location in zone_locations def set_destination_and_done(self, move, scanned_location): ","class PackTransferValidateAction(Component): zone_locations = self.env[""stock.location""].search( [(""id"", ""child_of"", move_dest_location.id)] ) return scanned_location not in zone_locations def set_destination_and_done(self, move, scanned_location): " 2425,https://:@github.com/OCA/wms.git,47a835c99aa0b8c1c4db3fd8b73fa04b8eca6d95,"@@ -245,7 +245,7 @@ class SinglePackTransfer(Component): if not pack_transfer.is_dest_location_valid(move, scanned_location): return self._response_for_forbidden_location() - if not pack_transfer.is_dest_location_to_confirm(move, scanned_location): + if pack_transfer.is_dest_location_to_confirm(move, scanned_location): if confirmation: # keep the move in sync otherwise we would have a move line outside # the dest location of the move ",shopfloor/services/single_pack_transfer.py,"ReplaceText(target='' @(248,11)->(248,15))","class SinglePackTransfer(Component): if not pack_transfer.is_dest_location_valid(move, scanned_location): return self._response_for_forbidden_location() if not pack_transfer.is_dest_location_to_confirm(move, scanned_location): if confirmation: # keep the move in sync otherwise we would have a move line outside # the dest location of the move","class SinglePackTransfer(Component): if not pack_transfer.is_dest_location_valid(move, scanned_location): return self._response_for_forbidden_location() if pack_transfer.is_dest_location_to_confirm(move, scanned_location): if confirmation: # keep the move in sync otherwise we would have a move line outside # the dest location of the move" 2426,https://:@github.com/OCA/wms.git,0355f73436ee7b90b46f3e740313a8a7bdc5dd8a,"@@ -19,7 +19,7 @@ class SelectDestPackageMixin: ""partner"": {""id"": self.customer.id, ""name"": self.customer.name}, }, ""packages"": [ - self._package_data(picking, package) for package in packages + self._package_data(package, picking) for package in packages ], ""selected_move_lines"": [ self._move_line_data(ml) for ml in selected_lines.sorted() ",shopfloor/tests/test_checkout_list_package.py,"ArgSwap(idxs=0<->1 @(22,20)->(22,38))","class SelectDestPackageMixin: ""partner"": {""id"": self.customer.id, ""name"": self.customer.name}, }, ""packages"": [ self._package_data(picking, package) for package in packages ], ""selected_move_lines"": [ self._move_line_data(ml) for ml in selected_lines.sorted()","class SelectDestPackageMixin: ""partner"": {""id"": self.customer.id, ""name"": self.customer.name}, }, ""packages"": [ self._package_data(package, picking) for package in packages ], ""selected_move_lines"": [ self._move_line_data(ml) for ml in selected_lines.sorted()" 2427,https://:@github.com/OCA/wms.git,6901f38959994d8c64f55a8ab3aad53896f34655,"@@ -193,7 +193,7 @@ class StockMove(models.Model): new_move_per_location[routing_location.id].append(new_move_id) new_moves = self.browse(chain.from_iterable(new_move_per_location.values())) - return self + new_moves + return self | new_moves def _apply_routing_rule_pull(self): """"""Apply routing operations ",stock_routing_operation/models/stock_move.py,"ReplaceText(target='|' @(196,20)->(196,21))","class StockMove(models.Model): new_move_per_location[routing_location.id].append(new_move_id) new_moves = self.browse(chain.from_iterable(new_move_per_location.values())) return self + new_moves def _apply_routing_rule_pull(self): """"""Apply routing operations","class StockMove(models.Model): new_move_per_location[routing_location.id].append(new_move_id) new_moves = self.browse(chain.from_iterable(new_move_per_location.values())) return self | new_moves def _apply_routing_rule_pull(self): """"""Apply routing operations" 2428,https://:@github.com/yassersouri/fandak.git,c75c70e67f2839cbb16b79fded8694c085d7fb24,"@@ -77,7 +77,7 @@ class ScalarMetricCollection: else: value = attr self.writer.add_scalar(tag_name, scalar_value=value, global_step=step) - self.values[attr_name].append(dc_value) + self.values[attr_name].append(value) def epoch_finished(self, epoch_num: int): if self.report_average: ",fandak/utils/metrics.py,"ReplaceText(target='value' @(80,42)->(80,50))","class ScalarMetricCollection: else: value = attr self.writer.add_scalar(tag_name, scalar_value=value, global_step=step) self.values[attr_name].append(dc_value) def epoch_finished(self, epoch_num: int): if self.report_average:","class ScalarMetricCollection: else: value = attr self.writer.add_scalar(tag_name, scalar_value=value, global_step=step) self.values[attr_name].append(value) def epoch_finished(self, epoch_num: int): if self.report_average:" 2429,https://:@gitlab.com/pelops/alcathous.git,df1f1b67170560bac0eb6273711f3f8787965e24,"@@ -86,7 +86,7 @@ class DataPointManager(AbstractMicroservice): _config_methods[key] = m for config_data_point in self._config[""datapoints""]: - dp = DataPoint(config_data_point, _config_methods, self._logger, self._mqtt_client, + dp = DataPoint(config_data_point, _config_methods, self._mqtt_client, self._logger, self._no_data_behavior) self._purges.append(dp.purge_old_values) for method in dp.methods: ",alcathous/datapointmanager.py,"ArgSwap(idxs=2<->3 @(89,17)->(89,26))","class DataPointManager(AbstractMicroservice): _config_methods[key] = m for config_data_point in self._config[""datapoints""]: dp = DataPoint(config_data_point, _config_methods, self._logger, self._mqtt_client, self._no_data_behavior) self._purges.append(dp.purge_old_values) for method in dp.methods:","class DataPointManager(AbstractMicroservice): _config_methods[key] = m for config_data_point in self._config[""datapoints""]: dp = DataPoint(config_data_point, _config_methods, self._mqtt_client, self._logger, self._no_data_behavior) self._purges.append(dp.purge_old_values) for method in dp.methods:" 2430,https://:@github.com/miracle2k/docker-deploy.git,f91f61ec18461b9f88802f2c01ed463565b66f19,"@@ -61,7 +61,7 @@ class DomainPlugin(Plugin): strowger = StrowgerClient(api_ip) for domain, data in domains.items(): - service_name = domain.get('http') + service_name = data.get('http') if not service_name: continue strowger.set_http_route(domain, service_name) ",deploylib/plugins/domains.py,"ReplaceText(target='data' @(64,27)->(64,33))","class DomainPlugin(Plugin): strowger = StrowgerClient(api_ip) for domain, data in domains.items(): service_name = domain.get('http') if not service_name: continue strowger.set_http_route(domain, service_name)","class DomainPlugin(Plugin): strowger = StrowgerClient(api_ip) for domain, data in domains.items(): service_name = data.get('http') if not service_name: continue strowger.set_http_route(domain, service_name)" 2431,https://:@github.com/ttm/participation.git,205208b5b8f477ae40de7453c98fba77d7faf6ef,"@@ -43,7 +43,7 @@ def connectMongo(): client=pymongo.MongoClient(aa.mongouri) shouts=client.aaserver.shouts.find({}) shouts_=[shout for shout in shouts] - return shouts + return shouts_ def accessIrcLog(): with codecs.open(""../../social/data/irc/labmacambira_lalenia3.txt"",""rb"",""iso-8859-1"") as f: ",participation/aa/access.py,"ReplaceText(target='shouts_' @(46,11)->(46,17))","def connectMongo(): client=pymongo.MongoClient(aa.mongouri) shouts=client.aaserver.shouts.find({}) shouts_=[shout for shout in shouts] return shouts def accessIrcLog(): with codecs.open(""../../social/data/irc/labmacambira_lalenia3.txt"",""rb"",""iso-8859-1"") as f:","def connectMongo(): client=pymongo.MongoClient(aa.mongouri) shouts=client.aaserver.shouts.find({}) shouts_=[shout for shout in shouts] return shouts_ def accessIrcLog(): with codecs.open(""../../social/data/irc/labmacambira_lalenia3.txt"",""rb"",""iso-8859-1"") as f:" 2432,https://:@github.com/malicialab/avclass.git,4850b49eb120c39ebcdb4c1b77a3717b00b9666c,"@@ -399,7 +399,7 @@ class Update: tagging.expand_all_destinations() tagging.to_file(tag_filepath) log.info('[-] Output %d tagging rules to %s' % ( - len(tagging), tax_filepath)) + len(tagging), tag_filepath)) expansion.to_file(exp_filepath) log.info('[-] Output %d expansion rules to %s' % ( len(expansion), exp_filepath)) ",avclass2/avclass2_update_module.py,"ReplaceText(target='tag_filepath' @(402,38)->(402,50))","class Update: tagging.expand_all_destinations() tagging.to_file(tag_filepath) log.info('[-] Output %d tagging rules to %s' % ( len(tagging), tax_filepath)) expansion.to_file(exp_filepath) log.info('[-] Output %d expansion rules to %s' % ( len(expansion), exp_filepath))","class Update: tagging.expand_all_destinations() tagging.to_file(tag_filepath) log.info('[-] Output %d tagging rules to %s' % ( len(tagging), tag_filepath)) expansion.to_file(exp_filepath) log.info('[-] Output %d expansion rules to %s' % ( len(expansion), exp_filepath))" 2433,https://:@gitlab.com/crem-repository/dhd.git,ffbb2435ba6d85b4ad2008e8268fbbe66781a4be,"@@ -288,7 +288,7 @@ def test_get_best_terminal_steiner_tree(load_pkl_evolve): evolution = evolve.run_evolution(vertices, terminals, 5, n=16, n1=2, n2=8) genes = evolve.get_best_individual(evolution) - tst = evolve.get_best_terminal_steiner_tree(vertices, terminals, genes) + tst = evolve.get_best_terminal_steiner_tree(vertices, terminals, evolution) w1 = tst['weight'].sum() w2 = evolution.at[len(evolution)-1,'weight'] ",tests/test_evolve.py,"ReplaceText(target='evolution' @(291,69)->(291,74))","def test_get_best_terminal_steiner_tree(load_pkl_evolve): evolution = evolve.run_evolution(vertices, terminals, 5, n=16, n1=2, n2=8) genes = evolve.get_best_individual(evolution) tst = evolve.get_best_terminal_steiner_tree(vertices, terminals, genes) w1 = tst['weight'].sum() w2 = evolution.at[len(evolution)-1,'weight'] ","def test_get_best_terminal_steiner_tree(load_pkl_evolve): evolution = evolve.run_evolution(vertices, terminals, 5, n=16, n1=2, n2=8) genes = evolve.get_best_individual(evolution) tst = evolve.get_best_terminal_steiner_tree(vertices, terminals, evolution) w1 = tst['weight'].sum() w2 = evolution.at[len(evolution)-1,'weight'] " 2434,https://:@github.com/xia2/xia2.git,904123ce19ff3a06c124ad2ca3ee8ca905e7ffa8,"@@ -102,7 +102,7 @@ def reconstruct_rogues(params): for j, rogue in enumerate(rogues): reflections['id'][ann.nn[j]] = 1701 - rogues = reflections.select(reflections['id'] == 1701) + reflections = reflections.select(reflections['id'] == 1701) if params.extract: reflections[""shoebox""] = flex.shoebox( ",command_line/rogues_gallery.py,"ReplaceText(target='reflections' @(105,4)->(105,10))","def reconstruct_rogues(params): for j, rogue in enumerate(rogues): reflections['id'][ann.nn[j]] = 1701 rogues = reflections.select(reflections['id'] == 1701) if params.extract: reflections[""shoebox""] = flex.shoebox(","def reconstruct_rogues(params): for j, rogue in enumerate(rogues): reflections['id'][ann.nn[j]] = 1701 reflections = reflections.select(reflections['id'] == 1701) if params.extract: reflections[""shoebox""] = flex.shoebox(" 2435,https://:@github.com/xia2/xia2.git,849c882a900c44d75c5d4112ca2dc279398b17a6,"@@ -330,7 +330,7 @@ class DialsScaler(Scaler): Debug.write('X1698: %s: %s' % (pointgroup, reindex_op)) if ntr: - integrater.integrater_reset_reindex_operator() + intgr.integrater_reset_reindex_operator() need_to_return = True if pt and not probably_twinned: ",Modules/Scaler/DialsScaler.py,"ReplaceText(target='intgr' @(333,12)->(333,22))","class DialsScaler(Scaler): Debug.write('X1698: %s: %s' % (pointgroup, reindex_op)) if ntr: integrater.integrater_reset_reindex_operator() need_to_return = True if pt and not probably_twinned:","class DialsScaler(Scaler): Debug.write('X1698: %s: %s' % (pointgroup, reindex_op)) if ntr: intgr.integrater_reset_reindex_operator() need_to_return = True if pt and not probably_twinned:"
Statistics for the last 500 blocks
Kilobytes transferred: {}
Transactions: {}
Transactions per block: {}
Total BIS transferred {}Kindergartenblock - Verbinden, vergleichen, Fehler finden ab 4 Jahre / Linda Bayerl
Kindergartenblock - Verbinden, vergleichen, Fehler finden ab 4 Jahre / Linda Bayerl
Kindergartenblock - Verbinden, vergleichen, Fehler finden ab 4 Jahre / Linda Bayerl